1
0

test.cc 331 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(ConnectionErrorTest, InvalidHost) {
  1092. auto host = "-abcde.com";
  1093. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1094. auto port = 443;
  1095. SSLClient cli(host, port);
  1096. #else
  1097. auto port = 80;
  1098. Client cli(host, port);
  1099. #endif
  1100. cli.set_connection_timeout(std::chrono::seconds(2));
  1101. auto res = cli.Get("/");
  1102. ASSERT_TRUE(!res);
  1103. EXPECT_EQ(Error::Connection, res.error());
  1104. }
  1105. TEST(ConnectionErrorTest, InvalidHost2) {
  1106. auto host = "httpbin.org/";
  1107. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1108. SSLClient cli(host);
  1109. #else
  1110. Client cli(host);
  1111. #endif
  1112. cli.set_connection_timeout(std::chrono::seconds(2));
  1113. auto res = cli.Get("/");
  1114. ASSERT_TRUE(!res);
  1115. EXPECT_EQ(Error::Connection, res.error());
  1116. }
  1117. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1118. auto host = "httpbin.org/";
  1119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1120. SSLClient cli(host);
  1121. #else
  1122. Client cli(host);
  1123. #endif
  1124. cli.set_connection_timeout(std::chrono::seconds(2));
  1125. auto res = cli.Get("/");
  1126. ASSERT_TRUE(!res);
  1127. stringstream s;
  1128. s << "error code: " << res.error();
  1129. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1130. }
  1131. TEST(ConnectionErrorTest, InvalidPort) {
  1132. auto host = "localhost";
  1133. auto port = 44380;
  1134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1135. SSLClient cli(host, port);
  1136. #else
  1137. Client cli(host, port);
  1138. #endif
  1139. cli.set_connection_timeout(std::chrono::seconds(2));
  1140. auto res = cli.Get("/");
  1141. ASSERT_TRUE(!res);
  1142. EXPECT_TRUE(Error::Connection == res.error() ||
  1143. Error::ConnectionTimeout == res.error());
  1144. }
  1145. TEST(ConnectionErrorTest, Timeout_Online) {
  1146. auto host = "google.com";
  1147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1148. auto port = 44380;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 8080;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(std::chrono::seconds(2));
  1155. // only probe one address type so that the error reason
  1156. // correlates to the timed-out IPv4, not the unsupported
  1157. // IPv6 connection attempt
  1158. cli.set_address_family(AF_INET);
  1159. auto res = cli.Get("/");
  1160. ASSERT_TRUE(!res);
  1161. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1162. }
  1163. TEST(CancelTest, NoCancel_Online) {
  1164. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1165. auto host = "httpbin.org";
  1166. auto path = std::string{"/range/32"};
  1167. #else
  1168. auto host = "nghttp2.org";
  1169. auto path = std::string{"/httpbin/range/32"};
  1170. #endif
  1171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1172. auto port = 443;
  1173. SSLClient cli(host, port);
  1174. #else
  1175. auto port = 80;
  1176. Client cli(host, port);
  1177. #endif
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. }
  1184. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1185. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1186. auto host = "httpbin.org";
  1187. auto path = std::string{"/range/32"};
  1188. #else
  1189. auto host = "nghttp2.org";
  1190. auto path = std::string{"/httpbin/range/32"};
  1191. #endif
  1192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1193. auto port = 443;
  1194. SSLClient cli(host, port);
  1195. #else
  1196. auto port = 80;
  1197. Client cli(host, port);
  1198. #endif
  1199. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1200. cli.set_connection_timeout(std::chrono::seconds(5));
  1201. ASSERT_TRUE(!res);
  1202. EXPECT_EQ(Error::Canceled, res.error());
  1203. }
  1204. TEST(CancelTest, WithCancelLargePayload_Online) {
  1205. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1206. auto host = "httpbin.org";
  1207. auto path = std::string{"/range/65536"};
  1208. #else
  1209. auto host = "nghttp2.org";
  1210. auto path = std::string{"/httpbin/range/65536"};
  1211. #endif
  1212. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(5));
  1220. uint32_t count = 0;
  1221. auto res =
  1222. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1223. ASSERT_TRUE(!res);
  1224. EXPECT_EQ(Error::Canceled, res.error());
  1225. }
  1226. TEST(CancelTest, NoCancelPost) {
  1227. Server svr;
  1228. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1229. res.set_content("Hello World!", "text/plain");
  1230. });
  1231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1232. auto se = detail::scope_exit([&] {
  1233. svr.stop();
  1234. thread.join();
  1235. ASSERT_FALSE(svr.is_running());
  1236. });
  1237. svr.wait_until_ready();
  1238. Client cli(HOST, PORT);
  1239. cli.set_connection_timeout(std::chrono::seconds(5));
  1240. auto res =
  1241. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1242. "application/json", [](uint64_t, uint64_t) { return true; });
  1243. ASSERT_TRUE(res);
  1244. EXPECT_EQ("Hello World!", res->body);
  1245. EXPECT_EQ(StatusCode::OK_200, res->status);
  1246. }
  1247. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1248. Server svr;
  1249. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1250. res.set_content("Hello World!", "text/plain");
  1251. });
  1252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1253. auto se = detail::scope_exit([&] {
  1254. svr.stop();
  1255. thread.join();
  1256. ASSERT_FALSE(svr.is_running());
  1257. });
  1258. svr.wait_until_ready();
  1259. Client cli(HOST, PORT);
  1260. cli.set_connection_timeout(std::chrono::seconds(5));
  1261. auto res =
  1262. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1263. "application/json", [](uint64_t, uint64_t) { return false; });
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::Canceled, res.error());
  1266. }
  1267. TEST(CancelTest, WithCancelLargePayloadPost) {
  1268. Server svr;
  1269. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1270. res.set_content(LARGE_DATA, "text/plain");
  1271. });
  1272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1273. auto se = detail::scope_exit([&] {
  1274. svr.stop();
  1275. thread.join();
  1276. ASSERT_FALSE(svr.is_running());
  1277. });
  1278. svr.wait_until_ready();
  1279. Client cli(HOST, PORT);
  1280. cli.set_connection_timeout(std::chrono::seconds(5));
  1281. auto res =
  1282. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1283. "application/json", [](uint64_t, uint64_t) { return false; });
  1284. ASSERT_TRUE(!res);
  1285. EXPECT_EQ(Error::Canceled, res.error());
  1286. }
  1287. TEST(CancelTest, NoCancelPut) {
  1288. Server svr;
  1289. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1290. res.set_content("Hello World!", "text/plain");
  1291. });
  1292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1293. auto se = detail::scope_exit([&] {
  1294. svr.stop();
  1295. thread.join();
  1296. ASSERT_FALSE(svr.is_running());
  1297. });
  1298. svr.wait_until_ready();
  1299. Client cli(HOST, PORT);
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res =
  1302. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1303. "application/json", [](uint64_t, uint64_t) { return true; });
  1304. ASSERT_TRUE(res);
  1305. EXPECT_EQ("Hello World!", res->body);
  1306. EXPECT_EQ(StatusCode::OK_200, res->status);
  1307. }
  1308. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1309. Server svr;
  1310. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1311. res.set_content("Hello World!", "text/plain");
  1312. });
  1313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1314. auto se = detail::scope_exit([&] {
  1315. svr.stop();
  1316. thread.join();
  1317. ASSERT_FALSE(svr.is_running());
  1318. });
  1319. svr.wait_until_ready();
  1320. Client cli(HOST, PORT);
  1321. cli.set_connection_timeout(std::chrono::seconds(5));
  1322. auto res =
  1323. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1324. "application/json", [](uint64_t, uint64_t) { return false; });
  1325. ASSERT_TRUE(!res);
  1326. EXPECT_EQ(Error::Canceled, res.error());
  1327. }
  1328. TEST(CancelTest, WithCancelLargePayloadPut) {
  1329. Server svr;
  1330. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1331. res.set_content(LARGE_DATA, "text/plain");
  1332. });
  1333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1334. auto se = detail::scope_exit([&] {
  1335. svr.stop();
  1336. thread.join();
  1337. ASSERT_FALSE(svr.is_running());
  1338. });
  1339. svr.wait_until_ready();
  1340. Client cli(HOST, PORT);
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. auto res =
  1343. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1344. "application/json", [](uint64_t, uint64_t) { return false; });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPatch) {
  1349. Server svr;
  1350. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1370. Server svr;
  1371. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1390. Server svr;
  1391. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1392. res.set_content(LARGE_DATA, "text/plain");
  1393. });
  1394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1395. auto se = detail::scope_exit([&] {
  1396. svr.stop();
  1397. thread.join();
  1398. ASSERT_FALSE(svr.is_running());
  1399. });
  1400. svr.wait_until_ready();
  1401. Client cli(HOST, PORT);
  1402. cli.set_connection_timeout(std::chrono::seconds(5));
  1403. auto res =
  1404. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1405. "application/json", [](uint64_t, uint64_t) { return false; });
  1406. ASSERT_TRUE(!res);
  1407. EXPECT_EQ(Error::Canceled, res.error());
  1408. }
  1409. TEST(CancelTest, NoCancelDelete) {
  1410. Server svr;
  1411. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1412. res.set_content("Hello World!", "text/plain");
  1413. });
  1414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1415. auto se = detail::scope_exit([&] {
  1416. svr.stop();
  1417. thread.join();
  1418. ASSERT_FALSE(svr.is_running());
  1419. });
  1420. svr.wait_until_ready();
  1421. Client cli(HOST, PORT);
  1422. cli.set_connection_timeout(std::chrono::seconds(5));
  1423. auto res =
  1424. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1425. "application/json", [](uint64_t, uint64_t) { return true; });
  1426. ASSERT_TRUE(res);
  1427. EXPECT_EQ("Hello World!", res->body);
  1428. EXPECT_EQ(StatusCode::OK_200, res->status);
  1429. }
  1430. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1431. Server svr;
  1432. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1433. res.set_content("Hello World!", "text/plain");
  1434. });
  1435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1436. auto se = detail::scope_exit([&] {
  1437. svr.stop();
  1438. thread.join();
  1439. ASSERT_FALSE(svr.is_running());
  1440. });
  1441. svr.wait_until_ready();
  1442. Client cli(HOST, PORT);
  1443. cli.set_connection_timeout(std::chrono::seconds(5));
  1444. auto res =
  1445. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1446. "application/json", [](uint64_t, uint64_t) { return false; });
  1447. ASSERT_TRUE(!res);
  1448. EXPECT_EQ(Error::Canceled, res.error());
  1449. }
  1450. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1451. Server svr;
  1452. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_connection_timeout(std::chrono::seconds(5));
  1464. auto res =
  1465. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1466. "application/json", [](uint64_t, uint64_t) { return false; });
  1467. ASSERT_TRUE(!res);
  1468. EXPECT_EQ(Error::Canceled, res.error());
  1469. }
  1470. static std::string remove_whitespace(const std::string &input) {
  1471. std::string output;
  1472. output.reserve(input.size());
  1473. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1474. [](unsigned char c) { return !std::isspace(c); });
  1475. return output;
  1476. }
  1477. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1478. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1479. auto host = "httpbin.org";
  1480. auto path = std::string{"/basic-auth/hello/world"};
  1481. #else
  1482. auto host = "nghttp2.org";
  1483. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1484. #endif
  1485. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1486. auto port = 443;
  1487. SSLClient cli(host, port);
  1488. #else
  1489. auto port = 80;
  1490. Client cli(host, port);
  1491. #endif
  1492. {
  1493. auto res = cli.Get(path);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1496. }
  1497. {
  1498. auto res =
  1499. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1502. remove_whitespace(res->body));
  1503. EXPECT_EQ(StatusCode::OK_200, res->status);
  1504. }
  1505. {
  1506. cli.set_basic_auth("hello", "world");
  1507. auto res = cli.Get(path);
  1508. ASSERT_TRUE(res);
  1509. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1510. remove_whitespace(res->body));
  1511. EXPECT_EQ(StatusCode::OK_200, res->status);
  1512. }
  1513. {
  1514. cli.set_basic_auth("hello", "bad");
  1515. auto res = cli.Get(path);
  1516. ASSERT_TRUE(res);
  1517. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1518. }
  1519. {
  1520. cli.set_basic_auth("bad", "world");
  1521. auto res = cli.Get(path);
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1524. }
  1525. }
  1526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1527. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1528. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1529. auto host = "httpbin.org";
  1530. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1531. auto paths = std::vector<std::string>{
  1532. "/digest-auth/auth/hello/world/MD5",
  1533. "/digest-auth/auth/hello/world/SHA-256",
  1534. "/digest-auth/auth/hello/world/SHA-512",
  1535. "/digest-auth/auth-int/hello/world/MD5",
  1536. };
  1537. #else
  1538. auto host = "nghttp2.org";
  1539. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1540. auto paths = std::vector<std::string>{
  1541. "/httpbin/digest-auth/auth/hello/world/MD5",
  1542. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1543. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1544. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1545. };
  1546. #endif
  1547. auto port = 443;
  1548. SSLClient cli(host, port);
  1549. {
  1550. auto res = cli.Get(unauth_path);
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1553. }
  1554. {
  1555. cli.set_digest_auth("hello", "world");
  1556. for (const auto &path : paths) {
  1557. auto res = cli.Get(path.c_str());
  1558. ASSERT_TRUE(res);
  1559. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1560. remove_whitespace(res->body));
  1561. EXPECT_EQ(StatusCode::OK_200, res->status);
  1562. }
  1563. cli.set_digest_auth("hello", "bad");
  1564. for (const auto &path : paths) {
  1565. auto res = cli.Get(path.c_str());
  1566. ASSERT_TRUE(res);
  1567. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1568. }
  1569. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1570. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1571. // cli.set_digest_auth("bad", "world");
  1572. // for (const auto& path : paths) {
  1573. // auto res = cli.Get(path.c_str());
  1574. // ASSERT_TRUE(res);
  1575. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1576. // }
  1577. }
  1578. }
  1579. #endif
  1580. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1581. auto host = "google.com";
  1582. auto another_host = "example.com";
  1583. auto wrong_ip = "0.0.0.0";
  1584. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1585. SSLClient cli(host);
  1586. #else
  1587. Client cli(host);
  1588. #endif
  1589. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1590. auto res = cli.Get("/");
  1591. ASSERT_TRUE(res);
  1592. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1593. }
  1594. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1595. auto host = "google.com";
  1596. auto wrong_ip = "0.0.0.0";
  1597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1598. SSLClient cli(host);
  1599. #else
  1600. Client cli(host);
  1601. #endif
  1602. cli.set_hostname_addr_map({{host, wrong_ip}});
  1603. auto res = cli.Get("/");
  1604. ASSERT_TRUE(!res);
  1605. EXPECT_EQ(Error::Connection, res.error());
  1606. }
  1607. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1608. auto host = "nghttp2.org";
  1609. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1610. SSLClient cli(host);
  1611. #else
  1612. Client cli(host);
  1613. #endif
  1614. cli.set_follow_location(true);
  1615. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1616. ASSERT_TRUE(res);
  1617. EXPECT_EQ(StatusCode::OK_200, res->status);
  1618. }
  1619. TEST(RedirectTest, Redirect_Online) {
  1620. auto host = "nghttp2.org";
  1621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1622. SSLClient cli(host);
  1623. #else
  1624. Client cli(host);
  1625. #endif
  1626. cli.set_follow_location(true);
  1627. auto res = cli.Get("/httpbin/redirect/3");
  1628. ASSERT_TRUE(res);
  1629. EXPECT_EQ(StatusCode::OK_200, res->status);
  1630. }
  1631. TEST(RelativeRedirectTest, Redirect_Online) {
  1632. auto host = "nghttp2.org";
  1633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1634. SSLClient cli(host);
  1635. #else
  1636. Client cli(host);
  1637. #endif
  1638. cli.set_follow_location(true);
  1639. auto res = cli.Get("/httpbin/relative-redirect/3");
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. TEST(TooManyRedirectTest, Redirect_Online) {
  1644. auto host = "nghttp2.org";
  1645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1646. SSLClient cli(host);
  1647. #else
  1648. Client cli(host);
  1649. #endif
  1650. cli.set_follow_location(true);
  1651. auto res = cli.Get("/httpbin/redirect/21");
  1652. ASSERT_TRUE(!res);
  1653. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1654. }
  1655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1656. TEST(YahooRedirectTest, Redirect_Online) {
  1657. Client cli("yahoo.com");
  1658. auto res = cli.Get("/");
  1659. ASSERT_TRUE(res);
  1660. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1661. cli.set_follow_location(true);
  1662. res = cli.Get("/");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1666. }
  1667. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1668. #define REDIR_HOST "httpbingo.org"
  1669. #define REDIR_PATH "/redirect-to"
  1670. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1671. SSLClient cli(REDIR_HOST);
  1672. cli.set_follow_location(true);
  1673. auto res =
  1674. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1675. ASSERT_TRUE(res);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1679. SSLClient cli(REDIR_HOST);
  1680. cli.set_follow_location(true);
  1681. Params params;
  1682. params.emplace("url", "http://example.com");
  1683. params.emplace("status_code", "302");
  1684. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1689. SSLClient cli(REDIR_HOST);
  1690. cli.set_follow_location(true);
  1691. Params params;
  1692. params.emplace("url", "http://example.com");
  1693. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1694. ASSERT_TRUE(res);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. TEST(UrlWithSpace, Redirect_Online) {
  1698. SSLClient cli("edge.forgecdn.net");
  1699. cli.set_follow_location(true);
  1700. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1704. }
  1705. #endif
  1706. #if !defined(_WIN32) && !defined(_WIN64)
  1707. TEST(ReceiveSignals, Signal) {
  1708. auto setupSignalHandlers = []() {
  1709. struct sigaction act;
  1710. sigemptyset(&act.sa_mask);
  1711. act.sa_flags = SA_SIGINFO;
  1712. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1713. switch (sig) {
  1714. case SIGINT:
  1715. default: break;
  1716. }
  1717. };
  1718. ::sigaction(SIGINT, &act, nullptr);
  1719. };
  1720. Server svr;
  1721. int port = 0;
  1722. auto thread = std::thread([&]() {
  1723. setupSignalHandlers();
  1724. port = svr.bind_to_any_port("localhost");
  1725. svr.listen_after_bind();
  1726. });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. ASSERT_TRUE(svr.is_running());
  1734. pthread_kill(thread.native_handle(), SIGINT);
  1735. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1736. ASSERT_TRUE(svr.is_running());
  1737. }
  1738. #endif
  1739. TEST(RedirectToDifferentPort, Redirect) {
  1740. Server svr1;
  1741. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1742. res.set_content("Hello World!", "text/plain");
  1743. });
  1744. int svr1_port = 0;
  1745. auto thread1 = std::thread([&]() {
  1746. svr1_port = svr1.bind_to_any_port("localhost");
  1747. svr1.listen_after_bind();
  1748. });
  1749. Server svr2;
  1750. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1751. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1752. });
  1753. int svr2_port = 0;
  1754. auto thread2 = std::thread([&]() {
  1755. svr2_port = svr2.bind_to_any_port("localhost");
  1756. svr2.listen_after_bind();
  1757. });
  1758. auto se = detail::scope_exit([&] {
  1759. svr2.stop();
  1760. thread2.join();
  1761. svr1.stop();
  1762. thread1.join();
  1763. ASSERT_FALSE(svr2.is_running());
  1764. ASSERT_FALSE(svr1.is_running());
  1765. });
  1766. svr1.wait_until_ready();
  1767. svr2.wait_until_ready();
  1768. Client cli("localhost", svr2_port);
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/2");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. EXPECT_EQ("Hello World!", res->body);
  1774. }
  1775. TEST(RedirectFromPageWithContent, Redirect) {
  1776. Server svr;
  1777. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1778. res.set_content("___", "text/plain");
  1779. res.set_redirect("/2");
  1780. });
  1781. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1782. res.set_content("Hello World!", "text/plain");
  1783. });
  1784. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1785. auto se = detail::scope_exit([&] {
  1786. svr.stop();
  1787. th.join();
  1788. ASSERT_FALSE(svr.is_running());
  1789. });
  1790. svr.wait_until_ready();
  1791. {
  1792. Client cli("localhost", PORT);
  1793. cli.set_follow_location(true);
  1794. std::string body;
  1795. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1796. body.append(data, data_length);
  1797. return true;
  1798. });
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. EXPECT_EQ("Hello World!", body);
  1802. }
  1803. {
  1804. Client cli("localhost", PORT);
  1805. std::string body;
  1806. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1807. body.append(data, data_length);
  1808. return true;
  1809. });
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::Found_302, res->status);
  1812. EXPECT_EQ("___", body);
  1813. }
  1814. }
  1815. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1816. Server svr;
  1817. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1818. res.set_content("___", "text/plain");
  1819. // res.set_redirect("/2");
  1820. res.set_redirect("http://[::1]:1234/2");
  1821. });
  1822. svr.Get("/2", [&](const Request &req, Response &res) {
  1823. auto host_header = req.headers.find("Host");
  1824. ASSERT_TRUE(host_header != req.headers.end());
  1825. EXPECT_EQ("[::1]:1234", host_header->second);
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. th.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1835. // actually starts anything, so the condition !svr.is_running() will
  1836. // always remain true, and the loop never stops.
  1837. // This basically counts how many milliseconds have passed since the
  1838. // call to svr.listen(), and if after 5 seconds nothing started yet
  1839. // aborts the test.
  1840. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1841. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1842. ASSERT_LT(milliseconds, 5000U);
  1843. }
  1844. {
  1845. Client cli("http://[::1]:1234");
  1846. cli.set_follow_location(true);
  1847. std::string body;
  1848. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1849. body.append(data, data_length);
  1850. return true;
  1851. });
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. EXPECT_EQ("Hello World!", body);
  1855. }
  1856. {
  1857. Client cli("http://[::1]:1234");
  1858. std::string body;
  1859. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1860. body.append(data, data_length);
  1861. return true;
  1862. });
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::Found_302, res->status);
  1865. EXPECT_EQ("___", body);
  1866. }
  1867. }
  1868. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1869. Server svr;
  1870. svr.Get("/foo", [](const Request &req, Response &res) {
  1871. auto a = req.params.find("a");
  1872. if (a != req.params.end()) {
  1873. res.set_content((*a).second, "text/plain");
  1874. res.status = StatusCode::OK_200;
  1875. } else {
  1876. res.status = StatusCode::BadRequest_400;
  1877. }
  1878. });
  1879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. {
  1887. Client cli(HOST, PORT);
  1888. cli.set_path_encode(false);
  1889. auto res = cli.Get("/foo?a=explicitly+encoded");
  1890. ASSERT_TRUE(res);
  1891. EXPECT_EQ(StatusCode::OK_200, res->status);
  1892. // This expects it back with a space, as the `+` won't have been
  1893. // url-encoded, and server-side the params get decoded turning `+`
  1894. // into spaces.
  1895. EXPECT_EQ("explicitly encoded", res->body);
  1896. }
  1897. }
  1898. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1899. Server svr;
  1900. svr.Get("/", [](const Request &req, Response &) {
  1901. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1902. });
  1903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. {
  1911. Client cli(HOST, PORT);
  1912. cli.set_path_encode(false);
  1913. auto res = cli.Get("/?something=%0A");
  1914. ASSERT_TRUE(res);
  1915. EXPECT_EQ(StatusCode::OK_200, res->status);
  1916. }
  1917. }
  1918. TEST(BindServerTest, DISABLED_BindDualStack) {
  1919. Server svr;
  1920. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1921. res.set_content("Hello World!", "text/plain");
  1922. });
  1923. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1924. auto se = detail::scope_exit([&] {
  1925. svr.stop();
  1926. thread.join();
  1927. ASSERT_FALSE(svr.is_running());
  1928. });
  1929. svr.wait_until_ready();
  1930. {
  1931. Client cli("127.0.0.1", PORT);
  1932. auto res = cli.Get("/1");
  1933. ASSERT_TRUE(res);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ("Hello World!", res->body);
  1936. }
  1937. {
  1938. Client cli("::1", PORT);
  1939. auto res = cli.Get("/1");
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::OK_200, res->status);
  1942. EXPECT_EQ("Hello World!", res->body);
  1943. }
  1944. }
  1945. TEST(BindServerTest, BindAndListenSeparately) {
  1946. Server svr;
  1947. int port = svr.bind_to_any_port("0.0.0.0");
  1948. ASSERT_TRUE(svr.is_valid());
  1949. ASSERT_TRUE(port > 0);
  1950. svr.stop();
  1951. }
  1952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1953. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1955. CLIENT_CA_CERT_DIR);
  1956. int port = svr.bind_to_any_port("0.0.0.0");
  1957. ASSERT_TRUE(svr.is_valid());
  1958. ASSERT_TRUE(port > 0);
  1959. svr.stop();
  1960. }
  1961. #endif
  1962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1963. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1964. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1965. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1966. int port = svr.bind_to_any_port("0.0.0.0");
  1967. ASSERT_TRUE(svr.is_valid());
  1968. ASSERT_TRUE(port > 0);
  1969. svr.stop();
  1970. }
  1971. #endif
  1972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1973. X509 *readCertificate(const std::string &strFileName) {
  1974. std::ifstream inStream(strFileName);
  1975. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1976. std::istreambuf_iterator<char>());
  1977. if (strCertPEM.empty()) return (nullptr);
  1978. BIO *pbCert = BIO_new(BIO_s_mem());
  1979. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1980. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1981. BIO_free(pbCert);
  1982. return (pCert);
  1983. }
  1984. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1985. std::ifstream inStream(strFileName);
  1986. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1987. std::istreambuf_iterator<char>());
  1988. if (strPrivateKeyPEM.empty()) return (nullptr);
  1989. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1990. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1991. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1992. BIO_free(pbPrivKey);
  1993. return (pPrivateKey);
  1994. }
  1995. TEST(BindServerTest, UpdateCerts) {
  1996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1997. int port = svr.bind_to_any_port("0.0.0.0");
  1998. ASSERT_TRUE(svr.is_valid());
  1999. ASSERT_TRUE(port > 0);
  2000. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2001. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2002. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2003. ASSERT_TRUE(cert != nullptr);
  2004. ASSERT_TRUE(ca_cert != nullptr);
  2005. ASSERT_TRUE(key != nullptr);
  2006. X509_STORE *cert_store = X509_STORE_new();
  2007. X509_STORE_add_cert(cert_store, ca_cert);
  2008. svr.update_certs(cert, key, cert_store);
  2009. ASSERT_TRUE(svr.is_valid());
  2010. svr.stop();
  2011. X509_free(cert);
  2012. X509_free(ca_cert);
  2013. EVP_PKEY_free(key);
  2014. }
  2015. #endif
  2016. TEST(ErrorHandlerTest, ContentLength) {
  2017. Server svr;
  2018. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2019. res.status = StatusCode::OK_200;
  2020. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2021. "text/html"); // <= Content-Length still 13
  2022. });
  2023. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2024. res.set_content("Hello World!\n", "text/plain");
  2025. res.status = 524;
  2026. });
  2027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2028. auto se = detail::scope_exit([&] {
  2029. svr.stop();
  2030. thread.join();
  2031. ASSERT_FALSE(svr.is_running());
  2032. });
  2033. svr.wait_until_ready();
  2034. {
  2035. Client cli(HOST, PORT);
  2036. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2042. }
  2043. }
  2044. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2045. TEST(ExceptionTest, WithoutExceptionHandler) {
  2046. Server svr;
  2047. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2048. throw std::runtime_error("exception...");
  2049. });
  2050. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2051. throw std::runtime_error("exception\r\n...");
  2052. });
  2053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2054. auto se = detail::scope_exit([&] {
  2055. svr.stop();
  2056. listen_thread.join();
  2057. ASSERT_FALSE(svr.is_running());
  2058. });
  2059. svr.wait_until_ready();
  2060. Client cli("localhost", PORT);
  2061. {
  2062. auto res = cli.Get("/exception");
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2065. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2066. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2067. }
  2068. {
  2069. auto res = cli.Get("/unknown");
  2070. ASSERT_TRUE(res);
  2071. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2072. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2073. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2074. }
  2075. }
  2076. TEST(ExceptionTest, WithExceptionHandler) {
  2077. Server svr;
  2078. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2079. std::exception_ptr ep) {
  2080. EXPECT_FALSE(ep == nullptr);
  2081. try {
  2082. std::rethrow_exception(ep);
  2083. } catch (std::exception &e) {
  2084. EXPECT_EQ("abc", std::string(e.what()));
  2085. } catch (...) {}
  2086. res.status = StatusCode::InternalServerError_500;
  2087. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2088. "text/html"); // <= Content-Length still 13 at this point
  2089. });
  2090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2091. res.set_content("Hello World!\n", "text/plain");
  2092. throw std::runtime_error("abc");
  2093. });
  2094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2095. auto se = detail::scope_exit([&] {
  2096. svr.stop();
  2097. thread.join();
  2098. ASSERT_FALSE(svr.is_running());
  2099. });
  2100. svr.wait_until_ready();
  2101. for (size_t i = 0; i < 10; i++) {
  2102. Client cli(HOST, PORT);
  2103. for (size_t j = 0; j < 100; j++) {
  2104. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2108. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2109. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2110. }
  2111. cli.set_keep_alive(true);
  2112. for (size_t j = 0; j < 100; j++) {
  2113. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2118. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2119. }
  2120. }
  2121. }
  2122. TEST(ExceptionTest, AndErrorHandler) {
  2123. Server svr;
  2124. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2125. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2126. });
  2127. svr.set_exception_handler(
  2128. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2129. EXPECT_FALSE(ep == nullptr);
  2130. try {
  2131. std::rethrow_exception(ep);
  2132. } catch (std::exception &e) {
  2133. res.set_content(e.what(), "text/html");
  2134. } catch (...) {}
  2135. res.status = StatusCode::InternalServerError_500;
  2136. });
  2137. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2138. throw std::runtime_error("EXCEPTION");
  2139. });
  2140. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2141. res.set_content("ERROR", "text/html");
  2142. res.status = StatusCode::InternalServerError_500;
  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. Client cli(HOST, PORT);
  2152. {
  2153. auto res = cli.Get("/exception");
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2156. EXPECT_EQ("EXCEPTION", res->body);
  2157. }
  2158. {
  2159. auto res = cli.Get("/error");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. EXPECT_EQ("ERROR", res->body);
  2163. }
  2164. {
  2165. auto res = cli.Get("/invalid");
  2166. ASSERT_TRUE(res);
  2167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2168. EXPECT_EQ("NOT_FOUND", res->body);
  2169. }
  2170. }
  2171. #endif
  2172. TEST(NoContentTest, ContentLength) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.status = StatusCode::NoContent_204;
  2176. });
  2177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. thread.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. svr.wait_until_ready();
  2184. {
  2185. Client cli(HOST, PORT);
  2186. auto res = cli.Get("/hi");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2189. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2190. }
  2191. }
  2192. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2195. ASSERT_TRUE(svr.is_valid());
  2196. #else
  2197. Server svr;
  2198. #endif
  2199. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2200. if (req.path == "/routing_handler") {
  2201. res.set_header("PRE_ROUTING", "on");
  2202. res.set_content("Routing Handler", "text/plain");
  2203. return httplib::Server::HandlerResponse::Handled;
  2204. }
  2205. return httplib::Server::HandlerResponse::Unhandled;
  2206. });
  2207. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2208. res.set_content("Error", "text/html");
  2209. });
  2210. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2211. if (req.path == "/routing_handler") {
  2212. res.set_header("POST_ROUTING", "on");
  2213. }
  2214. });
  2215. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2216. res.set_content("Hello World!\n", "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. SSLClient cli(HOST, PORT);
  2228. cli.enable_server_certificate_verification(false);
  2229. #else
  2230. Client cli(HOST, PORT);
  2231. #endif
  2232. auto res = cli.Get("/routing_handler");
  2233. ASSERT_TRUE(res);
  2234. EXPECT_EQ(StatusCode::OK_200, res->status);
  2235. EXPECT_EQ("Routing Handler", res->body);
  2236. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2237. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2238. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2239. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2240. }
  2241. {
  2242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2243. SSLClient cli(HOST, PORT);
  2244. cli.enable_server_certificate_verification(false);
  2245. #else
  2246. Client cli(HOST, PORT);
  2247. #endif
  2248. auto res = cli.Get("/hi");
  2249. ASSERT_TRUE(res);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ("Hello World!\n", res->body);
  2252. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2253. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2254. }
  2255. {
  2256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2257. SSLClient cli(HOST, PORT);
  2258. cli.enable_server_certificate_verification(false);
  2259. #else
  2260. Client cli(HOST, PORT);
  2261. #endif
  2262. auto res = cli.Get("/aaa");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("Error", res->body);
  2266. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2267. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2268. }
  2269. }
  2270. TEST(RequestHandlerTest, PreRequestHandler) {
  2271. auto route_path = "/user/:user";
  2272. Server svr;
  2273. svr.Get("/hi", [](const Request &, Response &res) {
  2274. res.set_content("hi", "text/plain");
  2275. });
  2276. svr.Get(route_path, [](const Request &req, Response &res) {
  2277. res.set_content(req.path_params.at("user"), "text/plain");
  2278. });
  2279. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2280. if (req.matched_route == route_path) {
  2281. auto user = req.path_params.at("user");
  2282. if (user != "john") {
  2283. res.status = StatusCode::Forbidden_403;
  2284. res.set_content("error", "text/html");
  2285. return Server::HandlerResponse::Handled;
  2286. }
  2287. }
  2288. return Server::HandlerResponse::Unhandled;
  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. Client cli(HOST, PORT);
  2298. {
  2299. auto res = cli.Get("/hi");
  2300. ASSERT_TRUE(res);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. EXPECT_EQ("hi", res->body);
  2303. }
  2304. {
  2305. auto res = cli.Get("/user/john");
  2306. ASSERT_TRUE(res);
  2307. EXPECT_EQ(StatusCode::OK_200, res->status);
  2308. EXPECT_EQ("john", res->body);
  2309. }
  2310. {
  2311. auto res = cli.Get("/user/invalid-user");
  2312. ASSERT_TRUE(res);
  2313. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2314. EXPECT_EQ("error", res->body);
  2315. }
  2316. }
  2317. TEST(InvalidFormatTest, StatusCode) {
  2318. Server svr;
  2319. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2320. res.set_content("Hello World!\n", "text/plain");
  2321. res.status = 9999; // Status should be a three-digit code...
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. Client cli(HOST, PORT);
  2332. auto res = cli.Get("/hi");
  2333. ASSERT_FALSE(res);
  2334. }
  2335. }
  2336. TEST(URLFragmentTest, WithFragment) {
  2337. Server svr;
  2338. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2339. EXPECT_TRUE(req.target == "/hi");
  2340. });
  2341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2342. auto se = detail::scope_exit([&] {
  2343. svr.stop();
  2344. thread.join();
  2345. ASSERT_FALSE(svr.is_running());
  2346. });
  2347. svr.wait_until_ready();
  2348. {
  2349. Client cli(HOST, PORT);
  2350. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2351. EXPECT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. res = cli.Get("/hi%23key1=val1=key2=val2");
  2354. EXPECT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2356. }
  2357. }
  2358. TEST(HeaderWriter, SetHeaderWriter) {
  2359. Server svr;
  2360. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2361. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2362. return detail::write_headers(strm, hdrs);
  2363. });
  2364. svr.Get("/hi", [](const Request &req, Response &res) {
  2365. auto it = req.headers.find("CustomClientHeader");
  2366. EXPECT_TRUE(it != req.headers.end());
  2367. EXPECT_EQ(it->second, "CustomClientValue");
  2368. res.set_content("Hello World!\n", "text/plain");
  2369. });
  2370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2371. auto se = detail::scope_exit([&] {
  2372. svr.stop();
  2373. thread.join();
  2374. ASSERT_FALSE(svr.is_running());
  2375. });
  2376. svr.wait_until_ready();
  2377. {
  2378. Client cli(HOST, PORT);
  2379. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2380. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2381. return detail::write_headers(strm, hdrs);
  2382. });
  2383. auto res = cli.Get("/hi");
  2384. EXPECT_TRUE(res);
  2385. EXPECT_EQ(StatusCode::OK_200, res->status);
  2386. auto it = res->headers.find("CustomServerHeader");
  2387. EXPECT_TRUE(it != res->headers.end());
  2388. EXPECT_EQ(it->second, "CustomServerValue");
  2389. }
  2390. }
  2391. class ServerTest : public ::testing::Test {
  2392. protected:
  2393. ServerTest()
  2394. : cli_(HOST, PORT)
  2395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2396. ,
  2397. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2398. #endif
  2399. {
  2400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2401. cli_.enable_server_certificate_verification(false);
  2402. #endif
  2403. }
  2404. virtual void SetUp() {
  2405. svr_.set_mount_point("/", "./www");
  2406. svr_.set_mount_point("/mount", "./www2");
  2407. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2408. svr_.Get("/hi",
  2409. [&](const Request & /*req*/, Response &res) {
  2410. res.set_content("Hello World!", "text/plain");
  2411. })
  2412. .Get("/file_content",
  2413. [&](const Request & /*req*/, Response &res) {
  2414. res.set_file_content("./www/dir/test.html");
  2415. })
  2416. .Get("/file_content_with_content_type",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. res.set_file_content("./www/file", "text/plain");
  2419. })
  2420. .Get("/invalid_file_content",
  2421. [&](const Request & /*req*/, Response &res) {
  2422. res.set_file_content("./www/dir/invalid_file_path");
  2423. })
  2424. .Get("/http_response_splitting",
  2425. [&](const Request & /*req*/, Response &res) {
  2426. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2427. EXPECT_EQ(0U, res.headers.size());
  2428. EXPECT_FALSE(res.has_header("a"));
  2429. res.set_header("a", "1\nSet-Cookie: a=1");
  2430. EXPECT_EQ(0U, res.headers.size());
  2431. EXPECT_FALSE(res.has_header("a"));
  2432. res.set_header("a", "1\rSet-Cookie: a=1");
  2433. EXPECT_EQ(0U, res.headers.size());
  2434. EXPECT_FALSE(res.has_header("a"));
  2435. res.set_header("a\r\nb", "0");
  2436. EXPECT_EQ(0U, res.headers.size());
  2437. EXPECT_FALSE(res.has_header("a"));
  2438. res.set_header("a\rb", "0");
  2439. EXPECT_EQ(0U, res.headers.size());
  2440. EXPECT_FALSE(res.has_header("a"));
  2441. res.set_header("a\nb", "0");
  2442. EXPECT_EQ(0U, res.headers.size());
  2443. EXPECT_FALSE(res.has_header("a"));
  2444. res.set_redirect("1\r\nSet-Cookie: a=1");
  2445. EXPECT_EQ(0U, res.headers.size());
  2446. EXPECT_FALSE(res.has_header("Location"));
  2447. })
  2448. .Get("/slow",
  2449. [&](const Request & /*req*/, Response &res) {
  2450. std::this_thread::sleep_for(std::chrono::seconds(2));
  2451. res.set_content("slow", "text/plain");
  2452. })
  2453. #if 0
  2454. .Post("/slowpost",
  2455. [&](const Request & /*req*/, Response &res) {
  2456. std::this_thread::sleep_for(std::chrono::seconds(2));
  2457. res.set_content("slow", "text/plain");
  2458. })
  2459. #endif
  2460. .Get("/remote_addr",
  2461. [&](const Request &req, Response &res) {
  2462. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2463. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2464. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2465. EXPECT_EQ(req.remote_port,
  2466. std::stoi(req.get_header_value("REMOTE_PORT")));
  2467. res.set_content(remote_addr.c_str(), "text/plain");
  2468. })
  2469. .Get("/local_addr",
  2470. [&](const Request &req, Response &res) {
  2471. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2472. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2473. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2474. auto local_port = req.get_header_value("LOCAL_PORT");
  2475. EXPECT_EQ(req.local_addr, local_addr);
  2476. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2477. res.set_content(local_addr.append(":").append(local_port),
  2478. "text/plain");
  2479. })
  2480. .Get("/endwith%",
  2481. [&](const Request & /*req*/, Response &res) {
  2482. res.set_content("Hello World!", "text/plain");
  2483. })
  2484. .Get("/a\\+\\+b",
  2485. [&](const Request &req, Response &res) {
  2486. ASSERT_TRUE(req.has_param("a +b"));
  2487. auto val = req.get_param_value("a +b");
  2488. res.set_content(val, "text/plain");
  2489. })
  2490. .Get("/", [&](const Request & /*req*/,
  2491. Response &res) { res.set_redirect("/hi"); })
  2492. .Post("/1",
  2493. [](const Request & /*req*/, Response &res) {
  2494. res.set_redirect("/2", StatusCode::SeeOther_303);
  2495. })
  2496. .Get("/2",
  2497. [](const Request & /*req*/, Response &res) {
  2498. res.set_content("redirected.", "text/plain");
  2499. res.status = StatusCode::OK_200;
  2500. })
  2501. .Post("/person",
  2502. [&](const Request &req, Response &res) {
  2503. if (req.has_param("name") && req.has_param("note")) {
  2504. persons_[req.get_param_value("name")] =
  2505. req.get_param_value("note");
  2506. } else {
  2507. res.status = StatusCode::BadRequest_400;
  2508. }
  2509. })
  2510. .Put("/person",
  2511. [&](const Request &req, Response &res) {
  2512. if (req.has_param("name") && req.has_param("note")) {
  2513. persons_[req.get_param_value("name")] =
  2514. req.get_param_value("note");
  2515. } else {
  2516. res.status = StatusCode::BadRequest_400;
  2517. }
  2518. })
  2519. .Get("/person/(.*)",
  2520. [&](const Request &req, Response &res) {
  2521. string name = req.matches[1];
  2522. if (persons_.find(name) != persons_.end()) {
  2523. auto note = persons_[name];
  2524. res.set_content(note, "text/plain");
  2525. } else {
  2526. res.status = StatusCode::NotFound_404;
  2527. }
  2528. })
  2529. .Delete("/person",
  2530. [&](const Request &req, Response &res) {
  2531. if (req.has_param("name")) {
  2532. string name = req.get_param_value("name");
  2533. if (persons_.find(name) != persons_.end()) {
  2534. persons_.erase(name);
  2535. res.set_content("DELETED", "text/plain");
  2536. } else {
  2537. res.status = StatusCode::NotFound_404;
  2538. }
  2539. } else {
  2540. res.status = StatusCode::BadRequest_400;
  2541. }
  2542. })
  2543. .Post("/x-www-form-urlencoded-json",
  2544. [&](const Request &req, Response &res) {
  2545. auto json = req.get_param_value("json");
  2546. ASSERT_EQ(JSON_DATA, json);
  2547. res.set_content(json, "appliation/json");
  2548. res.status = StatusCode::OK_200;
  2549. })
  2550. .Get("/streamed-chunked",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_chunked_content_provider(
  2553. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2554. sink.os << "123";
  2555. sink.os << "456";
  2556. sink.os << "789";
  2557. sink.done();
  2558. return true;
  2559. });
  2560. })
  2561. .Get("/streamed-chunked2",
  2562. [&](const Request & /*req*/, Response &res) {
  2563. auto i = new int(0);
  2564. res.set_chunked_content_provider(
  2565. "text/plain",
  2566. [i](size_t /*offset*/, DataSink &sink) {
  2567. switch (*i) {
  2568. case 0: sink.os << "123"; break;
  2569. case 1: sink.os << "456"; break;
  2570. case 2: sink.os << "789"; break;
  2571. case 3: sink.done(); break;
  2572. }
  2573. (*i)++;
  2574. return true;
  2575. },
  2576. [i](bool success) {
  2577. EXPECT_TRUE(success);
  2578. delete i;
  2579. });
  2580. })
  2581. .Get("/streamed-chunked-with-trailer",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. auto i = new int(0);
  2584. res.set_header("Trailer", "Dummy1, Dummy2");
  2585. res.set_chunked_content_provider(
  2586. "text/plain",
  2587. [i](size_t /*offset*/, DataSink &sink) {
  2588. switch (*i) {
  2589. case 0: sink.os << "123"; break;
  2590. case 1: sink.os << "456"; break;
  2591. case 2: sink.os << "789"; break;
  2592. case 3: {
  2593. sink.done_with_trailer(
  2594. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2595. } break;
  2596. }
  2597. (*i)++;
  2598. return true;
  2599. },
  2600. [i](bool success) {
  2601. EXPECT_TRUE(success);
  2602. delete i;
  2603. });
  2604. })
  2605. .Get("/streamed",
  2606. [&](const Request & /*req*/, Response &res) {
  2607. res.set_content_provider(
  2608. 6, "text/plain",
  2609. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2610. sink.os << (offset < 3 ? "a" : "b");
  2611. return true;
  2612. });
  2613. })
  2614. .Get("/streamed-with-range",
  2615. [&](const Request &req, Response &res) {
  2616. auto data = new std::string("abcdefg");
  2617. res.set_content_provider(
  2618. data->size(), "text/plain",
  2619. [data](size_t offset, size_t length, DataSink &sink) {
  2620. size_t DATA_CHUNK_SIZE = 4;
  2621. const auto &d = *data;
  2622. auto out_len =
  2623. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2624. auto ret =
  2625. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2626. EXPECT_TRUE(ret);
  2627. return true;
  2628. },
  2629. [data, &req](bool success) {
  2630. EXPECT_EQ(success, !req.has_param("error"));
  2631. delete data;
  2632. });
  2633. })
  2634. .Get("/streamed-cancel",
  2635. [&](const Request & /*req*/, Response &res) {
  2636. res.set_content_provider(
  2637. size_t(-1), "text/plain",
  2638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2639. sink.os << "data_chunk";
  2640. return true;
  2641. });
  2642. })
  2643. .Get("/regex-with-delimiter",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. ASSERT_TRUE(req.has_param("key"));
  2646. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2647. })
  2648. .Get("/with-range",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_content("abcdefg", "text/plain");
  2651. })
  2652. .Get("/test-start-time",
  2653. [&](const Request &req, Response & /*res*/) {
  2654. EXPECT_NE(req.start_time_,
  2655. std::chrono::steady_clock::time_point::min());
  2656. })
  2657. .Get("/with-range-customized-response",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. res.status = StatusCode::BadRequest_400;
  2660. res.set_content(JSON_DATA, "application/json");
  2661. })
  2662. .Post("/chunked",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. EXPECT_EQ(req.body, "dechunked post body");
  2665. })
  2666. .Post("/large-chunked",
  2667. [&](const Request &req, Response & /*res*/) {
  2668. std::string expected(6 * 30 * 1024u, 'a');
  2669. EXPECT_EQ(req.body, expected);
  2670. })
  2671. .Post("/multipart",
  2672. [&](const Request &req, Response & /*res*/) {
  2673. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2674. req.form.get_field_count("text2") +
  2675. req.form.get_field_count("file3") +
  2676. req.form.get_field_count("file4"));
  2677. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2678. req.form.get_file_count("file2"));
  2679. ASSERT_TRUE(!req.form.has_file("???"));
  2680. ASSERT_TRUE(!req.form.has_field("???"));
  2681. ASSERT_TRUE(req.body.empty());
  2682. {
  2683. const auto &text = req.form.get_field("text1");
  2684. EXPECT_EQ("text default", text);
  2685. }
  2686. {
  2687. const auto &text = req.form.get_field("text2");
  2688. EXPECT_EQ("aωb", text);
  2689. }
  2690. {
  2691. const auto &file = req.form.get_file("file1");
  2692. EXPECT_EQ("hello.txt", file.filename);
  2693. EXPECT_EQ("text/plain", file.content_type);
  2694. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2695. }
  2696. {
  2697. const auto &file = req.form.get_file("file2");
  2698. EXPECT_EQ("world.json", file.filename);
  2699. EXPECT_EQ("application/json", file.content_type);
  2700. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2701. }
  2702. {
  2703. const auto &text = req.form.get_field("file3");
  2704. EXPECT_EQ(0u, text.size());
  2705. }
  2706. {
  2707. const auto &text = req.form.get_field("file4");
  2708. EXPECT_EQ(0u, text.size());
  2709. }
  2710. })
  2711. .Post("/multipart/multi_file_values",
  2712. [&](const Request &req, Response & /*res*/) {
  2713. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2714. req.form.get_field_count("multi_text1"));
  2715. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2716. ASSERT_TRUE(!req.form.has_file("???"));
  2717. ASSERT_TRUE(!req.form.has_field("???"));
  2718. ASSERT_TRUE(req.body.empty());
  2719. {
  2720. const auto &text = req.form.get_field("text");
  2721. EXPECT_EQ("default text", text);
  2722. }
  2723. {
  2724. const auto &text1_values = req.form.get_fields("multi_text1");
  2725. EXPECT_EQ(2u, text1_values.size());
  2726. EXPECT_EQ("aaaaa", text1_values[0]);
  2727. EXPECT_EQ("bbbbb", text1_values[1]);
  2728. }
  2729. {
  2730. const auto &file1_values = req.form.get_files("multi_file1");
  2731. EXPECT_EQ(2u, file1_values.size());
  2732. auto file1 = file1_values[0];
  2733. EXPECT_EQ(file1.filename, "hello.txt");
  2734. EXPECT_EQ(file1.content_type, "text/plain");
  2735. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2736. auto file2 = file1_values[1];
  2737. EXPECT_EQ(file2.filename, "world.json");
  2738. EXPECT_EQ(file2.content_type, "application/json");
  2739. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2740. }
  2741. })
  2742. .Post("/empty",
  2743. [&](const Request &req, Response &res) {
  2744. EXPECT_EQ(req.body, "");
  2745. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2746. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2747. res.set_content("empty", "text/plain");
  2748. })
  2749. .Post("/empty-no-content-type",
  2750. [&](const Request &req, Response &res) {
  2751. EXPECT_EQ(req.body, "");
  2752. EXPECT_FALSE(req.has_header("Content-Type"));
  2753. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2754. res.set_content("empty-no-content-type", "text/plain");
  2755. })
  2756. .Post("/path-only",
  2757. [&](const Request &req, Response &res) {
  2758. EXPECT_EQ(req.body, "");
  2759. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2760. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2761. res.set_content("path-only", "text/plain");
  2762. })
  2763. .Post("/path-headers-only",
  2764. [&](const Request &req, Response &res) {
  2765. EXPECT_EQ(req.body, "");
  2766. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2767. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2768. EXPECT_EQ("world", req.get_header_value("hello"));
  2769. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2770. res.set_content("path-headers-only", "text/plain");
  2771. })
  2772. .Post("/post-large",
  2773. [&](const Request &req, Response &res) {
  2774. EXPECT_EQ(req.body, LARGE_DATA);
  2775. res.set_content(req.body, "text/plain");
  2776. })
  2777. .Put("/empty-no-content-type",
  2778. [&](const Request &req, Response &res) {
  2779. EXPECT_EQ(req.body, "");
  2780. EXPECT_FALSE(req.has_header("Content-Type"));
  2781. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2782. res.set_content("empty-no-content-type", "text/plain");
  2783. })
  2784. .Put("/put",
  2785. [&](const Request &req, Response &res) {
  2786. EXPECT_EQ(req.body, "PUT");
  2787. res.set_content(req.body, "text/plain");
  2788. })
  2789. .Put("/put-large",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, LARGE_DATA);
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Patch("/patch",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(req.body, "PATCH");
  2797. res.set_content(req.body, "text/plain");
  2798. })
  2799. .Delete("/delete",
  2800. [&](const Request & /*req*/, Response &res) {
  2801. res.set_content("DELETE", "text/plain");
  2802. })
  2803. .Delete("/delete-body",
  2804. [&](const Request &req, Response &res) {
  2805. EXPECT_EQ(req.body, "content");
  2806. res.set_content(req.body, "text/plain");
  2807. })
  2808. .Options(R"(\*)",
  2809. [&](const Request & /*req*/, Response &res) {
  2810. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2811. })
  2812. .Get("/request-target",
  2813. [&](const Request &req, Response & /*res*/) {
  2814. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2815. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2816. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2817. })
  2818. .Get("/long-query-value",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2821. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2822. })
  2823. .Get("/too-long-query-value",
  2824. [&](const Request &req, Response & /*res*/) {
  2825. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2826. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2827. })
  2828. .Get("/array-param",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2831. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2832. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2833. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2834. })
  2835. .Post("/validate-no-multiple-headers",
  2836. [&](const Request &req, Response & /*res*/) {
  2837. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2838. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2839. })
  2840. .Post("/content_receiver",
  2841. [&](const Request &req, Response &res,
  2842. const ContentReader &content_reader) {
  2843. if (req.is_multipart_form_data()) {
  2844. std::vector<FormData> items;
  2845. content_reader(
  2846. [&](const FormData &file) {
  2847. items.push_back(file);
  2848. return true;
  2849. },
  2850. [&](const char *data, size_t data_length) {
  2851. items.back().content.append(data, data_length);
  2852. return true;
  2853. });
  2854. EXPECT_EQ(5u, items.size());
  2855. {
  2856. const auto &file = get_file_value(items, "text1");
  2857. EXPECT_TRUE(file.filename.empty());
  2858. EXPECT_EQ("text default", file.content);
  2859. }
  2860. {
  2861. const auto &file = get_file_value(items, "text2");
  2862. EXPECT_TRUE(file.filename.empty());
  2863. EXPECT_EQ("aωb", file.content);
  2864. }
  2865. {
  2866. const auto &file = get_file_value(items, "file1");
  2867. EXPECT_EQ("hello.txt", file.filename);
  2868. EXPECT_EQ("text/plain", file.content_type);
  2869. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2870. }
  2871. {
  2872. const auto &file = get_file_value(items, "file2");
  2873. EXPECT_EQ("world.json", file.filename);
  2874. EXPECT_EQ("application/json", file.content_type);
  2875. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2876. }
  2877. {
  2878. const auto &file = get_file_value(items, "file3");
  2879. EXPECT_TRUE(file.filename.empty());
  2880. EXPECT_EQ("application/octet-stream", file.content_type);
  2881. EXPECT_EQ(0u, file.content.size());
  2882. }
  2883. } else {
  2884. std::string body;
  2885. content_reader([&](const char *data, size_t data_length) {
  2886. EXPECT_EQ(7U, data_length);
  2887. body.append(data, data_length);
  2888. return true;
  2889. });
  2890. EXPECT_EQ(body, "content");
  2891. res.set_content(body, "text/plain");
  2892. }
  2893. })
  2894. .Put("/content_receiver",
  2895. [&](const Request & /*req*/, Response &res,
  2896. const ContentReader &content_reader) {
  2897. std::string body;
  2898. content_reader([&](const char *data, size_t data_length) {
  2899. body.append(data, data_length);
  2900. return true;
  2901. });
  2902. EXPECT_EQ(body, "content");
  2903. res.set_content(body, "text/plain");
  2904. })
  2905. .Patch("/content_receiver",
  2906. [&](const Request & /*req*/, Response &res,
  2907. const ContentReader &content_reader) {
  2908. std::string body;
  2909. content_reader([&](const char *data, size_t data_length) {
  2910. body.append(data, data_length);
  2911. return true;
  2912. });
  2913. EXPECT_EQ(body, "content");
  2914. res.set_content(body, "text/plain");
  2915. })
  2916. .Post("/query-string-and-body",
  2917. [&](const Request &req, Response & /*res*/) {
  2918. ASSERT_TRUE(req.has_param("key"));
  2919. EXPECT_EQ(req.get_param_value("key"), "value");
  2920. EXPECT_EQ(req.body, "content");
  2921. })
  2922. .Get("/last-request",
  2923. [&](const Request &req, Response & /*res*/) {
  2924. EXPECT_EQ("close", req.get_header_value("Connection"));
  2925. })
  2926. .Get(R"(/redirect/(\d+))",
  2927. [&](const Request &req, Response &res) {
  2928. auto num = std::stoi(req.matches[1]) + 1;
  2929. std::string url = "/redirect/" + std::to_string(num);
  2930. res.set_redirect(url);
  2931. })
  2932. .Post("/binary",
  2933. [&](const Request &req, Response &res) {
  2934. EXPECT_EQ(4U, req.body.size());
  2935. EXPECT_EQ("application/octet-stream",
  2936. req.get_header_value("Content-Type"));
  2937. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2938. res.set_content(req.body, "application/octet-stream");
  2939. })
  2940. .Put("/binary",
  2941. [&](const Request &req, Response &res) {
  2942. EXPECT_EQ(4U, req.body.size());
  2943. EXPECT_EQ("application/octet-stream",
  2944. req.get_header_value("Content-Type"));
  2945. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2946. res.set_content(req.body, "application/octet-stream");
  2947. })
  2948. .Patch("/binary",
  2949. [&](const Request &req, Response &res) {
  2950. EXPECT_EQ(4U, req.body.size());
  2951. EXPECT_EQ("application/octet-stream",
  2952. req.get_header_value("Content-Type"));
  2953. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2954. res.set_content(req.body, "application/octet-stream");
  2955. })
  2956. .Delete("/binary",
  2957. [&](const Request &req, Response &res) {
  2958. EXPECT_EQ(4U, req.body.size());
  2959. EXPECT_EQ("application/octet-stream",
  2960. req.get_header_value("Content-Type"));
  2961. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2962. res.set_content(req.body, "application/octet-stream");
  2963. })
  2964. .Get("/issue1772",
  2965. [&](const Request & /*req*/, Response &res) {
  2966. res.status = 401;
  2967. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2968. })
  2969. .Delete("/issue609",
  2970. [](const httplib::Request &, httplib::Response &res,
  2971. const httplib::ContentReader &) {
  2972. res.set_content("ok", "text/plain");
  2973. })
  2974. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2975. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2976. .Get("/compress",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content(
  2979. "12345678901234567890123456789012345678901234567890123456789"
  2980. "01234567890123456789012345678901234567890",
  2981. "text/plain");
  2982. })
  2983. .Get("/nocompress",
  2984. [&](const Request & /*req*/, Response &res) {
  2985. res.set_content(
  2986. "12345678901234567890123456789012345678901234567890123456789"
  2987. "01234567890123456789012345678901234567890",
  2988. "application/octet-stream");
  2989. })
  2990. .Post("/compress-multipart",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. EXPECT_EQ(2u, req.form.fields.size());
  2993. ASSERT_TRUE(!req.form.has_field("???"));
  2994. {
  2995. const auto &text = req.form.get_field("key1");
  2996. EXPECT_EQ("test", text);
  2997. }
  2998. {
  2999. const auto &text = req.form.get_field("key2");
  3000. EXPECT_EQ("--abcdefg123", text);
  3001. }
  3002. })
  3003. #endif
  3004. ;
  3005. persons_["john"] = "programmer";
  3006. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3007. svr_.wait_until_ready();
  3008. }
  3009. virtual void TearDown() {
  3010. svr_.stop();
  3011. if (!request_threads_.empty()) {
  3012. std::this_thread::sleep_for(std::chrono::seconds(1));
  3013. for (auto &t : request_threads_) {
  3014. t.join();
  3015. }
  3016. }
  3017. t_.join();
  3018. }
  3019. map<string, string> persons_;
  3020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3021. SSLClient cli_;
  3022. SSLServer svr_;
  3023. #else
  3024. Client cli_;
  3025. Server svr_;
  3026. #endif
  3027. thread t_;
  3028. std::vector<thread> request_threads_;
  3029. };
  3030. TEST_F(ServerTest, GetMethod200) {
  3031. auto res = cli_.Get("/hi");
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ("HTTP/1.1", res->version);
  3034. EXPECT_EQ(StatusCode::OK_200, res->status);
  3035. EXPECT_EQ("OK", res->reason);
  3036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3037. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3038. EXPECT_EQ("Hello World!", res->body);
  3039. }
  3040. void performance_test(const char *host) {
  3041. auto port = 1234;
  3042. Server svr;
  3043. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3044. res.set_content("Benchmark Response", "text/plain");
  3045. });
  3046. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3047. auto se = detail::scope_exit([&] {
  3048. svr.stop();
  3049. listen_thread.join();
  3050. ASSERT_FALSE(svr.is_running());
  3051. });
  3052. svr.wait_until_ready();
  3053. Client cli(host, port);
  3054. auto start = std::chrono::high_resolution_clock::now();
  3055. auto res = cli.Get("/benchmark");
  3056. ASSERT_TRUE(res);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. auto end = std::chrono::high_resolution_clock::now();
  3059. auto elapsed =
  3060. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3061. .count();
  3062. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3063. << "ms (Issue #1777)";
  3064. }
  3065. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3066. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3067. TEST_F(ServerTest, GetEmptyFile) {
  3068. auto res = cli_.Get("/empty_file");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3072. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3073. EXPECT_EQ("", res->body);
  3074. }
  3075. TEST_F(ServerTest, GetFileContent) {
  3076. auto res = cli_.Get("/file_content");
  3077. ASSERT_TRUE(res);
  3078. EXPECT_EQ(StatusCode::OK_200, res->status);
  3079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3080. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3081. EXPECT_EQ("test.html", res->body);
  3082. }
  3083. TEST_F(ServerTest, GetFileContentWithRange) {
  3084. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3087. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3088. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3089. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3090. EXPECT_EQ("est", res->body);
  3091. }
  3092. TEST_F(ServerTest, GetFileContentWithContentType) {
  3093. auto res = cli_.Get("/file_content_with_content_type");
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3097. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3098. EXPECT_EQ("file\n", res->body);
  3099. }
  3100. TEST_F(ServerTest, GetInvalidFileContent) {
  3101. auto res = cli_.Get("/invalid_file_content");
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3104. }
  3105. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3106. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3107. ASSERT_TRUE(res);
  3108. EXPECT_EQ("HTTP/1.1", res->version);
  3109. EXPECT_EQ(StatusCode::OK_200, res->status);
  3110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3111. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3112. EXPECT_EQ("Hello World!", res->body);
  3113. }
  3114. TEST_F(ServerTest, GetMethod302) {
  3115. auto res = cli_.Get("/");
  3116. ASSERT_TRUE(res);
  3117. EXPECT_EQ(StatusCode::Found_302, res->status);
  3118. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3119. }
  3120. TEST_F(ServerTest, GetMethod302Redirect) {
  3121. cli_.set_follow_location(true);
  3122. auto res = cli_.Get("/");
  3123. ASSERT_TRUE(res);
  3124. EXPECT_EQ(StatusCode::OK_200, res->status);
  3125. EXPECT_EQ("Hello World!", res->body);
  3126. EXPECT_EQ("/hi", res->location);
  3127. }
  3128. TEST_F(ServerTest, GetMethod404) {
  3129. auto res = cli_.Get("/invalid");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3132. }
  3133. TEST_F(ServerTest, HeadMethod200) {
  3134. auto res = cli_.Head("/hi");
  3135. ASSERT_TRUE(res);
  3136. EXPECT_EQ(StatusCode::OK_200, res->status);
  3137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3138. EXPECT_TRUE(res->body.empty());
  3139. }
  3140. TEST_F(ServerTest, HeadMethod200Static) {
  3141. auto res = cli_.Head("/mount/dir/index.html");
  3142. ASSERT_TRUE(res);
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3145. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3146. EXPECT_TRUE(res->body.empty());
  3147. }
  3148. TEST_F(ServerTest, HeadMethod404) {
  3149. auto res = cli_.Head("/invalid");
  3150. ASSERT_TRUE(res);
  3151. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3152. EXPECT_TRUE(res->body.empty());
  3153. }
  3154. TEST_F(ServerTest, GetMethodPersonJohn) {
  3155. auto res = cli_.Get("/person/john");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(StatusCode::OK_200, res->status);
  3158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("programmer", res->body);
  3160. }
  3161. TEST_F(ServerTest, PostMethod1) {
  3162. auto res = cli_.Get("/person/john1");
  3163. ASSERT_TRUE(res);
  3164. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3165. res = cli_.Post("/person", "name=john1&note=coder",
  3166. "application/x-www-form-urlencoded");
  3167. ASSERT_TRUE(res);
  3168. ASSERT_EQ(StatusCode::OK_200, res->status);
  3169. res = cli_.Get("/person/john1");
  3170. ASSERT_TRUE(res);
  3171. ASSERT_EQ(StatusCode::OK_200, res->status);
  3172. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3173. ASSERT_EQ("coder", res->body);
  3174. }
  3175. TEST_F(ServerTest, PostMethod2) {
  3176. auto res = cli_.Get("/person/john2");
  3177. ASSERT_TRUE(res);
  3178. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3179. Params params;
  3180. params.emplace("name", "john2");
  3181. params.emplace("note", "coder");
  3182. res = cli_.Post("/person", params);
  3183. ASSERT_TRUE(res);
  3184. ASSERT_EQ(StatusCode::OK_200, res->status);
  3185. res = cli_.Get("/person/john2");
  3186. ASSERT_TRUE(res);
  3187. ASSERT_EQ(StatusCode::OK_200, res->status);
  3188. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. ASSERT_EQ("coder", res->body);
  3190. }
  3191. TEST_F(ServerTest, PutMethod3) {
  3192. auto res = cli_.Get("/person/john3");
  3193. ASSERT_TRUE(res);
  3194. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3195. Params params;
  3196. params.emplace("name", "john3");
  3197. params.emplace("note", "coder");
  3198. res = cli_.Put("/person", params);
  3199. ASSERT_TRUE(res);
  3200. ASSERT_EQ(StatusCode::OK_200, res->status);
  3201. res = cli_.Get("/person/john3");
  3202. ASSERT_TRUE(res);
  3203. ASSERT_EQ(StatusCode::OK_200, res->status);
  3204. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3205. ASSERT_EQ("coder", res->body);
  3206. }
  3207. TEST_F(ServerTest, DeleteMethod1) {
  3208. auto res = cli_.Get("/person/john4");
  3209. ASSERT_TRUE(res);
  3210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3211. Params params;
  3212. params.emplace("name", "john4");
  3213. params.emplace("note", "coder");
  3214. res = cli_.Post("/person", params);
  3215. ASSERT_TRUE(res);
  3216. ASSERT_EQ(StatusCode::OK_200, res->status);
  3217. res = cli_.Get("/person/john4");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::OK_200, res->status);
  3220. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3221. ASSERT_EQ("coder", res->body);
  3222. Params delete_params;
  3223. delete_params.emplace("name", "john4");
  3224. res = cli_.Delete("/person", delete_params);
  3225. ASSERT_TRUE(res);
  3226. ASSERT_EQ(StatusCode::OK_200, res->status);
  3227. ASSERT_EQ("DELETED", res->body);
  3228. res = cli_.Get("/person/john4");
  3229. ASSERT_TRUE(res);
  3230. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3231. }
  3232. TEST_F(ServerTest, DeleteMethod2) {
  3233. auto res = cli_.Get("/person/john5");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. Params params;
  3237. params.emplace("name", "john5");
  3238. params.emplace("note", "developer");
  3239. res = cli_.Post("/person", params);
  3240. ASSERT_TRUE(res);
  3241. ASSERT_EQ(StatusCode::OK_200, res->status);
  3242. res = cli_.Get("/person/john5");
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3246. ASSERT_EQ("developer", res->body);
  3247. Params delete_params;
  3248. delete_params.emplace("name", "john5");
  3249. Headers headers;
  3250. headers.emplace("Custom-Header", "test-value");
  3251. res = cli_.Delete("/person", headers, delete_params);
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::OK_200, res->status);
  3254. ASSERT_EQ("DELETED", res->body);
  3255. res = cli_.Get("/person/john5");
  3256. ASSERT_TRUE(res);
  3257. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3258. }
  3259. TEST_F(ServerTest, DeleteMethod3) {
  3260. auto res = cli_.Get("/person/john6");
  3261. ASSERT_TRUE(res);
  3262. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3263. Params params;
  3264. params.emplace("name", "john6");
  3265. params.emplace("note", "tester");
  3266. res = cli_.Post("/person", params);
  3267. ASSERT_TRUE(res);
  3268. ASSERT_EQ(StatusCode::OK_200, res->status);
  3269. res = cli_.Get("/person/john6");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3273. ASSERT_EQ("tester", res->body);
  3274. Params delete_params;
  3275. delete_params.emplace("name", "john6");
  3276. Headers headers;
  3277. headers.emplace("Custom-Header", "test-value");
  3278. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3279. ASSERT_TRUE(res);
  3280. ASSERT_EQ(StatusCode::OK_200, res->status);
  3281. ASSERT_EQ("DELETED", res->body);
  3282. res = cli_.Get("/person/john6");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3285. }
  3286. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3287. Params params;
  3288. params.emplace("json", JSON_DATA);
  3289. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3290. ASSERT_TRUE(res);
  3291. ASSERT_EQ(StatusCode::OK_200, res->status);
  3292. ASSERT_EQ(JSON_DATA, res->body);
  3293. }
  3294. TEST_F(ServerTest, PostEmptyContent) {
  3295. auto res = cli_.Post("/empty", "", "text/plain");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("empty", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3301. auto res = cli_.Post("/empty-no-content-type");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::OK_200, res->status);
  3304. ASSERT_EQ("empty-no-content-type", res->body);
  3305. }
  3306. TEST_F(ServerTest, PostPathOnly) {
  3307. auto res = cli_.Post("/path-only");
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. ASSERT_EQ("path-only", res->body);
  3311. }
  3312. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3313. auto res = cli_.Post("/path-headers-only",
  3314. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3315. ASSERT_TRUE(res);
  3316. ASSERT_EQ(StatusCode::OK_200, res->status);
  3317. ASSERT_EQ("path-headers-only", res->body);
  3318. }
  3319. TEST_F(ServerTest, PostLarge) {
  3320. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3321. ASSERT_TRUE(res);
  3322. ASSERT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ(LARGE_DATA, res->body);
  3324. }
  3325. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3326. auto res = cli_.Put("/empty-no-content-type");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("empty-no-content-type", res->body);
  3330. }
  3331. TEST_F(ServerTest, GetMethodDir) {
  3332. auto res = cli_.Get("/dir/");
  3333. ASSERT_TRUE(res);
  3334. EXPECT_EQ(StatusCode::OK_200, res->status);
  3335. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3336. auto body = R"(<html>
  3337. <head>
  3338. </head>
  3339. <body>
  3340. <a href="/dir/test.html">Test</a>
  3341. <a href="/hi">hi</a>
  3342. </body>
  3343. </html>
  3344. )";
  3345. EXPECT_EQ(body, res->body);
  3346. }
  3347. TEST_F(ServerTest, GetMethodDirTest) {
  3348. auto res = cli_.Get("/dir/test.html");
  3349. ASSERT_TRUE(res);
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3352. EXPECT_EQ("test.html", res->body);
  3353. }
  3354. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3355. auto res = cli_.Get("/dir/../dir/test.html");
  3356. ASSERT_TRUE(res);
  3357. EXPECT_EQ(StatusCode::OK_200, res->status);
  3358. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3359. EXPECT_EQ("test.html", res->body);
  3360. }
  3361. TEST_F(ServerTest, GetMethodInvalidPath) {
  3362. auto res = cli_.Get("/dir/../test.html");
  3363. ASSERT_TRUE(res);
  3364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3365. }
  3366. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3367. auto res = cli_.Get("/../www/dir/test.html");
  3368. ASSERT_TRUE(res);
  3369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3370. }
  3371. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3372. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3375. }
  3376. TEST_F(ServerTest, GetMethodDirMountTest) {
  3377. auto res = cli_.Get("/mount/dir/test.html");
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3381. EXPECT_EQ("test.html", res->body);
  3382. }
  3383. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3384. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(StatusCode::OK_200, res->status);
  3387. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3388. EXPECT_EQ("test.html", res->body);
  3389. }
  3390. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3391. auto res = cli_.Get("/mount/dir/../test.html");
  3392. ASSERT_TRUE(res);
  3393. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3394. }
  3395. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3396. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3397. ASSERT_TRUE(res);
  3398. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3399. }
  3400. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3401. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3404. }
  3405. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3406. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3407. ASSERT_TRUE(res);
  3408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3409. }
  3410. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3411. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3414. }
  3415. TEST_F(ServerTest, PostMethod303) {
  3416. auto res = cli_.Post("/1", "body", "text/plain");
  3417. ASSERT_TRUE(res);
  3418. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3419. EXPECT_EQ("/2", res->get_header_value("Location"));
  3420. }
  3421. TEST_F(ServerTest, PostMethod303Redirect) {
  3422. cli_.set_follow_location(true);
  3423. auto res = cli_.Post("/1", "body", "text/plain");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("redirected.", res->body);
  3427. EXPECT_EQ("/2", res->location);
  3428. }
  3429. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3430. auto res = cli_.Get("/dir/test.abcde");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ("abcde", res->body);
  3435. }
  3436. TEST_F(ServerTest, StaticFileRange) {
  3437. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3440. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3442. EXPECT_EQ(true, res->has_header("Content-Range"));
  3443. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3444. EXPECT_EQ(std::string("cd"), res->body);
  3445. }
  3446. TEST_F(ServerTest, StaticFileRanges) {
  3447. auto res =
  3448. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3451. EXPECT_TRUE(
  3452. res->get_header_value("Content-Type")
  3453. .find(
  3454. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3455. 0);
  3456. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3457. }
  3458. TEST_F(ServerTest, StaticFileRangeHead) {
  3459. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3462. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3463. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3464. EXPECT_EQ(true, res->has_header("Content-Range"));
  3465. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3466. }
  3467. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3468. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3473. EXPECT_EQ(true, res->has_header("Content-Range"));
  3474. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3475. res->get_header_value("Content-Range"));
  3476. EXPECT_EQ("LAST\n", res->body);
  3477. }
  3478. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3479. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3480. ASSERT_TRUE(res);
  3481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3483. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3484. EXPECT_EQ(true, res->has_header("Content-Range"));
  3485. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3486. }
  3487. TEST_F(ServerTest, StaticFileBigFile) {
  3488. auto res = cli_.Get("/dir/1MB.txt");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3493. }
  3494. TEST_F(ServerTest, InvalidBaseDirMount) {
  3495. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3496. }
  3497. TEST_F(ServerTest, Binary) {
  3498. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3499. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3500. "application/octet-stream");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ(4U, res->body.size());
  3504. res = cli_.Put("/binary", binary.data(), binary.size(),
  3505. "application/octet-stream");
  3506. ASSERT_TRUE(res);
  3507. ASSERT_EQ(StatusCode::OK_200, res->status);
  3508. ASSERT_EQ(4U, res->body.size());
  3509. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3510. "application/octet-stream");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::OK_200, res->status);
  3513. ASSERT_EQ(4U, res->body.size());
  3514. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3515. "application/octet-stream");
  3516. ASSERT_TRUE(res);
  3517. ASSERT_EQ(StatusCode::OK_200, res->status);
  3518. ASSERT_EQ(4U, res->body.size());
  3519. }
  3520. TEST_F(ServerTest, BinaryString) {
  3521. auto binary = std::string("\x00\x01\x02\x03", 4);
  3522. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3523. ASSERT_TRUE(res);
  3524. ASSERT_EQ(StatusCode::OK_200, res->status);
  3525. ASSERT_EQ(4U, res->body.size());
  3526. res = cli_.Put("/binary", binary, "application/octet-stream");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::OK_200, res->status);
  3529. ASSERT_EQ(4U, res->body.size());
  3530. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. ASSERT_EQ(4U, res->body.size());
  3534. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. ASSERT_EQ(4U, res->body.size());
  3538. }
  3539. TEST_F(ServerTest, EmptyRequest) {
  3540. auto res = cli_.Get("");
  3541. ASSERT_TRUE(!res);
  3542. EXPECT_EQ(Error::Connection, res.error());
  3543. }
  3544. TEST_F(ServerTest, LongRequest) {
  3545. std::string request;
  3546. for (size_t i = 0; i < 545; i++) {
  3547. request += "/TooLongRequest";
  3548. }
  3549. request += "OK";
  3550. auto res = cli_.Get(request.c_str());
  3551. ASSERT_TRUE(res);
  3552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3553. }
  3554. TEST_F(ServerTest, TooLongRequest) {
  3555. std::string request;
  3556. for (size_t i = 0; i < 546; i++) {
  3557. request += "/TooLongRequest";
  3558. }
  3559. request += "_NG";
  3560. auto res = cli_.Get(request.c_str());
  3561. ASSERT_TRUE(res);
  3562. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3563. }
  3564. TEST_F(ServerTest, AlmostTooLongRequest) {
  3565. // test for #2046 - URI length check shouldn't include other content on req
  3566. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3567. // leading /, space, HTTP/1.1)
  3568. std::string request =
  3569. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3570. auto res = cli_.Get(request.c_str());
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, LongHeader) {
  3575. Request req;
  3576. req.method = "GET";
  3577. req.path = "/hi";
  3578. std::string host_and_port;
  3579. host_and_port += HOST;
  3580. host_and_port += ":";
  3581. host_and_port += std::to_string(PORT);
  3582. req.headers.emplace("Host", host_and_port.c_str());
  3583. req.headers.emplace("Accept", "*/*");
  3584. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3585. req.headers.emplace(
  3586. "Header-Name",
  3587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@");
  3616. auto res = std::make_shared<Response>();
  3617. auto error = Error::Success;
  3618. auto ret = cli_.send(req, *res, error);
  3619. ASSERT_TRUE(ret);
  3620. EXPECT_EQ(StatusCode::OK_200, res->status);
  3621. }
  3622. TEST_F(ServerTest, LongQueryValue) {
  3623. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3626. }
  3627. TEST_F(ServerTest, TooLongQueryValue) {
  3628. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3629. ASSERT_FALSE(res);
  3630. EXPECT_EQ(Error::Read, res.error());
  3631. }
  3632. TEST_F(ServerTest, TooLongHeader) {
  3633. Request req;
  3634. req.method = "GET";
  3635. req.path = "/hi";
  3636. std::string host_and_port;
  3637. host_and_port += HOST;
  3638. host_and_port += ":";
  3639. host_and_port += std::to_string(PORT);
  3640. req.headers.emplace("Host", host_and_port.c_str());
  3641. req.headers.emplace("Accept", "*/*");
  3642. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3643. req.headers.emplace(
  3644. "Header-Name",
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@");
  3674. auto res = std::make_shared<Response>();
  3675. auto error = Error::Success;
  3676. auto ret = cli_.send(req, *res, error);
  3677. ASSERT_TRUE(ret);
  3678. EXPECT_EQ(StatusCode::OK_200, res->status);
  3679. }
  3680. TEST_F(ServerTest, HeaderCountAtLimit) {
  3681. // Test with headers just under the 100 limit
  3682. httplib::Headers headers;
  3683. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3684. // This should keep us just under the 100 header limit
  3685. for (int i = 0; i < 95; i++) {
  3686. std::string name = "X-Test-Header-" + std::to_string(i);
  3687. std::string value = "value" + std::to_string(i);
  3688. headers.emplace(name, value);
  3689. }
  3690. // This should work fine as we're under the limit
  3691. auto res = cli_.Get("/hi", headers);
  3692. EXPECT_TRUE(res);
  3693. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3694. }
  3695. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3696. // Test with many headers to exceed the 100 limit
  3697. httplib::Headers headers;
  3698. // Add 150 headers to definitely exceed the 100 limit
  3699. for (int i = 0; i < 150; i++) {
  3700. std::string name = "X-Test-Header-" + std::to_string(i);
  3701. std::string value = "value" + std::to_string(i);
  3702. headers.emplace(name, value);
  3703. }
  3704. // This should fail due to exceeding header count limit
  3705. auto res = cli_.Get("/hi", headers);
  3706. // The request should either fail or return 400 Bad Request
  3707. if (res) {
  3708. // If we get a response, it should be 400 Bad Request
  3709. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3710. } else {
  3711. // Or the request should fail entirely
  3712. EXPECT_FALSE(res);
  3713. }
  3714. }
  3715. TEST_F(ServerTest, PercentEncoding) {
  3716. auto res = cli_.Get("/e%6edwith%");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::OK_200, res->status);
  3719. }
  3720. TEST_F(ServerTest, PercentEncodingUnicode) {
  3721. auto res = cli_.Get("/e%u006edwith%");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. }
  3725. TEST_F(ServerTest, InvalidPercentEncoding) {
  3726. auto res = cli_.Get("/%endwith%");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3731. auto res = cli_.Get("/%uendwith%");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3734. }
  3735. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3736. auto res = cli_.Get("/hello?aaa=bbb%");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3739. }
  3740. TEST_F(ServerTest, PlusSignEncoding) {
  3741. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. EXPECT_EQ("a +b", res->body);
  3745. }
  3746. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3747. // This test simulates a potential DoS attack using many headers
  3748. // to verify our security fix prevents memory exhaustion
  3749. httplib::Headers attack_headers;
  3750. // Attempt to add many headers like an attacker would (200 headers to far
  3751. // exceed limit)
  3752. for (int i = 0; i < 200; i++) {
  3753. std::string name = "X-Attack-Header-" + std::to_string(i);
  3754. std::string value = "attack_payload_" + std::to_string(i);
  3755. attack_headers.emplace(name, value);
  3756. }
  3757. // Try to POST with excessive headers
  3758. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3759. // Should either fail or return 400 Bad Request due to security limit
  3760. if (res) {
  3761. // If we get a response, it should be 400 Bad Request
  3762. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3763. } else {
  3764. // Request failed, which is the expected behavior for DoS protection
  3765. EXPECT_FALSE(res);
  3766. }
  3767. }
  3768. TEST_F(ServerTest, MultipartFormData) {
  3769. UploadFormDataItems items = {
  3770. {"text1", "text default", "", ""},
  3771. {"text2", "aωb", "", ""},
  3772. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3773. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3774. {"file3", "", "", "application/octet-stream"},
  3775. {"file4", "", "", " application/json tmp-string "}};
  3776. auto res = cli_.Post("/multipart", items);
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::OK_200, res->status);
  3779. }
  3780. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3781. UploadFormDataItems items = {
  3782. {"text", "default text", "", ""},
  3783. {"multi_text1", "aaaaa", "", ""},
  3784. {"multi_text1", "bbbbb", "", ""},
  3785. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3786. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3787. "application/json"},
  3788. };
  3789. auto res = cli_.Post("/multipart/multi_file_values", items);
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. }
  3793. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3794. auto res = cli_.Get("/hi");
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3798. EXPECT_EQ("Hello World!", res->body);
  3799. }
  3800. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3801. Request req;
  3802. req.method = "POST";
  3803. req.path = "/chunked";
  3804. std::string host_and_port;
  3805. host_and_port += HOST;
  3806. host_and_port += ":";
  3807. host_and_port += std::to_string(PORT);
  3808. req.headers.emplace("Host", host_and_port.c_str());
  3809. req.headers.emplace("Accept", "*/*");
  3810. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3811. req.headers.emplace("Content-Type", "text/plain");
  3812. req.headers.emplace("Content-Length", "0");
  3813. req.headers.emplace(
  3814. "Transfer-Encoding",
  3815. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3816. // Client does not chunk, so make a chunked body manually.
  3817. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3818. auto res = std::make_shared<Response>();
  3819. auto error = Error::Success;
  3820. auto ret = cli_.send(req, *res, error);
  3821. ASSERT_TRUE(ret);
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. }
  3824. TEST_F(ServerTest, GetStreamed2) {
  3825. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3826. ASSERT_TRUE(res);
  3827. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3829. EXPECT_EQ(true, res->has_header("Content-Range"));
  3830. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3831. EXPECT_EQ(std::string("ab"), res->body);
  3832. }
  3833. TEST_F(ServerTest, GetStreamed) {
  3834. auto res = cli_.Get("/streamed");
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(std::string("aaabbb"), res->body);
  3839. }
  3840. TEST_F(ServerTest, GetStreamedWithRange1) {
  3841. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3844. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3847. EXPECT_EQ(std::string("def"), res->body);
  3848. }
  3849. TEST_F(ServerTest, GetStreamedWithRange2) {
  3850. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3851. ASSERT_TRUE(res);
  3852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3853. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ(true, res->has_header("Content-Range"));
  3855. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3856. EXPECT_EQ(std::string("bcdefg"), res->body);
  3857. }
  3858. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3859. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3862. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3863. EXPECT_EQ(true, res->has_header("Content-Range"));
  3864. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3865. EXPECT_EQ(std::string("efg"), res->body);
  3866. }
  3867. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3868. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3871. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3872. EXPECT_EQ(false, res->has_header("Content-Range"));
  3873. EXPECT_EQ(0U, res->body.size());
  3874. }
  3875. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3876. auto res = cli_.Get("/streamed-with-range",
  3877. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3878. "92233720368547758079223372036854775807"}});
  3879. ASSERT_TRUE(res);
  3880. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3881. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3882. EXPECT_EQ(false, res->has_header("Content-Range"));
  3883. EXPECT_EQ(0U, res->body.size());
  3884. }
  3885. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3886. auto res = cli_.Get(
  3887. "/with-range",
  3888. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3889. {"Accept-Encoding", ""}});
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3892. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3893. EXPECT_EQ(true, res->has_header("Content-Range"));
  3894. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3895. EXPECT_EQ(std::string("abcdefg"), res->body);
  3896. }
  3897. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3898. auto res = cli_.Get("/with-range", {
  3899. {"Range", "bytes=0-"},
  3900. {"Accept-Encoding", ""},
  3901. });
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3904. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3905. EXPECT_EQ(true, res->has_header("Content-Range"));
  3906. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3907. EXPECT_EQ(std::string("abcdefg"), res->body);
  3908. }
  3909. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3910. auto res =
  3911. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3914. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3915. EXPECT_EQ(false, res->has_header("Content-Range"));
  3916. EXPECT_EQ(267U, res->body.size());
  3917. // Check that both range contents are present
  3918. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3919. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3920. // Check that Content-Range headers are present for both ranges
  3921. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3922. std::string::npos);
  3923. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3924. std::string::npos);
  3925. }
  3926. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3927. Ranges ranges;
  3928. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3929. ranges.emplace_back(0, -1);
  3930. }
  3931. auto res =
  3932. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3933. ASSERT_TRUE(res);
  3934. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3935. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3936. EXPECT_EQ(false, res->has_header("Content-Range"));
  3937. EXPECT_EQ(0U, res->body.size());
  3938. }
  3939. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3940. auto res =
  3941. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3942. ASSERT_TRUE(res);
  3943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3944. EXPECT_EQ(5U, res->body.size());
  3945. // Check that overlapping ranges are coalesced into a single range
  3946. EXPECT_EQ("bcdef", res->body);
  3947. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3948. // Should be single range, not multipart
  3949. EXPECT_TRUE(res->has_header("Content-Range"));
  3950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3951. }
  3952. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3953. auto res =
  3954. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ(268U, res->body.size());
  3958. // Check that both range contents are present
  3959. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3960. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3961. // Check that Content-Range headers are present for both ranges
  3962. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3963. std::string::npos);
  3964. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3965. std::string::npos);
  3966. }
  3967. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3968. auto res =
  3969. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ(269U, res->body.size());
  3973. // Check that both duplicate range contents are present
  3974. size_t first_abc = res->body.find("abc\r\n");
  3975. EXPECT_TRUE(first_abc != std::string::npos);
  3976. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3977. EXPECT_TRUE(second_abc != std::string::npos);
  3978. // Check that Content-Range headers are present for both ranges
  3979. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3980. EXPECT_TRUE(first_range != std::string::npos);
  3981. size_t second_range =
  3982. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3983. EXPECT_TRUE(second_range != std::string::npos);
  3984. }
  3985. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3986. auto res = cli_.Get("/streamed-with-range?error",
  3987. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3990. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3991. EXPECT_EQ(false, res->has_header("Content-Range"));
  3992. EXPECT_EQ(0U, res->body.size());
  3993. }
  3994. TEST_F(ServerTest, GetStreamedEndless) {
  3995. uint64_t offset = 0;
  3996. auto res = cli_.Get("/streamed-cancel",
  3997. [&](const char * /*data*/, uint64_t data_length) {
  3998. if (offset < 100) {
  3999. offset += data_length;
  4000. return true;
  4001. }
  4002. return false;
  4003. });
  4004. ASSERT_TRUE(!res);
  4005. EXPECT_EQ(Error::Canceled, res.error());
  4006. }
  4007. TEST_F(ServerTest, ClientStop) {
  4008. std::atomic_size_t count{4};
  4009. std::vector<std::thread> threads;
  4010. for (auto i = count.load(); i != 0; --i) {
  4011. threads.emplace_back([&]() {
  4012. auto res = cli_.Get("/streamed-cancel",
  4013. [&](const char *, uint64_t) { return true; });
  4014. --count;
  4015. ASSERT_TRUE(!res);
  4016. EXPECT_TRUE(res.error() == Error::Canceled ||
  4017. res.error() == Error::Read || res.error() == Error::Write);
  4018. });
  4019. }
  4020. std::this_thread::sleep_for(std::chrono::seconds(2));
  4021. while (count != 0) {
  4022. cli_.stop();
  4023. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4024. }
  4025. for (auto &t : threads) {
  4026. t.join();
  4027. }
  4028. }
  4029. TEST_F(ServerTest, GetWithRange1) {
  4030. auto res = cli_.Get("/with-range", {
  4031. make_range_header({{3, 5}}),
  4032. {"Accept-Encoding", ""},
  4033. });
  4034. ASSERT_TRUE(res);
  4035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4036. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4037. EXPECT_EQ(true, res->has_header("Content-Range"));
  4038. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4039. EXPECT_EQ(std::string("def"), res->body);
  4040. }
  4041. TEST_F(ServerTest, GetWithRange2) {
  4042. auto res = cli_.Get("/with-range", {
  4043. make_range_header({{1, -1}}),
  4044. {"Accept-Encoding", ""},
  4045. });
  4046. ASSERT_TRUE(res);
  4047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4048. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4049. EXPECT_EQ(true, res->has_header("Content-Range"));
  4050. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4051. EXPECT_EQ(std::string("bcdefg"), res->body);
  4052. }
  4053. TEST_F(ServerTest, GetWithRange3) {
  4054. auto res = cli_.Get("/with-range", {
  4055. make_range_header({{0, 0}}),
  4056. {"Accept-Encoding", ""},
  4057. });
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4060. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ(true, res->has_header("Content-Range"));
  4062. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4063. EXPECT_EQ(std::string("a"), res->body);
  4064. }
  4065. TEST_F(ServerTest, GetWithRange4) {
  4066. auto res = cli_.Get("/with-range", {
  4067. make_range_header({{-1, 2}}),
  4068. {"Accept-Encoding", ""},
  4069. });
  4070. ASSERT_TRUE(res);
  4071. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4072. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4073. EXPECT_EQ(true, res->has_header("Content-Range"));
  4074. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4075. EXPECT_EQ(std::string("fg"), res->body);
  4076. }
  4077. TEST_F(ServerTest, GetWithRange5) {
  4078. auto res = cli_.Get("/with-range", {
  4079. make_range_header({{0, 5}}),
  4080. {"Accept-Encoding", ""},
  4081. });
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4084. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(true, res->has_header("Content-Range"));
  4086. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4087. EXPECT_EQ(std::string("abcdef"), res->body);
  4088. }
  4089. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4090. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4093. }
  4094. TEST_F(ServerTest, GetWithRangeMultipart) {
  4095. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4096. ASSERT_TRUE(res);
  4097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4098. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4099. EXPECT_EQ(false, res->has_header("Content-Range"));
  4100. EXPECT_EQ(267U, res->body.size());
  4101. }
  4102. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4103. auto res =
  4104. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4107. }
  4108. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4109. auto res = cli_.Get("/with-range-customized-response",
  4110. {{make_range_header({{1, 2}})}});
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4113. EXPECT_EQ(true, res->has_header("Content-Length"));
  4114. EXPECT_EQ(false, res->has_header("Content-Range"));
  4115. EXPECT_EQ(JSON_DATA, res->body);
  4116. }
  4117. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4118. auto res = cli_.Get("/with-range-customized-response",
  4119. {{make_range_header({{1, 2}, {4, 5}})}});
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4122. EXPECT_EQ(true, res->has_header("Content-Length"));
  4123. EXPECT_EQ(false, res->has_header("Content-Range"));
  4124. EXPECT_EQ(JSON_DATA, res->body);
  4125. }
  4126. TEST_F(ServerTest, Issue1772) {
  4127. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4130. }
  4131. TEST_F(ServerTest, Issue609) {
  4132. auto res = cli_.Delete("/issue609");
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::OK_200, res->status);
  4135. EXPECT_EQ(std::string("ok"), res->body);
  4136. }
  4137. TEST_F(ServerTest, GetStreamedChunked) {
  4138. auto res = cli_.Get("/streamed-chunked");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. EXPECT_EQ(std::string("123456789"), res->body);
  4142. }
  4143. TEST_F(ServerTest, GetStreamedChunked2) {
  4144. auto res = cli_.Get("/streamed-chunked2");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ(std::string("123456789"), res->body);
  4148. }
  4149. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4150. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4151. ASSERT_TRUE(res);
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ(std::string("123456789"), res->body);
  4154. EXPECT_TRUE(res->has_header("Trailer"));
  4155. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4156. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4157. // Trailers are now stored separately from headers (security fix)
  4158. EXPECT_EQ(2U, res->trailers.size());
  4159. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4160. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4161. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4162. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4163. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4164. // Verify trailers are NOT in headers (security verification)
  4165. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4166. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4167. }
  4168. TEST_F(ServerTest, LargeChunkedPost) {
  4169. Request req;
  4170. req.method = "POST";
  4171. req.path = "/large-chunked";
  4172. std::string host_and_port;
  4173. host_and_port += HOST;
  4174. host_and_port += ":";
  4175. host_and_port += std::to_string(PORT);
  4176. req.headers.emplace("Host", host_and_port.c_str());
  4177. req.headers.emplace("Accept", "*/*");
  4178. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4179. req.headers.emplace("Content-Type", "text/plain");
  4180. req.headers.emplace("Content-Length", "0");
  4181. req.headers.emplace("Transfer-Encoding", "chunked");
  4182. std::string long_string(30 * 1024u, 'a');
  4183. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4184. // Attempt to make a large enough post to exceed OS buffers, to test that
  4185. // the server handles short reads if the full chunk data isn't available.
  4186. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4187. auto res = std::make_shared<Response>();
  4188. auto error = Error::Success;
  4189. auto ret = cli_.send(req, *res, error);
  4190. ASSERT_TRUE(ret);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. }
  4193. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4194. auto res = cli_.Get("/remote_addr");
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::OK_200, res->status);
  4197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4198. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4199. }
  4200. TEST_F(ServerTest, GetMethodLocalAddr) {
  4201. auto res = cli_.Get("/local_addr");
  4202. ASSERT_TRUE(res);
  4203. EXPECT_EQ(StatusCode::OK_200, res->status);
  4204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4205. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4206. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4207. }
  4208. TEST_F(ServerTest, HTTPResponseSplitting) {
  4209. auto res = cli_.Get("/http_response_splitting");
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. }
  4213. TEST_F(ServerTest, SlowRequest) {
  4214. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4215. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4216. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4217. }
  4218. #if 0
  4219. TEST_F(ServerTest, SlowPost) {
  4220. char buffer[64 * 1024];
  4221. memset(buffer, 0x42, sizeof(buffer));
  4222. auto res = cli_.Post(
  4223. "/slowpost", 64 * 1024 * 1024,
  4224. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4225. auto ret = sink.write(buffer, sizeof(buffer));
  4226. EXPECT_TRUE(ret);
  4227. return true;
  4228. },
  4229. "text/plain");
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::OK_200, res->status);
  4232. }
  4233. TEST_F(ServerTest, SlowPostFail) {
  4234. char buffer[64 * 1024];
  4235. memset(buffer, 0x42, sizeof(buffer));
  4236. cli_.set_write_timeout(std::chrono::seconds(0));
  4237. auto res = cli_.Post(
  4238. "/slowpost", 64 * 1024 * 1024,
  4239. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4240. sink.write(buffer, sizeof(buffer));
  4241. return true;
  4242. },
  4243. "text/plain");
  4244. ASSERT_TRUE(!res);
  4245. EXPECT_EQ(Error::Write, res.error());
  4246. }
  4247. #endif
  4248. TEST_F(ServerTest, Put) {
  4249. auto res = cli_.Put("/put", "PUT", "text/plain");
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("PUT", res->body);
  4253. }
  4254. TEST_F(ServerTest, PutWithContentProvider) {
  4255. auto res = cli_.Put(
  4256. "/put", 3,
  4257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4258. sink.os << "PUT";
  4259. return true;
  4260. },
  4261. "text/plain");
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("PUT", res->body);
  4265. }
  4266. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4267. auto res = cli_.Post(
  4268. "/post", 42,
  4269. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4270. return false;
  4271. },
  4272. "text/plain");
  4273. ASSERT_TRUE(!res);
  4274. EXPECT_EQ(Error::Canceled, res.error());
  4275. }
  4276. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4277. auto res = cli_.Put(
  4278. "/put",
  4279. [](size_t /*offset*/, DataSink &sink) {
  4280. sink.os << "PUT";
  4281. sink.done();
  4282. return true;
  4283. },
  4284. "text/plain");
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::OK_200, res->status);
  4287. EXPECT_EQ("PUT", res->body);
  4288. }
  4289. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4290. auto res = cli_.Post(
  4291. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4292. "text/plain");
  4293. ASSERT_TRUE(!res);
  4294. EXPECT_EQ(Error::Canceled, res.error());
  4295. }
  4296. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4297. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4298. cli_.set_compress(true);
  4299. auto res = cli_.Put(
  4300. "/put", 3,
  4301. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4302. sink.os << "PUT";
  4303. return true;
  4304. },
  4305. "text/plain");
  4306. ASSERT_TRUE(res);
  4307. EXPECT_EQ(StatusCode::OK_200, res->status);
  4308. EXPECT_EQ("PUT", res->body);
  4309. }
  4310. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4311. cli_.set_compress(true);
  4312. auto res = cli_.Post(
  4313. "/post", 42,
  4314. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4315. return false;
  4316. },
  4317. "text/plain");
  4318. ASSERT_TRUE(!res);
  4319. EXPECT_EQ(Error::Canceled, res.error());
  4320. }
  4321. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4322. cli_.set_compress(true);
  4323. auto res = cli_.Put(
  4324. "/put",
  4325. [](size_t /*offset*/, DataSink &sink) {
  4326. sink.os << "PUT";
  4327. sink.done();
  4328. return true;
  4329. },
  4330. "text/plain");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. EXPECT_EQ("PUT", res->body);
  4334. }
  4335. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4336. cli_.set_compress(true);
  4337. auto res = cli_.Post(
  4338. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4339. "text/plain");
  4340. ASSERT_TRUE(!res);
  4341. EXPECT_EQ(Error::Canceled, res.error());
  4342. }
  4343. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4344. cli_.set_compress(true);
  4345. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4346. ASSERT_TRUE(res);
  4347. EXPECT_EQ(StatusCode::OK_200, res->status);
  4348. EXPECT_EQ(LARGE_DATA, res->body);
  4349. }
  4350. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4351. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4352. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4353. Client cli(s.c_str());
  4354. cli.enable_server_certificate_verification(false);
  4355. #else
  4356. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4357. Client cli(s.c_str());
  4358. #endif
  4359. cli.set_compress(true);
  4360. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4361. ASSERT_TRUE(res);
  4362. EXPECT_EQ(StatusCode::OK_200, res->status);
  4363. EXPECT_EQ(LARGE_DATA, res->body);
  4364. // The compressed size should be less than a 10th of the original. May vary
  4365. // depending on the zlib library.
  4366. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4367. static_cast<uint64_t>(10 * 1024 * 1024));
  4368. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4369. }
  4370. TEST_F(ServerTest, PutContentWithDeflate) {
  4371. cli_.set_compress(false);
  4372. Headers headers;
  4373. headers.emplace("Content-Encoding", "deflate");
  4374. // PUT in deflate format:
  4375. auto res = cli_.Put("/put", headers,
  4376. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::OK_200, res->status);
  4379. EXPECT_EQ("PUT", res->body);
  4380. }
  4381. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4382. Headers headers;
  4383. headers.emplace("Accept-Encoding", "gzip, deflate");
  4384. auto res = cli_.Get("/streamed-chunked", headers);
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::OK_200, res->status);
  4387. EXPECT_EQ(std::string("123456789"), res->body);
  4388. }
  4389. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4390. Headers headers;
  4391. headers.emplace("Accept-Encoding", "gzip, deflate");
  4392. auto res = cli_.Get("/streamed-chunked2", headers);
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::OK_200, res->status);
  4395. EXPECT_EQ(std::string("123456789"), res->body);
  4396. }
  4397. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4398. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST(GzipDecompressor, ChunkedDecompression) {
  4403. std::string data;
  4404. for (size_t i = 0; i < 32 * 1024; ++i) {
  4405. data.push_back(static_cast<char>('a' + i % 26));
  4406. }
  4407. std::string compressed_data;
  4408. {
  4409. httplib::detail::gzip_compressor compressor;
  4410. bool result = compressor.compress(
  4411. data.data(), data.size(),
  4412. /*last=*/true,
  4413. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4414. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4415. compressed_data_size);
  4416. return true;
  4417. });
  4418. ASSERT_TRUE(result);
  4419. }
  4420. std::string decompressed_data;
  4421. {
  4422. httplib::detail::gzip_decompressor decompressor;
  4423. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4424. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4425. size_t chunk_size = 130;
  4426. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4427. chunk_begin += chunk_size) {
  4428. size_t current_chunk_size =
  4429. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4430. bool result = decompressor.decompress(
  4431. compressed_data.data() + chunk_begin, current_chunk_size,
  4432. [&](const char *decompressed_data_chunk,
  4433. size_t decompressed_data_chunk_size) {
  4434. decompressed_data.insert(decompressed_data.size(),
  4435. decompressed_data_chunk,
  4436. decompressed_data_chunk_size);
  4437. return true;
  4438. });
  4439. ASSERT_TRUE(result);
  4440. }
  4441. }
  4442. ASSERT_EQ(data, decompressed_data);
  4443. }
  4444. TEST(GzipDecompressor, DeflateDecompression) {
  4445. std::string original_text = "Raw deflate without gzip";
  4446. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4447. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4448. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4449. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4450. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4451. std::string decompressed_data;
  4452. {
  4453. httplib::detail::gzip_decompressor decompressor;
  4454. bool result = decompressor.decompress(
  4455. compressed_data.data(), compressed_data.size(),
  4456. [&](const char *decompressed_data_chunk,
  4457. size_t decompressed_data_chunk_size) {
  4458. decompressed_data.insert(decompressed_data.size(),
  4459. decompressed_data_chunk,
  4460. decompressed_data_chunk_size);
  4461. return true;
  4462. });
  4463. ASSERT_TRUE(result);
  4464. }
  4465. ASSERT_EQ(original_text, decompressed_data);
  4466. }
  4467. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4468. std::string original_text = "Raw deflate without gzip";
  4469. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4470. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4471. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4472. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4473. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4474. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4475. std::string decompressed_data;
  4476. {
  4477. httplib::detail::gzip_decompressor decompressor;
  4478. bool result = decompressor.decompress(
  4479. compressed_data.data(), compressed_data.size(),
  4480. [&](const char *decompressed_data_chunk,
  4481. size_t decompressed_data_chunk_size) {
  4482. decompressed_data.insert(decompressed_data.size(),
  4483. decompressed_data_chunk,
  4484. decompressed_data_chunk_size);
  4485. return true;
  4486. });
  4487. ASSERT_TRUE(result);
  4488. }
  4489. ASSERT_EQ(original_text, decompressed_data);
  4490. }
  4491. #ifdef _WIN32
  4492. TEST(GzipDecompressor, LargeRandomData) {
  4493. // prepare large random data that is difficult to be compressed and is
  4494. // expected to have large size even when compressed
  4495. std::random_device seed_gen;
  4496. std::mt19937 random(seed_gen());
  4497. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4498. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4499. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4500. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4501. // compress data over 4GiB
  4502. std::string compressed_data;
  4503. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4504. httplib::detail::gzip_compressor compressor;
  4505. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4506. data.size() * sizeof(std::uint32_t), true,
  4507. [&](const char *data, size_t size) {
  4508. compressed_data.insert(
  4509. compressed_data.size(), data, size);
  4510. return true;
  4511. });
  4512. ASSERT_TRUE(result);
  4513. // FIXME: compressed data size is expected to be greater than 4GiB,
  4514. // but there is no guarantee
  4515. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4516. // decompress data over 4GiB
  4517. std::string decompressed_data;
  4518. decompressed_data.reserve(data_size);
  4519. httplib::detail::gzip_decompressor decompressor;
  4520. result = decompressor.decompress(
  4521. compressed_data.data(), compressed_data.size(),
  4522. [&](const char *data, size_t size) {
  4523. decompressed_data.insert(decompressed_data.size(), data, size);
  4524. return true;
  4525. });
  4526. ASSERT_TRUE(result);
  4527. // compare
  4528. ASSERT_EQ(data_size, decompressed_data.size());
  4529. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4530. 0);
  4531. }
  4532. #endif
  4533. #endif
  4534. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4535. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4536. Headers headers;
  4537. headers.emplace("Accept-Encoding", "br");
  4538. auto res = cli_.Get("/streamed-chunked", headers);
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ(std::string("123456789"), res->body);
  4542. }
  4543. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4544. Headers headers;
  4545. headers.emplace("Accept-Encoding", "br");
  4546. auto res = cli_.Get("/streamed-chunked2", headers);
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::OK_200, res->status);
  4549. EXPECT_EQ(std::string("123456789"), res->body);
  4550. }
  4551. #endif
  4552. TEST_F(ServerTest, Patch) {
  4553. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4554. ASSERT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("PATCH", res->body);
  4557. }
  4558. TEST_F(ServerTest, Delete) {
  4559. auto res = cli_.Delete("/delete");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("DELETE", res->body);
  4563. }
  4564. TEST_F(ServerTest, DeleteContentReceiver) {
  4565. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4566. ASSERT_TRUE(res);
  4567. EXPECT_EQ(StatusCode::OK_200, res->status);
  4568. EXPECT_EQ("content", res->body);
  4569. }
  4570. TEST_F(ServerTest, Options) {
  4571. auto res = cli_.Options("*");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4575. EXPECT_TRUE(res->body.empty());
  4576. }
  4577. TEST_F(ServerTest, URL) {
  4578. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. }
  4582. TEST_F(ServerTest, ArrayParam) {
  4583. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. }
  4587. TEST_F(ServerTest, NoMultipleHeaders) {
  4588. Headers headers = {{"Content-Length", "5"}};
  4589. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4590. "text/plain");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. }
  4594. TEST_F(ServerTest, PostContentReceiver) {
  4595. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4596. ASSERT_TRUE(res);
  4597. ASSERT_EQ(StatusCode::OK_200, res->status);
  4598. ASSERT_EQ("content", res->body);
  4599. }
  4600. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4601. UploadFormDataItems items = {
  4602. {"text1", "text default", "", ""},
  4603. {"text2", "aωb", "", ""},
  4604. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4605. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4606. {"file3", "", "", "application/octet-stream"},
  4607. };
  4608. auto res = cli_.Post("/content_receiver", items);
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. }
  4612. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4613. UploadFormDataItems items = {
  4614. {"text1", "text default", "", ""},
  4615. {"text2", "aωb", "", ""},
  4616. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4617. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4618. {"file3", "", "", "application/octet-stream"},
  4619. };
  4620. auto boundary = std::string("+++++");
  4621. std::string body;
  4622. for (const auto &item : items) {
  4623. body += "--" + boundary + "\r\n";
  4624. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4625. if (!item.filename.empty()) {
  4626. body += "; filename=\"" + item.filename + "\"";
  4627. }
  4628. body += "\r\n";
  4629. if (!item.content_type.empty()) {
  4630. body += "Content-Type: " + item.content_type + "\r\n";
  4631. }
  4632. body += "\r\n";
  4633. body += item.content + "\r\n";
  4634. }
  4635. body += "--" + boundary + "--\r\n";
  4636. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4637. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::OK_200, res->status);
  4640. }
  4641. TEST_F(ServerTest, PostContentReceiverGzip) {
  4642. cli_.set_compress(true);
  4643. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4644. ASSERT_TRUE(res);
  4645. ASSERT_EQ(StatusCode::OK_200, res->status);
  4646. ASSERT_EQ("content", res->body);
  4647. }
  4648. TEST_F(ServerTest, PutContentReceiver) {
  4649. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4650. ASSERT_TRUE(res);
  4651. ASSERT_EQ(StatusCode::OK_200, res->status);
  4652. ASSERT_EQ("content", res->body);
  4653. }
  4654. TEST_F(ServerTest, PatchContentReceiver) {
  4655. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4656. ASSERT_TRUE(res);
  4657. ASSERT_EQ(StatusCode::OK_200, res->status);
  4658. ASSERT_EQ("content", res->body);
  4659. }
  4660. template <typename ClientType>
  4661. void TestWithHeadersAndContentReceiver(
  4662. ClientType &cli,
  4663. std::function<Result(ClientType &, const std::string &, const Headers &,
  4664. const std::string &, const std::string &,
  4665. ContentReceiver, DownloadProgress)>
  4666. request_func) {
  4667. Headers headers;
  4668. headers.emplace("X-Custom-Header", "test-value");
  4669. std::string received_body;
  4670. auto res = request_func(
  4671. cli, "/content_receiver", headers, "content", "application/json",
  4672. [&](const char *data, size_t data_length) {
  4673. received_body.append(data, data_length);
  4674. return true;
  4675. },
  4676. nullptr);
  4677. ASSERT_TRUE(res);
  4678. EXPECT_EQ(StatusCode::OK_200, res->status);
  4679. EXPECT_EQ("content", received_body);
  4680. }
  4681. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4683. using ClientT = SSLClient;
  4684. #else
  4685. using ClientT = Client;
  4686. #endif
  4687. TestWithHeadersAndContentReceiver<ClientT>(
  4688. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4689. const std::string &body, const std::string &content_type,
  4690. ContentReceiver receiver, DownloadProgress progress) {
  4691. return cli.Post(path, headers, body, content_type, receiver, progress);
  4692. });
  4693. }
  4694. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4696. using ClientT = SSLClient;
  4697. #else
  4698. using ClientT = Client;
  4699. #endif
  4700. TestWithHeadersAndContentReceiver<ClientT>(
  4701. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4702. const std::string &body, const std::string &content_type,
  4703. ContentReceiver receiver, DownloadProgress progress) {
  4704. return cli.Put(path, headers, body, content_type, receiver, progress);
  4705. });
  4706. }
  4707. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4708. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4709. using ClientT = SSLClient;
  4710. #else
  4711. using ClientT = Client;
  4712. #endif
  4713. TestWithHeadersAndContentReceiver<ClientT>(
  4714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4715. const std::string &body, const std::string &content_type,
  4716. ContentReceiver receiver, DownloadProgress progress) {
  4717. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4718. });
  4719. }
  4720. template <typename ClientType>
  4721. void TestWithHeadersAndContentReceiverWithProgress(
  4722. ClientType &cli,
  4723. std::function<Result(ClientType &, const std::string &, const Headers &,
  4724. const std::string &, const std::string &,
  4725. ContentReceiver, DownloadProgress)>
  4726. request_func) {
  4727. Headers headers;
  4728. headers.emplace("X-Test-Header", "progress-test");
  4729. std::string received_body;
  4730. auto progress_called = false;
  4731. auto res = request_func(
  4732. cli, "/content_receiver", headers, "content", "text/plain",
  4733. [&](const char *data, size_t data_length) {
  4734. received_body.append(data, data_length);
  4735. return true;
  4736. },
  4737. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4738. progress_called = true;
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("content", received_body);
  4744. EXPECT_TRUE(progress_called);
  4745. }
  4746. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4748. using ClientT = SSLClient;
  4749. #else
  4750. using ClientT = Client;
  4751. #endif
  4752. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4753. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4754. const std::string &body, const std::string &content_type,
  4755. ContentReceiver receiver, DownloadProgress progress) {
  4756. return cli.Post(path, headers, body, content_type, receiver, progress);
  4757. });
  4758. }
  4759. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4761. using ClientT = SSLClient;
  4762. #else
  4763. using ClientT = Client;
  4764. #endif
  4765. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4766. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4767. const std::string &body, const std::string &content_type,
  4768. ContentReceiver receiver, DownloadProgress progress) {
  4769. return cli.Put(path, headers, body, content_type, receiver, progress);
  4770. });
  4771. }
  4772. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4774. using ClientT = SSLClient;
  4775. #else
  4776. using ClientT = Client;
  4777. #endif
  4778. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4779. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4780. const std::string &body, const std::string &content_type,
  4781. ContentReceiver receiver, DownloadProgress progress) {
  4782. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4783. });
  4784. }
  4785. template <typename ClientType>
  4786. void TestWithHeadersAndContentReceiverError(
  4787. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4788. const Headers &, const std::string &,
  4789. const std::string &, ContentReceiver)>
  4790. request_func) {
  4791. Headers headers;
  4792. headers.emplace("X-Error-Test", "true");
  4793. std::string received_body;
  4794. auto receiver_failed = false;
  4795. auto res =
  4796. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4797. [&](const char *data, size_t data_length) {
  4798. received_body.append(data, data_length);
  4799. receiver_failed = true;
  4800. return false;
  4801. });
  4802. ASSERT_FALSE(res);
  4803. EXPECT_TRUE(receiver_failed);
  4804. }
  4805. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4806. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4807. using ClientT = SSLClient;
  4808. #else
  4809. using ClientT = Client;
  4810. #endif
  4811. TestWithHeadersAndContentReceiverError<ClientT>(
  4812. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4813. const std::string &body, const std::string &content_type,
  4814. ContentReceiver receiver) {
  4815. return cli.Post(path, headers, body, content_type, receiver);
  4816. });
  4817. }
  4818. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4820. using ClientT = SSLClient;
  4821. #else
  4822. using ClientT = Client;
  4823. #endif
  4824. TestWithHeadersAndContentReceiverError<ClientT>(
  4825. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4826. const std::string &body, const std::string &content_type,
  4827. ContentReceiver receiver) {
  4828. return cli.Put(path, headers, body, content_type, receiver);
  4829. });
  4830. }
  4831. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4833. using ClientT = SSLClient;
  4834. #else
  4835. using ClientT = Client;
  4836. #endif
  4837. TestWithHeadersAndContentReceiverError<ClientT>(
  4838. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4839. const std::string &body, const std::string &content_type,
  4840. ContentReceiver receiver) {
  4841. return cli.Patch(path, headers, body, content_type, receiver);
  4842. });
  4843. }
  4844. TEST_F(ServerTest, PostQueryStringAndBody) {
  4845. auto res =
  4846. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4847. ASSERT_TRUE(res);
  4848. ASSERT_EQ(StatusCode::OK_200, res->status);
  4849. }
  4850. TEST_F(ServerTest, HTTP2Magic) {
  4851. Request req;
  4852. req.method = "PRI";
  4853. req.path = "*";
  4854. req.body = "SM";
  4855. auto res = std::make_shared<Response>();
  4856. auto error = Error::Success;
  4857. auto ret = cli_.send(req, *res, error);
  4858. ASSERT_TRUE(ret);
  4859. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4860. }
  4861. TEST_F(ServerTest, KeepAlive) {
  4862. auto res = cli_.Get("/hi");
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. EXPECT_EQ("Hello World!", res->body);
  4867. res = cli_.Get("/hi");
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4871. EXPECT_EQ("Hello World!", res->body);
  4872. res = cli_.Get("/hi");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4876. EXPECT_EQ("Hello World!", res->body);
  4877. res = cli_.Get("/not-exist");
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4880. res = cli_.Post("/empty", "", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::OK_200, res->status);
  4883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4884. EXPECT_EQ("empty", res->body);
  4885. EXPECT_EQ("close", res->get_header_value("Connection"));
  4886. res = cli_.Post(
  4887. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4888. "text/plain");
  4889. ASSERT_TRUE(res);
  4890. EXPECT_EQ(StatusCode::OK_200, res->status);
  4891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4892. EXPECT_EQ("empty", res->body);
  4893. cli_.set_keep_alive(false);
  4894. res = cli_.Get("/last-request");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("close", res->get_header_value("Connection"));
  4898. }
  4899. TEST_F(ServerTest, TooManyRedirect) {
  4900. cli_.set_follow_location(true);
  4901. auto res = cli_.Get("/redirect/0");
  4902. ASSERT_TRUE(!res);
  4903. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4904. }
  4905. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4906. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4907. TEST_F(ServerTest, Gzip) {
  4908. Headers headers;
  4909. headers.emplace("Accept-Encoding", "gzip, deflate");
  4910. auto res = cli_.Get("/compress", headers);
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4914. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4916. "7890123456789012345678901234567890",
  4917. res->body);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. }
  4920. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4921. Headers headers;
  4922. headers.emplace("Accept-Encoding", "");
  4923. auto res = cli_.Get("/compress", headers);
  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. res->body);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. }
  4933. TEST_F(ServerTest, GzipWithContentReceiver) {
  4934. Headers headers;
  4935. headers.emplace("Accept-Encoding", "gzip, deflate");
  4936. std::string body;
  4937. auto res = cli_.Get("/compress", headers,
  4938. [&](const char *data, uint64_t data_length) {
  4939. EXPECT_EQ(100U, data_length);
  4940. body.append(data, data_length);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4948. "7890123456789012345678901234567890",
  4949. body);
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. }
  4952. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4953. Headers headers;
  4954. headers.emplace("Accept-Encoding", "gzip, deflate");
  4955. cli_.set_decompress(false);
  4956. auto res = cli_.Get("/compress", headers);
  4957. ASSERT_TRUE(res);
  4958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4960. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4961. EXPECT_EQ(33U, res->body.size());
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. }
  4964. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4965. Headers headers;
  4966. headers.emplace("Accept-Encoding", "");
  4967. std::string body;
  4968. auto res = cli_.Get("/compress", headers,
  4969. [&](const char *data, uint64_t data_length) {
  4970. EXPECT_EQ(100U, data_length);
  4971. body.append(data, data_length);
  4972. return true;
  4973. });
  4974. ASSERT_TRUE(res);
  4975. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4977. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4979. "7890123456789012345678901234567890",
  4980. body);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. }
  4983. TEST_F(ServerTest, NoGzip) {
  4984. Headers headers;
  4985. headers.emplace("Accept-Encoding", "gzip, deflate");
  4986. auto res = cli_.Get("/nocompress", headers);
  4987. ASSERT_TRUE(res);
  4988. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4989. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4990. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4992. "7890123456789012345678901234567890",
  4993. res->body);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4997. Headers headers;
  4998. headers.emplace("Accept-Encoding", "gzip, deflate");
  4999. std::string body;
  5000. auto res = cli_.Get("/nocompress", headers,
  5001. [&](const char *data, uint64_t data_length) {
  5002. EXPECT_EQ(100U, data_length);
  5003. body.append(data, data_length);
  5004. return true;
  5005. });
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5008. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5009. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5011. "7890123456789012345678901234567890",
  5012. body);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. }
  5015. TEST_F(ServerTest, MultipartFormDataGzip) {
  5016. UploadFormDataItems items = {
  5017. {"key1", "test", "", ""},
  5018. {"key2", "--abcdefg123", "", ""},
  5019. };
  5020. cli_.set_compress(true);
  5021. auto res = cli_.Post("/compress-multipart", items);
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. #endif
  5026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5027. TEST_F(ServerTest, Brotli) {
  5028. Headers headers;
  5029. headers.emplace("Accept-Encoding", "br");
  5030. auto res = cli_.Get("/compress", headers);
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5034. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5035. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5036. "7890123456789012345678901234567890",
  5037. res->body);
  5038. EXPECT_EQ(StatusCode::OK_200, res->status);
  5039. }
  5040. #endif
  5041. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5042. TEST_F(ServerTest, Zstd) {
  5043. Headers headers;
  5044. headers.emplace("Accept-Encoding", "zstd");
  5045. auto res = cli_.Get("/compress", headers);
  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("123456789012345678901234567890123456789012345678901234567890123456"
  5051. "7890123456789012345678901234567890",
  5052. res->body);
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. }
  5055. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5056. Headers headers;
  5057. headers.emplace("Accept-Encoding", "");
  5058. auto res = cli_.Get("/compress", headers);
  5059. ASSERT_TRUE(res);
  5060. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5061. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5062. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5063. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5064. "7890123456789012345678901234567890",
  5065. res->body);
  5066. EXPECT_EQ(StatusCode::OK_200, res->status);
  5067. }
  5068. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5069. Headers headers;
  5070. headers.emplace("Accept-Encoding", "zstd");
  5071. std::string body;
  5072. auto res = cli_.Get("/compress", headers,
  5073. [&](const char *data, uint64_t data_length) {
  5074. EXPECT_EQ(100U, data_length);
  5075. body.append(data, data_length);
  5076. return true;
  5077. });
  5078. ASSERT_TRUE(res);
  5079. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5080. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5081. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5082. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5083. "7890123456789012345678901234567890",
  5084. body);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5088. Headers headers;
  5089. headers.emplace("Accept-Encoding", "zstd");
  5090. cli_.set_decompress(false);
  5091. auto res = cli_.Get("/compress", headers);
  5092. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5093. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5094. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5095. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5099. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5100. EXPECT_EQ(StatusCode::OK_200, res->status);
  5101. ASSERT_EQ(26U, res->body.size());
  5102. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5103. 0);
  5104. }
  5105. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5106. Headers headers;
  5107. headers.emplace("Accept-Encoding", "");
  5108. std::string body;
  5109. auto res = cli_.Get("/compress", headers,
  5110. [&](const char *data, uint64_t data_length) {
  5111. EXPECT_EQ(100U, data_length);
  5112. body.append(data, data_length);
  5113. return true;
  5114. });
  5115. ASSERT_TRUE(res);
  5116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5120. "7890123456789012345678901234567890",
  5121. body);
  5122. EXPECT_EQ(StatusCode::OK_200, res->status);
  5123. }
  5124. TEST_F(ServerTest, NoZstd) {
  5125. Headers headers;
  5126. headers.emplace("Accept-Encoding", "zstd");
  5127. auto res = cli_.Get("/nocompress", headers);
  5128. ASSERT_TRUE(res);
  5129. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5130. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5133. "7890123456789012345678901234567890",
  5134. res->body);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. }
  5137. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5138. Headers headers;
  5139. headers.emplace("Accept-Encoding", "zstd");
  5140. std::string body;
  5141. auto res = cli_.Get("/nocompress", headers,
  5142. [&](const char *data, uint64_t data_length) {
  5143. EXPECT_EQ(100U, data_length);
  5144. body.append(data, data_length);
  5145. return true;
  5146. });
  5147. ASSERT_TRUE(res);
  5148. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5149. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5150. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5152. "7890123456789012345678901234567890",
  5153. body);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. // TODO: How to enable zstd ??
  5157. TEST_F(ServerTest, MultipartFormDataZstd) {
  5158. UploadFormDataItems items = {
  5159. {"key1", "test", "", ""},
  5160. {"key2", "--abcdefg123", "", ""},
  5161. };
  5162. Headers headers;
  5163. headers.emplace("Accept-Encoding", "zstd");
  5164. cli_.set_compress(true);
  5165. auto res = cli_.Post("/compress-multipart", headers, items);
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. }
  5169. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5170. Headers headers;
  5171. headers.emplace("Accept-Encoding", "zstd");
  5172. cli_.set_compress(true);
  5173. auto res = cli_.Put(
  5174. "/put", headers, 3,
  5175. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5176. sink.os << "PUT";
  5177. return true;
  5178. },
  5179. "text/plain");
  5180. ASSERT_TRUE(res);
  5181. EXPECT_EQ(StatusCode::OK_200, res->status);
  5182. EXPECT_EQ("PUT", res->body);
  5183. }
  5184. // Pre-compression logging tests
  5185. TEST_F(ServerTest, PreCompressionLogging) {
  5186. // Test data for compression (matches the actual /compress endpoint content)
  5187. const std::string test_content =
  5188. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5189. "3456789012345678901234567890";
  5190. // Variables to capture logging data
  5191. std::string pre_compression_body;
  5192. std::string pre_compression_content_type;
  5193. std::string pre_compression_content_encoding;
  5194. std::string post_compression_body;
  5195. std::string post_compression_content_type;
  5196. std::string post_compression_content_encoding;
  5197. // Set up pre-compression logger
  5198. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5199. const Response &res) {
  5200. pre_compression_body = res.body;
  5201. pre_compression_content_type = res.get_header_value("Content-Type");
  5202. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5203. });
  5204. // Set up post-compression logger
  5205. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5206. post_compression_body = res.body;
  5207. post_compression_content_type = res.get_header_value("Content-Type");
  5208. post_compression_content_encoding =
  5209. res.get_header_value("Content-Encoding");
  5210. });
  5211. // Test with gzip compression
  5212. Headers headers;
  5213. headers.emplace("Accept-Encoding", "gzip");
  5214. auto res = cli_.Get("/compress", headers);
  5215. // Verify response was compressed
  5216. ASSERT_TRUE(res);
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5219. // Verify pre-compression logger captured uncompressed content
  5220. EXPECT_EQ(test_content, pre_compression_body);
  5221. EXPECT_EQ("text/plain", pre_compression_content_type);
  5222. EXPECT_TRUE(pre_compression_content_encoding
  5223. .empty()); // No encoding header before compression
  5224. // Verify post-compression logger captured compressed content
  5225. EXPECT_NE(test_content,
  5226. post_compression_body); // Should be different after compression
  5227. EXPECT_EQ("text/plain", post_compression_content_type);
  5228. EXPECT_EQ("gzip", post_compression_content_encoding);
  5229. // Verify compressed content is smaller
  5230. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5231. }
  5232. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5233. const std::string test_content =
  5234. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5235. "3456789012345678901234567890";
  5236. std::string pre_compression_body;
  5237. std::string post_compression_body;
  5238. svr_.set_pre_compression_logger(
  5239. [&](const Request & /*req*/, const Response &res) {
  5240. pre_compression_body = res.body;
  5241. });
  5242. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5243. post_compression_body = res.body;
  5244. });
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "br");
  5247. auto res = cli_.Get("/compress", headers);
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5251. // Verify pre-compression content is uncompressed
  5252. EXPECT_EQ(test_content, pre_compression_body);
  5253. // Verify post-compression content is compressed
  5254. EXPECT_NE(test_content, post_compression_body);
  5255. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5256. }
  5257. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5258. const std::string test_content =
  5259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5260. "3456789012345678901234567890";
  5261. std::string pre_compression_body;
  5262. std::string post_compression_body;
  5263. svr_.set_pre_compression_logger(
  5264. [&](const Request & /*req*/, const Response &res) {
  5265. pre_compression_body = res.body;
  5266. });
  5267. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5268. post_compression_body = res.body;
  5269. });
  5270. // Request without compression (use /nocompress endpoint)
  5271. Headers headers;
  5272. auto res = cli_.Get("/nocompress", headers);
  5273. ASSERT_TRUE(res);
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5276. // Pre-compression logger should not be called when no compression is applied
  5277. EXPECT_TRUE(
  5278. pre_compression_body.empty()); // Pre-compression logger not called
  5279. EXPECT_EQ(
  5280. test_content,
  5281. post_compression_body); // Post-compression logger captures final content
  5282. }
  5283. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5284. const std::string test_content =
  5285. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5286. "3456789012345678901234567890";
  5287. std::string pre_compression_body;
  5288. bool pre_logger_called = false;
  5289. // Set only pre-compression logger
  5290. svr_.set_pre_compression_logger(
  5291. [&](const Request & /*req*/, const Response &res) {
  5292. pre_compression_body = res.body;
  5293. pre_logger_called = true;
  5294. });
  5295. Headers headers;
  5296. headers.emplace("Accept-Encoding", "gzip");
  5297. auto res = cli_.Get("/compress", headers);
  5298. ASSERT_TRUE(res);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5301. // Verify pre-compression logger was called
  5302. EXPECT_TRUE(pre_logger_called);
  5303. EXPECT_EQ(test_content, pre_compression_body);
  5304. }
  5305. TEST(ZstdDecompressor, ChunkedDecompression) {
  5306. std::string data;
  5307. for (size_t i = 0; i < 32 * 1024; ++i) {
  5308. data.push_back(static_cast<char>('a' + i % 26));
  5309. }
  5310. std::string compressed_data;
  5311. {
  5312. httplib::detail::zstd_compressor compressor;
  5313. bool result = compressor.compress(
  5314. data.data(), data.size(),
  5315. /*last=*/true,
  5316. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5317. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5318. compressed_data_size);
  5319. return true;
  5320. });
  5321. ASSERT_TRUE(result);
  5322. }
  5323. std::string decompressed_data;
  5324. {
  5325. httplib::detail::zstd_decompressor decompressor;
  5326. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5327. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5328. size_t chunk_size = 130;
  5329. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5330. chunk_begin += chunk_size) {
  5331. size_t current_chunk_size =
  5332. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5333. bool result = decompressor.decompress(
  5334. compressed_data.data() + chunk_begin, current_chunk_size,
  5335. [&](const char *decompressed_data_chunk,
  5336. size_t decompressed_data_chunk_size) {
  5337. decompressed_data.insert(decompressed_data.size(),
  5338. decompressed_data_chunk,
  5339. decompressed_data_chunk_size);
  5340. return true;
  5341. });
  5342. ASSERT_TRUE(result);
  5343. }
  5344. }
  5345. ASSERT_EQ(data, decompressed_data);
  5346. }
  5347. TEST(ZstdDecompressor, Decompress) {
  5348. std::string original_text = "Compressed with ZSTD";
  5349. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5350. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5351. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5352. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5353. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5354. std::string decompressed_data;
  5355. {
  5356. httplib::detail::zstd_decompressor decompressor;
  5357. bool result = decompressor.decompress(
  5358. compressed_data.data(), compressed_data.size(),
  5359. [&](const char *decompressed_data_chunk,
  5360. size_t decompressed_data_chunk_size) {
  5361. decompressed_data.insert(decompressed_data.size(),
  5362. decompressed_data_chunk,
  5363. decompressed_data_chunk_size);
  5364. return true;
  5365. });
  5366. ASSERT_TRUE(result);
  5367. }
  5368. ASSERT_EQ(original_text, decompressed_data);
  5369. }
  5370. #endif
  5371. // Sends a raw request to a server listening at HOST:PORT.
  5372. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5373. std::string *resp = nullptr) {
  5374. auto error = Error::Success;
  5375. auto client_sock = detail::create_client_socket(
  5376. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5377. /*connection_timeout_sec=*/5, 0,
  5378. /*read_timeout_sec=*/5, 0,
  5379. /*write_timeout_sec=*/5, 0, std::string(), error);
  5380. if (client_sock == INVALID_SOCKET) { return false; }
  5381. auto ret = detail::process_client_socket(
  5382. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5383. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5384. if (req.size() !=
  5385. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5386. return false;
  5387. }
  5388. char buf[512];
  5389. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5390. while (line_reader.getline()) {
  5391. if (resp) { *resp += line_reader.ptr(); }
  5392. }
  5393. return true;
  5394. });
  5395. detail::close_socket(client_sock);
  5396. return ret;
  5397. }
  5398. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5399. Server svr;
  5400. std::string header_value;
  5401. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5402. header_value = req.get_header_value("foo");
  5403. res.set_content("ok", "text/plain");
  5404. });
  5405. thread t = thread([&] { svr.listen(HOST, PORT); });
  5406. auto se = detail::scope_exit([&] {
  5407. svr.stop();
  5408. t.join();
  5409. ASSERT_FALSE(svr.is_running());
  5410. });
  5411. svr.wait_until_ready();
  5412. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5413. // like characters are not treated the same - use vertical tab and escape.
  5414. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5415. "foo: \t \v bar \x1B\t \r\n"
  5416. "Connection: close\r\n"
  5417. "\r\n";
  5418. std::string res;
  5419. ASSERT_TRUE(send_request(5, req, &res));
  5420. EXPECT_EQ(header_value, "");
  5421. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5422. }
  5423. // Sends a raw request and verifies that there isn't a crash or exception.
  5424. static void test_raw_request(const std::string &req,
  5425. std::string *out = nullptr) {
  5426. Server svr;
  5427. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5428. res.set_content("ok", "text/plain");
  5429. });
  5430. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5431. res.set_content("ok", "text/plain");
  5432. });
  5433. svr.Get("/header_field_value_check",
  5434. [&](const Request & /*req*/, Response &res) {
  5435. res.set_content("ok", "text/plain");
  5436. });
  5437. // Server read timeout must be longer than the client read timeout for the
  5438. // bug to reproduce, probably to force the server to process a request
  5439. // without a trailing blank line.
  5440. const time_t client_read_timeout_sec = 1;
  5441. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5442. bool listen_thread_ok = false;
  5443. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5444. auto se = detail::scope_exit([&] {
  5445. svr.stop();
  5446. t.join();
  5447. ASSERT_FALSE(svr.is_running());
  5448. EXPECT_TRUE(listen_thread_ok);
  5449. });
  5450. svr.wait_until_ready();
  5451. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5452. }
  5453. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5454. // A certain header line causes an exception if the header property is parsed
  5455. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5456. test_raw_request(
  5457. "GET /hi HTTP/1.1\r\n"
  5458. " : "
  5459. " "
  5460. " ");
  5461. }
  5462. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5463. // A certain header line causes an exception if the header property *name* is
  5464. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5465. // greedy matcher and requires backtracking when there are a lot of ":"
  5466. // characters.
  5467. // This occurs with libc++ but not libstdc++.
  5468. test_raw_request(
  5469. "GET /hi HTTP/1.1\r\n"
  5470. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5471. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5472. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5473. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5474. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5475. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5476. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5477. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5478. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5479. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5480. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5481. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5482. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5483. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5484. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5485. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5486. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5487. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5488. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5489. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5490. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5491. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5492. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5493. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5494. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5495. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5496. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5497. "&&&%%%");
  5498. }
  5499. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5500. // Make sure this doesn't crash the server.
  5501. // In a previous version of the header line regex, the "\r" rendered the line
  5502. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5503. // a new position where the leading white space ended and the field value
  5504. // began.
  5505. // The crash occurs with libc++ but not libstdc++.
  5506. test_raw_request("GET /hi HTTP/1.1\r\n"
  5507. "a:" +
  5508. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5509. "\r\n"
  5510. "\r\n");
  5511. }
  5512. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5513. std::string out;
  5514. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5515. "Content-Type: text/plain\r\n"
  5516. "Transfer-Encoding: chunked\r\n"
  5517. "\r\n"
  5518. "nothex\r\n",
  5519. &out);
  5520. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5521. }
  5522. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5523. std::string out;
  5524. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5525. "Content-Type: text/plain\r\n"
  5526. "Transfer-Encoding: chunked\r\n"
  5527. "\r\n"
  5528. "3\r\n"
  5529. "xyz\r\n"
  5530. "NaN\r\n",
  5531. &out);
  5532. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5533. }
  5534. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5535. std::string out;
  5536. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5537. "Content-Type: text/plain\r\n"
  5538. "Transfer-Encoding: chunked\r\n"
  5539. "\r\n"
  5540. // Length is too large for 64 bits.
  5541. "1ffffffffffffffff\r\n"
  5542. "xyz\r\n",
  5543. &out);
  5544. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5545. }
  5546. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5547. test_raw_request("GET /hi HTTP/1.1\r\n"
  5548. "Content-Type: text/plain\r\n\r");
  5549. }
  5550. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5551. std::string out;
  5552. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5553. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5554. }
  5555. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5556. std::string out;
  5557. std::string request(
  5558. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5559. test_raw_request(request, &out);
  5560. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5561. }
  5562. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5563. std::string out;
  5564. std::string request(
  5565. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5566. test_raw_request(request, &out);
  5567. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5568. }
  5569. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5570. std::string out;
  5571. std::string request(
  5572. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5573. test_raw_request(request, &out);
  5574. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5575. }
  5576. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5577. std::string out;
  5578. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5579. "Test: \r\n\r\n",
  5580. &out);
  5581. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5582. }
  5583. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5584. Server svr;
  5585. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5586. res.set_header("Cache-Control", "no-cache");
  5587. res.set_chunked_content_provider(
  5588. "text/event-stream", [](size_t offset, DataSink &sink) {
  5589. std::string s = "data:";
  5590. s += std::to_string(offset);
  5591. s += "\n\n";
  5592. auto ret = sink.write(s.data(), s.size());
  5593. EXPECT_TRUE(ret);
  5594. std::this_thread::sleep_for(std::chrono::seconds(1));
  5595. return true;
  5596. });
  5597. });
  5598. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5599. svr.wait_until_ready();
  5600. Client client(HOST, PORT);
  5601. const Headers headers = {{"Accept", "text/event-stream"}};
  5602. auto get_thread = std::thread([&client, &headers]() {
  5603. auto res = client.Get(
  5604. "/events", headers,
  5605. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5606. });
  5607. auto se = detail::scope_exit([&] {
  5608. svr.stop();
  5609. get_thread.join();
  5610. listen_thread.join();
  5611. ASSERT_FALSE(svr.is_running());
  5612. });
  5613. // Give GET time to get a few messages.
  5614. std::this_thread::sleep_for(std::chrono::seconds(2));
  5615. }
  5616. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5617. httplib::Server svr;
  5618. svr.Post("/hi",
  5619. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5620. res.status = StatusCode::OK_200;
  5621. });
  5622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5623. svr.wait_until_ready();
  5624. Client cli(HOST, PORT);
  5625. auto res = cli.Post("/hi", "data", "text/plain");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. svr.stop();
  5629. thread.join();
  5630. ASSERT_FALSE(svr.is_running());
  5631. res = cli.Post("/hi", "data", "text/plain");
  5632. ASSERT_FALSE(res);
  5633. }
  5634. TEST(ServerStopTest, ListenFailure) {
  5635. Server svr;
  5636. auto t = thread([&]() {
  5637. auto ret = svr.listen("????", PORT);
  5638. EXPECT_FALSE(ret);
  5639. });
  5640. svr.wait_until_ready();
  5641. svr.stop();
  5642. t.join();
  5643. }
  5644. TEST(ServerStopTest, Decommision) {
  5645. Server svr;
  5646. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5647. for (int i = 0; i < 4; i++) {
  5648. auto is_even = !(i % 2);
  5649. std::thread t{[&] {
  5650. try {
  5651. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5652. if (is_even) {
  5653. throw std::runtime_error("Some thing that happens to go wrong.");
  5654. }
  5655. svr.listen(HOST, PORT);
  5656. } catch (...) { svr.decommission(); }
  5657. }};
  5658. svr.wait_until_ready();
  5659. // Server is up
  5660. {
  5661. Client cli(HOST, PORT);
  5662. auto res = cli.Get("/hi");
  5663. if (is_even) {
  5664. EXPECT_FALSE(res);
  5665. } else {
  5666. EXPECT_TRUE(res);
  5667. EXPECT_EQ("hi...", res->body);
  5668. }
  5669. }
  5670. svr.stop();
  5671. t.join();
  5672. // Server is down...
  5673. {
  5674. Client cli(HOST, PORT);
  5675. auto res = cli.Get("/hi");
  5676. EXPECT_FALSE(res);
  5677. }
  5678. }
  5679. }
  5680. // Helper function for string body upload progress tests
  5681. template <typename SetupHandler, typename ClientCall>
  5682. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5683. ClientCall &&client_call,
  5684. const string &body) {
  5685. Server svr;
  5686. setup_handler(svr);
  5687. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5688. auto se = detail::scope_exit([&] {
  5689. svr.stop();
  5690. t.join();
  5691. });
  5692. svr.wait_until_ready();
  5693. Client cli(HOST, PORT);
  5694. vector<uint64_t> progress_values;
  5695. bool progress_called = false;
  5696. auto res =
  5697. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5698. progress_values.push_back(current);
  5699. progress_called = true;
  5700. return true;
  5701. });
  5702. ASSERT_TRUE(res);
  5703. EXPECT_EQ(200, res->status);
  5704. EXPECT_TRUE(progress_called);
  5705. }
  5706. TEST(UploadProgressTest, PostStringBodyBasic) {
  5707. TestStringBodyUploadProgress(
  5708. [](Server &svr) {
  5709. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5710. res.set_content("received", "text/plain");
  5711. });
  5712. },
  5713. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5714. return cli.Post("/test", body, "text/plain", progress_callback);
  5715. },
  5716. "test data for upload progress");
  5717. }
  5718. TEST(UploadProgressTest, PutStringBodyBasic) {
  5719. TestStringBodyUploadProgress(
  5720. [](Server &svr) {
  5721. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5722. res.set_content("put received", "text/plain");
  5723. });
  5724. },
  5725. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5726. return cli.Put("/test", body, "text/plain", progress_callback);
  5727. },
  5728. "put test data for upload progress");
  5729. }
  5730. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5731. TestStringBodyUploadProgress(
  5732. [](Server &svr) {
  5733. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5734. res.set_content("patch received", "text/plain");
  5735. });
  5736. },
  5737. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5738. return cli.Patch("/test", body, "text/plain", progress_callback);
  5739. },
  5740. "patch test data for upload progress");
  5741. }
  5742. // Helper function for content provider upload progress tests
  5743. template <typename SetupHandler, typename ClientCall>
  5744. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5745. ClientCall &&client_call) {
  5746. Server svr;
  5747. setup_handler(svr);
  5748. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5749. auto se = detail::scope_exit([&] {
  5750. svr.stop();
  5751. t.join();
  5752. });
  5753. svr.wait_until_ready();
  5754. Client cli(HOST, PORT);
  5755. vector<uint64_t> progress_values;
  5756. auto res =
  5757. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5758. progress_values.push_back(current);
  5759. return true;
  5760. });
  5761. ASSERT_TRUE(res);
  5762. EXPECT_EQ(200, res->status);
  5763. EXPECT_FALSE(progress_values.empty());
  5764. }
  5765. TEST(UploadProgressTest, PostContentProviderProgress) {
  5766. TestContentProviderUploadProgress(
  5767. [](Server &svr) {
  5768. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5769. res.set_content("provider received", "text/plain");
  5770. });
  5771. },
  5772. [](Client &cli, UploadProgress progress_callback) {
  5773. return cli.Post(
  5774. "/test", 10,
  5775. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5776. sink.os << "test data";
  5777. return true;
  5778. },
  5779. "text/plain", progress_callback);
  5780. });
  5781. }
  5782. // Helper function for multipart upload progress tests
  5783. template <typename SetupHandler, typename ClientCall>
  5784. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5785. ClientCall &&client_call,
  5786. const string &endpoint) {
  5787. Server svr;
  5788. setup_handler(svr);
  5789. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5790. auto se = detail::scope_exit([&] {
  5791. svr.stop();
  5792. t.join();
  5793. });
  5794. svr.wait_until_ready();
  5795. Client cli(HOST, PORT);
  5796. vector<uint64_t> progress_values;
  5797. UploadFormDataItems items = {
  5798. {"field1", "value1", "", ""},
  5799. {"field2", "longer value for progress tracking test", "", ""},
  5800. {"file1", "file content data for upload progress", "test.txt",
  5801. "text/plain"}};
  5802. auto res = client_call(cli, endpoint, items,
  5803. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5804. progress_values.push_back(current);
  5805. return true;
  5806. });
  5807. ASSERT_TRUE(res);
  5808. EXPECT_EQ(200, res->status);
  5809. EXPECT_FALSE(progress_values.empty());
  5810. }
  5811. TEST(UploadProgressTest, PostMultipartProgress) {
  5812. TestMultipartUploadProgress(
  5813. [](Server &svr) {
  5814. svr.Post("/multipart", [](const Request &req, Response &res) {
  5815. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5816. res.set_content("multipart received", "text/plain");
  5817. });
  5818. },
  5819. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5820. UploadProgress progress_callback) {
  5821. return cli.Post(endpoint, items, progress_callback);
  5822. },
  5823. "/multipart");
  5824. }
  5825. // Helper function for basic download progress tests
  5826. template <typename SetupHandler, typename ClientCall>
  5827. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5828. ClientCall &&client_call, const string &endpoint,
  5829. size_t expected_content_size) {
  5830. Server svr;
  5831. setup_handler(svr);
  5832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5833. auto se = detail::scope_exit([&] {
  5834. svr.stop();
  5835. t.join();
  5836. });
  5837. svr.wait_until_ready();
  5838. Client cli(HOST, PORT);
  5839. vector<uint64_t> progress_values;
  5840. auto res = client_call(cli, endpoint,
  5841. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5842. progress_values.push_back(current);
  5843. return true;
  5844. });
  5845. ASSERT_TRUE(res);
  5846. EXPECT_EQ(200, res->status);
  5847. EXPECT_FALSE(progress_values.empty());
  5848. EXPECT_EQ(expected_content_size, res->body.size());
  5849. }
  5850. TEST(DownloadProgressTest, GetBasic) {
  5851. TestBasicDownloadProgress(
  5852. [](Server &svr) {
  5853. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5854. string content(1000, 'D');
  5855. res.set_content(content, "text/plain");
  5856. });
  5857. },
  5858. [](Client &cli, const string &endpoint,
  5859. DownloadProgress progress_callback) {
  5860. return cli.Get(endpoint, progress_callback);
  5861. },
  5862. "/download", 1000u);
  5863. }
  5864. // Helper function for content receiver download progress tests
  5865. template <typename SetupHandler, typename ClientCall>
  5866. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5867. ClientCall &&client_call,
  5868. const string &endpoint,
  5869. size_t expected_content_size) {
  5870. Server svr;
  5871. setup_handler(svr);
  5872. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5873. auto se = detail::scope_exit([&] {
  5874. svr.stop();
  5875. t.join();
  5876. });
  5877. svr.wait_until_ready();
  5878. Client cli(HOST, PORT);
  5879. vector<uint64_t> progress_values;
  5880. string received_body;
  5881. auto res = client_call(
  5882. cli, endpoint,
  5883. [&](const char *data, size_t data_length) -> bool {
  5884. received_body.append(data, data_length);
  5885. return true;
  5886. },
  5887. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5888. progress_values.push_back(current);
  5889. return true;
  5890. });
  5891. ASSERT_TRUE(res);
  5892. EXPECT_EQ(200, res->status);
  5893. EXPECT_FALSE(progress_values.empty());
  5894. EXPECT_EQ(expected_content_size, received_body.size());
  5895. EXPECT_TRUE(res->body.empty());
  5896. }
  5897. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5898. TestContentReceiverDownloadProgress(
  5899. [](Server &svr) {
  5900. svr.Get("/download-receiver",
  5901. [](const Request & /*req*/, Response &res) {
  5902. string content(2000, 'R');
  5903. res.set_content(content, "text/plain");
  5904. });
  5905. },
  5906. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5907. DownloadProgress progress_callback) {
  5908. return cli.Get(endpoint, content_receiver, progress_callback);
  5909. },
  5910. "/download-receiver", 2000u);
  5911. }
  5912. TEST(StreamingTest, NoContentLengthStreaming) {
  5913. Server svr;
  5914. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5915. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5916. if (offset < 6) {
  5917. sink.os << (offset < 3 ? "a" : "b");
  5918. } else {
  5919. sink.done();
  5920. }
  5921. return true;
  5922. });
  5923. });
  5924. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5925. auto listen_se = detail::scope_exit([&] {
  5926. svr.stop();
  5927. listen_thread.join();
  5928. ASSERT_FALSE(svr.is_running());
  5929. });
  5930. svr.wait_until_ready();
  5931. Client client(HOST, PORT);
  5932. auto get_thread = std::thread([&client]() {
  5933. std::string s;
  5934. auto res =
  5935. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5936. s += std::string(data, len);
  5937. return true;
  5938. });
  5939. ASSERT_TRUE(res);
  5940. EXPECT_EQ(StatusCode::OK_200, res->status);
  5941. EXPECT_EQ("aaabbb", s);
  5942. });
  5943. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5944. // Give GET time to get a few messages.
  5945. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5946. }
  5947. TEST(MountTest, Unmount) {
  5948. Server svr;
  5949. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5950. auto se = detail::scope_exit([&] {
  5951. svr.stop();
  5952. listen_thread.join();
  5953. ASSERT_FALSE(svr.is_running());
  5954. });
  5955. svr.wait_until_ready();
  5956. Client cli("localhost", PORT);
  5957. svr.set_mount_point("/mount2", "./www2");
  5958. auto res = cli.Get("/");
  5959. ASSERT_TRUE(res);
  5960. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5961. res = cli.Get("/mount2/dir/test.html");
  5962. ASSERT_TRUE(res);
  5963. EXPECT_EQ(StatusCode::OK_200, res->status);
  5964. svr.set_mount_point("/", "./www");
  5965. res = cli.Get("/dir/");
  5966. ASSERT_TRUE(res);
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. svr.remove_mount_point("/");
  5969. res = cli.Get("/dir/");
  5970. ASSERT_TRUE(res);
  5971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5972. svr.remove_mount_point("/mount2");
  5973. res = cli.Get("/mount2/dir/test.html");
  5974. ASSERT_TRUE(res);
  5975. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5976. }
  5977. TEST(MountTest, Redicect) {
  5978. Server svr;
  5979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5980. auto se = detail::scope_exit([&] {
  5981. svr.stop();
  5982. listen_thread.join();
  5983. ASSERT_FALSE(svr.is_running());
  5984. });
  5985. svr.set_mount_point("/", "./www");
  5986. svr.wait_until_ready();
  5987. Client cli("localhost", PORT);
  5988. auto res = cli.Get("/dir/");
  5989. ASSERT_TRUE(res);
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. res = cli.Get("/dir");
  5992. ASSERT_TRUE(res);
  5993. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5994. res = cli.Get("/file");
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. res = cli.Get("/file/");
  5998. ASSERT_TRUE(res);
  5999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6000. cli.set_follow_location(true);
  6001. res = cli.Get("/dir");
  6002. ASSERT_TRUE(res);
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. }
  6005. TEST(MountTest, MultibytesPathName) {
  6006. Server svr;
  6007. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6008. auto se = detail::scope_exit([&] {
  6009. svr.stop();
  6010. listen_thread.join();
  6011. ASSERT_FALSE(svr.is_running());
  6012. });
  6013. svr.set_mount_point("/", "./www");
  6014. svr.wait_until_ready();
  6015. Client cli("localhost", PORT);
  6016. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6017. ASSERT_TRUE(res);
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6020. }
  6021. TEST(KeepAliveTest, ReadTimeout) {
  6022. Server svr;
  6023. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6024. std::this_thread::sleep_for(std::chrono::seconds(2));
  6025. res.set_content("a", "text/plain");
  6026. });
  6027. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6028. res.set_content("b", "text/plain");
  6029. });
  6030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6031. auto se = detail::scope_exit([&] {
  6032. svr.stop();
  6033. listen_thread.join();
  6034. ASSERT_FALSE(svr.is_running());
  6035. });
  6036. svr.wait_until_ready();
  6037. Client cli("localhost", PORT);
  6038. cli.set_keep_alive(true);
  6039. cli.set_read_timeout(std::chrono::seconds(1));
  6040. auto resa = cli.Get("/a");
  6041. ASSERT_FALSE(resa);
  6042. EXPECT_EQ(Error::Read, resa.error());
  6043. auto resb = cli.Get("/b");
  6044. ASSERT_TRUE(resb);
  6045. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6046. EXPECT_EQ("b", resb->body);
  6047. }
  6048. TEST(KeepAliveTest, MaxCount) {
  6049. size_t keep_alive_max_count = 3;
  6050. Server svr;
  6051. svr.set_keep_alive_max_count(keep_alive_max_count);
  6052. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6053. res.set_content("Hello World!", "text/plain");
  6054. });
  6055. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6056. auto se = detail::scope_exit([&] {
  6057. svr.stop();
  6058. listen_thread.join();
  6059. ASSERT_FALSE(svr.is_running());
  6060. });
  6061. svr.wait_until_ready();
  6062. Client cli(HOST, PORT);
  6063. cli.set_keep_alive(true);
  6064. for (size_t i = 0; i < 5; i++) {
  6065. auto result = cli.Get("/hi");
  6066. ASSERT_TRUE(result);
  6067. EXPECT_EQ(StatusCode::OK_200, result->status);
  6068. if (i == keep_alive_max_count - 1) {
  6069. EXPECT_EQ("close", result->get_header_value("Connection"));
  6070. } else {
  6071. EXPECT_FALSE(result->has_header("Connection"));
  6072. }
  6073. }
  6074. }
  6075. TEST(KeepAliveTest, Issue1041) {
  6076. Server svr;
  6077. svr.set_keep_alive_timeout(3);
  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. Client cli(HOST, PORT);
  6089. cli.set_keep_alive(true);
  6090. auto result = cli.Get("/hi");
  6091. ASSERT_TRUE(result);
  6092. EXPECT_EQ(StatusCode::OK_200, result->status);
  6093. std::this_thread::sleep_for(std::chrono::seconds(5));
  6094. result = cli.Get("/hi");
  6095. ASSERT_TRUE(result);
  6096. EXPECT_EQ(StatusCode::OK_200, result->status);
  6097. }
  6098. TEST(KeepAliveTest, Issue1959) {
  6099. Server svr;
  6100. svr.set_keep_alive_timeout(5);
  6101. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6102. res.set_content("a", "text/plain");
  6103. });
  6104. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6105. auto se = detail::scope_exit([&] {
  6106. if (!svr.is_running()) return;
  6107. svr.stop();
  6108. listen_thread.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. Client cli("localhost", PORT);
  6113. cli.set_keep_alive(true);
  6114. using namespace std::chrono;
  6115. auto start = steady_clock::now();
  6116. cli.Get("/a");
  6117. svr.stop();
  6118. listen_thread.join();
  6119. auto end = steady_clock::now();
  6120. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6121. EXPECT_LT(elapsed, 5000);
  6122. }
  6123. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6124. TEST(KeepAliveTest, SSLClientReconnection) {
  6125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6126. ASSERT_TRUE(svr.is_valid());
  6127. svr.set_keep_alive_timeout(1);
  6128. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6129. res.set_content("Hello World!", "text/plain");
  6130. });
  6131. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6132. auto se = detail::scope_exit([&] {
  6133. svr.stop();
  6134. listen_thread.join();
  6135. ASSERT_FALSE(svr.is_running());
  6136. });
  6137. svr.wait_until_ready();
  6138. SSLClient cli(HOST, PORT);
  6139. cli.enable_server_certificate_verification(false);
  6140. cli.set_keep_alive(true);
  6141. auto result = cli.Get("/hi");
  6142. ASSERT_TRUE(result);
  6143. EXPECT_EQ(StatusCode::OK_200, result->status);
  6144. result = cli.Get("/hi");
  6145. ASSERT_TRUE(result);
  6146. EXPECT_EQ(StatusCode::OK_200, result->status);
  6147. std::this_thread::sleep_for(std::chrono::seconds(2));
  6148. // Recoonect
  6149. result = cli.Get("/hi");
  6150. ASSERT_TRUE(result);
  6151. EXPECT_EQ(StatusCode::OK_200, result->status);
  6152. result = cli.Get("/hi");
  6153. ASSERT_TRUE(result);
  6154. EXPECT_EQ(StatusCode::OK_200, result->status);
  6155. }
  6156. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6158. ASSERT_TRUE(svr.is_valid());
  6159. svr.set_keep_alive_timeout(1);
  6160. std::string content = "reconnect";
  6161. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6162. res.set_content("Hello World!", "text/plain");
  6163. });
  6164. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6165. auto se = detail::scope_exit([&] {
  6166. svr.stop();
  6167. listen_thread.join();
  6168. ASSERT_FALSE(svr.is_running());
  6169. });
  6170. svr.wait_until_ready();
  6171. SSLClient cli(HOST, PORT);
  6172. cli.enable_server_certificate_verification(false);
  6173. cli.set_keep_alive(true);
  6174. auto result = cli.Post(
  6175. "/hi", content.size(),
  6176. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6177. sink.write(content.c_str(), content.size());
  6178. return true;
  6179. },
  6180. "text/plain");
  6181. ASSERT_TRUE(result);
  6182. EXPECT_EQ(200, result->status);
  6183. std::this_thread::sleep_for(std::chrono::seconds(2));
  6184. // Recoonect
  6185. result = cli.Post(
  6186. "/hi", content.size(),
  6187. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6188. sink.write(content.c_str(), content.size());
  6189. return true;
  6190. },
  6191. "text/plain");
  6192. ASSERT_TRUE(result);
  6193. EXPECT_EQ(200, result->status);
  6194. result = cli.Post(
  6195. "/hi", content.size(),
  6196. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6197. sink.write(content.c_str(), content.size());
  6198. return true;
  6199. },
  6200. "text/plain");
  6201. ASSERT_TRUE(result);
  6202. EXPECT_EQ(200, result->status);
  6203. }
  6204. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6205. {
  6206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6207. ASSERT_TRUE(svr.is_valid());
  6208. svr.Get("/sni", [&](const Request &req, Response &res) {
  6209. std::string expected;
  6210. if (req.ssl) {
  6211. if (const char *sni =
  6212. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6213. expected = sni;
  6214. }
  6215. }
  6216. EXPECT_EQ(expected, req.get_param_value("expected"));
  6217. res.set_content("ok", "text/plain");
  6218. });
  6219. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.wait_until_ready();
  6226. {
  6227. SSLClient cli("localhost", PORT);
  6228. cli.enable_server_certificate_verification(false);
  6229. auto res = cli.Get("/sni?expected=localhost");
  6230. ASSERT_TRUE(res);
  6231. }
  6232. {
  6233. SSLClient cli("::1", PORT);
  6234. cli.enable_server_certificate_verification(false);
  6235. auto res = cli.Get("/sni?expected=");
  6236. ASSERT_TRUE(res);
  6237. }
  6238. }
  6239. }
  6240. #endif
  6241. TEST(ClientProblemDetectionTest, ContentProvider) {
  6242. Server svr;
  6243. size_t content_length = 1024 * 1024;
  6244. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6245. res.set_content_provider(
  6246. content_length, "text/plain",
  6247. [&](size_t offset, size_t length, DataSink &sink) {
  6248. auto out_len = std::min(length, static_cast<size_t>(1024));
  6249. std::string out(out_len, '@');
  6250. sink.write(out.data(), out_len);
  6251. return offset < 4096;
  6252. },
  6253. [](bool success) { ASSERT_FALSE(success); });
  6254. });
  6255. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6256. res.set_content_provider(
  6257. 0, "text/plain",
  6258. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6259. EXPECT_TRUE(false);
  6260. return true;
  6261. },
  6262. [](bool success) { ASSERT_FALSE(success); });
  6263. });
  6264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6265. auto se = detail::scope_exit([&] {
  6266. svr.stop();
  6267. listen_thread.join();
  6268. ASSERT_FALSE(svr.is_running());
  6269. });
  6270. svr.wait_until_ready();
  6271. Client cli("localhost", PORT);
  6272. {
  6273. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6274. size_t /*data_length*/) { return false; });
  6275. ASSERT_FALSE(res);
  6276. }
  6277. {
  6278. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6279. size_t /*data_length*/) { return false; });
  6280. ASSERT_TRUE(res);
  6281. }
  6282. }
  6283. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6284. Server svr;
  6285. svr.set_error_handler([](Request const &, Response &res) -> void {
  6286. res.set_chunked_content_provider(
  6287. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6288. sink.os << "hello";
  6289. sink.os << "world";
  6290. sink.done();
  6291. return true;
  6292. });
  6293. });
  6294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6295. auto se = detail::scope_exit([&] {
  6296. svr.stop();
  6297. listen_thread.join();
  6298. ASSERT_FALSE(svr.is_running());
  6299. });
  6300. svr.wait_until_ready();
  6301. Client cli("localhost", PORT);
  6302. auto res = cli.Get("/");
  6303. ASSERT_TRUE(res);
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. EXPECT_EQ("helloworld", res->body);
  6306. }
  6307. TEST(LongPollingTest, ClientCloseDetection) {
  6308. Server svr;
  6309. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6310. res.set_chunked_content_provider(
  6311. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6312. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6313. sink.os << "hello";
  6314. auto count = 10;
  6315. while (count > 0 && sink.is_writable()) {
  6316. this_thread::sleep_for(chrono::milliseconds(10));
  6317. count--;
  6318. }
  6319. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6320. return true;
  6321. });
  6322. });
  6323. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6324. auto se = detail::scope_exit([&] {
  6325. svr.stop();
  6326. listen_thread.join();
  6327. ASSERT_FALSE(svr.is_running());
  6328. });
  6329. svr.wait_until_ready();
  6330. Client cli("localhost", PORT);
  6331. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6332. EXPECT_EQ("hello", string(data, data_length));
  6333. return false; // close the socket immediately.
  6334. });
  6335. ASSERT_FALSE(res);
  6336. }
  6337. TEST(GetWithParametersTest, GetWithParameters) {
  6338. Server svr;
  6339. svr.Get("/", [&](const Request &req, Response &) {
  6340. EXPECT_EQ("world", req.get_param_value("hello"));
  6341. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6342. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6343. });
  6344. svr.Get("/params", [&](const Request &req, Response &) {
  6345. EXPECT_EQ("world", req.get_param_value("hello"));
  6346. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6347. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6348. });
  6349. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6350. EXPECT_EQ("resource-id", req.matches[1]);
  6351. EXPECT_EQ("foo", req.get_param_value("param1"));
  6352. EXPECT_EQ("bar", req.get_param_value("param2"));
  6353. });
  6354. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6355. EXPECT_EQ("user-id", req.path_params.at("id"));
  6356. EXPECT_EQ("foo", req.get_param_value("param1"));
  6357. EXPECT_EQ("bar", req.get_param_value("param2"));
  6358. });
  6359. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6360. auto se = detail::scope_exit([&] {
  6361. svr.stop();
  6362. listen_thread.join();
  6363. ASSERT_FALSE(svr.is_running());
  6364. });
  6365. svr.wait_until_ready();
  6366. {
  6367. Client cli(HOST, PORT);
  6368. Params params;
  6369. params.emplace("hello", "world");
  6370. params.emplace("hello2", "world2");
  6371. params.emplace("hello3", "world3");
  6372. auto res = cli.Get("/", params, Headers{});
  6373. ASSERT_TRUE(res);
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. }
  6376. {
  6377. Client cli(HOST, PORT);
  6378. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6379. ASSERT_TRUE(res);
  6380. EXPECT_EQ(StatusCode::OK_200, res->status);
  6381. }
  6382. {
  6383. Client cli(HOST, PORT);
  6384. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6385. ASSERT_TRUE(res);
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. }
  6388. {
  6389. Client cli(HOST, PORT);
  6390. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6391. ASSERT_TRUE(res);
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. }
  6395. TEST(GetWithParametersTest, GetWithParameters2) {
  6396. Server svr;
  6397. svr.Get("/", [&](const Request &req, Response &res) {
  6398. auto text = req.get_param_value("hello");
  6399. res.set_content(text, "text/plain");
  6400. });
  6401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6402. auto se = detail::scope_exit([&] {
  6403. svr.stop();
  6404. listen_thread.join();
  6405. ASSERT_FALSE(svr.is_running());
  6406. });
  6407. svr.wait_until_ready();
  6408. Client cli("localhost", PORT);
  6409. Params params;
  6410. params.emplace("hello", "world");
  6411. std::string body;
  6412. auto res = cli.Get("/", params, Headers{},
  6413. [&](const char *data, size_t data_length) {
  6414. body.append(data, data_length);
  6415. return true;
  6416. });
  6417. ASSERT_TRUE(res);
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("world", body);
  6420. }
  6421. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6422. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6423. auto host = "httpbin.org";
  6424. auto path = std::string{"/range/32"};
  6425. #else
  6426. auto host = "nghttp2.org";
  6427. auto path = std::string{"/httpbin/range/32"};
  6428. #endif
  6429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6430. SSLClient cli(host);
  6431. #else
  6432. Client cli(host);
  6433. #endif
  6434. cli.set_default_headers({make_range_header({{1, 10}})});
  6435. cli.set_connection_timeout(5);
  6436. {
  6437. auto res = cli.Get(path);
  6438. ASSERT_TRUE(res);
  6439. EXPECT_EQ("bcdefghijk", res->body);
  6440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6441. }
  6442. {
  6443. auto res = cli.Get(path);
  6444. ASSERT_TRUE(res);
  6445. EXPECT_EQ("bcdefghijk", res->body);
  6446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6447. }
  6448. }
  6449. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6450. Server svr;
  6451. svr.set_default_headers({{"Hello", "World"}});
  6452. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6453. res.set_content("ok", "text/plain");
  6454. });
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client cli("localhost", PORT);
  6463. auto res = cli.Get("/");
  6464. ASSERT_TRUE(res);
  6465. EXPECT_EQ(StatusCode::OK_200, res->status);
  6466. EXPECT_EQ("ok", res->body);
  6467. EXPECT_EQ("World", res->get_header_value("Hello"));
  6468. }
  6469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6470. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6472. ASSERT_TRUE(svr.is_valid());
  6473. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6474. std::this_thread::sleep_for(std::chrono::seconds(2));
  6475. res.set_content("a", "text/plain");
  6476. });
  6477. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6478. res.set_content("b", "text/plain");
  6479. });
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. SSLClient cli("localhost", PORT);
  6488. cli.enable_server_certificate_verification(false);
  6489. cli.set_keep_alive(true);
  6490. cli.set_read_timeout(std::chrono::seconds(1));
  6491. auto resa = cli.Get("/a");
  6492. ASSERT_TRUE(!resa);
  6493. EXPECT_EQ(Error::Read, resa.error());
  6494. auto resb = cli.Get("/b");
  6495. ASSERT_TRUE(resb);
  6496. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6497. EXPECT_EQ("b", resb->body);
  6498. }
  6499. #endif
  6500. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6501. protected:
  6502. ServerTestWithAI_PASSIVE()
  6503. : cli_(HOST, PORT)
  6504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6505. ,
  6506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6507. #endif
  6508. {
  6509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6510. cli_.enable_server_certificate_verification(false);
  6511. #endif
  6512. }
  6513. virtual void SetUp() {
  6514. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6515. res.set_content("Hello World!", "text/plain");
  6516. });
  6517. t_ = thread(
  6518. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6519. svr_.wait_until_ready();
  6520. }
  6521. virtual void TearDown() {
  6522. svr_.stop();
  6523. t_.join();
  6524. }
  6525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6526. SSLClient cli_;
  6527. SSLServer svr_;
  6528. #else
  6529. Client cli_;
  6530. Server svr_;
  6531. #endif
  6532. thread t_;
  6533. };
  6534. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6535. auto res = cli_.Get("/hi");
  6536. ASSERT_TRUE(res);
  6537. EXPECT_EQ(StatusCode::OK_200, res->status);
  6538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6539. EXPECT_EQ("Hello World!", res->body);
  6540. }
  6541. class ServerUpDownTest : public ::testing::Test {
  6542. protected:
  6543. ServerUpDownTest() : cli_(HOST, PORT) {}
  6544. virtual void SetUp() {
  6545. t_ = thread([&]() {
  6546. svr_.bind_to_any_port(HOST);
  6547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6548. ASSERT_TRUE(svr_.listen_after_bind());
  6549. });
  6550. svr_.wait_until_ready();
  6551. }
  6552. virtual void TearDown() {
  6553. svr_.stop();
  6554. t_.join();
  6555. }
  6556. Client cli_;
  6557. Server svr_;
  6558. thread t_;
  6559. };
  6560. TEST_F(ServerUpDownTest, QuickStartStop) {
  6561. // Should not crash, especially when run with
  6562. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6563. }
  6564. class PayloadMaxLengthTest : public ::testing::Test {
  6565. protected:
  6566. PayloadMaxLengthTest()
  6567. : cli_(HOST, PORT)
  6568. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6569. ,
  6570. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6571. #endif
  6572. {
  6573. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6574. cli_.enable_server_certificate_verification(false);
  6575. #endif
  6576. }
  6577. virtual void SetUp() {
  6578. svr_.set_payload_max_length(8);
  6579. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6580. res.set_content("test", "text/plain");
  6581. });
  6582. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6583. svr_.wait_until_ready();
  6584. }
  6585. virtual void TearDown() {
  6586. svr_.stop();
  6587. t_.join();
  6588. }
  6589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6590. SSLClient cli_;
  6591. SSLServer svr_;
  6592. #else
  6593. Client cli_;
  6594. Server svr_;
  6595. #endif
  6596. thread t_;
  6597. };
  6598. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6599. auto res = cli_.Post("/test", "123456789", "text/plain");
  6600. ASSERT_TRUE(res);
  6601. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6602. res = cli_.Post("/test", "12345678", "text/plain");
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. }
  6606. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6607. // Test chunked encoding with payload exceeding the 8-byte limit
  6608. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6609. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6610. ASSERT_TRUE(res);
  6611. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6612. }
  6613. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6614. // Test chunked encoding with payload within the 8-byte limit
  6615. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6616. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6617. ASSERT_TRUE(res);
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. }
  6620. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6621. // Test using send_request to send chunked data exceeding payload limit
  6622. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6623. "Host: " +
  6624. std::string(HOST) + ":" + std::to_string(PORT) +
  6625. "\r\n"
  6626. "Transfer-Encoding: chunked\r\n"
  6627. "Connection: close\r\n"
  6628. "\r\n"
  6629. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6630. "0123456789\r\n"
  6631. "0\r\n" // End chunk
  6632. "\r\n";
  6633. std::string response;
  6634. bool result = send_request(1, chunked_request, &response);
  6635. if (!result) {
  6636. // If send_request fails, it might be because the server closed the
  6637. // connection due to payload limit enforcement, which is acceptable
  6638. SUCCEED()
  6639. << "Server rejected oversized chunked request (connection closed)";
  6640. } else {
  6641. // If we got a response, check if it's an error response or connection was
  6642. // closed early Short response length indicates connection was closed due to
  6643. // payload limit
  6644. if (response.length() <= 10) {
  6645. SUCCEED() << "Server closed connection for oversized chunked request";
  6646. } else {
  6647. // Check for error status codes
  6648. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6649. response.find("Payload Too Large") != std::string::npos ||
  6650. response.find("400") != std::string::npos);
  6651. }
  6652. }
  6653. }
  6654. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6655. // Test request without Content-Length header exceeding payload limit
  6656. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6657. "Host: " +
  6658. std::string(HOST) + ":" +
  6659. std::to_string(PORT) +
  6660. "\r\n"
  6661. "Connection: close\r\n"
  6662. "\r\n";
  6663. // Add payload exceeding the 8-byte limit
  6664. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6665. request_without_content_length += large_payload;
  6666. std::string response;
  6667. bool result = send_request(1, request_without_content_length, &response);
  6668. if (!result) {
  6669. // If send_request fails, server likely closed connection due to payload
  6670. // limit
  6671. SUCCEED() << "Server rejected oversized request without Content-Length "
  6672. "(connection closed)";
  6673. } else {
  6674. // Check if server responded with error or closed connection early
  6675. if (response.length() <= 10) {
  6676. SUCCEED() << "Server closed connection for oversized request without "
  6677. "Content-Length";
  6678. } else {
  6679. // Check for error status codes
  6680. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6681. response.find("Payload Too Large") != std::string::npos ||
  6682. response.find("400") != std::string::npos);
  6683. }
  6684. }
  6685. }
  6686. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6687. // Test request without Content-Length header within payload limit
  6688. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6689. "Host: " +
  6690. std::string(HOST) + ":" +
  6691. std::to_string(PORT) +
  6692. "\r\n"
  6693. "Connection: close\r\n"
  6694. "\r\n";
  6695. // Add payload within the 8-byte limit
  6696. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6697. request_without_content_length += small_payload;
  6698. std::string response;
  6699. bool result = send_request(1, request_without_content_length, &response);
  6700. // For requests without Content-Length, the server may have different behavior
  6701. // The key is that it should not reject due to payload limit for small
  6702. // payloads
  6703. if (result) {
  6704. // Check for any HTTP response (success or error, but not connection closed)
  6705. if (response.length() > 10) {
  6706. SUCCEED()
  6707. << "Server processed request without Content-Length within limit";
  6708. } else {
  6709. // Short response might indicate connection closed, which is acceptable
  6710. SUCCEED() << "Server closed connection for request without "
  6711. "Content-Length (acceptable behavior)";
  6712. }
  6713. } else {
  6714. // Connection failure might be due to protocol requirements
  6715. SUCCEED() << "Connection issue with request without Content-Length "
  6716. "(environment-specific)";
  6717. }
  6718. }
  6719. class LargePayloadMaxLengthTest : public ::testing::Test {
  6720. protected:
  6721. LargePayloadMaxLengthTest()
  6722. : cli_(HOST, PORT)
  6723. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6724. ,
  6725. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6726. #endif
  6727. {
  6728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6729. cli_.enable_server_certificate_verification(false);
  6730. #endif
  6731. }
  6732. virtual void SetUp() {
  6733. // Set 10MB payload limit
  6734. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6735. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6736. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6737. res.set_content("Large payload test", "text/plain");
  6738. });
  6739. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6740. svr_.wait_until_ready();
  6741. }
  6742. virtual void TearDown() {
  6743. svr_.stop();
  6744. t_.join();
  6745. }
  6746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6747. SSLClient cli_;
  6748. SSLServer svr_;
  6749. #else
  6750. Client cli_;
  6751. Server svr_;
  6752. #endif
  6753. thread t_;
  6754. };
  6755. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6756. // Test chunked encoding with payload within 10MB limit
  6757. std::string medium_payload(5 * 1024 * 1024,
  6758. 'A'); // 5MB payload, within 10MB limit
  6759. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6760. ASSERT_TRUE(res);
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6764. // Test chunked encoding with payload exceeding 10MB limit
  6765. std::string large_payload(12 * 1024 * 1024,
  6766. 'B'); // 12MB payload, exceeds 10MB limit
  6767. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6768. ASSERT_TRUE(res);
  6769. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6770. }
  6771. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6772. // Test request without Content-Length header within 10MB limit
  6773. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6774. "Host: " +
  6775. std::string(HOST) + ":" +
  6776. std::to_string(PORT) +
  6777. "\r\n"
  6778. "Connection: close\r\n"
  6779. "\r\n";
  6780. // Add 1MB payload (within 10MB limit)
  6781. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6782. request_without_content_length += medium_payload;
  6783. std::string response;
  6784. bool result = send_request(5, request_without_content_length, &response);
  6785. if (result) {
  6786. // Should get a proper HTTP response for payloads within limit
  6787. if (response.length() > 10) {
  6788. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6789. "10MB limit";
  6790. } else {
  6791. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6792. "Content-Length)";
  6793. }
  6794. } else {
  6795. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6796. }
  6797. }
  6798. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6799. // Test request without Content-Length header exceeding 10MB limit
  6800. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6801. "Host: " +
  6802. std::string(HOST) + ":" +
  6803. std::to_string(PORT) +
  6804. "\r\n"
  6805. "Connection: close\r\n"
  6806. "\r\n";
  6807. // Add 12MB payload (exceeds 10MB limit)
  6808. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6809. request_without_content_length += large_payload;
  6810. std::string response;
  6811. bool result = send_request(10, request_without_content_length, &response);
  6812. if (!result) {
  6813. // Server should close connection due to payload limit
  6814. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6815. "(connection closed)";
  6816. } else {
  6817. // Check for error response
  6818. if (response.length() <= 10) {
  6819. SUCCEED()
  6820. << "Server closed connection for 12MB request exceeding 10MB limit";
  6821. } else {
  6822. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6823. response.find("Payload Too Large") != std::string::npos ||
  6824. response.find("400") != std::string::npos);
  6825. }
  6826. }
  6827. }
  6828. TEST(HostAndPortPropertiesTest, NoSSL) {
  6829. httplib::Client cli("www.google.com", 1234);
  6830. ASSERT_EQ("www.google.com", cli.host());
  6831. ASSERT_EQ(1234, cli.port());
  6832. }
  6833. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6834. httplib::Client cli("www.google.com:1234");
  6835. ASSERT_EQ("www.google.com", cli.host());
  6836. ASSERT_EQ(1234, cli.port());
  6837. }
  6838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6839. TEST(HostAndPortPropertiesTest, SSL) {
  6840. httplib::SSLClient cli("www.google.com");
  6841. ASSERT_EQ("www.google.com", cli.host());
  6842. ASSERT_EQ(443, cli.port());
  6843. }
  6844. #endif
  6845. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6846. TEST(SSLClientTest, UpdateCAStore) {
  6847. httplib::SSLClient httplib_client("www.google.com");
  6848. auto ca_store_1 = X509_STORE_new();
  6849. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6850. nullptr);
  6851. httplib_client.set_ca_cert_store(ca_store_1);
  6852. auto ca_store_2 = X509_STORE_new();
  6853. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6854. nullptr);
  6855. httplib_client.set_ca_cert_store(ca_store_2);
  6856. }
  6857. TEST(SSLClientTest, ServerNameIndication_Online) {
  6858. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6859. auto host = "httpbin.org";
  6860. auto path = std::string{"/get"};
  6861. #else
  6862. auto host = "nghttp2.org";
  6863. auto path = std::string{"/httpbin/get"};
  6864. #endif
  6865. SSLClient cli(host, 443);
  6866. auto res = cli.Get(path);
  6867. ASSERT_TRUE(res);
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6871. // Use a site that will cause SSL verification failure due to self-signed cert
  6872. SSLClient cli("self-signed.badssl.com", 443);
  6873. cli.enable_server_certificate_verification(true);
  6874. auto res = cli.Get("/");
  6875. ASSERT_TRUE(!res);
  6876. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6877. // For SSL server verification errors, ssl_error should be 0, only
  6878. // ssl_openssl_error should be set
  6879. EXPECT_EQ(0, res.ssl_error());
  6880. // Verify OpenSSL error is captured for SSLServerVerification
  6881. // This occurs when SSL_get_verify_result() returns a verification failure
  6882. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6883. res.ssl_openssl_error());
  6884. }
  6885. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6886. // Use a site where hostname doesn't match the certificate
  6887. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6888. SSLClient cli("wrong.host.badssl.com", 443);
  6889. cli.enable_server_certificate_verification(true);
  6890. cli.enable_server_hostname_verification(true);
  6891. auto res = cli.Get("/");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6894. // For SSL hostname verification errors, ssl_error should be 0, only
  6895. // ssl_openssl_error should be set
  6896. EXPECT_EQ(0, res.ssl_error());
  6897. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6898. // This occurs when verify_host() fails due to hostname mismatch
  6899. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6900. res.ssl_openssl_error());
  6901. }
  6902. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6903. Client cli("https://google.com");
  6904. auto res = cli.Get("/");
  6905. ASSERT_TRUE(res);
  6906. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6907. }
  6908. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6909. SSLClient cli("google.com");
  6910. cli.set_ca_cert_path(CA_CERT_FILE);
  6911. auto res = cli.Get("/");
  6912. ASSERT_TRUE(res);
  6913. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6914. }
  6915. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6916. SSLClient cli("google.com");
  6917. cli.enable_server_certificate_verification(true);
  6918. cli.set_ca_cert_path("hello");
  6919. auto res = cli.Get("/");
  6920. ASSERT_TRUE(!res);
  6921. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6922. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6923. // should be set
  6924. EXPECT_EQ(0, res.ssl_error());
  6925. // Verify OpenSSL error is captured for SSLLoadingCerts
  6926. // This error occurs when SSL_CTX_load_verify_locations() fails
  6927. // > openssl errstr 0x80000002
  6928. // error:80000002:system library::No such file or directory
  6929. // > openssl errstr 0xA000126
  6930. // error:0A000126:SSL routines::unexpected eof while reading
  6931. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6932. res.ssl_openssl_error() == 0xA000126);
  6933. }
  6934. TEST(SSLClientTest, ServerCertificateVerification4) {
  6935. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6936. ASSERT_TRUE(svr.is_valid());
  6937. svr.Get("/test", [&](const Request &, Response &res) {
  6938. res.set_content("test", "text/plain");
  6939. svr.stop();
  6940. ASSERT_TRUE(true);
  6941. });
  6942. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6943. auto se = detail::scope_exit([&] {
  6944. t.join();
  6945. ASSERT_FALSE(svr.is_running());
  6946. });
  6947. svr.wait_until_ready();
  6948. SSLClient cli("127.0.0.1", PORT);
  6949. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6950. cli.enable_server_certificate_verification(true);
  6951. cli.set_connection_timeout(30);
  6952. auto res = cli.Get("/test");
  6953. ASSERT_TRUE(res);
  6954. ASSERT_EQ(StatusCode::OK_200, res->status);
  6955. }
  6956. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6957. std::string cert;
  6958. read_file(CA_CERT_FILE, cert);
  6959. SSLClient cli("google.com");
  6960. cli.load_ca_cert_store(cert.data(), cert.size());
  6961. const auto res = cli.Get("/");
  6962. ASSERT_TRUE(res);
  6963. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6964. }
  6965. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6966. // clang-format off
  6967. static constexpr char cert[] =
  6968. "GlobalSign Root CA\n"
  6969. "==================\n"
  6970. "-----BEGIN CERTIFICATE-----\n"
  6971. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6972. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6973. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6974. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6975. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6976. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6977. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6978. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6979. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6980. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6981. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6982. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6983. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6984. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6985. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6986. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6987. "-----END CERTIFICATE-----\n";
  6988. // clang-format on
  6989. SSLClient cli("google.com");
  6990. cli.load_ca_cert_store(cert, sizeof(cert));
  6991. const auto res = cli.Get("/");
  6992. ASSERT_TRUE(res);
  6993. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6994. }
  6995. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6996. SSLClient cli("www.youtube.com");
  6997. cli.set_ca_cert_path(CA_CERT_FILE);
  6998. cli.enable_server_certificate_verification(true);
  6999. cli.set_follow_location(true);
  7000. auto res = cli.Get("/");
  7001. ASSERT_TRUE(res);
  7002. ASSERT_EQ(StatusCode::OK_200, res->status);
  7003. }
  7004. TEST(SSLClientTest, Issue2004_Online) {
  7005. Client client("https://google.com");
  7006. client.set_follow_location(true);
  7007. auto res = client.Get("/");
  7008. ASSERT_TRUE(res);
  7009. ASSERT_EQ(StatusCode::OK_200, res->status);
  7010. auto body = res->body;
  7011. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7012. }
  7013. #if 0
  7014. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7015. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7016. ASSERT_TRUE(cli != nullptr);
  7017. cli->set_address_family(AF_INET6);
  7018. cli->set_interface("en0");
  7019. auto res = cli->Get("/get");
  7020. ASSERT_TRUE(res);
  7021. ASSERT_EQ(StatusCode::OK_200, res->status);
  7022. }
  7023. #endif
  7024. void ClientCertPresent(
  7025. const std::string &client_cert_file,
  7026. const std::string &client_private_key_file,
  7027. const std::string &client_encrypted_private_key_pass = std::string()) {
  7028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7029. CLIENT_CA_CERT_DIR);
  7030. ASSERT_TRUE(svr.is_valid());
  7031. svr.Get("/test", [&](const Request &req, Response &res) {
  7032. res.set_content("test", "text/plain");
  7033. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7034. ASSERT_TRUE(peer_cert != nullptr);
  7035. auto subject_name = X509_get_subject_name(peer_cert);
  7036. ASSERT_TRUE(subject_name != nullptr);
  7037. std::string common_name;
  7038. {
  7039. char name[BUFSIZ];
  7040. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7041. name, sizeof(name));
  7042. common_name.assign(name, static_cast<size_t>(name_len));
  7043. }
  7044. EXPECT_EQ("Common Name", common_name);
  7045. X509_free(peer_cert);
  7046. });
  7047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7048. auto se = detail::scope_exit([&] {
  7049. svr.stop();
  7050. t.join();
  7051. ASSERT_FALSE(svr.is_running());
  7052. });
  7053. svr.wait_until_ready();
  7054. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7055. client_encrypted_private_key_pass);
  7056. cli.enable_server_certificate_verification(false);
  7057. cli.set_connection_timeout(30);
  7058. auto res = cli.Get("/test");
  7059. ASSERT_TRUE(res);
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST(SSLClientServerTest, ClientCertPresent) {
  7063. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7064. }
  7065. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7066. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7067. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7068. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7069. }
  7070. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7071. void MemoryClientCertPresent(
  7072. const std::string &client_cert_file,
  7073. const std::string &client_private_key_file,
  7074. const std::string &client_encrypted_private_key_pass = std::string()) {
  7075. auto f = fopen(SERVER_CERT_FILE, "r+");
  7076. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7077. fclose(f);
  7078. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7079. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7080. fclose(f);
  7081. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7082. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7083. auto client_ca_cert_store = X509_STORE_new();
  7084. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7085. X509_free(client_cert);
  7086. fclose(f);
  7087. f = fopen(client_cert_file.c_str(), "r+");
  7088. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7089. fclose(f);
  7090. f = fopen(client_private_key_file.c_str(), "r+");
  7091. auto client_private_key = PEM_read_PrivateKey(
  7092. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7093. fclose(f);
  7094. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7095. ASSERT_TRUE(svr.is_valid());
  7096. svr.Get("/test", [&](const Request &req, Response &res) {
  7097. res.set_content("test", "text/plain");
  7098. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7099. ASSERT_TRUE(peer_cert != nullptr);
  7100. auto subject_name = X509_get_subject_name(peer_cert);
  7101. ASSERT_TRUE(subject_name != nullptr);
  7102. std::string common_name;
  7103. {
  7104. char name[BUFSIZ];
  7105. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7106. name, sizeof(name));
  7107. common_name.assign(name, static_cast<size_t>(name_len));
  7108. }
  7109. EXPECT_EQ("Common Name", common_name);
  7110. X509_free(peer_cert);
  7111. });
  7112. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7113. auto se = detail::scope_exit([&] {
  7114. svr.stop();
  7115. t.join();
  7116. ASSERT_FALSE(svr.is_running());
  7117. });
  7118. svr.wait_until_ready();
  7119. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7120. client_encrypted_private_key_pass);
  7121. cli.enable_server_certificate_verification(false);
  7122. cli.set_connection_timeout(30);
  7123. auto res = cli.Get("/test");
  7124. ASSERT_TRUE(res);
  7125. ASSERT_EQ(StatusCode::OK_200, res->status);
  7126. X509_free(server_cert);
  7127. EVP_PKEY_free(server_private_key);
  7128. X509_free(client_cert);
  7129. EVP_PKEY_free(client_private_key);
  7130. }
  7131. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7132. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7133. }
  7134. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7135. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7136. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7137. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7138. }
  7139. #endif
  7140. TEST(SSLClientServerTest, ClientCertMissing) {
  7141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7142. CLIENT_CA_CERT_DIR);
  7143. ASSERT_TRUE(svr.is_valid());
  7144. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7146. auto se = detail::scope_exit([&] {
  7147. svr.stop();
  7148. t.join();
  7149. ASSERT_FALSE(svr.is_running());
  7150. });
  7151. svr.wait_until_ready();
  7152. SSLClient cli(HOST, PORT);
  7153. cli.set_connection_timeout(30);
  7154. auto res = cli.Get("/test");
  7155. ASSERT_TRUE(!res);
  7156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7157. // For SSL server verification errors, ssl_error should be 0, only
  7158. // ssl_openssl_error should be set
  7159. EXPECT_EQ(0, res.ssl_error());
  7160. // Verify OpenSSL error is captured for SSLServerVerification
  7161. // Note: This test may have different error codes depending on the exact
  7162. // verification failure
  7163. EXPECT_NE(0UL, res.ssl_openssl_error());
  7164. }
  7165. TEST(SSLClientServerTest, TrustDirOptional) {
  7166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7167. ASSERT_TRUE(svr.is_valid());
  7168. svr.Get("/test", [&](const Request &, Response &res) {
  7169. res.set_content("test", "text/plain");
  7170. });
  7171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7172. auto se = detail::scope_exit([&] {
  7173. svr.stop();
  7174. t.join();
  7175. ASSERT_FALSE(svr.is_running());
  7176. });
  7177. svr.wait_until_ready();
  7178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7179. cli.enable_server_certificate_verification(false);
  7180. cli.set_connection_timeout(30);
  7181. auto res = cli.Get("/test");
  7182. ASSERT_TRUE(res);
  7183. ASSERT_EQ(StatusCode::OK_200, res->status);
  7184. }
  7185. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7186. class NoListenSSLServer : public SSLServer {
  7187. public:
  7188. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7189. const char *client_ca_cert_file_path,
  7190. const char *client_ca_cert_dir_path = nullptr)
  7191. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7192. client_ca_cert_dir_path),
  7193. stop_(false) {}
  7194. std::atomic_bool stop_;
  7195. private:
  7196. bool process_and_close_socket(socket_t /*sock*/) override {
  7197. // Don't create SSL context
  7198. while (!stop_.load()) {
  7199. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7200. }
  7201. return true;
  7202. }
  7203. };
  7204. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7205. CLIENT_CA_CERT_FILE);
  7206. ASSERT_TRUE(svr.is_valid());
  7207. svr.Get("/test", [&](const Request &, Response &res) {
  7208. res.set_content("test", "text/plain");
  7209. });
  7210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7211. auto se = detail::scope_exit([&] {
  7212. svr.stop_ = true;
  7213. svr.stop();
  7214. t.join();
  7215. ASSERT_FALSE(svr.is_running());
  7216. });
  7217. svr.wait_until_ready();
  7218. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7219. cli.enable_server_certificate_verification(false);
  7220. cli.set_connection_timeout(1);
  7221. auto res = cli.Get("/test");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::SSLConnection, res.error());
  7224. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7225. }
  7226. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7227. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7228. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7229. SSL_CTX_set_options(&ssl_ctx,
  7230. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7231. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7232. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7233. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7234. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7235. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7236. "ECDHE-DSS-AES128-SHA256:"
  7237. "ECDHE-RSA-AES256-SHA256:"
  7238. "ECDHE-DSS-AES256-SHA256:";
  7239. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7240. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7241. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7242. SSL_FILETYPE_PEM) != 1) {
  7243. return false;
  7244. }
  7245. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7246. CLIENT_CA_CERT_DIR);
  7247. SSL_CTX_set_verify(
  7248. &ssl_ctx,
  7249. SSL_VERIFY_PEER |
  7250. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7251. nullptr);
  7252. return true;
  7253. };
  7254. SSLServer svr(setup_ssl_ctx_callback);
  7255. ASSERT_TRUE(svr.is_valid());
  7256. svr.Get("/test", [&](const Request &req, Response &res) {
  7257. res.set_content("test", "text/plain");
  7258. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7259. ASSERT_TRUE(peer_cert != nullptr);
  7260. auto subject_name = X509_get_subject_name(peer_cert);
  7261. ASSERT_TRUE(subject_name != nullptr);
  7262. std::string common_name;
  7263. {
  7264. char name[BUFSIZ];
  7265. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7266. name, sizeof(name));
  7267. common_name.assign(name, static_cast<size_t>(name_len));
  7268. }
  7269. EXPECT_EQ("Common Name", common_name);
  7270. X509_free(peer_cert);
  7271. });
  7272. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  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. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7280. cli.enable_server_certificate_verification(false);
  7281. cli.set_connection_timeout(30);
  7282. auto res = cli.Get("/test");
  7283. ASSERT_TRUE(res);
  7284. ASSERT_EQ(StatusCode::OK_200, res->status);
  7285. }
  7286. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7287. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7288. // prepare large data
  7289. std::random_device seed_gen;
  7290. std::mt19937 random(seed_gen());
  7291. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7292. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7293. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7294. // server
  7295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7296. ASSERT_TRUE(svr.is_valid());
  7297. svr.Post("/binary", [&](const Request &req, Response &res) {
  7298. EXPECT_EQ(large_size_byte, req.body.size());
  7299. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7300. res.set_content(req.body, "application/octet-stream");
  7301. });
  7302. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7303. auto se = detail::scope_exit([&] {
  7304. svr.stop();
  7305. listen_thread.join();
  7306. ASSERT_FALSE(svr.is_running());
  7307. });
  7308. svr.wait_until_ready();
  7309. // client POST
  7310. SSLClient cli("localhost", PORT);
  7311. cli.enable_server_certificate_verification(false);
  7312. cli.set_read_timeout(std::chrono::seconds(100));
  7313. cli.set_write_timeout(std::chrono::seconds(100));
  7314. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7315. large_size_byte, "application/octet-stream");
  7316. // compare
  7317. EXPECT_EQ(StatusCode::OK_200, res->status);
  7318. EXPECT_EQ(large_size_byte, res->body.size());
  7319. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7320. }
  7321. #endif
  7322. #ifdef _WIN32
  7323. TEST(CleanupTest, WSACleanup) {
  7324. int ret = WSACleanup();
  7325. ASSERT_EQ(0, ret);
  7326. }
  7327. #endif
  7328. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7329. TEST(NoSSLSupport, SimpleInterface) {
  7330. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7331. }
  7332. #endif
  7333. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7334. TEST(InvalidScheme, SimpleInterface) {
  7335. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7336. }
  7337. #endif
  7338. TEST(NoScheme, SimpleInterface) {
  7339. Client cli("yahoo.com:80");
  7340. ASSERT_TRUE(cli.is_valid());
  7341. }
  7342. TEST(SendAPI, SimpleInterface_Online) {
  7343. Client cli("http://yahoo.com");
  7344. Request req;
  7345. req.method = "GET";
  7346. req.path = "/";
  7347. auto res = cli.send(req);
  7348. ASSERT_TRUE(res);
  7349. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7350. }
  7351. TEST(SendAPI, WithParamsInRequest) {
  7352. Server svr;
  7353. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7354. EXPECT_TRUE(req.has_param("test"));
  7355. EXPECT_EQ("test_value", req.get_param_value("test"));
  7356. });
  7357. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7358. auto se = detail::scope_exit([&] {
  7359. svr.stop();
  7360. t.join();
  7361. ASSERT_FALSE(svr.is_running());
  7362. });
  7363. svr.wait_until_ready();
  7364. Client cli(HOST, PORT);
  7365. {
  7366. Request req;
  7367. req.method = "GET";
  7368. req.path = "/";
  7369. req.params.emplace("test", "test_value");
  7370. auto res = cli.send(req);
  7371. ASSERT_TRUE(res);
  7372. }
  7373. {
  7374. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7375. ASSERT_TRUE(res);
  7376. }
  7377. }
  7378. TEST(ClientImplMethods, GetSocketTest) {
  7379. httplib::Server svr;
  7380. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7381. res.status = StatusCode::OK_200;
  7382. });
  7383. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. thread.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. {
  7391. httplib::Client cli("http://127.0.0.1:3333");
  7392. cli.set_keep_alive(true);
  7393. // Use the behavior of cpp-httplib of opening the connection
  7394. // only when the first request happens. If that changes,
  7395. // this test would be obsolete.
  7396. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7397. // This also implicitly tests the server. But other tests would fail much
  7398. // earlier than this one to be considered.
  7399. auto res = cli.Get("/");
  7400. ASSERT_TRUE(res);
  7401. EXPECT_EQ(StatusCode::OK_200, res->status);
  7402. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7403. }
  7404. }
  7405. // Disabled due to out-of-memory problem on GitHub Actions
  7406. #ifdef _WIN64
  7407. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7408. // allocate content size larger than 2GB in memory
  7409. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7410. char *content = (char *)malloc(content_size);
  7411. ASSERT_TRUE(content);
  7412. Server svr;
  7413. svr.Get("/foo",
  7414. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7415. res.set_content(content, content_size, "application/octet-stream");
  7416. });
  7417. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7418. auto se = detail::scope_exit([&] {
  7419. svr.stop();
  7420. listen_thread.join();
  7421. if (content) free(content);
  7422. ASSERT_FALSE(svr.is_running());
  7423. });
  7424. svr.wait_until_ready();
  7425. Client cli(HOST, PORT);
  7426. auto res = cli.Get("/foo");
  7427. ASSERT_TRUE(res);
  7428. EXPECT_EQ(StatusCode::OK_200, res->status);
  7429. EXPECT_EQ(content_size, res->body.length());
  7430. }
  7431. #endif
  7432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7433. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7434. Client cli("http://yahoo.com");
  7435. auto res = cli.Get("/");
  7436. ASSERT_TRUE(res);
  7437. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7438. cli.set_follow_location(true);
  7439. res = cli.Get("/");
  7440. ASSERT_TRUE(res);
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7443. }
  7444. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7445. Client cli("https://yahoo.com");
  7446. auto res = cli.Get("/");
  7447. ASSERT_TRUE(res);
  7448. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7449. cli.set_follow_location(true);
  7450. res = cli.Get("/");
  7451. ASSERT_TRUE(res);
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7454. }
  7455. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7456. Client cli("https://yahoo.com");
  7457. auto res = cli.Get("/");
  7458. ASSERT_TRUE(res);
  7459. ASSERT_FALSE(!res);
  7460. ASSERT_TRUE(res);
  7461. ASSERT_FALSE(res == nullptr);
  7462. ASSERT_TRUE(res != nullptr);
  7463. EXPECT_EQ(Error::Success, res.error());
  7464. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7465. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7466. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7467. cli.set_follow_location(true);
  7468. res = cli.Get("/");
  7469. ASSERT_TRUE(res);
  7470. EXPECT_EQ(Error::Success, res.error());
  7471. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7472. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7475. }
  7476. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7477. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7478. Client cli("https://cdnjs.cloudflare.com");
  7479. auto res =
  7480. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7481. ASSERT_TRUE(res);
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ(287630U, res->body.size());
  7484. EXPECT_EQ("application/javascript; charset=utf-8",
  7485. res->get_header_value("Content-Type"));
  7486. }
  7487. #endif
  7488. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7489. #undef REDIR_HOST // Silence compiler warning
  7490. #define REDIR_HOST "https://httpbingo.org"
  7491. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7492. Client cli(REDIR_HOST);
  7493. cli.set_follow_location(true);
  7494. auto res =
  7495. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(StatusCode::OK_200, res->status);
  7498. }
  7499. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7500. Client cli(REDIR_HOST);
  7501. cli.set_follow_location(true);
  7502. Params params;
  7503. params.emplace("url", "http://example.com");
  7504. params.emplace("status_code", "302");
  7505. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7506. ASSERT_TRUE(res);
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7510. Client cli(REDIR_HOST);
  7511. cli.set_follow_location(true);
  7512. Params params;
  7513. params.emplace("url", "http://example.com");
  7514. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7515. ASSERT_TRUE(res);
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST(HttpToHttpsRedirectTest, CertFile) {
  7519. Server svr;
  7520. ASSERT_TRUE(svr.is_valid());
  7521. svr.Get("/index", [&](const Request &, Response &res) {
  7522. res.set_redirect("https://127.0.0.1:1235/index");
  7523. svr.stop();
  7524. });
  7525. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7526. ASSERT_TRUE(ssl_svr.is_valid());
  7527. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7528. res.set_content("test", "text/plain");
  7529. ssl_svr.stop();
  7530. });
  7531. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7532. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7533. auto se = detail::scope_exit([&] {
  7534. t2.join();
  7535. t.join();
  7536. ASSERT_FALSE(svr.is_running());
  7537. });
  7538. svr.wait_until_ready();
  7539. ssl_svr.wait_until_ready();
  7540. Client cli("127.0.0.1", PORT);
  7541. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7542. cli.enable_server_certificate_verification(true);
  7543. cli.set_follow_location(true);
  7544. cli.set_connection_timeout(30);
  7545. auto res = cli.Get("/index");
  7546. ASSERT_TRUE(res);
  7547. ASSERT_EQ(StatusCode::OK_200, res->status);
  7548. }
  7549. TEST(SSLClientRedirectTest, CertFile) {
  7550. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7551. ASSERT_TRUE(ssl_svr1.is_valid());
  7552. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7553. res.set_redirect("https://127.0.0.1:1235/index");
  7554. ssl_svr1.stop();
  7555. });
  7556. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7557. ASSERT_TRUE(ssl_svr2.is_valid());
  7558. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7559. res.set_content("test", "text/plain");
  7560. ssl_svr2.stop();
  7561. });
  7562. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7563. thread t2 =
  7564. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7565. auto se = detail::scope_exit([&] {
  7566. t2.join();
  7567. t.join();
  7568. ASSERT_FALSE(ssl_svr1.is_running());
  7569. });
  7570. ssl_svr1.wait_until_ready();
  7571. ssl_svr2.wait_until_ready();
  7572. SSLClient cli("127.0.0.1", PORT);
  7573. std::string cert;
  7574. read_file(SERVER_CERT2_FILE, cert);
  7575. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7576. cli.enable_server_certificate_verification(true);
  7577. cli.set_follow_location(true);
  7578. cli.set_connection_timeout(30);
  7579. auto res = cli.Get("/index");
  7580. ASSERT_TRUE(res);
  7581. ASSERT_EQ(StatusCode::OK_200, res->status);
  7582. }
  7583. TEST(MultipartFormDataTest, LargeData) {
  7584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7585. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7586. const ContentReader &content_reader) {
  7587. if (req.is_multipart_form_data()) {
  7588. std::vector<FormData> items;
  7589. content_reader(
  7590. [&](const FormData &file) {
  7591. items.push_back(file);
  7592. return true;
  7593. },
  7594. [&](const char *data, size_t data_length) {
  7595. items.back().content.append(data, data_length);
  7596. return true;
  7597. });
  7598. EXPECT_TRUE(std::string(items[0].name) == "document");
  7599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7600. EXPECT_TRUE(items[0].filename == "2MB_data");
  7601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7602. EXPECT_TRUE(items[1].name == "hello");
  7603. EXPECT_TRUE(items[1].content == "world");
  7604. EXPECT_TRUE(items[1].filename == "");
  7605. EXPECT_TRUE(items[1].content_type == "");
  7606. } else {
  7607. std::string body;
  7608. content_reader([&](const char *data, size_t data_length) {
  7609. body.append(data, data_length);
  7610. return true;
  7611. });
  7612. }
  7613. });
  7614. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7615. auto se = detail::scope_exit([&] {
  7616. svr.stop();
  7617. t.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. {
  7622. std::string data(1024 * 1024 * 2, '.');
  7623. std::stringstream buffer;
  7624. buffer << data;
  7625. Client cli("https://localhost:8080");
  7626. cli.enable_server_certificate_verification(false);
  7627. UploadFormDataItems items{
  7628. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7629. {"hello", "world", "", ""},
  7630. };
  7631. auto res = cli.Post("/post", items);
  7632. ASSERT_TRUE(res);
  7633. ASSERT_EQ(StatusCode::OK_200, res->status);
  7634. }
  7635. }
  7636. TEST(MultipartFormDataTest, DataProviderItems) {
  7637. std::random_device seed_gen;
  7638. std::mt19937 random(seed_gen());
  7639. std::string rand1;
  7640. rand1.resize(1000);
  7641. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7642. std::string rand2;
  7643. rand2.resize(3000);
  7644. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7646. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7647. const ContentReader &content_reader) {
  7648. ASSERT_FALSE(req.is_multipart_form_data());
  7649. std::string body;
  7650. content_reader([&](const char *data, size_t data_length) {
  7651. body.append(data, data_length);
  7652. return true;
  7653. });
  7654. EXPECT_EQ(body, "");
  7655. });
  7656. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7657. const ContentReader &content_reader) {
  7658. ASSERT_TRUE(req.is_multipart_form_data());
  7659. std::vector<FormData> items;
  7660. content_reader(
  7661. [&](const FormData &file) {
  7662. items.push_back(file);
  7663. return true;
  7664. },
  7665. [&](const char *data, size_t data_length) {
  7666. items.back().content.append(data, data_length);
  7667. return true;
  7668. });
  7669. ASSERT_TRUE(items.size() == 2);
  7670. EXPECT_EQ(std::string(items[0].name), "name1");
  7671. EXPECT_EQ(items[0].content, "Testing123");
  7672. EXPECT_EQ(items[0].filename, "filename1");
  7673. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7674. EXPECT_EQ(items[1].name, "name2");
  7675. EXPECT_EQ(items[1].content, "Testing456");
  7676. EXPECT_EQ(items[1].filename, "");
  7677. EXPECT_EQ(items[1].content_type, "");
  7678. });
  7679. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7680. const ContentReader &content_reader) {
  7681. ASSERT_TRUE(req.is_multipart_form_data());
  7682. std::vector<FormData> items;
  7683. content_reader(
  7684. [&](const FormData &file) {
  7685. items.push_back(file);
  7686. return true;
  7687. },
  7688. [&](const char *data, size_t data_length) {
  7689. items.back().content.append(data, data_length);
  7690. return true;
  7691. });
  7692. ASSERT_TRUE(items.size() == 2);
  7693. EXPECT_EQ(items[0].name, "name3");
  7694. EXPECT_EQ(items[0].content, rand1);
  7695. EXPECT_EQ(items[0].filename, "filename3");
  7696. EXPECT_EQ(items[0].content_type, "");
  7697. EXPECT_EQ(items[1].name, "name4");
  7698. EXPECT_EQ(items[1].content, rand2);
  7699. EXPECT_EQ(items[1].filename, "filename4");
  7700. EXPECT_EQ(items[1].content_type, "");
  7701. });
  7702. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7703. const ContentReader &content_reader) {
  7704. ASSERT_TRUE(req.is_multipart_form_data());
  7705. std::vector<FormData> items;
  7706. content_reader(
  7707. [&](const FormData &file) {
  7708. items.push_back(file);
  7709. return true;
  7710. },
  7711. [&](const char *data, size_t data_length) {
  7712. items.back().content.append(data, data_length);
  7713. return true;
  7714. });
  7715. ASSERT_TRUE(items.size() == 4);
  7716. EXPECT_EQ(std::string(items[0].name), "name1");
  7717. EXPECT_EQ(items[0].content, "Testing123");
  7718. EXPECT_EQ(items[0].filename, "filename1");
  7719. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7720. EXPECT_EQ(items[1].name, "name2");
  7721. EXPECT_EQ(items[1].content, "Testing456");
  7722. EXPECT_EQ(items[1].filename, "");
  7723. EXPECT_EQ(items[1].content_type, "");
  7724. EXPECT_EQ(items[2].name, "name3");
  7725. EXPECT_EQ(items[2].content, rand1);
  7726. EXPECT_EQ(items[2].filename, "filename3");
  7727. EXPECT_EQ(items[2].content_type, "");
  7728. EXPECT_EQ(items[3].name, "name4");
  7729. EXPECT_EQ(items[3].content, rand2);
  7730. EXPECT_EQ(items[3].filename, "filename4");
  7731. EXPECT_EQ(items[3].content_type, "");
  7732. });
  7733. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7734. auto se = detail::scope_exit([&] {
  7735. svr.stop();
  7736. t.join();
  7737. ASSERT_FALSE(svr.is_running());
  7738. });
  7739. svr.wait_until_ready();
  7740. {
  7741. Client cli("https://localhost:8080");
  7742. cli.enable_server_certificate_verification(false);
  7743. UploadFormDataItems items{
  7744. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7745. {"name2", "Testing456", "", ""}, // not a file
  7746. };
  7747. {
  7748. auto res = cli.Post("/post-none", {}, {}, {});
  7749. ASSERT_TRUE(res);
  7750. ASSERT_EQ(StatusCode::OK_200, res->status);
  7751. }
  7752. FormDataProviderItems providers;
  7753. {
  7754. auto res =
  7755. cli.Post("/post-items", {}, items, providers); // empty providers
  7756. ASSERT_TRUE(res);
  7757. ASSERT_EQ(StatusCode::OK_200, res->status);
  7758. }
  7759. providers.push_back({"name3",
  7760. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7761. // test the offset is given correctly at each step
  7762. if (!offset)
  7763. sink.os.write(rand1.data(), 30);
  7764. else if (offset == 30)
  7765. sink.os.write(rand1.data() + 30, 300);
  7766. else if (offset == 330)
  7767. sink.os.write(rand1.data() + 330, 670);
  7768. else if (offset == rand1.size())
  7769. sink.done();
  7770. return true;
  7771. },
  7772. "filename3",
  7773. {}});
  7774. providers.push_back({"name4",
  7775. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7776. // test the offset is given correctly at each step
  7777. if (!offset)
  7778. sink.os.write(rand2.data(), 2000);
  7779. else if (offset == 2000)
  7780. sink.os.write(rand2.data() + 2000, 1);
  7781. else if (offset == 2001)
  7782. sink.os.write(rand2.data() + 2001, 999);
  7783. else if (offset == rand2.size())
  7784. sink.done();
  7785. return true;
  7786. },
  7787. "filename4",
  7788. {}});
  7789. {
  7790. auto res = cli.Post("/post-providers", {}, {}, providers);
  7791. ASSERT_TRUE(res);
  7792. ASSERT_EQ(StatusCode::OK_200, res->status);
  7793. }
  7794. {
  7795. auto res = cli.Post("/post-both", {}, items, providers);
  7796. ASSERT_TRUE(res);
  7797. ASSERT_EQ(StatusCode::OK_200, res->status);
  7798. }
  7799. }
  7800. }
  7801. TEST(MultipartFormDataTest, BadHeader) {
  7802. Server svr;
  7803. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7804. res.set_content("ok", "text/plain");
  7805. });
  7806. thread t = thread([&] { svr.listen(HOST, PORT); });
  7807. auto se = detail::scope_exit([&] {
  7808. svr.stop();
  7809. t.join();
  7810. ASSERT_FALSE(svr.is_running());
  7811. });
  7812. svr.wait_until_ready();
  7813. const std::string body =
  7814. "This is the preamble. It is to be ignored, though it\r\n"
  7815. "is a handy place for composition agents to include an\r\n"
  7816. "explanatory note to non-MIME conformant readers.\r\n"
  7817. "\r\n"
  7818. "\r\n"
  7819. "--simple boundary\r\n"
  7820. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7821. ": BAD...\r\n"
  7822. "\r\n"
  7823. "value1\r\n"
  7824. "--simple boundary\r\n"
  7825. "Content-Disposition: form-data; name=\"field2\"; "
  7826. "filename=\"example.txt\"\r\n"
  7827. "\r\n"
  7828. "value2\r\n"
  7829. "--simple boundary--\r\n"
  7830. "This is the epilogue. It is also to be ignored.\r\n";
  7831. std::string content_type =
  7832. R"(multipart/form-data; boundary="simple boundary")";
  7833. Client cli(HOST, PORT);
  7834. auto res = cli.Post("/post", body, content_type.c_str());
  7835. ASSERT_TRUE(res);
  7836. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7837. }
  7838. TEST(MultipartFormDataTest, WithPreamble) {
  7839. Server svr;
  7840. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7841. res.set_content("ok", "text/plain");
  7842. });
  7843. thread t = thread([&] { svr.listen(HOST, PORT); });
  7844. auto se = detail::scope_exit([&] {
  7845. svr.stop();
  7846. t.join();
  7847. ASSERT_FALSE(svr.is_running());
  7848. });
  7849. svr.wait_until_ready();
  7850. const std::string body =
  7851. "This is the preamble. It is to be ignored, though it\r\n"
  7852. "is a handy place for composition agents to include an\r\n"
  7853. "explanatory note to non-MIME conformant readers.\r\n"
  7854. "\r\n"
  7855. "\r\n"
  7856. "--simple boundary\r\n"
  7857. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7858. "\r\n"
  7859. "value1\r\n"
  7860. "--simple boundary\r\n"
  7861. "Content-Disposition: form-data; name=\"field2\"; "
  7862. "filename=\"example.txt\"\r\n"
  7863. "\r\n"
  7864. "value2\r\n"
  7865. "--simple boundary--\r\n"
  7866. "This is the epilogue. It is also to be ignored.\r\n";
  7867. std::string content_type =
  7868. R"(multipart/form-data; boundary="simple boundary")";
  7869. Client cli(HOST, PORT);
  7870. auto res = cli.Post("/post", body, content_type.c_str());
  7871. ASSERT_TRUE(res);
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7876. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7877. const ContentReader &content_reader) {
  7878. if (req.is_multipart_form_data()) {
  7879. std::vector<FormData> items;
  7880. content_reader(
  7881. [&](const FormData &file) {
  7882. items.push_back(file);
  7883. return true;
  7884. },
  7885. [&](const char *data, size_t data_length) {
  7886. items.back().content.append(data, data_length);
  7887. return true;
  7888. });
  7889. EXPECT_TRUE(std::string(items[0].name) == "document");
  7890. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7891. EXPECT_TRUE(items[0].filename == "2MB_data");
  7892. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7893. EXPECT_TRUE(items[1].name == "hello");
  7894. EXPECT_TRUE(items[1].content == "world");
  7895. EXPECT_TRUE(items[1].filename == "");
  7896. EXPECT_TRUE(items[1].content_type == "");
  7897. } else {
  7898. std::string body;
  7899. content_reader([&](const char *data, size_t data_length) {
  7900. body.append(data, data_length);
  7901. return true;
  7902. });
  7903. }
  7904. });
  7905. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7906. auto se = detail::scope_exit([&] {
  7907. svr.stop();
  7908. t.join();
  7909. ASSERT_FALSE(svr.is_running());
  7910. });
  7911. svr.wait_until_ready();
  7912. {
  7913. std::string data(1024 * 1024 * 2, '.');
  7914. std::stringstream buffer;
  7915. buffer << data;
  7916. Client cli("https://localhost:8080");
  7917. cli.enable_server_certificate_verification(false);
  7918. UploadFormDataItems items{
  7919. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7920. {"hello", "world", "", ""},
  7921. };
  7922. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7923. ASSERT_TRUE(res);
  7924. ASSERT_EQ(StatusCode::OK_200, res->status);
  7925. }
  7926. }
  7927. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7928. std::string data(1024 * 1024 * 2, '&');
  7929. std::stringstream buffer;
  7930. buffer << data;
  7931. Client cli("https://localhost:8080");
  7932. UploadFormDataItems items{
  7933. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7934. {"hello", "world", "", ""},
  7935. };
  7936. for (const char &c : " \t\r\n") {
  7937. auto res =
  7938. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7939. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7940. ASSERT_FALSE(res);
  7941. }
  7942. }
  7943. TEST(MultipartFormDataTest, PutFormData) {
  7944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7945. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7946. const ContentReader &content_reader) {
  7947. if (req.is_multipart_form_data()) {
  7948. std::vector<FormData> items;
  7949. content_reader(
  7950. [&](const FormData &file) {
  7951. items.push_back(file);
  7952. return true;
  7953. },
  7954. [&](const char *data, size_t data_length) {
  7955. items.back().content.append(data, data_length);
  7956. return true;
  7957. });
  7958. EXPECT_TRUE(std::string(items[0].name) == "document");
  7959. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7960. EXPECT_TRUE(items[0].filename == "2MB_data");
  7961. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7962. EXPECT_TRUE(items[1].name == "hello");
  7963. EXPECT_TRUE(items[1].content == "world");
  7964. EXPECT_TRUE(items[1].filename == "");
  7965. EXPECT_TRUE(items[1].content_type == "");
  7966. } else {
  7967. std::string body;
  7968. content_reader([&](const char *data, size_t data_length) {
  7969. body.append(data, data_length);
  7970. return true;
  7971. });
  7972. }
  7973. });
  7974. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7975. auto se = detail::scope_exit([&] {
  7976. svr.stop();
  7977. t.join();
  7978. ASSERT_FALSE(svr.is_running());
  7979. });
  7980. svr.wait_until_ready();
  7981. {
  7982. std::string data(1024 * 1024 * 2, '&');
  7983. std::stringstream buffer;
  7984. buffer << data;
  7985. Client cli("https://localhost:8080");
  7986. cli.enable_server_certificate_verification(false);
  7987. UploadFormDataItems items{
  7988. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7989. {"hello", "world", "", ""},
  7990. };
  7991. auto res = cli.Put("/put", items);
  7992. ASSERT_TRUE(res);
  7993. ASSERT_EQ(StatusCode::OK_200, res->status);
  7994. }
  7995. }
  7996. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7998. svr.Put("/put_customboundary",
  7999. [&](const Request &req, const Response & /*res*/,
  8000. const ContentReader &content_reader) {
  8001. if (req.is_multipart_form_data()) {
  8002. std::vector<FormData> items;
  8003. content_reader(
  8004. [&](const FormData &file) {
  8005. items.push_back(file);
  8006. return true;
  8007. },
  8008. [&](const char *data, size_t data_length) {
  8009. items.back().content.append(data, data_length);
  8010. return true;
  8011. });
  8012. EXPECT_TRUE(std::string(items[0].name) == "document");
  8013. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8014. EXPECT_TRUE(items[0].filename == "2MB_data");
  8015. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8016. EXPECT_TRUE(items[1].name == "hello");
  8017. EXPECT_TRUE(items[1].content == "world");
  8018. EXPECT_TRUE(items[1].filename == "");
  8019. EXPECT_TRUE(items[1].content_type == "");
  8020. } else {
  8021. std::string body;
  8022. content_reader([&](const char *data, size_t data_length) {
  8023. body.append(data, data_length);
  8024. return true;
  8025. });
  8026. }
  8027. });
  8028. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8029. auto se = detail::scope_exit([&] {
  8030. svr.stop();
  8031. t.join();
  8032. ASSERT_FALSE(svr.is_running());
  8033. });
  8034. svr.wait_until_ready();
  8035. {
  8036. std::string data(1024 * 1024 * 2, '&');
  8037. std::stringstream buffer;
  8038. buffer << data;
  8039. Client cli("https://localhost:8080");
  8040. cli.enable_server_certificate_verification(false);
  8041. UploadFormDataItems items{
  8042. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8043. {"hello", "world", "", ""},
  8044. };
  8045. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8046. ASSERT_TRUE(res);
  8047. ASSERT_EQ(StatusCode::OK_200, res->status);
  8048. }
  8049. }
  8050. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8051. std::string data(1024 * 1024 * 2, '&');
  8052. std::stringstream buffer;
  8053. buffer << data;
  8054. Client cli("https://localhost:8080");
  8055. cli.enable_server_certificate_verification(false);
  8056. UploadFormDataItems items{
  8057. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8058. {"hello", "world", "", ""},
  8059. };
  8060. for (const char &c : " \t\r\n") {
  8061. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8062. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8063. ASSERT_FALSE(res);
  8064. }
  8065. }
  8066. TEST(MultipartFormDataTest, AlternateFilename) {
  8067. auto handled = false;
  8068. Server svr;
  8069. svr.Post("/test", [&](const Request &req, Response &res) {
  8070. ASSERT_EQ(2u, req.form.files.size());
  8071. ASSERT_EQ(1u, req.form.fields.size());
  8072. // Test files
  8073. const auto &file1 = req.form.get_file("file1");
  8074. ASSERT_EQ("file1", file1.name);
  8075. ASSERT_EQ("A.txt", file1.filename);
  8076. ASSERT_EQ("text/plain", file1.content_type);
  8077. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8078. const auto &file2 = req.form.get_file("file2");
  8079. ASSERT_EQ("file2", file2.name);
  8080. ASSERT_EQ("a.html", file2.filename);
  8081. ASSERT_EQ("text/html", file2.content_type);
  8082. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8083. file2.content);
  8084. // Test text field
  8085. const auto &text = req.form.get_field("text");
  8086. ASSERT_EQ("text default", text);
  8087. res.set_content("ok", "text/plain");
  8088. handled = true;
  8089. });
  8090. thread t = thread([&] { svr.listen(HOST, PORT); });
  8091. auto se = detail::scope_exit([&] {
  8092. svr.stop();
  8093. t.join();
  8094. ASSERT_FALSE(svr.is_running());
  8095. ASSERT_TRUE(handled);
  8096. });
  8097. svr.wait_until_ready();
  8098. auto req = "POST /test HTTP/1.1\r\n"
  8099. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8100. "Content-Length: 399\r\n"
  8101. "\r\n"
  8102. "----------\r\n"
  8103. "Content-Disposition: form-data; name=\"text\"\r\n"
  8104. "\r\n"
  8105. "text default\r\n"
  8106. "----------\r\n"
  8107. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8108. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8109. "Content-Type: text/plain\r\n"
  8110. "\r\n"
  8111. "Content of a.txt.\r\n"
  8112. "\r\n"
  8113. "----------\r\n"
  8114. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8115. "\"a.html\"\r\n"
  8116. "Content-Type: text/html\r\n"
  8117. "\r\n"
  8118. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8119. "\r\n"
  8120. "------------\r\n";
  8121. ASSERT_TRUE(send_request(1, req));
  8122. }
  8123. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8124. auto handled = false;
  8125. Server svr;
  8126. svr.Post("/test", [&](const Request &req, Response &) {
  8127. ASSERT_EQ(2u, req.form.fields.size());
  8128. const auto &text1 = req.form.get_field("text1");
  8129. ASSERT_EQ("text1", text1);
  8130. const auto &text2 = req.form.get_field("text2");
  8131. ASSERT_EQ("text2", text2);
  8132. handled = true;
  8133. });
  8134. thread t = thread([&] { svr.listen(HOST, PORT); });
  8135. auto se = detail::scope_exit([&] {
  8136. svr.stop();
  8137. t.join();
  8138. ASSERT_FALSE(svr.is_running());
  8139. ASSERT_TRUE(handled);
  8140. });
  8141. svr.wait_until_ready();
  8142. auto req = "POST /test HTTP/1.1\r\n"
  8143. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8144. "Content-Length: 146\r\n"
  8145. "\r\n----------\r\n"
  8146. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8147. "\r\n"
  8148. "text1"
  8149. "\r\n----------\r\n"
  8150. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8151. "\r\n"
  8152. "text2"
  8153. "\r\n------------";
  8154. std::string response;
  8155. ASSERT_TRUE(send_request(1, req, &response));
  8156. ASSERT_EQ("200", response.substr(9, 3));
  8157. }
  8158. TEST(MultipartFormDataTest, ContentLength) {
  8159. auto handled = false;
  8160. Server svr;
  8161. svr.Post("/test", [&](const Request &req, Response &) {
  8162. ASSERT_EQ(2u, req.form.fields.size());
  8163. const auto &text1 = req.form.get_field("text1");
  8164. ASSERT_EQ("text1", text1);
  8165. const auto &text2 = req.form.get_field("text2");
  8166. ASSERT_EQ("text2", text2);
  8167. handled = true;
  8168. });
  8169. thread t = thread([&] { svr.listen(HOST, PORT); });
  8170. auto se = detail::scope_exit([&] {
  8171. svr.stop();
  8172. t.join();
  8173. ASSERT_FALSE(svr.is_running());
  8174. ASSERT_TRUE(handled);
  8175. });
  8176. svr.wait_until_ready();
  8177. auto req = "POST /test HTTP/1.1\r\n"
  8178. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8179. "Content-Length: 167\r\n"
  8180. "\r\n----------\r\n"
  8181. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8182. "Content-Length: 5\r\n"
  8183. "\r\n"
  8184. "text1"
  8185. "\r\n----------\r\n"
  8186. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8187. "\r\n"
  8188. "text2"
  8189. "\r\n------------\r\n";
  8190. std::string response;
  8191. ASSERT_TRUE(send_request(1, req, &response));
  8192. ASSERT_EQ("200", response.substr(9, 3));
  8193. }
  8194. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8195. auto handled = false;
  8196. Server svr;
  8197. svr.Post("/test", [&](const Request &req, Response &) {
  8198. ASSERT_EQ(2u, req.form.fields.size());
  8199. const auto &text1 = req.form.get_field("text1");
  8200. ASSERT_EQ("text1", text1);
  8201. // TODO: Add header access for text fields if needed
  8202. const auto &text2 = req.form.get_field("text2");
  8203. ASSERT_EQ("text2", text2);
  8204. // TODO: Header access for text fields needs to be implemented
  8205. // auto &headers = it->second.headers;
  8206. // ASSERT_EQ(3U, headers.size());
  8207. // auto custom_header = headers.find("x-whatever");
  8208. // ASSERT_TRUE(custom_header != headers.end());
  8209. // ASSERT_NE("customvalue", custom_header->second);
  8210. // ASSERT_EQ("CustomValue", custom_header->second);
  8211. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8212. handled = true;
  8213. });
  8214. thread t = thread([&] { svr.listen(HOST, PORT); });
  8215. auto se = detail::scope_exit([&] {
  8216. svr.stop();
  8217. t.join();
  8218. ASSERT_FALSE(svr.is_running());
  8219. ASSERT_TRUE(handled);
  8220. });
  8221. svr.wait_until_ready();
  8222. auto req = "POST /test HTTP/1.1\r\n"
  8223. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8224. "Content-Length: 232\r\n"
  8225. "\r\n----------\r\n"
  8226. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8227. "Content-Length: 5\r\n"
  8228. "X-Test: 1\r\n"
  8229. "\r\n"
  8230. "text1"
  8231. "\r\n----------\r\n"
  8232. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8233. "Content-Type: text/plain\r\n"
  8234. "X-Whatever: CustomValue\r\n"
  8235. "\r\n"
  8236. "text2"
  8237. "\r\n------------\r\n"
  8238. "That should be disregarded. Not even read";
  8239. std::string response;
  8240. ASSERT_TRUE(send_request(1, req, &response));
  8241. ASSERT_EQ("200", response.substr(9, 3));
  8242. }
  8243. #endif
  8244. TEST(MultipartFormDataTest, LargeHeader) {
  8245. auto handled = false;
  8246. Server svr;
  8247. svr.Post("/test", [&](const Request &req, Response &) {
  8248. ASSERT_EQ(1u, req.form.fields.size());
  8249. const auto &text = req.form.get_field("name1");
  8250. ASSERT_EQ("text1", text);
  8251. handled = true;
  8252. });
  8253. thread t = thread([&] { svr.listen(HOST, PORT); });
  8254. auto se = detail::scope_exit([&] {
  8255. svr.stop();
  8256. t.join();
  8257. ASSERT_FALSE(svr.is_running());
  8258. ASSERT_TRUE(handled);
  8259. });
  8260. svr.wait_until_ready();
  8261. auto boundary = std::string("cpp-httplib-multipart-data");
  8262. std::string content = "--" + boundary +
  8263. "\r\n"
  8264. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8265. "\r\n"
  8266. "text1\r\n"
  8267. "--" +
  8268. boundary + "--\r\n";
  8269. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8270. "Content-Type: multipart/form-data;boundary=" +
  8271. boundary +
  8272. "\r\n"
  8273. "Content-Length: " +
  8274. std::to_string(content.size()) +
  8275. "\r\n"
  8276. "Dummy-Header: ";
  8277. std::string header_suffix = "\r\n"
  8278. "\r\n";
  8279. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8280. size_t header_dummy_size =
  8281. read_buff_size -
  8282. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8283. auto header_dummy = std::string(header_dummy_size, '@');
  8284. auto req = header_prefix + header_dummy + header_suffix + content;
  8285. std::string response;
  8286. ASSERT_TRUE(send_request(1, req, &response));
  8287. ASSERT_EQ("200", response.substr(9, 3));
  8288. }
  8289. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8290. static constexpr unsigned int number_of_tasks{1000000};
  8291. std::atomic_uint count{0};
  8292. std::unique_ptr<TaskQueue> task_queue{
  8293. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8294. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8295. auto queued = task_queue->enqueue(
  8296. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8297. EXPECT_TRUE(queued);
  8298. }
  8299. EXPECT_NO_THROW(task_queue->shutdown());
  8300. EXPECT_EQ(number_of_tasks, count.load());
  8301. }
  8302. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8303. static constexpr unsigned int number_of_tasks{1000000};
  8304. static constexpr unsigned int qlimit{2};
  8305. unsigned int queued_count{0};
  8306. std::atomic_uint count{0};
  8307. std::unique_ptr<TaskQueue> task_queue{
  8308. new ThreadPool{/*num_threads=*/1, qlimit}};
  8309. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8310. if (task_queue->enqueue(
  8311. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8312. queued_count++;
  8313. }
  8314. }
  8315. EXPECT_NO_THROW(task_queue->shutdown());
  8316. EXPECT_EQ(queued_count, count.load());
  8317. EXPECT_TRUE(queued_count <= number_of_tasks);
  8318. EXPECT_TRUE(queued_count >= qlimit);
  8319. }
  8320. TEST(TaskQueueTest, MaxQueuedRequests) {
  8321. static constexpr unsigned int qlimit{3};
  8322. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8323. std::condition_variable sem_cv;
  8324. std::mutex sem_mtx;
  8325. int credits = 0;
  8326. bool queued;
  8327. /* Fill up the queue with tasks that will block until we give them credits to
  8328. * complete. */
  8329. for (unsigned int n = 0; n <= qlimit;) {
  8330. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8331. std::unique_lock<std::mutex> lock(sem_mtx);
  8332. while (credits <= 0) {
  8333. sem_cv.wait(lock);
  8334. }
  8335. /* Consume the credit and signal the test code if they are all gone. */
  8336. if (--credits == 0) { sem_cv.notify_one(); }
  8337. });
  8338. if (n < qlimit) {
  8339. /* The first qlimit enqueues must succeed. */
  8340. EXPECT_TRUE(queued);
  8341. } else {
  8342. /* The last one will succeed only when the worker thread
  8343. * starts and dequeues the first blocking task. Although
  8344. * not necessary for the correctness of this test, we sleep for
  8345. * a short while to avoid busy waiting. */
  8346. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8347. }
  8348. if (queued) { n++; }
  8349. }
  8350. /* Further enqueues must fail since the queue is full. */
  8351. for (auto i = 0; i < 4; i++) {
  8352. queued = task_queue->enqueue([] {});
  8353. EXPECT_FALSE(queued);
  8354. }
  8355. /* Give the credits to allow the previous tasks to complete. */
  8356. {
  8357. std::unique_lock<std::mutex> lock(sem_mtx);
  8358. credits += qlimit + 1;
  8359. }
  8360. sem_cv.notify_all();
  8361. /* Wait for all the credits to be consumed. */
  8362. {
  8363. std::unique_lock<std::mutex> lock(sem_mtx);
  8364. while (credits > 0) {
  8365. sem_cv.wait(lock);
  8366. }
  8367. }
  8368. /* Check that we are able again to enqueue at least qlimit tasks. */
  8369. for (unsigned int i = 0; i < qlimit; i++) {
  8370. queued = task_queue->enqueue([] {});
  8371. EXPECT_TRUE(queued);
  8372. }
  8373. EXPECT_NO_THROW(task_queue->shutdown());
  8374. }
  8375. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8376. Server svr;
  8377. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8378. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8379. });
  8380. svr.Get("/hello", [](const Request &req, Response &res) {
  8381. res.set_content(req.get_param_value("key"), "text/plain");
  8382. });
  8383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8384. auto se = detail::scope_exit([&] {
  8385. svr.stop();
  8386. thread.join();
  8387. ASSERT_FALSE(svr.is_running());
  8388. });
  8389. svr.wait_until_ready();
  8390. {
  8391. Client cli(HOST, PORT);
  8392. cli.set_follow_location(true);
  8393. auto res = cli.Get("/");
  8394. ASSERT_TRUE(res);
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. EXPECT_EQ("val&key2=val2", res->body);
  8397. }
  8398. }
  8399. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8400. Server svr;
  8401. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8402. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8403. });
  8404. svr.Get("/hello", [](const Request &req, Response &res) {
  8405. res.set_content(req.get_param_value("key"), "text/plain");
  8406. });
  8407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8408. auto se = detail::scope_exit([&] {
  8409. svr.stop();
  8410. thread.join();
  8411. ASSERT_FALSE(svr.is_running());
  8412. });
  8413. svr.wait_until_ready();
  8414. {
  8415. Client cli(HOST, PORT);
  8416. cli.set_follow_location(true);
  8417. auto res = cli.Get("/");
  8418. ASSERT_TRUE(res);
  8419. EXPECT_EQ(StatusCode::OK_200, res->status);
  8420. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8421. }
  8422. }
  8423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8424. TEST(RedirectTest, Issue2185_Online) {
  8425. SSLClient client("github.com");
  8426. client.set_follow_location(true);
  8427. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8428. "Coollab-Windows.zip");
  8429. ASSERT_TRUE(res);
  8430. EXPECT_EQ(StatusCode::OK_200, res->status);
  8431. EXPECT_EQ(9920427U, res->body.size());
  8432. }
  8433. #endif
  8434. TEST(VulnerabilityTest, CRLFInjection) {
  8435. Server svr;
  8436. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8437. res.set_content("Hello 1", "text/plain");
  8438. });
  8439. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8440. res.set_content("Hello 2", "text/plain");
  8441. });
  8442. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8443. res.set_content("Hello 3", "text/plain");
  8444. });
  8445. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8446. res.set_content("Hello 4", "text/plain");
  8447. });
  8448. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8449. for (const auto &x : req.headers) {
  8450. auto key = x.first;
  8451. EXPECT_STRNE("evil", key.c_str());
  8452. }
  8453. });
  8454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8455. auto se = detail::scope_exit([&] {
  8456. svr.stop();
  8457. thread.join();
  8458. ASSERT_FALSE(svr.is_running());
  8459. });
  8460. svr.wait_until_ready();
  8461. {
  8462. Client cli(HOST, PORT);
  8463. cli.Post("/test1", "A=B",
  8464. "application/x-www-form-urlencoded\r\nevil: hello1");
  8465. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8466. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8467. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8468. }
  8469. }
  8470. TEST(PathParamsTest, StaticMatch) {
  8471. const auto pattern = "/users/all";
  8472. detail::PathParamsMatcher matcher(pattern);
  8473. Request request;
  8474. request.path = "/users/all";
  8475. ASSERT_TRUE(matcher.match(request));
  8476. std::unordered_map<std::string, std::string> expected_params = {};
  8477. EXPECT_EQ(request.path_params, expected_params);
  8478. }
  8479. TEST(PathParamsTest, StaticMismatch) {
  8480. const auto pattern = "/users/all";
  8481. detail::PathParamsMatcher matcher(pattern);
  8482. Request request;
  8483. request.path = "/users/1";
  8484. ASSERT_FALSE(matcher.match(request));
  8485. }
  8486. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8487. const auto pattern = "/users/:id/subscriptions";
  8488. detail::PathParamsMatcher matcher(pattern);
  8489. Request request;
  8490. request.path = "/users/42/subscriptions";
  8491. ASSERT_TRUE(matcher.match(request));
  8492. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8493. EXPECT_EQ(request.path_params, expected_params);
  8494. }
  8495. TEST(PathParamsTest, SingleParamInTheEnd) {
  8496. const auto pattern = "/users/:id";
  8497. detail::PathParamsMatcher matcher(pattern);
  8498. Request request;
  8499. request.path = "/users/24";
  8500. ASSERT_TRUE(matcher.match(request));
  8501. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8502. EXPECT_EQ(request.path_params, expected_params);
  8503. }
  8504. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8505. const auto pattern = "/users/:id/";
  8506. detail::PathParamsMatcher matcher(pattern);
  8507. Request request;
  8508. request.path = "/users/42/";
  8509. ASSERT_TRUE(matcher.match(request));
  8510. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8511. EXPECT_EQ(request.path_params, expected_params);
  8512. }
  8513. TEST(PathParamsTest, EmptyParam) {
  8514. const auto pattern = "/users/:id/";
  8515. detail::PathParamsMatcher matcher(pattern);
  8516. Request request;
  8517. request.path = "/users//";
  8518. ASSERT_TRUE(matcher.match(request));
  8519. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8520. EXPECT_EQ(request.path_params, expected_params);
  8521. }
  8522. TEST(PathParamsTest, FragmentMismatch) {
  8523. const auto pattern = "/users/:id/";
  8524. detail::PathParamsMatcher matcher(pattern);
  8525. Request request;
  8526. request.path = "/admins/24/";
  8527. ASSERT_FALSE(matcher.match(request));
  8528. }
  8529. TEST(PathParamsTest, ExtraFragments) {
  8530. const auto pattern = "/users/:id";
  8531. detail::PathParamsMatcher matcher(pattern);
  8532. Request request;
  8533. request.path = "/users/42/subscriptions";
  8534. ASSERT_FALSE(matcher.match(request));
  8535. }
  8536. TEST(PathParamsTest, MissingTrailingParam) {
  8537. const auto pattern = "/users/:id";
  8538. detail::PathParamsMatcher matcher(pattern);
  8539. Request request;
  8540. request.path = "/users";
  8541. ASSERT_FALSE(matcher.match(request));
  8542. }
  8543. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8544. const auto pattern = "/users/:id/subscriptions";
  8545. detail::PathParamsMatcher matcher(pattern);
  8546. Request request;
  8547. request.path = "/users/subscriptions";
  8548. ASSERT_FALSE(matcher.match(request));
  8549. }
  8550. TEST(PathParamsTest, MultipleParams) {
  8551. const auto pattern = "/users/:userid/subscriptions/:subid";
  8552. detail::PathParamsMatcher matcher(pattern);
  8553. Request request;
  8554. request.path = "/users/42/subscriptions/2";
  8555. ASSERT_TRUE(matcher.match(request));
  8556. std::unordered_map<std::string, std::string> expected_params = {
  8557. {"userid", "42"}, {"subid", "2"}};
  8558. EXPECT_EQ(request.path_params, expected_params);
  8559. }
  8560. TEST(PathParamsTest, SequenceOfParams) {
  8561. const auto pattern = "/values/:x/:y/:z";
  8562. detail::PathParamsMatcher matcher(pattern);
  8563. Request request;
  8564. request.path = "/values/1/2/3";
  8565. ASSERT_TRUE(matcher.match(request));
  8566. std::unordered_map<std::string, std::string> expected_params = {
  8567. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8568. EXPECT_EQ(request.path_params, expected_params);
  8569. }
  8570. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8571. const auto pattern = "/prefix:suffix";
  8572. detail::PathParamsMatcher matcher(pattern);
  8573. Request request;
  8574. request.path = "/prefix:suffix";
  8575. ASSERT_TRUE(matcher.match(request));
  8576. const std::unordered_map<std::string, std::string> expected_params = {};
  8577. EXPECT_EQ(request.path_params, expected_params);
  8578. }
  8579. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8580. // If ipv6 regex working, regex match codepath is taken.
  8581. // else port will default to 80 in Client impl
  8582. int clientImplMagicPort = 80;
  8583. int port = 4321;
  8584. // above ports must be different to avoid false negative
  8585. EXPECT_NE(clientImplMagicPort, port);
  8586. std::string ipV6TestURL = "http://[ff06::c3]";
  8587. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8588. CLIENT_PRIVATE_KEY_FILE);
  8589. EXPECT_EQ(cli.port(), port);
  8590. }
  8591. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8592. auto file_path = "./www/dir/index.html";
  8593. auto dir_path = "./www/dir";
  8594. detail::FileStat stat_file(file_path);
  8595. EXPECT_TRUE(stat_file.is_file());
  8596. EXPECT_FALSE(stat_file.is_dir());
  8597. detail::FileStat stat_dir(dir_path);
  8598. EXPECT_FALSE(stat_dir.is_file());
  8599. EXPECT_TRUE(stat_dir.is_dir());
  8600. }
  8601. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8602. Server svr;
  8603. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8604. EXPECT_EQ(res.status, 400);
  8605. });
  8606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8607. auto se = detail::scope_exit([&] {
  8608. svr.stop();
  8609. thread.join();
  8610. ASSERT_FALSE(svr.is_running());
  8611. });
  8612. svr.wait_until_ready();
  8613. Client cli(HOST, PORT);
  8614. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8615. }
  8616. TEST(InvalidHeaderCharsTest, is_field_name) {
  8617. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8618. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8619. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8620. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8621. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8622. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8623. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8624. EXPECT_FALSE(detail::fields::is_field_name(""));
  8625. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8626. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8627. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8628. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8629. }
  8630. TEST(InvalidHeaderCharsTest, is_field_value) {
  8631. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8632. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8633. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8634. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8635. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8636. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8637. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8638. EXPECT_TRUE(detail::fields::is_field_value(""));
  8639. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8640. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8641. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8642. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8643. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8644. }
  8645. TEST(InvalidHeaderCharsTest, OnServer) {
  8646. Server svr;
  8647. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8648. std::string header = "Not Set";
  8649. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8650. res.set_header(header, "value");
  8651. res.set_content("Page Content Page Content", "text/plain");
  8652. });
  8653. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8654. std::string header = "Not Set";
  8655. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8656. res.set_header("X-Test", header);
  8657. res.set_content("Page Content Page Content", "text/plain");
  8658. });
  8659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8660. auto se = detail::scope_exit([&] {
  8661. svr.stop();
  8662. thread.join();
  8663. ASSERT_FALSE(svr.is_running());
  8664. });
  8665. svr.wait_until_ready();
  8666. Client cli(HOST, PORT);
  8667. {
  8668. auto res = cli.Get(
  8669. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8670. ASSERT_TRUE(res);
  8671. EXPECT_EQ("Page Content Page Content", res->body);
  8672. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8673. }
  8674. {
  8675. auto res = cli.Get(
  8676. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8677. ASSERT_TRUE(res);
  8678. EXPECT_EQ("Page Content Page Content", res->body);
  8679. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8680. }
  8681. }
  8682. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8683. auto handled = false;
  8684. Server svr;
  8685. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8686. thread t = thread([&] { svr.listen(HOST, PORT); });
  8687. auto se = detail::scope_exit([&] {
  8688. svr.stop();
  8689. t.join();
  8690. ASSERT_FALSE(svr.is_running());
  8691. ASSERT_FALSE(handled);
  8692. });
  8693. svr.wait_until_ready();
  8694. auto req = "POST /test HTTP/1.1\r\n"
  8695. "Content-Length: x\r\n"
  8696. "\r\n";
  8697. std::string response;
  8698. ASSERT_TRUE(send_request(1, req, &response));
  8699. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8700. response.substr(0, response.find("\r\n")));
  8701. }
  8702. #ifndef _WIN32
  8703. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8704. static constexpr char reject[] = "Unauthorized";
  8705. static constexpr char accept[] = "Upload accepted";
  8706. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8707. Server svr;
  8708. svr.set_expect_100_continue_handler(
  8709. [](const Request & /*req*/, Response &res) {
  8710. res.status = StatusCode::Unauthorized_401;
  8711. res.set_content(reject, "text/plain");
  8712. return res.status;
  8713. });
  8714. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8715. res.set_content(accept, "text/plain");
  8716. });
  8717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8718. auto se = detail::scope_exit([&] {
  8719. svr.stop();
  8720. thread.join();
  8721. ASSERT_FALSE(svr.is_running());
  8722. });
  8723. svr.wait_until_ready();
  8724. {
  8725. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8726. curl_easy_init(), &curl_easy_cleanup};
  8727. ASSERT_NE(curl, nullptr);
  8728. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8729. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8730. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8731. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8732. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8733. &curl_slist_free_all};
  8734. ASSERT_NE(list, nullptr);
  8735. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8736. struct read_data {
  8737. size_t read_size;
  8738. size_t total_size;
  8739. } data = {0, total_size};
  8740. using read_callback_t =
  8741. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8742. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8743. void *userdata) -> size_t {
  8744. read_data *data = (read_data *)userdata;
  8745. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8746. std::fill_n(ptr, size * nmemb, 'A');
  8747. data->read_size += size * nmemb;
  8748. return size * nmemb;
  8749. };
  8750. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8751. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8752. std::vector<char> buffer;
  8753. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8754. using write_callback_t =
  8755. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8756. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8757. void *userdata) -> size_t {
  8758. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8759. buffer->reserve(buffer->size() + size * nmemb + 1);
  8760. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8761. return size * nmemb;
  8762. };
  8763. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8764. {
  8765. const auto res = curl_easy_perform(curl.get());
  8766. ASSERT_EQ(res, CURLE_OK);
  8767. }
  8768. {
  8769. auto response_code = long{};
  8770. const auto res =
  8771. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8772. ASSERT_EQ(res, CURLE_OK);
  8773. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8774. }
  8775. {
  8776. auto dl = curl_off_t{};
  8777. const auto res =
  8778. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8779. ASSERT_EQ(res, CURLE_OK);
  8780. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8781. }
  8782. {
  8783. buffer.push_back('\0');
  8784. ASSERT_STRCASEEQ(buffer.data(), reject);
  8785. }
  8786. }
  8787. }
  8788. #endif
  8789. template <typename S, typename C>
  8790. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8791. svr.Get("/stream", [&](const Request &, Response &res) {
  8792. auto data = new std::string("01234567890123456789");
  8793. res.set_content_provider(
  8794. data->size(), "text/plain",
  8795. [&, data](size_t offset, size_t length, DataSink &sink) {
  8796. const size_t DATA_CHUNK_SIZE = 4;
  8797. const auto &d = *data;
  8798. std::this_thread::sleep_for(std::chrono::seconds(1));
  8799. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8800. return true;
  8801. },
  8802. [data](bool success) {
  8803. EXPECT_FALSE(success);
  8804. delete data;
  8805. });
  8806. });
  8807. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8808. auto i = new size_t(0);
  8809. res.set_content_provider(
  8810. "text/plain",
  8811. [i](size_t, DataSink &sink) {
  8812. if (*i < 5) {
  8813. std::this_thread::sleep_for(std::chrono::seconds(1));
  8814. sink.write("abcd", 4);
  8815. (*i)++;
  8816. } else {
  8817. sink.done();
  8818. }
  8819. return true;
  8820. },
  8821. [i](bool success) {
  8822. EXPECT_FALSE(success);
  8823. delete i;
  8824. });
  8825. });
  8826. svr.Get("/chunked", [&](const Request &, Response &res) {
  8827. auto i = new size_t(0);
  8828. res.set_chunked_content_provider(
  8829. "text/plain",
  8830. [i](size_t, DataSink &sink) {
  8831. if (*i < 5) {
  8832. std::this_thread::sleep_for(std::chrono::seconds(1));
  8833. sink.os << "abcd";
  8834. (*i)++;
  8835. } else {
  8836. sink.done();
  8837. }
  8838. return true;
  8839. },
  8840. [i](bool success) {
  8841. EXPECT_FALSE(success);
  8842. delete i;
  8843. });
  8844. });
  8845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8846. auto se = detail::scope_exit([&] {
  8847. svr.stop();
  8848. listen_thread.join();
  8849. ASSERT_FALSE(svr.is_running());
  8850. });
  8851. svr.wait_until_ready();
  8852. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8853. {
  8854. auto start = std::chrono::steady_clock::now();
  8855. auto res = cli.Get("/stream");
  8856. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8857. std::chrono::steady_clock::now() - start)
  8858. .count();
  8859. ASSERT_FALSE(res);
  8860. EXPECT_EQ(Error::Read, res.error());
  8861. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8862. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8863. }
  8864. {
  8865. auto start = std::chrono::steady_clock::now();
  8866. auto res = cli.Get("/stream_without_length");
  8867. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8868. std::chrono::steady_clock::now() - start)
  8869. .count();
  8870. ASSERT_FALSE(res);
  8871. EXPECT_EQ(Error::Read, res.error());
  8872. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8873. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8874. }
  8875. {
  8876. auto start = std::chrono::steady_clock::now();
  8877. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8878. EXPECT_EQ("abcd", string(data, data_length));
  8879. return true;
  8880. });
  8881. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8882. std::chrono::steady_clock::now() - start)
  8883. .count();
  8884. ASSERT_FALSE(res);
  8885. EXPECT_EQ(Error::Read, res.error());
  8886. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8887. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8888. }
  8889. }
  8890. TEST(MaxTimeoutTest, ContentStream) {
  8891. time_t timeout = 2000;
  8892. time_t threshold = 200;
  8893. Server svr;
  8894. Client cli("localhost", PORT);
  8895. max_timeout_test(svr, cli, timeout, threshold);
  8896. }
  8897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8898. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8899. time_t timeout = 2000;
  8900. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8902. SSLClient cli("localhost", PORT);
  8903. cli.enable_server_certificate_verification(false);
  8904. max_timeout_test(svr, cli, timeout, threshold);
  8905. }
  8906. #endif
  8907. class EventDispatcher {
  8908. public:
  8909. EventDispatcher() {}
  8910. void wait_event(DataSink *sink) {
  8911. unique_lock<mutex> lk(m_);
  8912. int id = id_;
  8913. cv_.wait(lk, [&] { return cid_ == id; });
  8914. sink->write(message_.data(), message_.size());
  8915. }
  8916. void send_event(const string &message) {
  8917. lock_guard<mutex> lk(m_);
  8918. cid_ = id_++;
  8919. message_ = message;
  8920. cv_.notify_all();
  8921. }
  8922. private:
  8923. mutex m_;
  8924. condition_variable cv_;
  8925. atomic_int id_{0};
  8926. atomic_int cid_{-1};
  8927. string message_;
  8928. };
  8929. TEST(ClientInThreadTest, Issue2068) {
  8930. EventDispatcher ed;
  8931. Server svr;
  8932. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8933. res.set_chunked_content_provider("text/event-stream",
  8934. [&](size_t /*offset*/, DataSink &sink) {
  8935. ed.wait_event(&sink);
  8936. return true;
  8937. });
  8938. });
  8939. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8940. svr.wait_until_ready();
  8941. thread event_thread([&] {
  8942. int id = 0;
  8943. while (svr.is_running()) {
  8944. this_thread::sleep_for(chrono::milliseconds(500));
  8945. std::stringstream ss;
  8946. ss << "data: " << id << "\n\n";
  8947. ed.send_event(ss.str());
  8948. id++;
  8949. }
  8950. });
  8951. auto se = detail::scope_exit([&] {
  8952. svr.stop();
  8953. listen_thread.join();
  8954. event_thread.join();
  8955. ASSERT_FALSE(svr.is_running());
  8956. });
  8957. {
  8958. auto client = detail::make_unique<Client>(HOST, PORT);
  8959. client->set_read_timeout(std::chrono::minutes(10));
  8960. std::atomic<bool> stop{false};
  8961. std::thread t([&] {
  8962. client->Get("/event1",
  8963. [&](const char *, size_t) -> bool { return !stop; });
  8964. });
  8965. std::this_thread::sleep_for(std::chrono::seconds(2));
  8966. stop = true;
  8967. client->stop();
  8968. client.reset();
  8969. t.join();
  8970. }
  8971. }
  8972. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8973. Server svr;
  8974. svr.Get("/", [](const Request &req, Response &res) {
  8975. EXPECT_EQ(2U, req.trailers.size());
  8976. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8977. // Denied
  8978. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8979. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8980. // Accepted
  8981. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8982. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  8983. EXPECT_TRUE(req.has_trailer("X-World"));
  8984. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  8985. res.set_content("ok", "text/plain");
  8986. });
  8987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. ASSERT_FALSE(svr.is_running());
  8992. });
  8993. svr.wait_until_ready();
  8994. const std::string req = "GET / HTTP/1.1\r\n"
  8995. "Transfer-Encoding: chunked\r\n"
  8996. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  8997. "\r\n"
  8998. "0\r\n"
  8999. "Content-Length: 10\r\n"
  9000. "Host: internal.local\r\n"
  9001. "Content-Type: malicious/content\r\n"
  9002. "Cookie: any\r\n"
  9003. "Set-Cookie: any\r\n"
  9004. "X-Forwarded-For: attacker.com\r\n"
  9005. "X-Real-Ip: 1.1.1.1\r\n"
  9006. "X-Hello: hello\r\n"
  9007. "X-World: world\r\n"
  9008. "\r\n";
  9009. std::string res;
  9010. ASSERT_TRUE(send_request(1, req, &res));
  9011. }