test.cc 285 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438
  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. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodeURLTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_url(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodeURLTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(TrimTests, TrimStringTests) {
  252. EXPECT_EQ("abc", detail::trim_copy("abc"));
  253. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  254. EXPECT_TRUE(detail::trim_copy("").empty());
  255. }
  256. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  257. // Simple case without quality values
  258. std::vector<std::string> result1;
  259. EXPECT_TRUE(detail::parse_accept_header(
  260. "text/html,application/json,text/plain", result1));
  261. EXPECT_EQ(result1.size(), 3);
  262. EXPECT_EQ(result1[0], "text/html");
  263. EXPECT_EQ(result1[1], "application/json");
  264. EXPECT_EQ(result1[2], "text/plain");
  265. // With quality values
  266. std::vector<std::string> result2;
  267. EXPECT_TRUE(detail::parse_accept_header(
  268. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  269. EXPECT_EQ(result2.size(), 3);
  270. EXPECT_EQ(result2[0], "application/json"); // highest q value
  271. EXPECT_EQ(result2[1], "text/html");
  272. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  273. }
  274. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  275. // Mixed with and without quality values
  276. std::vector<std::string> result;
  277. EXPECT_TRUE(detail::parse_accept_header(
  278. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  279. EXPECT_EQ(result.size(), 3);
  280. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  281. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  282. EXPECT_EQ(result[2], "application/json"); // q=0.5
  283. }
  284. TEST(ParseAcceptHeaderTest, EdgeCases) {
  285. // Empty header
  286. std::vector<std::string> empty_result;
  287. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  288. EXPECT_TRUE(empty_result.empty());
  289. // Single type
  290. std::vector<std::string> single_result;
  291. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  292. EXPECT_EQ(single_result.size(), 1);
  293. EXPECT_EQ(single_result[0], "application/json");
  294. // Wildcard types
  295. std::vector<std::string> wildcard_result;
  296. EXPECT_TRUE(detail::parse_accept_header(
  297. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  298. EXPECT_EQ(wildcard_result.size(), 3);
  299. EXPECT_EQ(wildcard_result[0], "application/json");
  300. EXPECT_EQ(wildcard_result[1], "text/*");
  301. EXPECT_EQ(wildcard_result[2], "*/*");
  302. }
  303. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  304. // Common browser Accept header
  305. std::vector<std::string> browser_result;
  306. EXPECT_TRUE(
  307. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  308. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  309. browser_result));
  310. EXPECT_EQ(browser_result.size(), 6);
  311. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  312. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  313. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  314. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  315. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  316. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  317. // API client header
  318. std::vector<std::string> api_result;
  319. EXPECT_TRUE(detail::parse_accept_header(
  320. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  321. api_result));
  322. EXPECT_EQ(api_result.size(), 3);
  323. EXPECT_EQ(api_result[0], "application/json");
  324. EXPECT_EQ(api_result[1], "application/xml");
  325. EXPECT_EQ(api_result[2], "text/plain");
  326. }
  327. TEST(ParseAcceptHeaderTest, SpecialCases) {
  328. // Quality value with 3 decimal places
  329. std::vector<std::string> decimal_result;
  330. EXPECT_TRUE(detail::parse_accept_header(
  331. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  332. EXPECT_EQ(decimal_result.size(), 2);
  333. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  334. EXPECT_EQ(decimal_result[1], "text/html");
  335. // Zero quality (should still be included but with lowest priority)
  336. std::vector<std::string> zero_q_result;
  337. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  338. zero_q_result));
  339. EXPECT_EQ(zero_q_result.size(), 2);
  340. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  341. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  342. // No spaces around commas
  343. std::vector<std::string> no_space_result;
  344. EXPECT_TRUE(detail::parse_accept_header(
  345. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  346. no_space_result));
  347. EXPECT_EQ(no_space_result.size(), 3);
  348. EXPECT_EQ(no_space_result[0], "text/html");
  349. EXPECT_EQ(no_space_result[1], "application/json");
  350. EXPECT_EQ(no_space_result[2], "text/plain");
  351. }
  352. TEST(ParseAcceptHeaderTest, InvalidCases) {
  353. std::vector<std::string> result;
  354. // Invalid quality value (> 1.0)
  355. EXPECT_FALSE(
  356. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  357. // Invalid quality value (< 0.0)
  358. EXPECT_FALSE(
  359. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  360. // Invalid quality value (not a number)
  361. EXPECT_FALSE(detail::parse_accept_header(
  362. "text/html;q=invalid,application/json", result));
  363. // Empty quality value
  364. EXPECT_FALSE(
  365. detail::parse_accept_header("text/html;q=,application/json", result));
  366. // Invalid media type format (no slash and not wildcard)
  367. EXPECT_FALSE(
  368. detail::parse_accept_header("invalidtype,application/json", result));
  369. // Empty media type
  370. result.clear();
  371. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  372. // Only commas
  373. result.clear();
  374. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  375. // Valid cases should still work
  376. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  377. EXPECT_EQ(result.size(), 1);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1);
  384. EXPECT_EQ(result[0], "text/*");
  385. }
  386. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  387. Server svr;
  388. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  389. EXPECT_EQ(req.accept_content_types.size(), 3);
  390. EXPECT_EQ(req.accept_content_types[0], "application/json");
  391. EXPECT_EQ(req.accept_content_types[1], "text/html");
  392. EXPECT_EQ(req.accept_content_types[2], "*/*");
  393. res.set_content("ok", "text/plain");
  394. });
  395. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  396. EXPECT_TRUE(false);
  397. res.set_content("bad request", "text/plain");
  398. });
  399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  400. auto se = detail::scope_exit([&] {
  401. svr.stop();
  402. listen_thread.join();
  403. ASSERT_FALSE(svr.is_running());
  404. });
  405. svr.wait_until_ready();
  406. Client cli("localhost", PORT);
  407. {
  408. auto res =
  409. cli.Get("/accept_ok",
  410. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ(StatusCode::OK_200, res->status);
  413. }
  414. {
  415. auto res = cli.Get("/accept_bad_request",
  416. {{"Accept", "text/html;q=abc,application/json"}});
  417. ASSERT_TRUE(res);
  418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  419. }
  420. }
  421. TEST(DivideTest, DivideStringTests) {
  422. auto divide = [](const std::string &str, char d) {
  423. std::string lhs;
  424. std::string rhs;
  425. detail::divide(str, d,
  426. [&](const char *lhs_data, std::size_t lhs_size,
  427. const char *rhs_data, std::size_t rhs_size) {
  428. lhs.assign(lhs_data, lhs_size);
  429. rhs.assign(rhs_data, rhs_size);
  430. });
  431. return std::make_pair(std::move(lhs), std::move(rhs));
  432. };
  433. {
  434. const auto res = divide("", '=');
  435. EXPECT_EQ(res.first, "");
  436. EXPECT_EQ(res.second, "");
  437. }
  438. {
  439. const auto res = divide("=", '=');
  440. EXPECT_EQ(res.first, "");
  441. EXPECT_EQ(res.second, "");
  442. }
  443. {
  444. const auto res = divide(" ", '=');
  445. EXPECT_EQ(res.first, " ");
  446. EXPECT_EQ(res.second, "");
  447. }
  448. {
  449. const auto res = divide("a", '=');
  450. EXPECT_EQ(res.first, "a");
  451. EXPECT_EQ(res.second, "");
  452. }
  453. {
  454. const auto res = divide("a=", '=');
  455. EXPECT_EQ(res.first, "a");
  456. EXPECT_EQ(res.second, "");
  457. }
  458. {
  459. const auto res = divide("=b", '=');
  460. EXPECT_EQ(res.first, "");
  461. EXPECT_EQ(res.second, "b");
  462. }
  463. {
  464. const auto res = divide("a=b", '=');
  465. EXPECT_EQ(res.first, "a");
  466. EXPECT_EQ(res.second, "b");
  467. }
  468. {
  469. const auto res = divide("a=b=", '=');
  470. EXPECT_EQ(res.first, "a");
  471. EXPECT_EQ(res.second, "b=");
  472. }
  473. {
  474. const auto res = divide("a=b=c", '=');
  475. EXPECT_EQ(res.first, "a");
  476. EXPECT_EQ(res.second, "b=c");
  477. }
  478. }
  479. TEST(SplitTest, ParseQueryString) {
  480. string s = "key1=val1&key2=val2&key3=val3";
  481. Params dic;
  482. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  483. [&](const char *b, const char *e) {
  484. string key, val;
  485. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  486. if (key.empty()) {
  487. key.assign(b2, e2);
  488. } else {
  489. val.assign(b2, e2);
  490. }
  491. });
  492. dic.emplace(key, val);
  493. });
  494. EXPECT_EQ("val1", dic.find("key1")->second);
  495. EXPECT_EQ("val2", dic.find("key2")->second);
  496. EXPECT_EQ("val3", dic.find("key3")->second);
  497. }
  498. TEST(SplitTest, ParseInvalidQueryTests) {
  499. {
  500. string s = " ";
  501. Params dict;
  502. detail::parse_query_text(s, dict);
  503. EXPECT_TRUE(dict.empty());
  504. }
  505. {
  506. string s = " = =";
  507. Params dict;
  508. detail::parse_query_text(s, dict);
  509. EXPECT_TRUE(dict.empty());
  510. }
  511. }
  512. TEST(ParseQueryTest, ParseQueryString) {
  513. {
  514. std::string s = "key1=val1&key2=val2&key3=val3";
  515. Params dic;
  516. detail::parse_query_text(s, dic);
  517. EXPECT_EQ("val1", dic.find("key1")->second);
  518. EXPECT_EQ("val2", dic.find("key2")->second);
  519. EXPECT_EQ("val3", dic.find("key3")->second);
  520. }
  521. {
  522. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  523. Params dic;
  524. detail::parse_query_text(s, dic);
  525. EXPECT_EQ("", dic.find("key1")->second);
  526. EXPECT_EQ("val1", dic.find("key2")->second);
  527. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  528. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  529. }
  530. }
  531. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  532. Params dic;
  533. EXPECT_EQ(detail::params_to_query_str(dic), "");
  534. dic.emplace("key1", "val1");
  535. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  536. dic.emplace("key2", "val2");
  537. dic.emplace("key3", "val3");
  538. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  539. }
  540. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  541. string content_type = "multipart/form-data; boundary=something";
  542. string boundary;
  543. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  544. EXPECT_TRUE(ret);
  545. EXPECT_EQ(boundary, "something");
  546. }
  547. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  548. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  549. string boundary;
  550. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  551. EXPECT_TRUE(ret);
  552. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  553. }
  554. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  555. string content_type =
  556. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  557. string boundary;
  558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  559. EXPECT_TRUE(ret);
  560. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  561. }
  562. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  563. string content_type =
  564. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  565. string boundary;
  566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  567. EXPECT_TRUE(ret);
  568. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  569. }
  570. TEST(GetHeaderValueTest, DefaultValue) {
  571. Headers headers = {{"Dummy", "Dummy"}};
  572. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  573. EXPECT_STREQ("text/plain", val);
  574. }
  575. TEST(GetHeaderValueTest, DefaultValueInt) {
  576. Headers headers = {{"Dummy", "Dummy"}};
  577. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  578. EXPECT_EQ(100ull, val);
  579. }
  580. TEST(GetHeaderValueTest, RegularValue) {
  581. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  582. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  583. EXPECT_STREQ("text/html", val);
  584. }
  585. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  586. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  587. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  588. EXPECT_STREQ("text/html", val);
  589. }
  590. TEST(GetHeaderValueTest, SetContent) {
  591. Response res;
  592. res.set_content("html", "text/html");
  593. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  594. res.set_content("text", "text/plain");
  595. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  596. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  597. }
  598. TEST(GetHeaderValueTest, RegularValueInt) {
  599. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  600. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  601. EXPECT_EQ(100ull, val);
  602. }
  603. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  604. Headers headers = {{"Content-Length", "x"}};
  605. auto is_invalid_value = false;
  606. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  607. is_invalid_value);
  608. EXPECT_EQ(0ull, val);
  609. EXPECT_TRUE(is_invalid_value);
  610. }
  611. TEST(GetHeaderValueTest, Range) {
  612. {
  613. Headers headers = {make_range_header({{1, -1}})};
  614. auto val = detail::get_header_value(headers, "Range", 0, 0);
  615. EXPECT_STREQ("bytes=1-", val);
  616. }
  617. {
  618. Headers headers = {make_range_header({{-1, 1}})};
  619. auto val = detail::get_header_value(headers, "Range", 0, 0);
  620. EXPECT_STREQ("bytes=-1", val);
  621. }
  622. {
  623. Headers headers = {make_range_header({{1, 10}})};
  624. auto val = detail::get_header_value(headers, "Range", 0, 0);
  625. EXPECT_STREQ("bytes=1-10", val);
  626. }
  627. {
  628. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  629. auto val = detail::get_header_value(headers, "Range", 0, 0);
  630. EXPECT_STREQ("bytes=1-10, 100-", val);
  631. }
  632. {
  633. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  634. auto val = detail::get_header_value(headers, "Range", 0, 0);
  635. EXPECT_STREQ("bytes=1-10, 100-200", val);
  636. }
  637. {
  638. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  639. auto val = detail::get_header_value(headers, "Range", 0, 0);
  640. EXPECT_STREQ("bytes=0-0, -1", val);
  641. }
  642. }
  643. TEST(ParseHeaderValueTest, Range) {
  644. {
  645. Ranges ranges;
  646. auto ret = detail::parse_range_header("bytes=1-", ranges);
  647. EXPECT_TRUE(ret);
  648. EXPECT_EQ(1u, ranges.size());
  649. EXPECT_EQ(1u, ranges[0].first);
  650. EXPECT_EQ(-1, ranges[0].second);
  651. }
  652. {
  653. Ranges ranges;
  654. auto ret = detail::parse_range_header("bytes=-1", ranges);
  655. EXPECT_TRUE(ret);
  656. EXPECT_EQ(1u, ranges.size());
  657. EXPECT_EQ(-1, ranges[0].first);
  658. EXPECT_EQ(1u, ranges[0].second);
  659. }
  660. {
  661. Ranges ranges;
  662. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(1u, ranges.size());
  665. EXPECT_EQ(1u, ranges[0].first);
  666. EXPECT_EQ(10u, ranges[0].second);
  667. }
  668. {
  669. Ranges ranges;
  670. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  671. EXPECT_FALSE(ret);
  672. }
  673. {
  674. Ranges ranges;
  675. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  676. EXPECT_TRUE(ret);
  677. EXPECT_EQ(2u, ranges.size());
  678. EXPECT_EQ(1u, ranges[0].first);
  679. EXPECT_EQ(10u, ranges[0].second);
  680. EXPECT_EQ(100u, ranges[1].first);
  681. EXPECT_EQ(-1, ranges[1].second);
  682. }
  683. {
  684. Ranges ranges;
  685. auto ret =
  686. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  687. EXPECT_TRUE(ret);
  688. EXPECT_EQ(3u, ranges.size());
  689. EXPECT_EQ(1u, ranges[0].first);
  690. EXPECT_EQ(10u, ranges[0].second);
  691. EXPECT_EQ(100u, ranges[1].first);
  692. EXPECT_EQ(200u, ranges[1].second);
  693. EXPECT_EQ(300u, ranges[2].first);
  694. EXPECT_EQ(400u, ranges[2].second);
  695. }
  696. {
  697. Ranges ranges;
  698. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  699. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  700. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  701. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  702. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  703. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  704. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  705. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  706. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  707. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  708. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  709. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  710. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  711. EXPECT_TRUE(ranges.empty());
  712. }
  713. }
  714. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  715. Request req;
  716. req.set_header("Accept-Encoding", "gzip");
  717. Response res;
  718. res.set_header("Content-Type", "text/plain");
  719. auto ret = detail::encoding_type(req, res);
  720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  721. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  722. #else
  723. EXPECT_TRUE(ret == detail::EncodingType::None);
  724. #endif
  725. }
  726. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  727. Request req;
  728. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  729. Response res;
  730. res.set_header("Content-Type", "text/plain");
  731. auto ret = detail::encoding_type(req, res);
  732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  733. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  734. #elif CPPHTTPLIB_ZLIB_SUPPORT
  735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  736. #elif CPPHTTPLIB_ZSTD_SUPPORT
  737. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  738. #else
  739. EXPECT_TRUE(ret == detail::EncodingType::None);
  740. #endif
  741. }
  742. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  743. Request req;
  744. req.set_header("Accept-Encoding",
  745. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  746. Response res;
  747. res.set_header("Content-Type", "text/plain");
  748. auto ret = detail::encoding_type(req, res);
  749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  750. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  751. #elif CPPHTTPLIB_ZLIB_SUPPORT
  752. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  753. #elif CPPHTTPLIB_ZSTD_SUPPORT
  754. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  755. #else
  756. EXPECT_TRUE(ret == detail::EncodingType::None);
  757. #endif
  758. }
  759. TEST(BufferStreamTest, read) {
  760. detail::BufferStream strm1;
  761. Stream &strm = strm1;
  762. EXPECT_EQ(5, strm.write("hello"));
  763. char buf[512];
  764. EXPECT_EQ(2, strm.read(buf, 2));
  765. EXPECT_EQ('h', buf[0]);
  766. EXPECT_EQ('e', buf[1]);
  767. EXPECT_EQ(2, strm.read(buf, 2));
  768. EXPECT_EQ('l', buf[0]);
  769. EXPECT_EQ('l', buf[1]);
  770. EXPECT_EQ(1, strm.read(buf, 1));
  771. EXPECT_EQ('o', buf[0]);
  772. EXPECT_EQ(0, strm.read(buf, 1));
  773. }
  774. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  777. auto port = 443;
  778. SSLClient cli(host, port);
  779. #else
  780. auto port = 80;
  781. Client cli(host, port);
  782. #endif
  783. cli.set_connection_timeout(2);
  784. auto res =
  785. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  786. ASSERT_TRUE(res);
  787. std::string out;
  788. read_file("./image.jpg", out);
  789. EXPECT_EQ(StatusCode::OK_200, res->status);
  790. EXPECT_EQ(out, res->body);
  791. }
  792. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  793. auto host = "www.httpwatch.com";
  794. auto ip = hosted_at(host);
  795. EXPECT_EQ("23.96.13.243", ip);
  796. std::vector<std::string> addrs;
  797. hosted_at(host, addrs);
  798. EXPECT_EQ(1u, addrs.size());
  799. }
  800. #if 0 // It depends on each test environment...
  801. TEST(HostnameToIPConversionTest, YouTube_Online) {
  802. auto host = "www.youtube.com";
  803. std::vector<std::string> addrs;
  804. hosted_at(host, addrs);
  805. EXPECT_EQ(20u, addrs.size());
  806. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  807. EXPECT_TRUE(it != addrs.end());
  808. }
  809. #endif
  810. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  811. auto host = "www.httpwatch.com";
  812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  813. auto port = 443;
  814. SSLClient cli(host, port);
  815. #else
  816. auto port = 80;
  817. Client cli(host, port);
  818. #endif
  819. cli.set_connection_timeout(2);
  820. std::string body;
  821. auto res =
  822. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  823. [&](const char *data, size_t data_length) {
  824. body.append(data, data_length);
  825. return true;
  826. });
  827. ASSERT_TRUE(res);
  828. std::string out;
  829. read_file("./image.jpg", out);
  830. EXPECT_EQ(StatusCode::OK_200, res->status);
  831. EXPECT_EQ(out, body);
  832. }
  833. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  834. auto host = "www.httpwatch.com";
  835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  836. auto port = 443;
  837. SSLClient cli(host, port);
  838. #else
  839. auto port = 80;
  840. Client cli(host, port);
  841. #endif
  842. cli.set_connection_timeout(2);
  843. std::string body;
  844. auto res = cli.Get(
  845. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  846. [&](const Response &response) {
  847. EXPECT_EQ(StatusCode::OK_200, response.status);
  848. return true;
  849. },
  850. [&](const char *data, size_t data_length) {
  851. body.append(data, data_length);
  852. return true;
  853. });
  854. ASSERT_TRUE(res);
  855. std::string out;
  856. read_file("./image.jpg", out);
  857. EXPECT_EQ(StatusCode::OK_200, res->status);
  858. EXPECT_EQ(out, body);
  859. }
  860. TEST(RangeTest, FromHTTPBin_Online) {
  861. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  862. auto host = "httpbin.org";
  863. auto path = std::string{"/range/32"};
  864. #else
  865. auto host = "nghttp2.org";
  866. auto path = std::string{"/httpbin/range/32"};
  867. #endif
  868. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  869. auto port = 443;
  870. SSLClient cli(host, port);
  871. #else
  872. auto port = 80;
  873. Client cli(host, port);
  874. #endif
  875. cli.set_connection_timeout(5);
  876. {
  877. auto res = cli.Get(path);
  878. ASSERT_TRUE(res);
  879. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  880. EXPECT_EQ(StatusCode::OK_200, res->status);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, -1}})};
  884. auto res = cli.Get(path, headers);
  885. ASSERT_TRUE(res);
  886. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  888. }
  889. {
  890. Headers headers = {make_range_header({{1, 10}})};
  891. auto res = cli.Get(path, headers);
  892. ASSERT_TRUE(res);
  893. EXPECT_EQ("bcdefghijk", res->body);
  894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  895. }
  896. {
  897. Headers headers = {make_range_header({{0, 31}})};
  898. auto res = cli.Get(path, headers);
  899. ASSERT_TRUE(res);
  900. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. }
  903. {
  904. Headers headers = {make_range_header({{0, -1}})};
  905. auto res = cli.Get(path, headers);
  906. ASSERT_TRUE(res);
  907. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  908. EXPECT_EQ(StatusCode::OK_200, res->status);
  909. }
  910. {
  911. Headers headers = {make_range_header({{0, 32}})};
  912. auto res = cli.Get(path, headers);
  913. ASSERT_TRUE(res);
  914. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  915. }
  916. }
  917. TEST(ConnectionErrorTest, InvalidHost) {
  918. auto host = "-abcde.com";
  919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  920. auto port = 443;
  921. SSLClient cli(host, port);
  922. #else
  923. auto port = 80;
  924. Client cli(host, port);
  925. #endif
  926. cli.set_connection_timeout(std::chrono::seconds(2));
  927. auto res = cli.Get("/");
  928. ASSERT_TRUE(!res);
  929. EXPECT_EQ(Error::Connection, res.error());
  930. }
  931. TEST(ConnectionErrorTest, InvalidHost2) {
  932. auto host = "httpbin.org/";
  933. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  934. SSLClient cli(host);
  935. #else
  936. Client cli(host);
  937. #endif
  938. cli.set_connection_timeout(std::chrono::seconds(2));
  939. auto res = cli.Get("/");
  940. ASSERT_TRUE(!res);
  941. EXPECT_EQ(Error::Connection, res.error());
  942. }
  943. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  944. auto host = "httpbin.org/";
  945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  946. SSLClient cli(host);
  947. #else
  948. Client cli(host);
  949. #endif
  950. cli.set_connection_timeout(std::chrono::seconds(2));
  951. auto res = cli.Get("/");
  952. ASSERT_TRUE(!res);
  953. stringstream s;
  954. s << "error code: " << res.error();
  955. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  956. }
  957. TEST(ConnectionErrorTest, InvalidPort) {
  958. auto host = "localhost";
  959. auto port = 44380;
  960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  961. SSLClient cli(host, port);
  962. #else
  963. Client cli(host, port);
  964. #endif
  965. cli.set_connection_timeout(std::chrono::seconds(2));
  966. auto res = cli.Get("/");
  967. ASSERT_TRUE(!res);
  968. EXPECT_TRUE(Error::Connection == res.error() ||
  969. Error::ConnectionTimeout == res.error());
  970. }
  971. TEST(ConnectionErrorTest, Timeout_Online) {
  972. auto host = "google.com";
  973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  974. auto port = 44380;
  975. SSLClient cli(host, port);
  976. #else
  977. auto port = 8080;
  978. Client cli(host, port);
  979. #endif
  980. cli.set_connection_timeout(std::chrono::seconds(2));
  981. // only probe one address type so that the error reason
  982. // correlates to the timed-out IPv4, not the unsupported
  983. // IPv6 connection attempt
  984. cli.set_address_family(AF_INET);
  985. auto res = cli.Get("/");
  986. ASSERT_TRUE(!res);
  987. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  988. }
  989. TEST(CancelTest, NoCancel_Online) {
  990. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  991. auto host = "httpbin.org";
  992. auto path = std::string{"/range/32"};
  993. #else
  994. auto host = "nghttp2.org";
  995. auto path = std::string{"/httpbin/range/32"};
  996. #endif
  997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  998. auto port = 443;
  999. SSLClient cli(host, port);
  1000. #else
  1001. auto port = 80;
  1002. Client cli(host, port);
  1003. #endif
  1004. cli.set_connection_timeout(std::chrono::seconds(5));
  1005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1006. ASSERT_TRUE(res);
  1007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1008. EXPECT_EQ(StatusCode::OK_200, res->status);
  1009. }
  1010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1011. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1012. auto host = "httpbin.org";
  1013. auto path = std::string{"/range/32"};
  1014. #else
  1015. auto host = "nghttp2.org";
  1016. auto path = std::string{"/httpbin/range/32"};
  1017. #endif
  1018. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1019. auto port = 443;
  1020. SSLClient cli(host, port);
  1021. #else
  1022. auto port = 80;
  1023. Client cli(host, port);
  1024. #endif
  1025. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1026. cli.set_connection_timeout(std::chrono::seconds(5));
  1027. ASSERT_TRUE(!res);
  1028. EXPECT_EQ(Error::Canceled, res.error());
  1029. }
  1030. TEST(CancelTest, WithCancelLargePayload_Online) {
  1031. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1032. auto host = "httpbin.org";
  1033. auto path = std::string{"/range/65536"};
  1034. #else
  1035. auto host = "nghttp2.org";
  1036. auto path = std::string{"/httpbin/range/65536"};
  1037. #endif
  1038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1039. auto port = 443;
  1040. SSLClient cli(host, port);
  1041. #else
  1042. auto port = 80;
  1043. Client cli(host, port);
  1044. #endif
  1045. cli.set_connection_timeout(std::chrono::seconds(5));
  1046. uint32_t count = 0;
  1047. auto res =
  1048. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1049. ASSERT_TRUE(!res);
  1050. EXPECT_EQ(Error::Canceled, res.error());
  1051. }
  1052. TEST(CancelTest, NoCancelPost) {
  1053. Server svr;
  1054. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1055. res.set_content("Hello World!", "text/plain");
  1056. });
  1057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1058. auto se = detail::scope_exit([&] {
  1059. svr.stop();
  1060. thread.join();
  1061. ASSERT_FALSE(svr.is_running());
  1062. });
  1063. svr.wait_until_ready();
  1064. Client cli(HOST, PORT);
  1065. cli.set_connection_timeout(std::chrono::seconds(5));
  1066. auto res =
  1067. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1068. "application/json", [](uint64_t, uint64_t) { return true; });
  1069. ASSERT_TRUE(res);
  1070. EXPECT_EQ("Hello World!", res->body);
  1071. EXPECT_EQ(StatusCode::OK_200, res->status);
  1072. }
  1073. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1074. Server svr;
  1075. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1076. res.set_content("Hello World!", "text/plain");
  1077. });
  1078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1079. auto se = detail::scope_exit([&] {
  1080. svr.stop();
  1081. thread.join();
  1082. ASSERT_FALSE(svr.is_running());
  1083. });
  1084. svr.wait_until_ready();
  1085. Client cli(HOST, PORT);
  1086. cli.set_connection_timeout(std::chrono::seconds(5));
  1087. auto res =
  1088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1089. "application/json", [](uint64_t, uint64_t) { return false; });
  1090. ASSERT_TRUE(!res);
  1091. EXPECT_EQ(Error::Canceled, res.error());
  1092. }
  1093. TEST(CancelTest, WithCancelLargePayloadPost) {
  1094. Server svr;
  1095. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1096. res.set_content(LARGE_DATA, "text/plain");
  1097. });
  1098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1099. auto se = detail::scope_exit([&] {
  1100. svr.stop();
  1101. thread.join();
  1102. ASSERT_FALSE(svr.is_running());
  1103. });
  1104. svr.wait_until_ready();
  1105. Client cli(HOST, PORT);
  1106. cli.set_connection_timeout(std::chrono::seconds(5));
  1107. auto res =
  1108. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1109. "application/json", [](uint64_t, uint64_t) { return false; });
  1110. ASSERT_TRUE(!res);
  1111. EXPECT_EQ(Error::Canceled, res.error());
  1112. }
  1113. TEST(CancelTest, NoCancelPut) {
  1114. Server svr;
  1115. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1119. auto se = detail::scope_exit([&] {
  1120. svr.stop();
  1121. thread.join();
  1122. ASSERT_FALSE(svr.is_running());
  1123. });
  1124. svr.wait_until_ready();
  1125. Client cli(HOST, PORT);
  1126. cli.set_connection_timeout(std::chrono::seconds(5));
  1127. auto res =
  1128. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1129. "application/json", [](uint64_t, uint64_t) { return true; });
  1130. ASSERT_TRUE(res);
  1131. EXPECT_EQ("Hello World!", res->body);
  1132. EXPECT_EQ(StatusCode::OK_200, res->status);
  1133. }
  1134. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1135. Server svr;
  1136. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1137. res.set_content("Hello World!", "text/plain");
  1138. });
  1139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli(HOST, PORT);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res =
  1149. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1150. "application/json", [](uint64_t, uint64_t) { return false; });
  1151. ASSERT_TRUE(!res);
  1152. EXPECT_EQ(Error::Canceled, res.error());
  1153. }
  1154. TEST(CancelTest, WithCancelLargePayloadPut) {
  1155. Server svr;
  1156. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1157. res.set_content(LARGE_DATA, "text/plain");
  1158. });
  1159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1160. auto se = detail::scope_exit([&] {
  1161. svr.stop();
  1162. thread.join();
  1163. ASSERT_FALSE(svr.is_running());
  1164. });
  1165. svr.wait_until_ready();
  1166. Client cli(HOST, PORT);
  1167. cli.set_connection_timeout(std::chrono::seconds(5));
  1168. auto res =
  1169. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1170. "application/json", [](uint64_t, uint64_t) { return false; });
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Canceled, res.error());
  1173. }
  1174. TEST(CancelTest, NoCancelPatch) {
  1175. Server svr;
  1176. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1177. res.set_content("Hello World!", "text/plain");
  1178. });
  1179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1180. auto se = detail::scope_exit([&] {
  1181. svr.stop();
  1182. thread.join();
  1183. ASSERT_FALSE(svr.is_running());
  1184. });
  1185. svr.wait_until_ready();
  1186. Client cli(HOST, PORT);
  1187. cli.set_connection_timeout(std::chrono::seconds(5));
  1188. auto res =
  1189. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1190. "application/json", [](uint64_t, uint64_t) { return true; });
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("Hello World!", res->body);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. }
  1195. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1196. Server svr;
  1197. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1198. res.set_content("Hello World!", "text/plain");
  1199. });
  1200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1201. auto se = detail::scope_exit([&] {
  1202. svr.stop();
  1203. thread.join();
  1204. ASSERT_FALSE(svr.is_running());
  1205. });
  1206. svr.wait_until_ready();
  1207. Client cli(HOST, PORT);
  1208. cli.set_connection_timeout(std::chrono::seconds(5));
  1209. auto res =
  1210. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1211. "application/json", [](uint64_t, uint64_t) { return false; });
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Canceled, res.error());
  1214. }
  1215. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1216. Server svr;
  1217. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1218. res.set_content(LARGE_DATA, "text/plain");
  1219. });
  1220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1221. auto se = detail::scope_exit([&] {
  1222. svr.stop();
  1223. thread.join();
  1224. ASSERT_FALSE(svr.is_running());
  1225. });
  1226. svr.wait_until_ready();
  1227. Client cli(HOST, PORT);
  1228. cli.set_connection_timeout(std::chrono::seconds(5));
  1229. auto res =
  1230. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1231. "application/json", [](uint64_t, uint64_t) { return false; });
  1232. ASSERT_TRUE(!res);
  1233. EXPECT_EQ(Error::Canceled, res.error());
  1234. }
  1235. TEST(CancelTest, NoCancelDelete) {
  1236. Server svr;
  1237. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1238. res.set_content("Hello World!", "text/plain");
  1239. });
  1240. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. thread.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. Client cli(HOST, PORT);
  1248. cli.set_connection_timeout(std::chrono::seconds(5));
  1249. auto res =
  1250. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1251. "application/json", [](uint64_t, uint64_t) { return true; });
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ("Hello World!", res->body);
  1254. EXPECT_EQ(StatusCode::OK_200, res->status);
  1255. }
  1256. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1257. Server svr;
  1258. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1259. res.set_content("Hello World!", "text/plain");
  1260. });
  1261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1262. auto se = detail::scope_exit([&] {
  1263. svr.stop();
  1264. thread.join();
  1265. ASSERT_FALSE(svr.is_running());
  1266. });
  1267. svr.wait_until_ready();
  1268. Client cli(HOST, PORT);
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. auto res =
  1271. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1272. "application/json", [](uint64_t, uint64_t) { return false; });
  1273. ASSERT_TRUE(!res);
  1274. EXPECT_EQ(Error::Canceled, res.error());
  1275. }
  1276. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1277. Server svr;
  1278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1279. res.set_content(LARGE_DATA, "text/plain");
  1280. });
  1281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1282. auto se = detail::scope_exit([&] {
  1283. svr.stop();
  1284. thread.join();
  1285. ASSERT_FALSE(svr.is_running());
  1286. });
  1287. svr.wait_until_ready();
  1288. Client cli(HOST, PORT);
  1289. cli.set_connection_timeout(std::chrono::seconds(5));
  1290. auto res =
  1291. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1292. "application/json", [](uint64_t, uint64_t) { return false; });
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_EQ(Error::Canceled, res.error());
  1295. }
  1296. static std::string remove_whitespace(const std::string &input) {
  1297. std::string output;
  1298. output.reserve(input.size());
  1299. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1300. [](unsigned char c) { return !std::isspace(c); });
  1301. return output;
  1302. }
  1303. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpbin.org";
  1306. auto path = std::string{"/basic-auth/hello/world"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. {
  1319. auto res = cli.Get(path);
  1320. ASSERT_TRUE(res);
  1321. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1322. }
  1323. {
  1324. auto res =
  1325. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1326. ASSERT_TRUE(res);
  1327. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1328. remove_whitespace(res->body));
  1329. EXPECT_EQ(StatusCode::OK_200, res->status);
  1330. }
  1331. {
  1332. cli.set_basic_auth("hello", "world");
  1333. auto res = cli.Get(path);
  1334. ASSERT_TRUE(res);
  1335. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1336. remove_whitespace(res->body));
  1337. EXPECT_EQ(StatusCode::OK_200, res->status);
  1338. }
  1339. {
  1340. cli.set_basic_auth("hello", "bad");
  1341. auto res = cli.Get(path);
  1342. ASSERT_TRUE(res);
  1343. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1344. }
  1345. {
  1346. cli.set_basic_auth("bad", "world");
  1347. auto res = cli.Get(path);
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1350. }
  1351. }
  1352. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1353. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1354. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1355. auto host = "httpbin.org";
  1356. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1357. auto paths = std::vector<std::string>{
  1358. "/digest-auth/auth/hello/world/MD5",
  1359. "/digest-auth/auth/hello/world/SHA-256",
  1360. "/digest-auth/auth/hello/world/SHA-512",
  1361. "/digest-auth/auth-int/hello/world/MD5",
  1362. };
  1363. #else
  1364. auto host = "nghttp2.org";
  1365. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1366. auto paths = std::vector<std::string>{
  1367. "/httpbin/digest-auth/auth/hello/world/MD5",
  1368. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1369. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1370. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1371. };
  1372. #endif
  1373. auto port = 443;
  1374. SSLClient cli(host, port);
  1375. {
  1376. auto res = cli.Get(unauth_path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. {
  1381. cli.set_digest_auth("hello", "world");
  1382. for (const auto &path : paths) {
  1383. auto res = cli.Get(path.c_str());
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1386. remove_whitespace(res->body));
  1387. EXPECT_EQ(StatusCode::OK_200, res->status);
  1388. }
  1389. cli.set_digest_auth("hello", "bad");
  1390. for (const auto &path : paths) {
  1391. auto res = cli.Get(path.c_str());
  1392. ASSERT_TRUE(res);
  1393. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1394. }
  1395. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1396. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1397. // cli.set_digest_auth("bad", "world");
  1398. // for (const auto& path : paths) {
  1399. // auto res = cli.Get(path.c_str());
  1400. // ASSERT_TRUE(res);
  1401. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1402. // }
  1403. }
  1404. }
  1405. #endif
  1406. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1407. auto host = "google.com";
  1408. auto another_host = "example.com";
  1409. auto wrong_ip = "0.0.0.0";
  1410. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1411. SSLClient cli(host);
  1412. #else
  1413. Client cli(host);
  1414. #endif
  1415. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1416. auto res = cli.Get("/");
  1417. ASSERT_TRUE(res);
  1418. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1419. }
  1420. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1421. auto host = "google.com";
  1422. auto wrong_ip = "0.0.0.0";
  1423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1424. SSLClient cli(host);
  1425. #else
  1426. Client cli(host);
  1427. #endif
  1428. cli.set_hostname_addr_map({{host, wrong_ip}});
  1429. auto res = cli.Get("/");
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Connection, res.error());
  1432. }
  1433. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1434. auto host = "nghttp2.org";
  1435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1436. SSLClient cli(host);
  1437. #else
  1438. Client cli(host);
  1439. #endif
  1440. cli.set_follow_location(true);
  1441. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1442. ASSERT_TRUE(res);
  1443. EXPECT_EQ(StatusCode::OK_200, res->status);
  1444. }
  1445. TEST(RedirectTest, Redirect_Online) {
  1446. auto host = "nghttp2.org";
  1447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1448. SSLClient cli(host);
  1449. #else
  1450. Client cli(host);
  1451. #endif
  1452. cli.set_follow_location(true);
  1453. auto res = cli.Get("/httpbin/redirect/3");
  1454. ASSERT_TRUE(res);
  1455. EXPECT_EQ(StatusCode::OK_200, res->status);
  1456. }
  1457. TEST(RelativeRedirectTest, Redirect_Online) {
  1458. auto host = "nghttp2.org";
  1459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1460. SSLClient cli(host);
  1461. #else
  1462. Client cli(host);
  1463. #endif
  1464. cli.set_follow_location(true);
  1465. auto res = cli.Get("/httpbin/relative-redirect/3");
  1466. ASSERT_TRUE(res);
  1467. EXPECT_EQ(StatusCode::OK_200, res->status);
  1468. }
  1469. TEST(TooManyRedirectTest, Redirect_Online) {
  1470. auto host = "nghttp2.org";
  1471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1472. SSLClient cli(host);
  1473. #else
  1474. Client cli(host);
  1475. #endif
  1476. cli.set_follow_location(true);
  1477. auto res = cli.Get("/httpbin/redirect/21");
  1478. ASSERT_TRUE(!res);
  1479. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1480. }
  1481. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1482. TEST(YahooRedirectTest, Redirect_Online) {
  1483. Client cli("yahoo.com");
  1484. auto res = cli.Get("/");
  1485. ASSERT_TRUE(res);
  1486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1487. cli.set_follow_location(true);
  1488. res = cli.Get("/");
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1492. }
  1493. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1494. #define REDIR_HOST "httpbingo.org"
  1495. #define REDIR_PATH "/redirect-to"
  1496. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1497. SSLClient cli(REDIR_HOST);
  1498. cli.set_follow_location(true);
  1499. auto res =
  1500. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1501. ASSERT_TRUE(res);
  1502. EXPECT_EQ(StatusCode::OK_200, res->status);
  1503. }
  1504. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1505. SSLClient cli(REDIR_HOST);
  1506. cli.set_follow_location(true);
  1507. Params params;
  1508. params.emplace("url", "http://example.com");
  1509. params.emplace("status_code", "302");
  1510. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::OK_200, res->status);
  1513. }
  1514. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1515. SSLClient cli(REDIR_HOST);
  1516. cli.set_follow_location(true);
  1517. Params params;
  1518. params.emplace("url", "http://example.com");
  1519. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1520. ASSERT_TRUE(res);
  1521. EXPECT_EQ(StatusCode::OK_200, res->status);
  1522. }
  1523. TEST(UrlWithSpace, Redirect_Online) {
  1524. SSLClient cli("edge.forgecdn.net");
  1525. cli.set_follow_location(true);
  1526. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1530. }
  1531. #endif
  1532. #if !defined(_WIN32) && !defined(_WIN64)
  1533. TEST(ReceiveSignals, Signal) {
  1534. auto setupSignalHandlers = []() {
  1535. struct sigaction act;
  1536. sigemptyset(&act.sa_mask);
  1537. act.sa_flags = SA_SIGINFO;
  1538. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1539. switch (sig) {
  1540. case SIGINT:
  1541. default: break;
  1542. }
  1543. };
  1544. ::sigaction(SIGINT, &act, nullptr);
  1545. };
  1546. Server svr;
  1547. int port = 0;
  1548. auto thread = std::thread([&]() {
  1549. setupSignalHandlers();
  1550. port = svr.bind_to_any_port("localhost");
  1551. svr.listen_after_bind();
  1552. });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. ASSERT_TRUE(svr.is_running());
  1560. pthread_kill(thread.native_handle(), SIGINT);
  1561. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1562. ASSERT_TRUE(svr.is_running());
  1563. }
  1564. #endif
  1565. TEST(RedirectToDifferentPort, Redirect) {
  1566. Server svr1;
  1567. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1568. res.set_content("Hello World!", "text/plain");
  1569. });
  1570. int svr1_port = 0;
  1571. auto thread1 = std::thread([&]() {
  1572. svr1_port = svr1.bind_to_any_port("localhost");
  1573. svr1.listen_after_bind();
  1574. });
  1575. Server svr2;
  1576. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1577. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1578. });
  1579. int svr2_port = 0;
  1580. auto thread2 = std::thread([&]() {
  1581. svr2_port = svr2.bind_to_any_port("localhost");
  1582. svr2.listen_after_bind();
  1583. });
  1584. auto se = detail::scope_exit([&] {
  1585. svr2.stop();
  1586. thread2.join();
  1587. svr1.stop();
  1588. thread1.join();
  1589. ASSERT_FALSE(svr2.is_running());
  1590. ASSERT_FALSE(svr1.is_running());
  1591. });
  1592. svr1.wait_until_ready();
  1593. svr2.wait_until_ready();
  1594. Client cli("localhost", svr2_port);
  1595. cli.set_follow_location(true);
  1596. auto res = cli.Get("/2");
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ(StatusCode::OK_200, res->status);
  1599. EXPECT_EQ("Hello World!", res->body);
  1600. }
  1601. TEST(RedirectFromPageWithContent, Redirect) {
  1602. Server svr;
  1603. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1604. res.set_content("___", "text/plain");
  1605. res.set_redirect("/2");
  1606. });
  1607. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. th.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. {
  1618. Client cli("localhost", PORT);
  1619. cli.set_follow_location(true);
  1620. std::string body;
  1621. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1622. body.append(data, data_length);
  1623. return true;
  1624. });
  1625. ASSERT_TRUE(res);
  1626. EXPECT_EQ(StatusCode::OK_200, res->status);
  1627. EXPECT_EQ("Hello World!", body);
  1628. }
  1629. {
  1630. Client cli("localhost", PORT);
  1631. std::string body;
  1632. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1633. body.append(data, data_length);
  1634. return true;
  1635. });
  1636. ASSERT_TRUE(res);
  1637. EXPECT_EQ(StatusCode::Found_302, res->status);
  1638. EXPECT_EQ("___", body);
  1639. }
  1640. }
  1641. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1642. Server svr;
  1643. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1644. res.set_content("___", "text/plain");
  1645. // res.set_redirect("/2");
  1646. res.set_redirect("http://[::1]:1234/2");
  1647. });
  1648. svr.Get("/2", [&](const Request &req, Response &res) {
  1649. auto host_header = req.headers.find("Host");
  1650. ASSERT_TRUE(host_header != req.headers.end());
  1651. EXPECT_EQ("[::1]:1234", host_header->second);
  1652. res.set_content("Hello World!", "text/plain");
  1653. });
  1654. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1655. auto se = detail::scope_exit([&] {
  1656. svr.stop();
  1657. th.join();
  1658. ASSERT_FALSE(svr.is_running());
  1659. });
  1660. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1661. // actually starts anything, so the condition !svr.is_running() will
  1662. // always remain true, and the loop never stops.
  1663. // This basically counts how many milliseconds have passed since the
  1664. // call to svr.listen(), and if after 5 seconds nothing started yet
  1665. // aborts the test.
  1666. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1667. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1668. ASSERT_LT(milliseconds, 5000U);
  1669. }
  1670. {
  1671. Client cli("http://[::1]:1234");
  1672. cli.set_follow_location(true);
  1673. std::string body;
  1674. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1675. body.append(data, data_length);
  1676. return true;
  1677. });
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. EXPECT_EQ("Hello World!", body);
  1681. }
  1682. {
  1683. Client cli("http://[::1]:1234");
  1684. std::string body;
  1685. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res);
  1690. EXPECT_EQ(StatusCode::Found_302, res->status);
  1691. EXPECT_EQ("___", body);
  1692. }
  1693. }
  1694. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1695. Server svr;
  1696. svr.Get("/foo", [](const Request &req, Response &res) {
  1697. auto a = req.params.find("a");
  1698. if (a != req.params.end()) {
  1699. res.set_content((*a).second, "text/plain");
  1700. res.status = StatusCode::OK_200;
  1701. } else {
  1702. res.status = StatusCode::BadRequest_400;
  1703. }
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. {
  1713. Client cli(HOST, PORT);
  1714. cli.set_url_encode(false);
  1715. auto res = cli.Get("/foo?a=explicitly+encoded");
  1716. ASSERT_TRUE(res);
  1717. EXPECT_EQ(StatusCode::OK_200, res->status);
  1718. // This expects it back with a space, as the `+` won't have been
  1719. // url-encoded, and server-side the params get decoded turning `+`
  1720. // into spaces.
  1721. EXPECT_EQ("explicitly encoded", res->body);
  1722. }
  1723. }
  1724. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1725. Server svr;
  1726. svr.Get("/", [](const Request &req, Response &) {
  1727. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1728. });
  1729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1730. auto se = detail::scope_exit([&] {
  1731. svr.stop();
  1732. thread.join();
  1733. ASSERT_FALSE(svr.is_running());
  1734. });
  1735. svr.wait_until_ready();
  1736. {
  1737. Client cli(HOST, PORT);
  1738. cli.set_url_encode(false);
  1739. auto res = cli.Get("/?something=%0A");
  1740. ASSERT_TRUE(res);
  1741. EXPECT_EQ(StatusCode::OK_200, res->status);
  1742. }
  1743. }
  1744. TEST(BindServerTest, DISABLED_BindDualStack) {
  1745. Server svr;
  1746. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content("Hello World!", "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. {
  1757. Client cli("127.0.0.1", PORT);
  1758. auto res = cli.Get("/1");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. EXPECT_EQ("Hello World!", res->body);
  1762. }
  1763. {
  1764. Client cli("::1", PORT);
  1765. auto res = cli.Get("/1");
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(StatusCode::OK_200, res->status);
  1768. EXPECT_EQ("Hello World!", res->body);
  1769. }
  1770. }
  1771. TEST(BindServerTest, BindAndListenSeparately) {
  1772. Server svr;
  1773. int port = svr.bind_to_any_port("0.0.0.0");
  1774. ASSERT_TRUE(svr.is_valid());
  1775. ASSERT_TRUE(port > 0);
  1776. svr.stop();
  1777. }
  1778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1779. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1781. CLIENT_CA_CERT_DIR);
  1782. int port = svr.bind_to_any_port("0.0.0.0");
  1783. ASSERT_TRUE(svr.is_valid());
  1784. ASSERT_TRUE(port > 0);
  1785. svr.stop();
  1786. }
  1787. #endif
  1788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1789. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1790. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1791. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1792. int port = svr.bind_to_any_port("0.0.0.0");
  1793. ASSERT_TRUE(svr.is_valid());
  1794. ASSERT_TRUE(port > 0);
  1795. svr.stop();
  1796. }
  1797. #endif
  1798. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1799. X509 *readCertificate(const std::string &strFileName) {
  1800. std::ifstream inStream(strFileName);
  1801. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1802. std::istreambuf_iterator<char>());
  1803. if (strCertPEM.empty()) return (nullptr);
  1804. BIO *pbCert = BIO_new(BIO_s_mem());
  1805. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1806. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1807. BIO_free(pbCert);
  1808. return (pCert);
  1809. }
  1810. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1811. std::ifstream inStream(strFileName);
  1812. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1813. std::istreambuf_iterator<char>());
  1814. if (strPrivateKeyPEM.empty()) return (nullptr);
  1815. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1816. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1817. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1818. BIO_free(pbPrivKey);
  1819. return (pPrivateKey);
  1820. }
  1821. TEST(BindServerTest, UpdateCerts) {
  1822. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1823. int port = svr.bind_to_any_port("0.0.0.0");
  1824. ASSERT_TRUE(svr.is_valid());
  1825. ASSERT_TRUE(port > 0);
  1826. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1827. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1828. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1829. ASSERT_TRUE(cert != nullptr);
  1830. ASSERT_TRUE(ca_cert != nullptr);
  1831. ASSERT_TRUE(key != nullptr);
  1832. X509_STORE *cert_store = X509_STORE_new();
  1833. X509_STORE_add_cert(cert_store, ca_cert);
  1834. svr.update_certs(cert, key, cert_store);
  1835. ASSERT_TRUE(svr.is_valid());
  1836. svr.stop();
  1837. X509_free(cert);
  1838. X509_free(ca_cert);
  1839. EVP_PKEY_free(key);
  1840. }
  1841. #endif
  1842. TEST(ErrorHandlerTest, ContentLength) {
  1843. Server svr;
  1844. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1845. res.status = StatusCode::OK_200;
  1846. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1847. "text/html"); // <= Content-Length still 13
  1848. });
  1849. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!\n", "text/plain");
  1851. res.status = 524;
  1852. });
  1853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. thread.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli(HOST, PORT);
  1862. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::OK_200, res->status);
  1865. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1866. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1867. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1868. }
  1869. }
  1870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1871. TEST(ExceptionTest, WithoutExceptionHandler) {
  1872. Server svr;
  1873. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1874. throw std::runtime_error("exception...");
  1875. });
  1876. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1877. throw std::runtime_error("exception\r\n...");
  1878. });
  1879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. listen_thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. Client cli("localhost", PORT);
  1887. {
  1888. auto res = cli.Get("/exception");
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1891. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1892. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1893. }
  1894. {
  1895. auto res = cli.Get("/unknown");
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1898. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1899. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1900. }
  1901. }
  1902. TEST(ExceptionTest, WithExceptionHandler) {
  1903. Server svr;
  1904. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1905. std::exception_ptr ep) {
  1906. EXPECT_FALSE(ep == nullptr);
  1907. try {
  1908. std::rethrow_exception(ep);
  1909. } catch (std::exception &e) {
  1910. EXPECT_EQ("abc", std::string(e.what()));
  1911. } catch (...) {}
  1912. res.status = StatusCode::InternalServerError_500;
  1913. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1914. "text/html"); // <= Content-Length still 13 at this point
  1915. });
  1916. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1917. res.set_content("Hello World!\n", "text/plain");
  1918. throw std::runtime_error("abc");
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. for (size_t i = 0; i < 10; i++) {
  1928. Client cli(HOST, PORT);
  1929. for (size_t j = 0; j < 100; j++) {
  1930. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1933. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1934. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1935. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1936. }
  1937. cli.set_keep_alive(true);
  1938. for (size_t j = 0; j < 100; j++) {
  1939. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1942. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1943. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1944. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1945. }
  1946. }
  1947. }
  1948. TEST(ExceptionTest, AndErrorHandler) {
  1949. Server svr;
  1950. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1951. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1952. });
  1953. svr.set_exception_handler(
  1954. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1955. EXPECT_FALSE(ep == nullptr);
  1956. try {
  1957. std::rethrow_exception(ep);
  1958. } catch (std::exception &e) {
  1959. res.set_content(e.what(), "text/html");
  1960. } catch (...) {}
  1961. res.status = StatusCode::InternalServerError_500;
  1962. });
  1963. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1964. throw std::runtime_error("EXCEPTION");
  1965. });
  1966. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1967. res.set_content("ERROR", "text/html");
  1968. res.status = StatusCode::InternalServerError_500;
  1969. });
  1970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1971. auto se = detail::scope_exit([&] {
  1972. svr.stop();
  1973. thread.join();
  1974. ASSERT_FALSE(svr.is_running());
  1975. });
  1976. svr.wait_until_ready();
  1977. Client cli(HOST, PORT);
  1978. {
  1979. auto res = cli.Get("/exception");
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1982. EXPECT_EQ("EXCEPTION", res->body);
  1983. }
  1984. {
  1985. auto res = cli.Get("/error");
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1988. EXPECT_EQ("ERROR", res->body);
  1989. }
  1990. {
  1991. auto res = cli.Get("/invalid");
  1992. ASSERT_TRUE(res);
  1993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1994. EXPECT_EQ("NOT_FOUND", res->body);
  1995. }
  1996. }
  1997. #endif
  1998. TEST(NoContentTest, ContentLength) {
  1999. Server svr;
  2000. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2001. res.status = StatusCode::NoContent_204;
  2002. });
  2003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2004. auto se = detail::scope_exit([&] {
  2005. svr.stop();
  2006. thread.join();
  2007. ASSERT_FALSE(svr.is_running());
  2008. });
  2009. svr.wait_until_ready();
  2010. {
  2011. Client cli(HOST, PORT);
  2012. auto res = cli.Get("/hi");
  2013. ASSERT_TRUE(res);
  2014. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2015. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2016. }
  2017. }
  2018. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2019. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2021. ASSERT_TRUE(svr.is_valid());
  2022. #else
  2023. Server svr;
  2024. #endif
  2025. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2026. if (req.path == "/routing_handler") {
  2027. res.set_header("PRE_ROUTING", "on");
  2028. res.set_content("Routing Handler", "text/plain");
  2029. return httplib::Server::HandlerResponse::Handled;
  2030. }
  2031. return httplib::Server::HandlerResponse::Unhandled;
  2032. });
  2033. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2034. res.set_content("Error", "text/html");
  2035. });
  2036. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2037. if (req.path == "/routing_handler") {
  2038. res.set_header("POST_ROUTING", "on");
  2039. }
  2040. });
  2041. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2042. res.set_content("Hello World!\n", "text/plain");
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2053. SSLClient cli(HOST, PORT);
  2054. cli.enable_server_certificate_verification(false);
  2055. #else
  2056. Client cli(HOST, PORT);
  2057. #endif
  2058. auto res = cli.Get("/routing_handler");
  2059. ASSERT_TRUE(res);
  2060. EXPECT_EQ(StatusCode::OK_200, res->status);
  2061. EXPECT_EQ("Routing Handler", res->body);
  2062. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2063. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2064. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2065. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2066. }
  2067. {
  2068. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2069. SSLClient cli(HOST, PORT);
  2070. cli.enable_server_certificate_verification(false);
  2071. #else
  2072. Client cli(HOST, PORT);
  2073. #endif
  2074. auto res = cli.Get("/hi");
  2075. ASSERT_TRUE(res);
  2076. EXPECT_EQ(StatusCode::OK_200, res->status);
  2077. EXPECT_EQ("Hello World!\n", res->body);
  2078. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2079. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2080. }
  2081. {
  2082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2083. SSLClient cli(HOST, PORT);
  2084. cli.enable_server_certificate_verification(false);
  2085. #else
  2086. Client cli(HOST, PORT);
  2087. #endif
  2088. auto res = cli.Get("/aaa");
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2091. EXPECT_EQ("Error", res->body);
  2092. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2093. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2094. }
  2095. }
  2096. TEST(RequestHandlerTest, PreRequestHandler) {
  2097. auto route_path = "/user/:user";
  2098. Server svr;
  2099. svr.Get("/hi", [](const Request &, Response &res) {
  2100. res.set_content("hi", "text/plain");
  2101. });
  2102. svr.Get(route_path, [](const Request &req, Response &res) {
  2103. res.set_content(req.path_params.at("user"), "text/plain");
  2104. });
  2105. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2106. if (req.matched_route == route_path) {
  2107. auto user = req.path_params.at("user");
  2108. if (user != "john") {
  2109. res.status = StatusCode::Forbidden_403;
  2110. res.set_content("error", "text/html");
  2111. return Server::HandlerResponse::Handled;
  2112. }
  2113. }
  2114. return Server::HandlerResponse::Unhandled;
  2115. });
  2116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2117. auto se = detail::scope_exit([&] {
  2118. svr.stop();
  2119. thread.join();
  2120. ASSERT_FALSE(svr.is_running());
  2121. });
  2122. svr.wait_until_ready();
  2123. Client cli(HOST, PORT);
  2124. {
  2125. auto res = cli.Get("/hi");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("hi", res->body);
  2129. }
  2130. {
  2131. auto res = cli.Get("/user/john");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::OK_200, res->status);
  2134. EXPECT_EQ("john", res->body);
  2135. }
  2136. {
  2137. auto res = cli.Get("/user/invalid-user");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2140. EXPECT_EQ("error", res->body);
  2141. }
  2142. }
  2143. TEST(InvalidFormatTest, StatusCode) {
  2144. Server svr;
  2145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2146. res.set_content("Hello World!\n", "text/plain");
  2147. res.status = 9999; // Status should be a three-digit code...
  2148. });
  2149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2150. auto se = detail::scope_exit([&] {
  2151. svr.stop();
  2152. thread.join();
  2153. ASSERT_FALSE(svr.is_running());
  2154. });
  2155. svr.wait_until_ready();
  2156. {
  2157. Client cli(HOST, PORT);
  2158. auto res = cli.Get("/hi");
  2159. ASSERT_FALSE(res);
  2160. }
  2161. }
  2162. TEST(URLFragmentTest, WithFragment) {
  2163. Server svr;
  2164. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2165. EXPECT_TRUE(req.target == "/hi");
  2166. });
  2167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2168. auto se = detail::scope_exit([&] {
  2169. svr.stop();
  2170. thread.join();
  2171. ASSERT_FALSE(svr.is_running());
  2172. });
  2173. svr.wait_until_ready();
  2174. {
  2175. Client cli(HOST, PORT);
  2176. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2177. EXPECT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. res = cli.Get("/hi%23key1=val1=key2=val2");
  2180. EXPECT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2182. }
  2183. }
  2184. TEST(HeaderWriter, SetHeaderWriter) {
  2185. Server svr;
  2186. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2187. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2188. return detail::write_headers(strm, hdrs);
  2189. });
  2190. svr.Get("/hi", [](const Request &req, Response &res) {
  2191. auto it = req.headers.find("CustomClientHeader");
  2192. EXPECT_TRUE(it != req.headers.end());
  2193. EXPECT_EQ(it->second, "CustomClientValue");
  2194. res.set_content("Hello World!\n", "text/plain");
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2206. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2207. return detail::write_headers(strm, hdrs);
  2208. });
  2209. auto res = cli.Get("/hi");
  2210. EXPECT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::OK_200, res->status);
  2212. auto it = res->headers.find("CustomServerHeader");
  2213. EXPECT_TRUE(it != res->headers.end());
  2214. EXPECT_EQ(it->second, "CustomServerValue");
  2215. }
  2216. }
  2217. class ServerTest : public ::testing::Test {
  2218. protected:
  2219. ServerTest()
  2220. : cli_(HOST, PORT)
  2221. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2222. ,
  2223. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2224. #endif
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. cli_.enable_server_certificate_verification(false);
  2228. #endif
  2229. }
  2230. virtual void SetUp() {
  2231. svr_.set_mount_point("/", "./www");
  2232. svr_.set_mount_point("/mount", "./www2");
  2233. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2234. svr_.Get("/hi",
  2235. [&](const Request & /*req*/, Response &res) {
  2236. res.set_content("Hello World!", "text/plain");
  2237. })
  2238. .Get("/file_content",
  2239. [&](const Request & /*req*/, Response &res) {
  2240. res.set_file_content("./www/dir/test.html");
  2241. })
  2242. .Get("/file_content_with_content_type",
  2243. [&](const Request & /*req*/, Response &res) {
  2244. res.set_file_content("./www/file", "text/plain");
  2245. })
  2246. .Get("/invalid_file_content",
  2247. [&](const Request & /*req*/, Response &res) {
  2248. res.set_file_content("./www/dir/invalid_file_path");
  2249. })
  2250. .Get("/http_response_splitting",
  2251. [&](const Request & /*req*/, Response &res) {
  2252. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2253. EXPECT_EQ(0U, res.headers.size());
  2254. EXPECT_FALSE(res.has_header("a"));
  2255. res.set_header("a", "1\nSet-Cookie: a=1");
  2256. EXPECT_EQ(0U, res.headers.size());
  2257. EXPECT_FALSE(res.has_header("a"));
  2258. res.set_header("a", "1\rSet-Cookie: a=1");
  2259. EXPECT_EQ(0U, res.headers.size());
  2260. EXPECT_FALSE(res.has_header("a"));
  2261. res.set_header("a\r\nb", "0");
  2262. EXPECT_EQ(0U, res.headers.size());
  2263. EXPECT_FALSE(res.has_header("a"));
  2264. res.set_header("a\rb", "0");
  2265. EXPECT_EQ(0U, res.headers.size());
  2266. EXPECT_FALSE(res.has_header("a"));
  2267. res.set_header("a\nb", "0");
  2268. EXPECT_EQ(0U, res.headers.size());
  2269. EXPECT_FALSE(res.has_header("a"));
  2270. res.set_redirect("1\r\nSet-Cookie: a=1");
  2271. EXPECT_EQ(0U, res.headers.size());
  2272. EXPECT_FALSE(res.has_header("Location"));
  2273. })
  2274. .Get("/slow",
  2275. [&](const Request & /*req*/, Response &res) {
  2276. std::this_thread::sleep_for(std::chrono::seconds(2));
  2277. res.set_content("slow", "text/plain");
  2278. })
  2279. #if 0
  2280. .Post("/slowpost",
  2281. [&](const Request & /*req*/, Response &res) {
  2282. std::this_thread::sleep_for(std::chrono::seconds(2));
  2283. res.set_content("slow", "text/plain");
  2284. })
  2285. #endif
  2286. .Get("/remote_addr",
  2287. [&](const Request &req, Response &res) {
  2288. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2289. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2290. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2291. EXPECT_EQ(req.remote_port,
  2292. std::stoi(req.get_header_value("REMOTE_PORT")));
  2293. res.set_content(remote_addr.c_str(), "text/plain");
  2294. })
  2295. .Get("/local_addr",
  2296. [&](const Request &req, Response &res) {
  2297. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2298. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2299. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2300. auto local_port = req.get_header_value("LOCAL_PORT");
  2301. EXPECT_EQ(req.local_addr, local_addr);
  2302. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2303. res.set_content(local_addr.append(":").append(local_port),
  2304. "text/plain");
  2305. })
  2306. .Get("/endwith%",
  2307. [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("Hello World!", "text/plain");
  2309. })
  2310. .Get("/a\\+\\+b",
  2311. [&](const Request &req, Response &res) {
  2312. ASSERT_TRUE(req.has_param("a +b"));
  2313. auto val = req.get_param_value("a +b");
  2314. res.set_content(val, "text/plain");
  2315. })
  2316. .Get("/", [&](const Request & /*req*/,
  2317. Response &res) { res.set_redirect("/hi"); })
  2318. .Post("/1",
  2319. [](const Request & /*req*/, Response &res) {
  2320. res.set_redirect("/2", StatusCode::SeeOther_303);
  2321. })
  2322. .Get("/2",
  2323. [](const Request & /*req*/, Response &res) {
  2324. res.set_content("redirected.", "text/plain");
  2325. res.status = StatusCode::OK_200;
  2326. })
  2327. .Post("/person",
  2328. [&](const Request &req, Response &res) {
  2329. if (req.has_param("name") && req.has_param("note")) {
  2330. persons_[req.get_param_value("name")] =
  2331. req.get_param_value("note");
  2332. } else {
  2333. res.status = StatusCode::BadRequest_400;
  2334. }
  2335. })
  2336. .Put("/person",
  2337. [&](const Request &req, Response &res) {
  2338. if (req.has_param("name") && req.has_param("note")) {
  2339. persons_[req.get_param_value("name")] =
  2340. req.get_param_value("note");
  2341. } else {
  2342. res.status = StatusCode::BadRequest_400;
  2343. }
  2344. })
  2345. .Get("/person/(.*)",
  2346. [&](const Request &req, Response &res) {
  2347. string name = req.matches[1];
  2348. if (persons_.find(name) != persons_.end()) {
  2349. auto note = persons_[name];
  2350. res.set_content(note, "text/plain");
  2351. } else {
  2352. res.status = StatusCode::NotFound_404;
  2353. }
  2354. })
  2355. .Delete("/person",
  2356. [&](const Request &req, Response &res) {
  2357. if (req.has_param("name")) {
  2358. string name = req.get_param_value("name");
  2359. if (persons_.find(name) != persons_.end()) {
  2360. persons_.erase(name);
  2361. res.set_content("DELETED", "text/plain");
  2362. } else {
  2363. res.status = StatusCode::NotFound_404;
  2364. }
  2365. } else {
  2366. res.status = StatusCode::BadRequest_400;
  2367. }
  2368. })
  2369. .Post("/x-www-form-urlencoded-json",
  2370. [&](const Request &req, Response &res) {
  2371. auto json = req.get_param_value("json");
  2372. ASSERT_EQ(JSON_DATA, json);
  2373. res.set_content(json, "appliation/json");
  2374. res.status = StatusCode::OK_200;
  2375. })
  2376. .Get("/streamed-chunked",
  2377. [&](const Request & /*req*/, Response &res) {
  2378. res.set_chunked_content_provider(
  2379. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2380. sink.os << "123";
  2381. sink.os << "456";
  2382. sink.os << "789";
  2383. sink.done();
  2384. return true;
  2385. });
  2386. })
  2387. .Get("/streamed-chunked2",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. auto i = new int(0);
  2390. res.set_chunked_content_provider(
  2391. "text/plain",
  2392. [i](size_t /*offset*/, DataSink &sink) {
  2393. switch (*i) {
  2394. case 0: sink.os << "123"; break;
  2395. case 1: sink.os << "456"; break;
  2396. case 2: sink.os << "789"; break;
  2397. case 3: sink.done(); break;
  2398. }
  2399. (*i)++;
  2400. return true;
  2401. },
  2402. [i](bool success) {
  2403. EXPECT_TRUE(success);
  2404. delete i;
  2405. });
  2406. })
  2407. .Get("/streamed-chunked-with-trailer",
  2408. [&](const Request & /*req*/, Response &res) {
  2409. auto i = new int(0);
  2410. res.set_header("Trailer", "Dummy1, Dummy2");
  2411. res.set_chunked_content_provider(
  2412. "text/plain",
  2413. [i](size_t /*offset*/, DataSink &sink) {
  2414. switch (*i) {
  2415. case 0: sink.os << "123"; break;
  2416. case 1: sink.os << "456"; break;
  2417. case 2: sink.os << "789"; break;
  2418. case 3: {
  2419. sink.done_with_trailer(
  2420. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2421. } break;
  2422. }
  2423. (*i)++;
  2424. return true;
  2425. },
  2426. [i](bool success) {
  2427. EXPECT_TRUE(success);
  2428. delete i;
  2429. });
  2430. })
  2431. .Get("/streamed",
  2432. [&](const Request & /*req*/, Response &res) {
  2433. res.set_content_provider(
  2434. 6, "text/plain",
  2435. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2436. sink.os << (offset < 3 ? "a" : "b");
  2437. return true;
  2438. });
  2439. })
  2440. .Get("/streamed-with-range",
  2441. [&](const Request &req, Response &res) {
  2442. auto data = new std::string("abcdefg");
  2443. res.set_content_provider(
  2444. data->size(), "text/plain",
  2445. [data](size_t offset, size_t length, DataSink &sink) {
  2446. size_t DATA_CHUNK_SIZE = 4;
  2447. const auto &d = *data;
  2448. auto out_len =
  2449. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2450. auto ret =
  2451. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2452. EXPECT_TRUE(ret);
  2453. return true;
  2454. },
  2455. [data, &req](bool success) {
  2456. EXPECT_EQ(success, !req.has_param("error"));
  2457. delete data;
  2458. });
  2459. })
  2460. .Get("/streamed-cancel",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. size_t(-1), "text/plain",
  2464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2465. sink.os << "data_chunk";
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/regex-with-delimiter",
  2470. [&](const Request &req, Response & /*res*/) {
  2471. ASSERT_TRUE(req.has_param("key"));
  2472. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2473. })
  2474. .Get("/with-range",
  2475. [&](const Request & /*req*/, Response &res) {
  2476. res.set_content("abcdefg", "text/plain");
  2477. })
  2478. .Get("/with-range-customized-response",
  2479. [&](const Request & /*req*/, Response &res) {
  2480. res.status = StatusCode::BadRequest_400;
  2481. res.set_content(JSON_DATA, "application/json");
  2482. })
  2483. .Post("/chunked",
  2484. [&](const Request &req, Response & /*res*/) {
  2485. EXPECT_EQ(req.body, "dechunked post body");
  2486. })
  2487. .Post("/large-chunked",
  2488. [&](const Request &req, Response & /*res*/) {
  2489. std::string expected(6 * 30 * 1024u, 'a');
  2490. EXPECT_EQ(req.body, expected);
  2491. })
  2492. .Post("/multipart",
  2493. [&](const Request &req, Response & /*res*/) {
  2494. EXPECT_EQ(6u, req.files.size());
  2495. ASSERT_TRUE(!req.has_file("???"));
  2496. ASSERT_TRUE(req.body.empty());
  2497. {
  2498. const auto &file = req.get_file_value("text1");
  2499. EXPECT_TRUE(file.filename.empty());
  2500. EXPECT_EQ("text default", file.content);
  2501. }
  2502. {
  2503. const auto &file = req.get_file_value("text2");
  2504. EXPECT_TRUE(file.filename.empty());
  2505. EXPECT_EQ("aωb", file.content);
  2506. }
  2507. {
  2508. const auto &file = req.get_file_value("file1");
  2509. EXPECT_EQ("hello.txt", file.filename);
  2510. EXPECT_EQ("text/plain", file.content_type);
  2511. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2512. }
  2513. {
  2514. const auto &file = req.get_file_value("file3");
  2515. EXPECT_TRUE(file.filename.empty());
  2516. EXPECT_EQ("application/octet-stream", file.content_type);
  2517. EXPECT_EQ(0u, file.content.size());
  2518. }
  2519. {
  2520. const auto &file = req.get_file_value("file4");
  2521. EXPECT_TRUE(file.filename.empty());
  2522. EXPECT_EQ(0u, file.content.size());
  2523. EXPECT_EQ("application/json tmp-string", file.content_type);
  2524. }
  2525. })
  2526. .Post("/multipart/multi_file_values",
  2527. [&](const Request &req, Response & /*res*/) {
  2528. EXPECT_EQ(5u, req.files.size());
  2529. ASSERT_TRUE(!req.has_file("???"));
  2530. ASSERT_TRUE(req.body.empty());
  2531. {
  2532. const auto &text_value = req.get_file_values("text");
  2533. EXPECT_EQ(1u, text_value.size());
  2534. auto &text = text_value[0];
  2535. EXPECT_TRUE(text.filename.empty());
  2536. EXPECT_EQ("default text", text.content);
  2537. }
  2538. {
  2539. const auto &text1_values = req.get_file_values("multi_text1");
  2540. EXPECT_EQ(2u, text1_values.size());
  2541. EXPECT_EQ("aaaaa", text1_values[0].content);
  2542. EXPECT_EQ("bbbbb", text1_values[1].content);
  2543. }
  2544. {
  2545. const auto &file1_values = req.get_file_values("multi_file1");
  2546. EXPECT_EQ(2u, file1_values.size());
  2547. auto file1 = file1_values[0];
  2548. EXPECT_EQ(file1.filename, "hello.txt");
  2549. EXPECT_EQ(file1.content_type, "text/plain");
  2550. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2551. auto file2 = file1_values[1];
  2552. EXPECT_EQ(file2.filename, "world.json");
  2553. EXPECT_EQ(file2.content_type, "application/json");
  2554. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2555. }
  2556. })
  2557. .Post("/empty",
  2558. [&](const Request &req, Response &res) {
  2559. EXPECT_EQ(req.body, "");
  2560. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2561. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2562. res.set_content("empty", "text/plain");
  2563. })
  2564. .Post("/empty-no-content-type",
  2565. [&](const Request &req, Response &res) {
  2566. EXPECT_EQ(req.body, "");
  2567. EXPECT_FALSE(req.has_header("Content-Type"));
  2568. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2569. res.set_content("empty-no-content-type", "text/plain");
  2570. })
  2571. .Post("/path-only",
  2572. [&](const Request &req, Response &res) {
  2573. EXPECT_EQ(req.body, "");
  2574. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2575. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2576. res.set_content("path-only", "text/plain");
  2577. })
  2578. .Post("/path-headers-only",
  2579. [&](const Request &req, Response &res) {
  2580. EXPECT_EQ(req.body, "");
  2581. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2582. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2583. EXPECT_EQ("world", req.get_header_value("hello"));
  2584. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2585. res.set_content("path-headers-only", "text/plain");
  2586. })
  2587. .Post("/post-large",
  2588. [&](const Request &req, Response &res) {
  2589. EXPECT_EQ(req.body, LARGE_DATA);
  2590. res.set_content(req.body, "text/plain");
  2591. })
  2592. .Put("/empty-no-content-type",
  2593. [&](const Request &req, Response &res) {
  2594. EXPECT_EQ(req.body, "");
  2595. EXPECT_FALSE(req.has_header("Content-Type"));
  2596. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2597. res.set_content("empty-no-content-type", "text/plain");
  2598. })
  2599. .Put("/put",
  2600. [&](const Request &req, Response &res) {
  2601. EXPECT_EQ(req.body, "PUT");
  2602. res.set_content(req.body, "text/plain");
  2603. })
  2604. .Put("/put-large",
  2605. [&](const Request &req, Response &res) {
  2606. EXPECT_EQ(req.body, LARGE_DATA);
  2607. res.set_content(req.body, "text/plain");
  2608. })
  2609. .Patch("/patch",
  2610. [&](const Request &req, Response &res) {
  2611. EXPECT_EQ(req.body, "PATCH");
  2612. res.set_content(req.body, "text/plain");
  2613. })
  2614. .Delete("/delete",
  2615. [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("DELETE", "text/plain");
  2617. })
  2618. .Delete("/delete-body",
  2619. [&](const Request &req, Response &res) {
  2620. EXPECT_EQ(req.body, "content");
  2621. res.set_content(req.body, "text/plain");
  2622. })
  2623. .Options(R"(\*)",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2626. })
  2627. .Get("/request-target",
  2628. [&](const Request &req, Response & /*res*/) {
  2629. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2630. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2631. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2632. })
  2633. .Get("/long-query-value",
  2634. [&](const Request &req, Response & /*res*/) {
  2635. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2636. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2637. })
  2638. .Get("/too-long-query-value",
  2639. [&](const Request &req, Response & /*res*/) {
  2640. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2641. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2642. })
  2643. .Get("/array-param",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2646. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2647. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2648. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2649. })
  2650. .Post("/validate-no-multiple-headers",
  2651. [&](const Request &req, Response & /*res*/) {
  2652. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2653. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2654. })
  2655. .Post("/content_receiver",
  2656. [&](const Request &req, Response &res,
  2657. const ContentReader &content_reader) {
  2658. if (req.is_multipart_form_data()) {
  2659. MultipartFormDataItems files;
  2660. content_reader(
  2661. [&](const MultipartFormData &file) {
  2662. files.push_back(file);
  2663. return true;
  2664. },
  2665. [&](const char *data, size_t data_length) {
  2666. files.back().content.append(data, data_length);
  2667. return true;
  2668. });
  2669. EXPECT_EQ(5u, files.size());
  2670. {
  2671. const auto &file = get_file_value(files, "text1");
  2672. EXPECT_TRUE(file.filename.empty());
  2673. EXPECT_EQ("text default", file.content);
  2674. }
  2675. {
  2676. const auto &file = get_file_value(files, "text2");
  2677. EXPECT_TRUE(file.filename.empty());
  2678. EXPECT_EQ("aωb", file.content);
  2679. }
  2680. {
  2681. const auto &file = get_file_value(files, "file1");
  2682. EXPECT_EQ("hello.txt", file.filename);
  2683. EXPECT_EQ("text/plain", file.content_type);
  2684. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2685. }
  2686. {
  2687. const auto &file = get_file_value(files, "file3");
  2688. EXPECT_TRUE(file.filename.empty());
  2689. EXPECT_EQ("application/octet-stream", file.content_type);
  2690. EXPECT_EQ(0u, file.content.size());
  2691. }
  2692. } else {
  2693. std::string body;
  2694. content_reader([&](const char *data, size_t data_length) {
  2695. EXPECT_EQ(7U, data_length);
  2696. body.append(data, data_length);
  2697. return true;
  2698. });
  2699. EXPECT_EQ(body, "content");
  2700. res.set_content(body, "text/plain");
  2701. }
  2702. })
  2703. .Put("/content_receiver",
  2704. [&](const Request & /*req*/, Response &res,
  2705. const ContentReader &content_reader) {
  2706. std::string body;
  2707. content_reader([&](const char *data, size_t data_length) {
  2708. body.append(data, data_length);
  2709. return true;
  2710. });
  2711. EXPECT_EQ(body, "content");
  2712. res.set_content(body, "text/plain");
  2713. })
  2714. .Patch("/content_receiver",
  2715. [&](const Request & /*req*/, Response &res,
  2716. const ContentReader &content_reader) {
  2717. std::string body;
  2718. content_reader([&](const char *data, size_t data_length) {
  2719. body.append(data, data_length);
  2720. return true;
  2721. });
  2722. EXPECT_EQ(body, "content");
  2723. res.set_content(body, "text/plain");
  2724. })
  2725. .Post("/query-string-and-body",
  2726. [&](const Request &req, Response & /*res*/) {
  2727. ASSERT_TRUE(req.has_param("key"));
  2728. EXPECT_EQ(req.get_param_value("key"), "value");
  2729. EXPECT_EQ(req.body, "content");
  2730. })
  2731. .Get("/last-request",
  2732. [&](const Request &req, Response & /*res*/) {
  2733. EXPECT_EQ("close", req.get_header_value("Connection"));
  2734. })
  2735. .Get(R"(/redirect/(\d+))",
  2736. [&](const Request &req, Response &res) {
  2737. auto num = std::stoi(req.matches[1]) + 1;
  2738. std::string url = "/redirect/" + std::to_string(num);
  2739. res.set_redirect(url);
  2740. })
  2741. .Post("/binary",
  2742. [&](const Request &req, Response &res) {
  2743. EXPECT_EQ(4U, req.body.size());
  2744. EXPECT_EQ("application/octet-stream",
  2745. req.get_header_value("Content-Type"));
  2746. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2747. res.set_content(req.body, "application/octet-stream");
  2748. })
  2749. .Put("/binary",
  2750. [&](const Request &req, Response &res) {
  2751. EXPECT_EQ(4U, req.body.size());
  2752. EXPECT_EQ("application/octet-stream",
  2753. req.get_header_value("Content-Type"));
  2754. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2755. res.set_content(req.body, "application/octet-stream");
  2756. })
  2757. .Patch("/binary",
  2758. [&](const Request &req, Response &res) {
  2759. EXPECT_EQ(4U, req.body.size());
  2760. EXPECT_EQ("application/octet-stream",
  2761. req.get_header_value("Content-Type"));
  2762. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2763. res.set_content(req.body, "application/octet-stream");
  2764. })
  2765. .Delete("/binary",
  2766. [&](const Request &req, Response &res) {
  2767. EXPECT_EQ(4U, req.body.size());
  2768. EXPECT_EQ("application/octet-stream",
  2769. req.get_header_value("Content-Type"));
  2770. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2771. res.set_content(req.body, "application/octet-stream");
  2772. })
  2773. .Get("/issue1772",
  2774. [&](const Request & /*req*/, Response &res) {
  2775. res.status = 401;
  2776. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2777. })
  2778. .Delete("/issue609",
  2779. [](const httplib::Request &, httplib::Response &res,
  2780. const httplib::ContentReader &) {
  2781. res.set_content("ok", "text/plain");
  2782. })
  2783. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2784. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2785. .Get("/compress",
  2786. [&](const Request & /*req*/, Response &res) {
  2787. res.set_content(
  2788. "12345678901234567890123456789012345678901234567890123456789"
  2789. "01234567890123456789012345678901234567890",
  2790. "text/plain");
  2791. })
  2792. .Get("/nocompress",
  2793. [&](const Request & /*req*/, Response &res) {
  2794. res.set_content(
  2795. "12345678901234567890123456789012345678901234567890123456789"
  2796. "01234567890123456789012345678901234567890",
  2797. "application/octet-stream");
  2798. })
  2799. .Post("/compress-multipart",
  2800. [&](const Request &req, Response & /*res*/) {
  2801. EXPECT_EQ(2u, req.files.size());
  2802. ASSERT_TRUE(!req.has_file("???"));
  2803. {
  2804. const auto &file = req.get_file_value("key1");
  2805. EXPECT_TRUE(file.filename.empty());
  2806. EXPECT_EQ("test", file.content);
  2807. }
  2808. {
  2809. const auto &file = req.get_file_value("key2");
  2810. EXPECT_TRUE(file.filename.empty());
  2811. EXPECT_EQ("--abcdefg123", file.content);
  2812. }
  2813. })
  2814. #endif
  2815. ;
  2816. persons_["john"] = "programmer";
  2817. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2818. svr_.wait_until_ready();
  2819. }
  2820. virtual void TearDown() {
  2821. svr_.stop();
  2822. if (!request_threads_.empty()) {
  2823. std::this_thread::sleep_for(std::chrono::seconds(1));
  2824. for (auto &t : request_threads_) {
  2825. t.join();
  2826. }
  2827. }
  2828. t_.join();
  2829. }
  2830. map<string, string> persons_;
  2831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2832. SSLClient cli_;
  2833. SSLServer svr_;
  2834. #else
  2835. Client cli_;
  2836. Server svr_;
  2837. #endif
  2838. thread t_;
  2839. std::vector<thread> request_threads_;
  2840. };
  2841. TEST_F(ServerTest, GetMethod200) {
  2842. auto res = cli_.Get("/hi");
  2843. ASSERT_TRUE(res);
  2844. EXPECT_EQ("HTTP/1.1", res->version);
  2845. EXPECT_EQ(StatusCode::OK_200, res->status);
  2846. EXPECT_EQ("OK", res->reason);
  2847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2848. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2849. EXPECT_EQ("Hello World!", res->body);
  2850. }
  2851. TEST(BenchmarkTest, SimpleGetPerformance) {
  2852. Server svr;
  2853. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2854. res.set_content("Benchmark Response", "text/plain");
  2855. });
  2856. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2857. auto se = detail::scope_exit([&] {
  2858. svr.stop();
  2859. listen_thread.join();
  2860. ASSERT_FALSE(svr.is_running());
  2861. });
  2862. svr.wait_until_ready();
  2863. Client cli("localhost", PORT);
  2864. const int NUM_REQUESTS = 50;
  2865. const int MAX_AVERAGE_MS = 5;
  2866. auto warmup = cli.Get("/benchmark");
  2867. ASSERT_TRUE(warmup);
  2868. auto start = std::chrono::high_resolution_clock::now();
  2869. for (int i = 0; i < NUM_REQUESTS; ++i) {
  2870. auto res = cli.Get("/benchmark");
  2871. ASSERT_TRUE(res) << "Request " << i << " failed";
  2872. EXPECT_EQ(StatusCode::OK_200, res->status);
  2873. }
  2874. auto end = std::chrono::high_resolution_clock::now();
  2875. auto total_ms =
  2876. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2877. .count();
  2878. double avg_ms = static_cast<double>(total_ms) / NUM_REQUESTS;
  2879. std::cout << "Standalone: " << NUM_REQUESTS << " requests in " << total_ms
  2880. << "ms (avg: " << avg_ms << "ms)" << std::endl;
  2881. EXPECT_LE(avg_ms, MAX_AVERAGE_MS)
  2882. << "Standalone test too slow: " << avg_ms << "ms (Issue #1777)";
  2883. }
  2884. TEST_F(ServerTest, GetEmptyFile) {
  2885. auto res = cli_.Get("/empty_file");
  2886. ASSERT_TRUE(res);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2889. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2890. EXPECT_EQ("", res->body);
  2891. }
  2892. TEST_F(ServerTest, GetFileContent) {
  2893. auto res = cli_.Get("/file_content");
  2894. ASSERT_TRUE(res);
  2895. EXPECT_EQ(StatusCode::OK_200, res->status);
  2896. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2897. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2898. EXPECT_EQ("test.html", res->body);
  2899. }
  2900. TEST_F(ServerTest, GetFileContentWithRange) {
  2901. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2902. ASSERT_TRUE(res);
  2903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2904. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2905. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2906. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2907. EXPECT_EQ("est", res->body);
  2908. }
  2909. TEST_F(ServerTest, GetFileContentWithContentType) {
  2910. auto res = cli_.Get("/file_content_with_content_type");
  2911. ASSERT_TRUE(res);
  2912. EXPECT_EQ(StatusCode::OK_200, res->status);
  2913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2914. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2915. EXPECT_EQ("file\n", res->body);
  2916. }
  2917. TEST_F(ServerTest, GetInvalidFileContent) {
  2918. auto res = cli_.Get("/invalid_file_content");
  2919. ASSERT_TRUE(res);
  2920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2921. }
  2922. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2923. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2924. ASSERT_TRUE(res);
  2925. EXPECT_EQ("HTTP/1.1", res->version);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2928. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2929. EXPECT_EQ("Hello World!", res->body);
  2930. }
  2931. TEST_F(ServerTest, GetMethod302) {
  2932. auto res = cli_.Get("/");
  2933. ASSERT_TRUE(res);
  2934. EXPECT_EQ(StatusCode::Found_302, res->status);
  2935. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2936. }
  2937. TEST_F(ServerTest, GetMethod302Redirect) {
  2938. cli_.set_follow_location(true);
  2939. auto res = cli_.Get("/");
  2940. ASSERT_TRUE(res);
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. EXPECT_EQ("Hello World!", res->body);
  2943. EXPECT_EQ("/hi", res->location);
  2944. }
  2945. TEST_F(ServerTest, GetMethod404) {
  2946. auto res = cli_.Get("/invalid");
  2947. ASSERT_TRUE(res);
  2948. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2949. }
  2950. TEST_F(ServerTest, HeadMethod200) {
  2951. auto res = cli_.Head("/hi");
  2952. ASSERT_TRUE(res);
  2953. EXPECT_EQ(StatusCode::OK_200, res->status);
  2954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2955. EXPECT_TRUE(res->body.empty());
  2956. }
  2957. TEST_F(ServerTest, HeadMethod200Static) {
  2958. auto res = cli_.Head("/mount/dir/index.html");
  2959. ASSERT_TRUE(res);
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2962. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2963. EXPECT_TRUE(res->body.empty());
  2964. }
  2965. TEST_F(ServerTest, HeadMethod404) {
  2966. auto res = cli_.Head("/invalid");
  2967. ASSERT_TRUE(res);
  2968. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2969. EXPECT_TRUE(res->body.empty());
  2970. }
  2971. TEST_F(ServerTest, GetMethodPersonJohn) {
  2972. auto res = cli_.Get("/person/john");
  2973. ASSERT_TRUE(res);
  2974. EXPECT_EQ(StatusCode::OK_200, res->status);
  2975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2976. EXPECT_EQ("programmer", res->body);
  2977. }
  2978. TEST_F(ServerTest, PostMethod1) {
  2979. auto res = cli_.Get("/person/john1");
  2980. ASSERT_TRUE(res);
  2981. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2982. res = cli_.Post("/person", "name=john1&note=coder",
  2983. "application/x-www-form-urlencoded");
  2984. ASSERT_TRUE(res);
  2985. ASSERT_EQ(StatusCode::OK_200, res->status);
  2986. res = cli_.Get("/person/john1");
  2987. ASSERT_TRUE(res);
  2988. ASSERT_EQ(StatusCode::OK_200, res->status);
  2989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2990. ASSERT_EQ("coder", res->body);
  2991. }
  2992. TEST_F(ServerTest, PostMethod2) {
  2993. auto res = cli_.Get("/person/john2");
  2994. ASSERT_TRUE(res);
  2995. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2996. Params params;
  2997. params.emplace("name", "john2");
  2998. params.emplace("note", "coder");
  2999. res = cli_.Post("/person", params);
  3000. ASSERT_TRUE(res);
  3001. ASSERT_EQ(StatusCode::OK_200, res->status);
  3002. res = cli_.Get("/person/john2");
  3003. ASSERT_TRUE(res);
  3004. ASSERT_EQ(StatusCode::OK_200, res->status);
  3005. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3006. ASSERT_EQ("coder", res->body);
  3007. }
  3008. TEST_F(ServerTest, PutMethod3) {
  3009. auto res = cli_.Get("/person/john3");
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3012. Params params;
  3013. params.emplace("name", "john3");
  3014. params.emplace("note", "coder");
  3015. res = cli_.Put("/person", params);
  3016. ASSERT_TRUE(res);
  3017. ASSERT_EQ(StatusCode::OK_200, res->status);
  3018. res = cli_.Get("/person/john3");
  3019. ASSERT_TRUE(res);
  3020. ASSERT_EQ(StatusCode::OK_200, res->status);
  3021. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3022. ASSERT_EQ("coder", res->body);
  3023. }
  3024. TEST_F(ServerTest, DeleteMethod1) {
  3025. auto res = cli_.Get("/person/john4");
  3026. ASSERT_TRUE(res);
  3027. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3028. Params params;
  3029. params.emplace("name", "john4");
  3030. params.emplace("note", "coder");
  3031. res = cli_.Post("/person", params);
  3032. ASSERT_TRUE(res);
  3033. ASSERT_EQ(StatusCode::OK_200, res->status);
  3034. res = cli_.Get("/person/john4");
  3035. ASSERT_TRUE(res);
  3036. ASSERT_EQ(StatusCode::OK_200, res->status);
  3037. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3038. ASSERT_EQ("coder", res->body);
  3039. Params delete_params;
  3040. delete_params.emplace("name", "john4");
  3041. res = cli_.Delete("/person", delete_params);
  3042. ASSERT_TRUE(res);
  3043. ASSERT_EQ(StatusCode::OK_200, res->status);
  3044. ASSERT_EQ("DELETED", res->body);
  3045. res = cli_.Get("/person/john4");
  3046. ASSERT_TRUE(res);
  3047. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3048. }
  3049. TEST_F(ServerTest, DeleteMethod2) {
  3050. auto res = cli_.Get("/person/john5");
  3051. ASSERT_TRUE(res);
  3052. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3053. Params params;
  3054. params.emplace("name", "john5");
  3055. params.emplace("note", "developer");
  3056. res = cli_.Post("/person", params);
  3057. ASSERT_TRUE(res);
  3058. ASSERT_EQ(StatusCode::OK_200, res->status);
  3059. res = cli_.Get("/person/john5");
  3060. ASSERT_TRUE(res);
  3061. ASSERT_EQ(StatusCode::OK_200, res->status);
  3062. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3063. ASSERT_EQ("developer", res->body);
  3064. Params delete_params;
  3065. delete_params.emplace("name", "john5");
  3066. Headers headers;
  3067. headers.emplace("Custom-Header", "test-value");
  3068. res = cli_.Delete("/person", headers, delete_params);
  3069. ASSERT_TRUE(res);
  3070. ASSERT_EQ(StatusCode::OK_200, res->status);
  3071. ASSERT_EQ("DELETED", res->body);
  3072. res = cli_.Get("/person/john5");
  3073. ASSERT_TRUE(res);
  3074. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3075. }
  3076. TEST_F(ServerTest, DeleteMethod3) {
  3077. auto res = cli_.Get("/person/john6");
  3078. ASSERT_TRUE(res);
  3079. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3080. Params params;
  3081. params.emplace("name", "john6");
  3082. params.emplace("note", "tester");
  3083. res = cli_.Post("/person", params);
  3084. ASSERT_TRUE(res);
  3085. ASSERT_EQ(StatusCode::OK_200, res->status);
  3086. res = cli_.Get("/person/john6");
  3087. ASSERT_TRUE(res);
  3088. ASSERT_EQ(StatusCode::OK_200, res->status);
  3089. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3090. ASSERT_EQ("tester", res->body);
  3091. Params delete_params;
  3092. delete_params.emplace("name", "john6");
  3093. Headers headers;
  3094. headers.emplace("Custom-Header", "test-value");
  3095. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3096. ASSERT_TRUE(res);
  3097. ASSERT_EQ(StatusCode::OK_200, res->status);
  3098. ASSERT_EQ("DELETED", res->body);
  3099. res = cli_.Get("/person/john6");
  3100. ASSERT_TRUE(res);
  3101. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3102. }
  3103. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3104. Params params;
  3105. params.emplace("json", JSON_DATA);
  3106. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3107. ASSERT_TRUE(res);
  3108. ASSERT_EQ(StatusCode::OK_200, res->status);
  3109. ASSERT_EQ(JSON_DATA, res->body);
  3110. }
  3111. TEST_F(ServerTest, PostEmptyContent) {
  3112. auto res = cli_.Post("/empty", "", "text/plain");
  3113. ASSERT_TRUE(res);
  3114. ASSERT_EQ(StatusCode::OK_200, res->status);
  3115. ASSERT_EQ("empty", res->body);
  3116. }
  3117. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3118. auto res = cli_.Post("/empty-no-content-type");
  3119. ASSERT_TRUE(res);
  3120. ASSERT_EQ(StatusCode::OK_200, res->status);
  3121. ASSERT_EQ("empty-no-content-type", res->body);
  3122. }
  3123. TEST_F(ServerTest, PostPathOnly) {
  3124. auto res = cli_.Post("/path-only");
  3125. ASSERT_TRUE(res);
  3126. ASSERT_EQ(StatusCode::OK_200, res->status);
  3127. ASSERT_EQ("path-only", res->body);
  3128. }
  3129. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3130. auto res = cli_.Post("/path-headers-only",
  3131. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3132. ASSERT_TRUE(res);
  3133. ASSERT_EQ(StatusCode::OK_200, res->status);
  3134. ASSERT_EQ("path-headers-only", res->body);
  3135. }
  3136. TEST_F(ServerTest, PostLarge) {
  3137. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3138. ASSERT_TRUE(res);
  3139. ASSERT_EQ(StatusCode::OK_200, res->status);
  3140. EXPECT_EQ(LARGE_DATA, res->body);
  3141. }
  3142. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3143. auto res = cli_.Put("/empty-no-content-type");
  3144. ASSERT_TRUE(res);
  3145. ASSERT_EQ(StatusCode::OK_200, res->status);
  3146. ASSERT_EQ("empty-no-content-type", res->body);
  3147. }
  3148. TEST_F(ServerTest, GetMethodDir) {
  3149. auto res = cli_.Get("/dir/");
  3150. ASSERT_TRUE(res);
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3153. auto body = R"(<html>
  3154. <head>
  3155. </head>
  3156. <body>
  3157. <a href="/dir/test.html">Test</a>
  3158. <a href="/hi">hi</a>
  3159. </body>
  3160. </html>
  3161. )";
  3162. EXPECT_EQ(body, res->body);
  3163. }
  3164. TEST_F(ServerTest, GetMethodDirTest) {
  3165. auto res = cli_.Get("/dir/test.html");
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3169. EXPECT_EQ("test.html", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3172. auto res = cli_.Get("/dir/../dir/test.html");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3176. EXPECT_EQ("test.html", res->body);
  3177. }
  3178. TEST_F(ServerTest, GetMethodInvalidPath) {
  3179. auto res = cli_.Get("/dir/../test.html");
  3180. ASSERT_TRUE(res);
  3181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3182. }
  3183. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3184. auto res = cli_.Get("/../www/dir/test.html");
  3185. ASSERT_TRUE(res);
  3186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3187. }
  3188. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3189. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3190. ASSERT_TRUE(res);
  3191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3192. }
  3193. TEST_F(ServerTest, GetMethodDirMountTest) {
  3194. auto res = cli_.Get("/mount/dir/test.html");
  3195. ASSERT_TRUE(res);
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3198. EXPECT_EQ("test.html", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3201. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ("test.html", res->body);
  3206. }
  3207. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3208. auto res = cli_.Get("/mount/dir/../test.html");
  3209. ASSERT_TRUE(res);
  3210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3211. }
  3212. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3213. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3214. ASSERT_TRUE(res);
  3215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3216. }
  3217. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3218. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3221. }
  3222. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3223. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3224. ASSERT_TRUE(res);
  3225. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3226. }
  3227. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3228. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3229. ASSERT_TRUE(res);
  3230. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3231. }
  3232. TEST_F(ServerTest, PostMethod303) {
  3233. auto res = cli_.Post("/1", "body", "text/plain");
  3234. ASSERT_TRUE(res);
  3235. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3236. EXPECT_EQ("/2", res->get_header_value("Location"));
  3237. }
  3238. TEST_F(ServerTest, PostMethod303Redirect) {
  3239. cli_.set_follow_location(true);
  3240. auto res = cli_.Post("/1", "body", "text/plain");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("redirected.", res->body);
  3244. EXPECT_EQ("/2", res->location);
  3245. }
  3246. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3247. auto res = cli_.Get("/dir/test.abcde");
  3248. ASSERT_TRUE(res);
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3251. EXPECT_EQ("abcde", res->body);
  3252. }
  3253. TEST_F(ServerTest, StaticFileRange) {
  3254. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3257. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3258. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3259. EXPECT_EQ(true, res->has_header("Content-Range"));
  3260. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3261. EXPECT_EQ(std::string("cd"), res->body);
  3262. }
  3263. TEST_F(ServerTest, StaticFileRanges) {
  3264. auto res =
  3265. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3268. EXPECT_TRUE(
  3269. res->get_header_value("Content-Type")
  3270. .find(
  3271. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3272. 0);
  3273. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3274. }
  3275. TEST_F(ServerTest, StaticFileRangeHead) {
  3276. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3277. ASSERT_TRUE(res);
  3278. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3279. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3280. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3281. EXPECT_EQ(true, res->has_header("Content-Range"));
  3282. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3283. }
  3284. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3285. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3286. ASSERT_TRUE(res);
  3287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3289. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3290. EXPECT_EQ(true, res->has_header("Content-Range"));
  3291. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3292. res->get_header_value("Content-Range"));
  3293. EXPECT_EQ("LAST\n", res->body);
  3294. }
  3295. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3296. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3297. ASSERT_TRUE(res);
  3298. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3300. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3301. EXPECT_EQ(true, res->has_header("Content-Range"));
  3302. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3303. }
  3304. TEST_F(ServerTest, StaticFileBigFile) {
  3305. auto res = cli_.Get("/dir/1MB.txt");
  3306. ASSERT_TRUE(res);
  3307. EXPECT_EQ(StatusCode::OK_200, res->status);
  3308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3309. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3310. }
  3311. TEST_F(ServerTest, InvalidBaseDirMount) {
  3312. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3313. }
  3314. TEST_F(ServerTest, Binary) {
  3315. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3316. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3317. "application/octet-stream");
  3318. ASSERT_TRUE(res);
  3319. ASSERT_EQ(StatusCode::OK_200, res->status);
  3320. ASSERT_EQ(4U, res->body.size());
  3321. res = cli_.Put("/binary", binary.data(), binary.size(),
  3322. "application/octet-stream");
  3323. ASSERT_TRUE(res);
  3324. ASSERT_EQ(StatusCode::OK_200, res->status);
  3325. ASSERT_EQ(4U, res->body.size());
  3326. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3327. "application/octet-stream");
  3328. ASSERT_TRUE(res);
  3329. ASSERT_EQ(StatusCode::OK_200, res->status);
  3330. ASSERT_EQ(4U, res->body.size());
  3331. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3332. "application/octet-stream");
  3333. ASSERT_TRUE(res);
  3334. ASSERT_EQ(StatusCode::OK_200, res->status);
  3335. ASSERT_EQ(4U, res->body.size());
  3336. }
  3337. TEST_F(ServerTest, BinaryString) {
  3338. auto binary = std::string("\x00\x01\x02\x03", 4);
  3339. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. ASSERT_EQ(4U, res->body.size());
  3343. res = cli_.Put("/binary", binary, "application/octet-stream");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ(4U, res->body.size());
  3347. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. ASSERT_EQ(4U, res->body.size());
  3351. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. ASSERT_EQ(4U, res->body.size());
  3355. }
  3356. TEST_F(ServerTest, EmptyRequest) {
  3357. auto res = cli_.Get("");
  3358. ASSERT_TRUE(!res);
  3359. EXPECT_EQ(Error::Connection, res.error());
  3360. }
  3361. TEST_F(ServerTest, LongRequest) {
  3362. std::string request;
  3363. for (size_t i = 0; i < 545; i++) {
  3364. request += "/TooLongRequest";
  3365. }
  3366. request += "OK";
  3367. auto res = cli_.Get(request.c_str());
  3368. ASSERT_TRUE(res);
  3369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3370. }
  3371. TEST_F(ServerTest, TooLongRequest) {
  3372. std::string request;
  3373. for (size_t i = 0; i < 546; i++) {
  3374. request += "/TooLongRequest";
  3375. }
  3376. request += "_NG";
  3377. auto res = cli_.Get(request.c_str());
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3380. }
  3381. TEST_F(ServerTest, AlmostTooLongRequest) {
  3382. // test for #2046 - URI length check shouldn't include other content on req
  3383. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3384. // leading /, space, HTTP/1.1)
  3385. std::string request =
  3386. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3387. auto res = cli_.Get(request.c_str());
  3388. ASSERT_TRUE(res);
  3389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3390. }
  3391. TEST_F(ServerTest, LongHeader) {
  3392. Request req;
  3393. req.method = "GET";
  3394. req.path = "/hi";
  3395. std::string host_and_port;
  3396. host_and_port += HOST;
  3397. host_and_port += ":";
  3398. host_and_port += std::to_string(PORT);
  3399. req.headers.emplace("Host", host_and_port.c_str());
  3400. req.headers.emplace("Accept", "*/*");
  3401. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3402. req.headers.emplace(
  3403. "Header-Name",
  3404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3426. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3432. "@@@@@@@@@@@@@@@@");
  3433. auto res = std::make_shared<Response>();
  3434. auto error = Error::Success;
  3435. auto ret = cli_.send(req, *res, error);
  3436. ASSERT_TRUE(ret);
  3437. EXPECT_EQ(StatusCode::OK_200, res->status);
  3438. }
  3439. TEST_F(ServerTest, LongQueryValue) {
  3440. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3443. }
  3444. TEST_F(ServerTest, TooLongQueryValue) {
  3445. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3446. ASSERT_FALSE(res);
  3447. EXPECT_EQ(Error::Read, res.error());
  3448. }
  3449. TEST_F(ServerTest, TooLongHeader) {
  3450. Request req;
  3451. req.method = "GET";
  3452. req.path = "/hi";
  3453. std::string host_and_port;
  3454. host_and_port += HOST;
  3455. host_and_port += ":";
  3456. host_and_port += std::to_string(PORT);
  3457. req.headers.emplace("Host", host_and_port.c_str());
  3458. req.headers.emplace("Accept", "*/*");
  3459. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3460. req.headers.emplace(
  3461. "Header-Name",
  3462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3473. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3474. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3484. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3490. "@@@@@@@@@@@@@@@@@");
  3491. auto res = std::make_shared<Response>();
  3492. auto error = Error::Success;
  3493. auto ret = cli_.send(req, *res, error);
  3494. ASSERT_TRUE(ret);
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. }
  3497. TEST_F(ServerTest, HeaderCountAtLimit) {
  3498. // Test with headers just under the 100 limit
  3499. httplib::Headers headers;
  3500. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3501. // This should keep us just under the 100 header limit
  3502. for (int i = 0; i < 95; i++) {
  3503. std::string name = "X-Test-Header-" + std::to_string(i);
  3504. std::string value = "value" + std::to_string(i);
  3505. headers.emplace(name, value);
  3506. }
  3507. // This should work fine as we're under the limit
  3508. auto res = cli_.Get("/hi", headers);
  3509. EXPECT_TRUE(res);
  3510. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3511. }
  3512. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3513. // Test with many headers to exceed the 100 limit
  3514. httplib::Headers headers;
  3515. // Add 150 headers to definitely exceed the 100 limit
  3516. for (int i = 0; i < 150; i++) {
  3517. std::string name = "X-Test-Header-" + std::to_string(i);
  3518. std::string value = "value" + std::to_string(i);
  3519. headers.emplace(name, value);
  3520. }
  3521. // This should fail due to exceeding header count limit
  3522. auto res = cli_.Get("/hi", headers);
  3523. // The request should either fail or return 400 Bad Request
  3524. if (res) {
  3525. // If we get a response, it should be 400 Bad Request
  3526. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3527. } else {
  3528. // Or the request should fail entirely
  3529. EXPECT_FALSE(res);
  3530. }
  3531. }
  3532. TEST_F(ServerTest, PercentEncoding) {
  3533. auto res = cli_.Get("/e%6edwith%");
  3534. ASSERT_TRUE(res);
  3535. EXPECT_EQ(StatusCode::OK_200, res->status);
  3536. }
  3537. TEST_F(ServerTest, PercentEncodingUnicode) {
  3538. auto res = cli_.Get("/e%u006edwith%");
  3539. ASSERT_TRUE(res);
  3540. EXPECT_EQ(StatusCode::OK_200, res->status);
  3541. }
  3542. TEST_F(ServerTest, InvalidPercentEncoding) {
  3543. auto res = cli_.Get("/%endwith%");
  3544. ASSERT_TRUE(res);
  3545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3546. }
  3547. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3548. auto res = cli_.Get("/%uendwith%");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3551. }
  3552. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3553. auto res = cli_.Get("/hello?aaa=bbb%");
  3554. ASSERT_TRUE(res);
  3555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3556. }
  3557. TEST_F(ServerTest, PlusSignEncoding) {
  3558. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("a +b", res->body);
  3562. }
  3563. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3564. // This test simulates a potential DoS attack using many headers
  3565. // to verify our security fix prevents memory exhaustion
  3566. httplib::Headers attack_headers;
  3567. // Attempt to add many headers like an attacker would (200 headers to far
  3568. // exceed limit)
  3569. for (int i = 0; i < 200; i++) {
  3570. std::string name = "X-Attack-Header-" + std::to_string(i);
  3571. std::string value = "attack_payload_" + std::to_string(i);
  3572. attack_headers.emplace(name, value);
  3573. }
  3574. // Try to POST with excessive headers
  3575. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3576. // Should either fail or return 400 Bad Request due to security limit
  3577. if (res) {
  3578. // If we get a response, it should be 400 Bad Request
  3579. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3580. } else {
  3581. // Request failed, which is the expected behavior for DoS protection
  3582. EXPECT_FALSE(res);
  3583. }
  3584. }
  3585. TEST_F(ServerTest, MultipartFormData) {
  3586. MultipartFormDataItemsForClientInput items = {
  3587. {"text1", "text default", "", ""},
  3588. {"text2", "aωb", "", ""},
  3589. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3590. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3591. {"file3", "", "", "application/octet-stream"},
  3592. {"file4", "", "", " application/json tmp-string "}};
  3593. auto res = cli_.Post("/multipart", items);
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::OK_200, res->status);
  3596. }
  3597. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3598. MultipartFormDataItemsForClientInput items = {
  3599. {"text", "default text", "", ""},
  3600. {"multi_text1", "aaaaa", "", ""},
  3601. {"multi_text1", "bbbbb", "", ""},
  3602. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3603. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3604. "application/json"},
  3605. };
  3606. auto res = cli_.Post("/multipart/multi_file_values", items);
  3607. ASSERT_TRUE(res);
  3608. EXPECT_EQ(StatusCode::OK_200, res->status);
  3609. }
  3610. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3611. auto res = cli_.Get("/hi");
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::OK_200, res->status);
  3614. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. }
  3617. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3618. Request req;
  3619. req.method = "POST";
  3620. req.path = "/chunked";
  3621. std::string host_and_port;
  3622. host_and_port += HOST;
  3623. host_and_port += ":";
  3624. host_and_port += std::to_string(PORT);
  3625. req.headers.emplace("Host", host_and_port.c_str());
  3626. req.headers.emplace("Accept", "*/*");
  3627. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3628. req.headers.emplace("Content-Type", "text/plain");
  3629. req.headers.emplace("Content-Length", "0");
  3630. req.headers.emplace(
  3631. "Transfer-Encoding",
  3632. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3633. // Client does not chunk, so make a chunked body manually.
  3634. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3635. auto res = std::make_shared<Response>();
  3636. auto error = Error::Success;
  3637. auto ret = cli_.send(req, *res, error);
  3638. ASSERT_TRUE(ret);
  3639. EXPECT_EQ(StatusCode::OK_200, res->status);
  3640. }
  3641. TEST_F(ServerTest, GetStreamed2) {
  3642. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3645. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3646. EXPECT_EQ(true, res->has_header("Content-Range"));
  3647. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3648. EXPECT_EQ(std::string("ab"), res->body);
  3649. }
  3650. TEST_F(ServerTest, GetStreamed) {
  3651. auto res = cli_.Get("/streamed");
  3652. ASSERT_TRUE(res);
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3655. EXPECT_EQ(std::string("aaabbb"), res->body);
  3656. }
  3657. TEST_F(ServerTest, GetStreamedWithRange1) {
  3658. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3659. ASSERT_TRUE(res);
  3660. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3661. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3662. EXPECT_EQ(true, res->has_header("Content-Range"));
  3663. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3664. EXPECT_EQ(std::string("def"), res->body);
  3665. }
  3666. TEST_F(ServerTest, GetStreamedWithRange2) {
  3667. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3668. ASSERT_TRUE(res);
  3669. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3670. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3671. EXPECT_EQ(true, res->has_header("Content-Range"));
  3672. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3673. EXPECT_EQ(std::string("bcdefg"), res->body);
  3674. }
  3675. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3676. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3679. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3680. EXPECT_EQ(true, res->has_header("Content-Range"));
  3681. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3682. EXPECT_EQ(std::string("efg"), res->body);
  3683. }
  3684. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3685. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3688. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3689. EXPECT_EQ(false, res->has_header("Content-Range"));
  3690. EXPECT_EQ(0U, res->body.size());
  3691. }
  3692. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3693. auto res = cli_.Get("/streamed-with-range",
  3694. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3695. "92233720368547758079223372036854775807"}});
  3696. ASSERT_TRUE(res);
  3697. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3698. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3699. EXPECT_EQ(false, res->has_header("Content-Range"));
  3700. EXPECT_EQ(0U, res->body.size());
  3701. }
  3702. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3703. auto res = cli_.Get(
  3704. "/with-range",
  3705. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3706. {"Accept-Encoding", ""}});
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3709. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ(true, res->has_header("Content-Range"));
  3711. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3712. EXPECT_EQ(std::string("abcdefg"), res->body);
  3713. }
  3714. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3715. auto res = cli_.Get("/with-range", {
  3716. {"Range", "bytes=0-"},
  3717. {"Accept-Encoding", ""},
  3718. });
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3721. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3722. EXPECT_EQ(true, res->has_header("Content-Range"));
  3723. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3724. EXPECT_EQ(std::string("abcdefg"), res->body);
  3725. }
  3726. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3727. auto res =
  3728. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3729. ASSERT_TRUE(res);
  3730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3731. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3732. EXPECT_EQ(false, res->has_header("Content-Range"));
  3733. EXPECT_EQ(267U, res->body.size());
  3734. // Check that both range contents are present
  3735. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3736. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3737. // Check that Content-Range headers are present for both ranges
  3738. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3739. std::string::npos);
  3740. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3741. std::string::npos);
  3742. }
  3743. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3744. Ranges ranges;
  3745. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3746. ranges.emplace_back(0, -1);
  3747. }
  3748. auto res =
  3749. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3752. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3753. EXPECT_EQ(false, res->has_header("Content-Range"));
  3754. EXPECT_EQ(0U, res->body.size());
  3755. }
  3756. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3757. auto res =
  3758. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3761. EXPECT_EQ(5U, res->body.size());
  3762. // Check that overlapping ranges are coalesced into a single range
  3763. EXPECT_EQ("bcdef", res->body);
  3764. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3765. // Should be single range, not multipart
  3766. EXPECT_TRUE(res->has_header("Content-Range"));
  3767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3768. }
  3769. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3770. auto res =
  3771. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3774. EXPECT_EQ(268U, res->body.size());
  3775. // Check that both range contents are present
  3776. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3777. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3778. // Check that Content-Range headers are present for both ranges
  3779. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3780. std::string::npos);
  3781. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3782. std::string::npos);
  3783. }
  3784. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3785. auto res =
  3786. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3787. ASSERT_TRUE(res);
  3788. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3789. EXPECT_EQ(269U, res->body.size());
  3790. // Check that both duplicate range contents are present
  3791. size_t first_abc = res->body.find("abc\r\n");
  3792. EXPECT_TRUE(first_abc != std::string::npos);
  3793. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3794. EXPECT_TRUE(second_abc != std::string::npos);
  3795. // Check that Content-Range headers are present for both ranges
  3796. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3797. EXPECT_TRUE(first_range != std::string::npos);
  3798. size_t second_range =
  3799. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3800. EXPECT_TRUE(second_range != std::string::npos);
  3801. }
  3802. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3803. auto res = cli_.Get("/streamed-with-range?error",
  3804. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3807. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3808. EXPECT_EQ(false, res->has_header("Content-Range"));
  3809. EXPECT_EQ(0U, res->body.size());
  3810. }
  3811. TEST_F(ServerTest, GetStreamedEndless) {
  3812. uint64_t offset = 0;
  3813. auto res = cli_.Get("/streamed-cancel",
  3814. [&](const char * /*data*/, uint64_t data_length) {
  3815. if (offset < 100) {
  3816. offset += data_length;
  3817. return true;
  3818. }
  3819. return false;
  3820. });
  3821. ASSERT_TRUE(!res);
  3822. EXPECT_EQ(Error::Canceled, res.error());
  3823. }
  3824. TEST_F(ServerTest, ClientStop) {
  3825. std::atomic_size_t count{4};
  3826. std::vector<std::thread> threads;
  3827. for (auto i = count.load(); i != 0; --i) {
  3828. threads.emplace_back([&]() {
  3829. auto res = cli_.Get("/streamed-cancel",
  3830. [&](const char *, uint64_t) { return true; });
  3831. --count;
  3832. ASSERT_TRUE(!res);
  3833. EXPECT_TRUE(res.error() == Error::Canceled ||
  3834. res.error() == Error::Read || res.error() == Error::Write);
  3835. });
  3836. }
  3837. std::this_thread::sleep_for(std::chrono::seconds(2));
  3838. while (count != 0) {
  3839. cli_.stop();
  3840. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3841. }
  3842. for (auto &t : threads) {
  3843. t.join();
  3844. }
  3845. }
  3846. TEST_F(ServerTest, GetWithRange1) {
  3847. auto res = cli_.Get("/with-range", {
  3848. make_range_header({{3, 5}}),
  3849. {"Accept-Encoding", ""},
  3850. });
  3851. ASSERT_TRUE(res);
  3852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3853. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ(true, res->has_header("Content-Range"));
  3855. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3856. EXPECT_EQ(std::string("def"), res->body);
  3857. }
  3858. TEST_F(ServerTest, GetWithRange2) {
  3859. auto res = cli_.Get("/with-range", {
  3860. make_range_header({{1, -1}}),
  3861. {"Accept-Encoding", ""},
  3862. });
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3865. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3866. EXPECT_EQ(true, res->has_header("Content-Range"));
  3867. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3868. EXPECT_EQ(std::string("bcdefg"), res->body);
  3869. }
  3870. TEST_F(ServerTest, GetWithRange3) {
  3871. auto res = cli_.Get("/with-range", {
  3872. make_range_header({{0, 0}}),
  3873. {"Accept-Encoding", ""},
  3874. });
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3877. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3878. EXPECT_EQ(true, res->has_header("Content-Range"));
  3879. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3880. EXPECT_EQ(std::string("a"), res->body);
  3881. }
  3882. TEST_F(ServerTest, GetWithRange4) {
  3883. auto res = cli_.Get("/with-range", {
  3884. make_range_header({{-1, 2}}),
  3885. {"Accept-Encoding", ""},
  3886. });
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3889. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3890. EXPECT_EQ(true, res->has_header("Content-Range"));
  3891. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3892. EXPECT_EQ(std::string("fg"), res->body);
  3893. }
  3894. TEST_F(ServerTest, GetWithRange5) {
  3895. auto res = cli_.Get("/with-range", {
  3896. make_range_header({{0, 5}}),
  3897. {"Accept-Encoding", ""},
  3898. });
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3901. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3902. EXPECT_EQ(true, res->has_header("Content-Range"));
  3903. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3904. EXPECT_EQ(std::string("abcdef"), res->body);
  3905. }
  3906. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3907. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3910. }
  3911. TEST_F(ServerTest, GetWithRangeMultipart) {
  3912. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3915. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3916. EXPECT_EQ(false, res->has_header("Content-Range"));
  3917. EXPECT_EQ(267U, res->body.size());
  3918. }
  3919. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3920. auto res =
  3921. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3924. }
  3925. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3926. auto res = cli_.Get("/with-range-customized-response",
  3927. {{make_range_header({{1, 2}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3930. EXPECT_EQ(true, res->has_header("Content-Length"));
  3931. EXPECT_EQ(false, res->has_header("Content-Range"));
  3932. EXPECT_EQ(JSON_DATA, res->body);
  3933. }
  3934. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3935. auto res = cli_.Get("/with-range-customized-response",
  3936. {{make_range_header({{1, 2}, {4, 5}})}});
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3939. EXPECT_EQ(true, res->has_header("Content-Length"));
  3940. EXPECT_EQ(false, res->has_header("Content-Range"));
  3941. EXPECT_EQ(JSON_DATA, res->body);
  3942. }
  3943. TEST_F(ServerTest, Issue1772) {
  3944. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3947. }
  3948. TEST_F(ServerTest, Issue609) {
  3949. auto res = cli_.Delete("/issue609");
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ(std::string("ok"), res->body);
  3953. }
  3954. TEST_F(ServerTest, GetStreamedChunked) {
  3955. auto res = cli_.Get("/streamed-chunked");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. EXPECT_EQ(std::string("123456789"), res->body);
  3959. }
  3960. TEST_F(ServerTest, GetStreamedChunked2) {
  3961. auto res = cli_.Get("/streamed-chunked2");
  3962. ASSERT_TRUE(res);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. EXPECT_EQ(std::string("123456789"), res->body);
  3965. }
  3966. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3967. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3968. ASSERT_TRUE(res);
  3969. EXPECT_EQ(StatusCode::OK_200, res->status);
  3970. EXPECT_EQ(std::string("123456789"), res->body);
  3971. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3972. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3973. }
  3974. TEST_F(ServerTest, LargeChunkedPost) {
  3975. Request req;
  3976. req.method = "POST";
  3977. req.path = "/large-chunked";
  3978. std::string host_and_port;
  3979. host_and_port += HOST;
  3980. host_and_port += ":";
  3981. host_and_port += std::to_string(PORT);
  3982. req.headers.emplace("Host", host_and_port.c_str());
  3983. req.headers.emplace("Accept", "*/*");
  3984. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3985. req.headers.emplace("Content-Type", "text/plain");
  3986. req.headers.emplace("Content-Length", "0");
  3987. req.headers.emplace("Transfer-Encoding", "chunked");
  3988. std::string long_string(30 * 1024u, 'a');
  3989. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3990. // Attempt to make a large enough post to exceed OS buffers, to test that
  3991. // the server handles short reads if the full chunk data isn't available.
  3992. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3993. auto res = std::make_shared<Response>();
  3994. auto error = Error::Success;
  3995. auto ret = cli_.send(req, *res, error);
  3996. ASSERT_TRUE(ret);
  3997. EXPECT_EQ(StatusCode::OK_200, res->status);
  3998. }
  3999. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4000. auto res = cli_.Get("/remote_addr");
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::OK_200, res->status);
  4003. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4004. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4005. }
  4006. TEST_F(ServerTest, GetMethodLocalAddr) {
  4007. auto res = cli_.Get("/local_addr");
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::OK_200, res->status);
  4010. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4011. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4012. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4013. }
  4014. TEST_F(ServerTest, HTTPResponseSplitting) {
  4015. auto res = cli_.Get("/http_response_splitting");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::OK_200, res->status);
  4018. }
  4019. TEST_F(ServerTest, SlowRequest) {
  4020. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4021. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4022. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4023. }
  4024. #if 0
  4025. TEST_F(ServerTest, SlowPost) {
  4026. char buffer[64 * 1024];
  4027. memset(buffer, 0x42, sizeof(buffer));
  4028. auto res = cli_.Post(
  4029. "/slowpost", 64 * 1024 * 1024,
  4030. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4031. auto ret = sink.write(buffer, sizeof(buffer));
  4032. EXPECT_TRUE(ret);
  4033. return true;
  4034. },
  4035. "text/plain");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. }
  4039. TEST_F(ServerTest, SlowPostFail) {
  4040. char buffer[64 * 1024];
  4041. memset(buffer, 0x42, sizeof(buffer));
  4042. cli_.set_write_timeout(std::chrono::seconds(0));
  4043. auto res = cli_.Post(
  4044. "/slowpost", 64 * 1024 * 1024,
  4045. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4046. sink.write(buffer, sizeof(buffer));
  4047. return true;
  4048. },
  4049. "text/plain");
  4050. ASSERT_TRUE(!res);
  4051. EXPECT_EQ(Error::Write, res.error());
  4052. }
  4053. #endif
  4054. TEST_F(ServerTest, Put) {
  4055. auto res = cli_.Put("/put", "PUT", "text/plain");
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. EXPECT_EQ("PUT", res->body);
  4059. }
  4060. TEST_F(ServerTest, PutWithContentProvider) {
  4061. auto res = cli_.Put(
  4062. "/put", 3,
  4063. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4064. sink.os << "PUT";
  4065. return true;
  4066. },
  4067. "text/plain");
  4068. ASSERT_TRUE(res);
  4069. EXPECT_EQ(StatusCode::OK_200, res->status);
  4070. EXPECT_EQ("PUT", res->body);
  4071. }
  4072. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4073. auto res = cli_.Post(
  4074. "/post", 42,
  4075. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4076. return false;
  4077. },
  4078. "text/plain");
  4079. ASSERT_TRUE(!res);
  4080. EXPECT_EQ(Error::Canceled, res.error());
  4081. }
  4082. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4083. auto res = cli_.Put(
  4084. "/put",
  4085. [](size_t /*offset*/, DataSink &sink) {
  4086. sink.os << "PUT";
  4087. sink.done();
  4088. return true;
  4089. },
  4090. "text/plain");
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("PUT", res->body);
  4094. }
  4095. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4096. auto res = cli_.Post(
  4097. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4098. "text/plain");
  4099. ASSERT_TRUE(!res);
  4100. EXPECT_EQ(Error::Canceled, res.error());
  4101. }
  4102. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4103. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4104. cli_.set_compress(true);
  4105. auto res = cli_.Put(
  4106. "/put", 3,
  4107. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4108. sink.os << "PUT";
  4109. return true;
  4110. },
  4111. "text/plain");
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. EXPECT_EQ("PUT", res->body);
  4115. }
  4116. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4117. cli_.set_compress(true);
  4118. auto res = cli_.Post(
  4119. "/post", 42,
  4120. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4121. return false;
  4122. },
  4123. "text/plain");
  4124. ASSERT_TRUE(!res);
  4125. EXPECT_EQ(Error::Canceled, res.error());
  4126. }
  4127. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4128. cli_.set_compress(true);
  4129. auto res = cli_.Put(
  4130. "/put",
  4131. [](size_t /*offset*/, DataSink &sink) {
  4132. sink.os << "PUT";
  4133. sink.done();
  4134. return true;
  4135. },
  4136. "text/plain");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::OK_200, res->status);
  4139. EXPECT_EQ("PUT", res->body);
  4140. }
  4141. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4142. cli_.set_compress(true);
  4143. auto res = cli_.Post(
  4144. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4145. "text/plain");
  4146. ASSERT_TRUE(!res);
  4147. EXPECT_EQ(Error::Canceled, res.error());
  4148. }
  4149. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4150. cli_.set_compress(true);
  4151. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. EXPECT_EQ(LARGE_DATA, res->body);
  4155. }
  4156. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4157. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4158. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4159. Client cli(s.c_str());
  4160. cli.enable_server_certificate_verification(false);
  4161. #else
  4162. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4163. Client cli(s.c_str());
  4164. #endif
  4165. cli.set_compress(true);
  4166. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ(LARGE_DATA, res->body);
  4170. // The compressed size should be less than a 10th of the original. May vary
  4171. // depending on the zlib library.
  4172. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4173. static_cast<uint64_t>(10 * 1024 * 1024));
  4174. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4175. }
  4176. TEST_F(ServerTest, PutContentWithDeflate) {
  4177. cli_.set_compress(false);
  4178. Headers headers;
  4179. headers.emplace("Content-Encoding", "deflate");
  4180. // PUT in deflate format:
  4181. auto res = cli_.Put("/put", headers,
  4182. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. EXPECT_EQ("PUT", res->body);
  4186. }
  4187. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4188. Headers headers;
  4189. headers.emplace("Accept-Encoding", "gzip, deflate");
  4190. auto res = cli_.Get("/streamed-chunked", headers);
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::OK_200, res->status);
  4193. EXPECT_EQ(std::string("123456789"), res->body);
  4194. }
  4195. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4196. Headers headers;
  4197. headers.emplace("Accept-Encoding", "gzip, deflate");
  4198. auto res = cli_.Get("/streamed-chunked2", headers);
  4199. ASSERT_TRUE(res);
  4200. EXPECT_EQ(StatusCode::OK_200, res->status);
  4201. EXPECT_EQ(std::string("123456789"), res->body);
  4202. }
  4203. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4204. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. }
  4208. TEST(GzipDecompressor, ChunkedDecompression) {
  4209. std::string data;
  4210. for (size_t i = 0; i < 32 * 1024; ++i) {
  4211. data.push_back(static_cast<char>('a' + i % 26));
  4212. }
  4213. std::string compressed_data;
  4214. {
  4215. httplib::detail::gzip_compressor compressor;
  4216. bool result = compressor.compress(
  4217. data.data(), data.size(),
  4218. /*last=*/true,
  4219. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4220. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4221. compressed_data_size);
  4222. return true;
  4223. });
  4224. ASSERT_TRUE(result);
  4225. }
  4226. std::string decompressed_data;
  4227. {
  4228. httplib::detail::gzip_decompressor decompressor;
  4229. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4230. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4231. size_t chunk_size = 130;
  4232. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4233. chunk_begin += chunk_size) {
  4234. size_t current_chunk_size =
  4235. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4236. bool result = decompressor.decompress(
  4237. compressed_data.data() + chunk_begin, current_chunk_size,
  4238. [&](const char *decompressed_data_chunk,
  4239. size_t decompressed_data_chunk_size) {
  4240. decompressed_data.insert(decompressed_data.size(),
  4241. decompressed_data_chunk,
  4242. decompressed_data_chunk_size);
  4243. return true;
  4244. });
  4245. ASSERT_TRUE(result);
  4246. }
  4247. }
  4248. ASSERT_EQ(data, decompressed_data);
  4249. }
  4250. TEST(GzipDecompressor, DeflateDecompression) {
  4251. std::string original_text = "Raw deflate without gzip";
  4252. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4253. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4254. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4255. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4256. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4257. std::string decompressed_data;
  4258. {
  4259. httplib::detail::gzip_decompressor decompressor;
  4260. bool result = decompressor.decompress(
  4261. compressed_data.data(), compressed_data.size(),
  4262. [&](const char *decompressed_data_chunk,
  4263. size_t decompressed_data_chunk_size) {
  4264. decompressed_data.insert(decompressed_data.size(),
  4265. decompressed_data_chunk,
  4266. decompressed_data_chunk_size);
  4267. return true;
  4268. });
  4269. ASSERT_TRUE(result);
  4270. }
  4271. ASSERT_EQ(original_text, decompressed_data);
  4272. }
  4273. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4274. std::string original_text = "Raw deflate without gzip";
  4275. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4276. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4277. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4278. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4279. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4280. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4281. std::string decompressed_data;
  4282. {
  4283. httplib::detail::gzip_decompressor decompressor;
  4284. bool result = decompressor.decompress(
  4285. compressed_data.data(), compressed_data.size(),
  4286. [&](const char *decompressed_data_chunk,
  4287. size_t decompressed_data_chunk_size) {
  4288. decompressed_data.insert(decompressed_data.size(),
  4289. decompressed_data_chunk,
  4290. decompressed_data_chunk_size);
  4291. return true;
  4292. });
  4293. ASSERT_TRUE(result);
  4294. }
  4295. ASSERT_EQ(original_text, decompressed_data);
  4296. }
  4297. #ifdef _WIN32
  4298. TEST(GzipDecompressor, LargeRandomData) {
  4299. // prepare large random data that is difficult to be compressed and is
  4300. // expected to have large size even when compressed
  4301. std::random_device seed_gen;
  4302. std::mt19937 random(seed_gen());
  4303. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4304. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4305. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4306. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4307. // compress data over 4GiB
  4308. std::string compressed_data;
  4309. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4310. httplib::detail::gzip_compressor compressor;
  4311. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4312. data.size() * sizeof(std::uint32_t), true,
  4313. [&](const char *data, size_t size) {
  4314. compressed_data.insert(
  4315. compressed_data.size(), data, size);
  4316. return true;
  4317. });
  4318. ASSERT_TRUE(result);
  4319. // FIXME: compressed data size is expected to be greater than 4GiB,
  4320. // but there is no guarantee
  4321. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4322. // decompress data over 4GiB
  4323. std::string decompressed_data;
  4324. decompressed_data.reserve(data_size);
  4325. httplib::detail::gzip_decompressor decompressor;
  4326. result = decompressor.decompress(
  4327. compressed_data.data(), compressed_data.size(),
  4328. [&](const char *data, size_t size) {
  4329. decompressed_data.insert(decompressed_data.size(), data, size);
  4330. return true;
  4331. });
  4332. ASSERT_TRUE(result);
  4333. // compare
  4334. ASSERT_EQ(data_size, decompressed_data.size());
  4335. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4336. 0);
  4337. }
  4338. #endif
  4339. #endif
  4340. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4341. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4342. Headers headers;
  4343. headers.emplace("Accept-Encoding", "br");
  4344. auto res = cli_.Get("/streamed-chunked", headers);
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ(std::string("123456789"), res->body);
  4348. }
  4349. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4350. Headers headers;
  4351. headers.emplace("Accept-Encoding", "br");
  4352. auto res = cli_.Get("/streamed-chunked2", headers);
  4353. ASSERT_TRUE(res);
  4354. EXPECT_EQ(StatusCode::OK_200, res->status);
  4355. EXPECT_EQ(std::string("123456789"), res->body);
  4356. }
  4357. #endif
  4358. TEST_F(ServerTest, Patch) {
  4359. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. EXPECT_EQ("PATCH", res->body);
  4363. }
  4364. TEST_F(ServerTest, Delete) {
  4365. auto res = cli_.Delete("/delete");
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. EXPECT_EQ("DELETE", res->body);
  4369. }
  4370. TEST_F(ServerTest, DeleteContentReceiver) {
  4371. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("content", res->body);
  4375. }
  4376. TEST_F(ServerTest, Options) {
  4377. auto res = cli_.Options("*");
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(StatusCode::OK_200, res->status);
  4380. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4381. EXPECT_TRUE(res->body.empty());
  4382. }
  4383. TEST_F(ServerTest, URL) {
  4384. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::OK_200, res->status);
  4387. }
  4388. TEST_F(ServerTest, ArrayParam) {
  4389. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4390. ASSERT_TRUE(res);
  4391. EXPECT_EQ(StatusCode::OK_200, res->status);
  4392. }
  4393. TEST_F(ServerTest, NoMultipleHeaders) {
  4394. Headers headers = {{"Content-Length", "5"}};
  4395. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4396. "text/plain");
  4397. ASSERT_TRUE(res);
  4398. EXPECT_EQ(StatusCode::OK_200, res->status);
  4399. }
  4400. TEST_F(ServerTest, PostContentReceiver) {
  4401. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4402. ASSERT_TRUE(res);
  4403. ASSERT_EQ(StatusCode::OK_200, res->status);
  4404. ASSERT_EQ("content", res->body);
  4405. }
  4406. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4407. MultipartFormDataItemsForClientInput items = {
  4408. {"text1", "text default", "", ""},
  4409. {"text2", "aωb", "", ""},
  4410. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4411. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4412. {"file3", "", "", "application/octet-stream"},
  4413. };
  4414. auto res = cli_.Post("/content_receiver", items);
  4415. ASSERT_TRUE(res);
  4416. EXPECT_EQ(StatusCode::OK_200, res->status);
  4417. }
  4418. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4419. MultipartFormDataItemsForClientInput items = {
  4420. {"text1", "text default", "", ""},
  4421. {"text2", "aωb", "", ""},
  4422. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4423. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4424. {"file3", "", "", "application/octet-stream"},
  4425. };
  4426. auto boundary = std::string("+++++");
  4427. std::string body;
  4428. for (const auto &item : items) {
  4429. body += "--" + boundary + "\r\n";
  4430. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4431. if (!item.filename.empty()) {
  4432. body += "; filename=\"" + item.filename + "\"";
  4433. }
  4434. body += "\r\n";
  4435. if (!item.content_type.empty()) {
  4436. body += "Content-Type: " + item.content_type + "\r\n";
  4437. }
  4438. body += "\r\n";
  4439. body += item.content + "\r\n";
  4440. }
  4441. body += "--" + boundary + "--\r\n";
  4442. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4443. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4444. ASSERT_TRUE(res);
  4445. EXPECT_EQ(StatusCode::OK_200, res->status);
  4446. }
  4447. TEST_F(ServerTest, PostContentReceiverGzip) {
  4448. cli_.set_compress(true);
  4449. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4450. ASSERT_TRUE(res);
  4451. ASSERT_EQ(StatusCode::OK_200, res->status);
  4452. ASSERT_EQ("content", res->body);
  4453. }
  4454. TEST_F(ServerTest, PutContentReceiver) {
  4455. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4456. ASSERT_TRUE(res);
  4457. ASSERT_EQ(StatusCode::OK_200, res->status);
  4458. ASSERT_EQ("content", res->body);
  4459. }
  4460. TEST_F(ServerTest, PatchContentReceiver) {
  4461. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4462. ASSERT_TRUE(res);
  4463. ASSERT_EQ(StatusCode::OK_200, res->status);
  4464. ASSERT_EQ("content", res->body);
  4465. }
  4466. TEST_F(ServerTest, PostQueryStringAndBody) {
  4467. auto res =
  4468. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4469. ASSERT_TRUE(res);
  4470. ASSERT_EQ(StatusCode::OK_200, res->status);
  4471. }
  4472. TEST_F(ServerTest, HTTP2Magic) {
  4473. Request req;
  4474. req.method = "PRI";
  4475. req.path = "*";
  4476. req.body = "SM";
  4477. auto res = std::make_shared<Response>();
  4478. auto error = Error::Success;
  4479. auto ret = cli_.send(req, *res, error);
  4480. ASSERT_TRUE(ret);
  4481. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4482. }
  4483. TEST_F(ServerTest, KeepAlive) {
  4484. auto res = cli_.Get("/hi");
  4485. ASSERT_TRUE(res);
  4486. EXPECT_EQ(StatusCode::OK_200, res->status);
  4487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4488. EXPECT_EQ("Hello World!", res->body);
  4489. res = cli_.Get("/hi");
  4490. ASSERT_TRUE(res);
  4491. EXPECT_EQ(StatusCode::OK_200, res->status);
  4492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("Hello World!", res->body);
  4494. res = cli_.Get("/hi");
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::OK_200, res->status);
  4497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4498. EXPECT_EQ("Hello World!", res->body);
  4499. res = cli_.Get("/not-exist");
  4500. ASSERT_TRUE(res);
  4501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4502. res = cli_.Post("/empty", "", "text/plain");
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4506. EXPECT_EQ("empty", res->body);
  4507. EXPECT_EQ("close", res->get_header_value("Connection"));
  4508. res = cli_.Post(
  4509. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4510. "text/plain");
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(StatusCode::OK_200, res->status);
  4513. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4514. EXPECT_EQ("empty", res->body);
  4515. cli_.set_keep_alive(false);
  4516. res = cli_.Get("/last-request");
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("close", res->get_header_value("Connection"));
  4520. }
  4521. TEST_F(ServerTest, TooManyRedirect) {
  4522. cli_.set_follow_location(true);
  4523. auto res = cli_.Get("/redirect/0");
  4524. ASSERT_TRUE(!res);
  4525. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4526. }
  4527. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4528. TEST_F(ServerTest, Gzip) {
  4529. Headers headers;
  4530. headers.emplace("Accept-Encoding", "gzip, deflate");
  4531. auto res = cli_.Get("/compress", headers);
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4535. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4536. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4537. "7890123456789012345678901234567890",
  4538. res->body);
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. }
  4541. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4542. Headers headers;
  4543. headers.emplace("Accept-Encoding", "");
  4544. auto res = cli_.Get("/compress", headers);
  4545. ASSERT_TRUE(res);
  4546. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4548. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4549. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4550. "7890123456789012345678901234567890",
  4551. res->body);
  4552. EXPECT_EQ(StatusCode::OK_200, res->status);
  4553. }
  4554. TEST_F(ServerTest, GzipWithContentReceiver) {
  4555. Headers headers;
  4556. headers.emplace("Accept-Encoding", "gzip, deflate");
  4557. std::string body;
  4558. auto res = cli_.Get("/compress", headers,
  4559. [&](const char *data, uint64_t data_length) {
  4560. EXPECT_EQ(100U, data_length);
  4561. body.append(data, data_length);
  4562. return true;
  4563. });
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4567. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4569. "7890123456789012345678901234567890",
  4570. body);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. }
  4573. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4574. Headers headers;
  4575. headers.emplace("Accept-Encoding", "gzip, deflate");
  4576. cli_.set_decompress(false);
  4577. auto res = cli_.Get("/compress", headers);
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4580. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4581. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ(33U, res->body.size());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. }
  4585. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4586. Headers headers;
  4587. headers.emplace("Accept-Encoding", "");
  4588. std::string body;
  4589. auto res = cli_.Get("/compress", headers,
  4590. [&](const char *data, uint64_t data_length) {
  4591. EXPECT_EQ(100U, data_length);
  4592. body.append(data, data_length);
  4593. return true;
  4594. });
  4595. ASSERT_TRUE(res);
  4596. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4598. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4599. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4600. "7890123456789012345678901234567890",
  4601. body);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. }
  4604. TEST_F(ServerTest, NoGzip) {
  4605. Headers headers;
  4606. headers.emplace("Accept-Encoding", "gzip, deflate");
  4607. auto res = cli_.Get("/nocompress", headers);
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4610. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4611. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4613. "7890123456789012345678901234567890",
  4614. res->body);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. }
  4617. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4618. Headers headers;
  4619. headers.emplace("Accept-Encoding", "gzip, deflate");
  4620. std::string body;
  4621. auto res = cli_.Get("/nocompress", headers,
  4622. [&](const char *data, uint64_t data_length) {
  4623. EXPECT_EQ(100U, data_length);
  4624. body.append(data, data_length);
  4625. return true;
  4626. });
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4629. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4631. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4632. "7890123456789012345678901234567890",
  4633. body);
  4634. EXPECT_EQ(StatusCode::OK_200, res->status);
  4635. }
  4636. TEST_F(ServerTest, MultipartFormDataGzip) {
  4637. MultipartFormDataItemsForClientInput items = {
  4638. {"key1", "test", "", ""},
  4639. {"key2", "--abcdefg123", "", ""},
  4640. };
  4641. cli_.set_compress(true);
  4642. auto res = cli_.Post("/compress-multipart", items);
  4643. ASSERT_TRUE(res);
  4644. EXPECT_EQ(StatusCode::OK_200, res->status);
  4645. }
  4646. #endif
  4647. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4648. TEST_F(ServerTest, Brotli) {
  4649. Headers headers;
  4650. headers.emplace("Accept-Encoding", "br");
  4651. auto res = cli_.Get("/compress", headers);
  4652. ASSERT_TRUE(res);
  4653. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4655. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4656. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4657. "7890123456789012345678901234567890",
  4658. res->body);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. }
  4661. #endif
  4662. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4663. TEST_F(ServerTest, Zstd) {
  4664. Headers headers;
  4665. headers.emplace("Accept-Encoding", "zstd");
  4666. auto res = cli_.Get("/compress", headers);
  4667. ASSERT_TRUE(res);
  4668. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4669. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4670. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4671. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4672. "7890123456789012345678901234567890",
  4673. res->body);
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. }
  4676. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4677. Headers headers;
  4678. headers.emplace("Accept-Encoding", "");
  4679. auto res = cli_.Get("/compress", headers);
  4680. ASSERT_TRUE(res);
  4681. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4682. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4683. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4684. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4685. "7890123456789012345678901234567890",
  4686. res->body);
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. }
  4689. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4690. Headers headers;
  4691. headers.emplace("Accept-Encoding", "zstd");
  4692. std::string body;
  4693. auto res = cli_.Get("/compress", headers,
  4694. [&](const char *data, uint64_t data_length) {
  4695. EXPECT_EQ(100U, data_length);
  4696. body.append(data, data_length);
  4697. return true;
  4698. });
  4699. ASSERT_TRUE(res);
  4700. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4701. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4702. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4703. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4704. "7890123456789012345678901234567890",
  4705. body);
  4706. EXPECT_EQ(StatusCode::OK_200, res->status);
  4707. }
  4708. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4709. Headers headers;
  4710. headers.emplace("Accept-Encoding", "zstd");
  4711. cli_.set_decompress(false);
  4712. auto res = cli_.Get("/compress", headers);
  4713. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4714. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4715. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4716. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4717. ASSERT_TRUE(res);
  4718. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4720. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. ASSERT_EQ(26U, res->body.size());
  4723. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4724. 0);
  4725. }
  4726. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4727. Headers headers;
  4728. headers.emplace("Accept-Encoding", "");
  4729. std::string body;
  4730. auto res = cli_.Get("/compress", headers,
  4731. [&](const char *data, uint64_t data_length) {
  4732. EXPECT_EQ(100U, data_length);
  4733. body.append(data, data_length);
  4734. return true;
  4735. });
  4736. ASSERT_TRUE(res);
  4737. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4738. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4739. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4740. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4741. "7890123456789012345678901234567890",
  4742. body);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. }
  4745. TEST_F(ServerTest, NoZstd) {
  4746. Headers headers;
  4747. headers.emplace("Accept-Encoding", "zstd");
  4748. auto res = cli_.Get("/nocompress", headers);
  4749. ASSERT_TRUE(res);
  4750. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4751. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4752. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4753. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4754. "7890123456789012345678901234567890",
  4755. res->body);
  4756. EXPECT_EQ(StatusCode::OK_200, res->status);
  4757. }
  4758. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4759. Headers headers;
  4760. headers.emplace("Accept-Encoding", "zstd");
  4761. std::string body;
  4762. auto res = cli_.Get("/nocompress", headers,
  4763. [&](const char *data, uint64_t data_length) {
  4764. EXPECT_EQ(100U, data_length);
  4765. body.append(data, data_length);
  4766. return true;
  4767. });
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4770. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4771. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4772. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4773. "7890123456789012345678901234567890",
  4774. body);
  4775. EXPECT_EQ(StatusCode::OK_200, res->status);
  4776. }
  4777. // TODO: How to enable zstd ??
  4778. TEST_F(ServerTest, MultipartFormDataZstd) {
  4779. MultipartFormDataItemsForClientInput items = {
  4780. {"key1", "test", "", ""},
  4781. {"key2", "--abcdefg123", "", ""},
  4782. };
  4783. Headers headers;
  4784. headers.emplace("Accept-Encoding", "zstd");
  4785. cli_.set_compress(true);
  4786. auto res = cli_.Post("/compress-multipart", headers, items);
  4787. ASSERT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. }
  4790. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4791. Headers headers;
  4792. headers.emplace("Accept-Encoding", "zstd");
  4793. cli_.set_compress(true);
  4794. auto res = cli_.Put(
  4795. "/put", headers, 3,
  4796. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4797. sink.os << "PUT";
  4798. return true;
  4799. },
  4800. "text/plain");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("PUT", res->body);
  4804. }
  4805. TEST(ZstdDecompressor, ChunkedDecompression) {
  4806. std::string data;
  4807. for (size_t i = 0; i < 32 * 1024; ++i) {
  4808. data.push_back(static_cast<char>('a' + i % 26));
  4809. }
  4810. std::string compressed_data;
  4811. {
  4812. httplib::detail::zstd_compressor compressor;
  4813. bool result = compressor.compress(
  4814. data.data(), data.size(),
  4815. /*last=*/true,
  4816. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4817. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4818. compressed_data_size);
  4819. return true;
  4820. });
  4821. ASSERT_TRUE(result);
  4822. }
  4823. std::string decompressed_data;
  4824. {
  4825. httplib::detail::zstd_decompressor decompressor;
  4826. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4827. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4828. size_t chunk_size = 130;
  4829. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4830. chunk_begin += chunk_size) {
  4831. size_t current_chunk_size =
  4832. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4833. bool result = decompressor.decompress(
  4834. compressed_data.data() + chunk_begin, current_chunk_size,
  4835. [&](const char *decompressed_data_chunk,
  4836. size_t decompressed_data_chunk_size) {
  4837. decompressed_data.insert(decompressed_data.size(),
  4838. decompressed_data_chunk,
  4839. decompressed_data_chunk_size);
  4840. return true;
  4841. });
  4842. ASSERT_TRUE(result);
  4843. }
  4844. }
  4845. ASSERT_EQ(data, decompressed_data);
  4846. }
  4847. TEST(ZstdDecompressor, Decompress) {
  4848. std::string original_text = "Compressed with ZSTD";
  4849. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4850. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4851. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4852. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4853. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4854. std::string decompressed_data;
  4855. {
  4856. httplib::detail::zstd_decompressor decompressor;
  4857. bool result = decompressor.decompress(
  4858. compressed_data.data(), compressed_data.size(),
  4859. [&](const char *decompressed_data_chunk,
  4860. size_t decompressed_data_chunk_size) {
  4861. decompressed_data.insert(decompressed_data.size(),
  4862. decompressed_data_chunk,
  4863. decompressed_data_chunk_size);
  4864. return true;
  4865. });
  4866. ASSERT_TRUE(result);
  4867. }
  4868. ASSERT_EQ(original_text, decompressed_data);
  4869. }
  4870. #endif
  4871. // Sends a raw request to a server listening at HOST:PORT.
  4872. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4873. std::string *resp = nullptr) {
  4874. auto error = Error::Success;
  4875. auto client_sock = detail::create_client_socket(
  4876. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4877. /*connection_timeout_sec=*/5, 0,
  4878. /*read_timeout_sec=*/5, 0,
  4879. /*write_timeout_sec=*/5, 0, std::string(), error);
  4880. if (client_sock == INVALID_SOCKET) { return false; }
  4881. auto ret = detail::process_client_socket(
  4882. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4883. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4884. if (req.size() !=
  4885. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4886. return false;
  4887. }
  4888. char buf[512];
  4889. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4890. while (line_reader.getline()) {
  4891. if (resp) { *resp += line_reader.ptr(); }
  4892. }
  4893. return true;
  4894. });
  4895. detail::close_socket(client_sock);
  4896. return ret;
  4897. }
  4898. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4899. Server svr;
  4900. std::string header_value;
  4901. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4902. header_value = req.get_header_value("foo");
  4903. res.set_content("ok", "text/plain");
  4904. });
  4905. thread t = thread([&] { svr.listen(HOST, PORT); });
  4906. auto se = detail::scope_exit([&] {
  4907. svr.stop();
  4908. t.join();
  4909. ASSERT_FALSE(svr.is_running());
  4910. });
  4911. svr.wait_until_ready();
  4912. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4913. // like characters are not treated the same - use vertical tab and escape.
  4914. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4915. "foo: \t \v bar \x1B\t \r\n"
  4916. "Connection: close\r\n"
  4917. "\r\n";
  4918. std::string res;
  4919. ASSERT_TRUE(send_request(5, req, &res));
  4920. EXPECT_EQ(header_value, "");
  4921. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4922. }
  4923. // Sends a raw request and verifies that there isn't a crash or exception.
  4924. static void test_raw_request(const std::string &req,
  4925. std::string *out = nullptr) {
  4926. Server svr;
  4927. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4928. res.set_content("ok", "text/plain");
  4929. });
  4930. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4931. res.set_content("ok", "text/plain");
  4932. });
  4933. svr.Get("/header_field_value_check",
  4934. [&](const Request & /*req*/, Response &res) {
  4935. res.set_content("ok", "text/plain");
  4936. });
  4937. // Server read timeout must be longer than the client read timeout for the
  4938. // bug to reproduce, probably to force the server to process a request
  4939. // without a trailing blank line.
  4940. const time_t client_read_timeout_sec = 1;
  4941. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4942. bool listen_thread_ok = false;
  4943. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4944. auto se = detail::scope_exit([&] {
  4945. svr.stop();
  4946. t.join();
  4947. ASSERT_FALSE(svr.is_running());
  4948. EXPECT_TRUE(listen_thread_ok);
  4949. });
  4950. svr.wait_until_ready();
  4951. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4952. }
  4953. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4954. // A certain header line causes an exception if the header property is parsed
  4955. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4956. test_raw_request(
  4957. "GET /hi HTTP/1.1\r\n"
  4958. " : "
  4959. " "
  4960. " ");
  4961. }
  4962. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4963. // A certain header line causes an exception if the header property *name* is
  4964. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4965. // greedy matcher and requires backtracking when there are a lot of ":"
  4966. // characters.
  4967. // This occurs with libc++ but not libstdc++.
  4968. test_raw_request(
  4969. "GET /hi HTTP/1.1\r\n"
  4970. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4971. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4972. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4973. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4974. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4975. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4976. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4977. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4978. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4979. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4980. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4981. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4982. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4983. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4984. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4985. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4986. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4987. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4988. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4989. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4990. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4991. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4992. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4993. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4994. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4995. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4996. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4997. "&&&%%%");
  4998. }
  4999. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5000. // Make sure this doesn't crash the server.
  5001. // In a previous version of the header line regex, the "\r" rendered the line
  5002. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5003. // a new position where the leading white space ended and the field value
  5004. // began.
  5005. // The crash occurs with libc++ but not libstdc++.
  5006. test_raw_request("GET /hi HTTP/1.1\r\n"
  5007. "a:" +
  5008. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5009. "\r\n"
  5010. "\r\n");
  5011. }
  5012. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5013. std::string out;
  5014. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5015. "Content-Type: text/plain\r\n"
  5016. "Transfer-Encoding: chunked\r\n"
  5017. "\r\n"
  5018. "nothex\r\n",
  5019. &out);
  5020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5021. }
  5022. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5023. std::string out;
  5024. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5025. "Content-Type: text/plain\r\n"
  5026. "Transfer-Encoding: chunked\r\n"
  5027. "\r\n"
  5028. "3\r\n"
  5029. "xyz\r\n"
  5030. "NaN\r\n",
  5031. &out);
  5032. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5033. }
  5034. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5035. std::string out;
  5036. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5037. "Content-Type: text/plain\r\n"
  5038. "Transfer-Encoding: chunked\r\n"
  5039. "\r\n"
  5040. // Length is too large for 64 bits.
  5041. "1ffffffffffffffff\r\n"
  5042. "xyz\r\n",
  5043. &out);
  5044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5045. }
  5046. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5047. test_raw_request("GET /hi HTTP/1.1\r\n"
  5048. "Content-Type: text/plain\r\n\r");
  5049. }
  5050. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5051. std::string out;
  5052. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5054. }
  5055. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5056. std::string out;
  5057. std::string request(
  5058. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5059. test_raw_request(request, &out);
  5060. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5061. }
  5062. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5063. std::string out;
  5064. std::string request(
  5065. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5066. test_raw_request(request, &out);
  5067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5068. }
  5069. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5070. std::string out;
  5071. std::string request(
  5072. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5073. test_raw_request(request, &out);
  5074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5075. }
  5076. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5077. std::string out;
  5078. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5079. "Test: \r\n\r\n",
  5080. &out);
  5081. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5082. }
  5083. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5084. Server svr;
  5085. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5086. res.set_header("Cache-Control", "no-cache");
  5087. res.set_chunked_content_provider(
  5088. "text/event-stream", [](size_t offset, DataSink &sink) {
  5089. std::string s = "data:";
  5090. s += std::to_string(offset);
  5091. s += "\n\n";
  5092. auto ret = sink.write(s.data(), s.size());
  5093. EXPECT_TRUE(ret);
  5094. std::this_thread::sleep_for(std::chrono::seconds(1));
  5095. return true;
  5096. });
  5097. });
  5098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5099. svr.wait_until_ready();
  5100. Client client(HOST, PORT);
  5101. const Headers headers = {{"Accept", "text/event-stream"}};
  5102. auto get_thread = std::thread([&client, &headers]() {
  5103. auto res = client.Get(
  5104. "/events", headers,
  5105. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5106. });
  5107. auto se = detail::scope_exit([&] {
  5108. svr.stop();
  5109. get_thread.join();
  5110. listen_thread.join();
  5111. ASSERT_FALSE(svr.is_running());
  5112. });
  5113. // Give GET time to get a few messages.
  5114. std::this_thread::sleep_for(std::chrono::seconds(2));
  5115. }
  5116. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5117. httplib::Server svr;
  5118. svr.Post("/hi",
  5119. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5120. res.status = StatusCode::OK_200;
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. svr.wait_until_ready();
  5124. Client cli(HOST, PORT);
  5125. auto res = cli.Post("/hi", "data", "text/plain");
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. svr.stop();
  5129. thread.join();
  5130. ASSERT_FALSE(svr.is_running());
  5131. res = cli.Post("/hi", "data", "text/plain");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. TEST(ServerStopTest, ListenFailure) {
  5135. Server svr;
  5136. auto t = thread([&]() {
  5137. auto ret = svr.listen("????", PORT);
  5138. EXPECT_FALSE(ret);
  5139. });
  5140. svr.wait_until_ready();
  5141. svr.stop();
  5142. t.join();
  5143. }
  5144. TEST(ServerStopTest, Decommision) {
  5145. Server svr;
  5146. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5147. for (int i = 0; i < 4; i++) {
  5148. auto is_even = !(i % 2);
  5149. std::thread t{[&] {
  5150. try {
  5151. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5152. if (is_even) {
  5153. throw std::runtime_error("Some thing that happens to go wrong.");
  5154. }
  5155. svr.listen(HOST, PORT);
  5156. } catch (...) { svr.decommission(); }
  5157. }};
  5158. svr.wait_until_ready();
  5159. // Server is up
  5160. {
  5161. Client cli(HOST, PORT);
  5162. auto res = cli.Get("/hi");
  5163. if (is_even) {
  5164. EXPECT_FALSE(res);
  5165. } else {
  5166. EXPECT_TRUE(res);
  5167. EXPECT_EQ("hi...", res->body);
  5168. }
  5169. }
  5170. svr.stop();
  5171. t.join();
  5172. // Server is down...
  5173. {
  5174. Client cli(HOST, PORT);
  5175. auto res = cli.Get("/hi");
  5176. EXPECT_FALSE(res);
  5177. }
  5178. }
  5179. }
  5180. TEST(StreamingTest, NoContentLengthStreaming) {
  5181. Server svr;
  5182. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5183. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5184. if (offset < 6) {
  5185. sink.os << (offset < 3 ? "a" : "b");
  5186. } else {
  5187. sink.done();
  5188. }
  5189. return true;
  5190. });
  5191. });
  5192. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5193. auto listen_se = detail::scope_exit([&] {
  5194. svr.stop();
  5195. listen_thread.join();
  5196. ASSERT_FALSE(svr.is_running());
  5197. });
  5198. svr.wait_until_ready();
  5199. Client client(HOST, PORT);
  5200. auto get_thread = std::thread([&client]() {
  5201. std::string s;
  5202. auto res =
  5203. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5204. s += std::string(data, len);
  5205. return true;
  5206. });
  5207. ASSERT_TRUE(res);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. EXPECT_EQ("aaabbb", s);
  5210. });
  5211. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5212. // Give GET time to get a few messages.
  5213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5214. }
  5215. TEST(MountTest, Unmount) {
  5216. Server svr;
  5217. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5218. auto se = detail::scope_exit([&] {
  5219. svr.stop();
  5220. listen_thread.join();
  5221. ASSERT_FALSE(svr.is_running());
  5222. });
  5223. svr.wait_until_ready();
  5224. Client cli("localhost", PORT);
  5225. svr.set_mount_point("/mount2", "./www2");
  5226. auto res = cli.Get("/");
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5229. res = cli.Get("/mount2/dir/test.html");
  5230. ASSERT_TRUE(res);
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. svr.set_mount_point("/", "./www");
  5233. res = cli.Get("/dir/");
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. svr.remove_mount_point("/");
  5237. res = cli.Get("/dir/");
  5238. ASSERT_TRUE(res);
  5239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5240. svr.remove_mount_point("/mount2");
  5241. res = cli.Get("/mount2/dir/test.html");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5244. }
  5245. TEST(MountTest, Redicect) {
  5246. Server svr;
  5247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5248. auto se = detail::scope_exit([&] {
  5249. svr.stop();
  5250. listen_thread.join();
  5251. ASSERT_FALSE(svr.is_running());
  5252. });
  5253. svr.set_mount_point("/", "./www");
  5254. svr.wait_until_ready();
  5255. Client cli("localhost", PORT);
  5256. auto res = cli.Get("/dir/");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. res = cli.Get("/dir");
  5260. ASSERT_TRUE(res);
  5261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5262. res = cli.Get("/file");
  5263. ASSERT_TRUE(res);
  5264. EXPECT_EQ(StatusCode::OK_200, res->status);
  5265. res = cli.Get("/file/");
  5266. ASSERT_TRUE(res);
  5267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5268. cli.set_follow_location(true);
  5269. res = cli.Get("/dir");
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST(MountTest, MultibytesPathName) {
  5274. Server svr;
  5275. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5276. auto se = detail::scope_exit([&] {
  5277. svr.stop();
  5278. listen_thread.join();
  5279. ASSERT_FALSE(svr.is_running());
  5280. });
  5281. svr.set_mount_point("/", "./www");
  5282. svr.wait_until_ready();
  5283. Client cli("localhost", PORT);
  5284. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5285. ASSERT_TRUE(res);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5288. }
  5289. TEST(KeepAliveTest, ReadTimeout) {
  5290. Server svr;
  5291. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5292. std::this_thread::sleep_for(std::chrono::seconds(2));
  5293. res.set_content("a", "text/plain");
  5294. });
  5295. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5296. res.set_content("b", "text/plain");
  5297. });
  5298. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5299. auto se = detail::scope_exit([&] {
  5300. svr.stop();
  5301. listen_thread.join();
  5302. ASSERT_FALSE(svr.is_running());
  5303. });
  5304. svr.wait_until_ready();
  5305. Client cli("localhost", PORT);
  5306. cli.set_keep_alive(true);
  5307. cli.set_read_timeout(std::chrono::seconds(1));
  5308. auto resa = cli.Get("/a");
  5309. ASSERT_FALSE(resa);
  5310. EXPECT_EQ(Error::Read, resa.error());
  5311. auto resb = cli.Get("/b");
  5312. ASSERT_TRUE(resb);
  5313. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5314. EXPECT_EQ("b", resb->body);
  5315. }
  5316. TEST(KeepAliveTest, MaxCount) {
  5317. size_t keep_alive_max_count = 3;
  5318. Server svr;
  5319. svr.set_keep_alive_max_count(keep_alive_max_count);
  5320. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5321. res.set_content("Hello World!", "text/plain");
  5322. });
  5323. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5324. auto se = detail::scope_exit([&] {
  5325. svr.stop();
  5326. listen_thread.join();
  5327. ASSERT_FALSE(svr.is_running());
  5328. });
  5329. svr.wait_until_ready();
  5330. Client cli(HOST, PORT);
  5331. cli.set_keep_alive(true);
  5332. for (size_t i = 0; i < 5; i++) {
  5333. auto result = cli.Get("/hi");
  5334. ASSERT_TRUE(result);
  5335. EXPECT_EQ(StatusCode::OK_200, result->status);
  5336. if (i == keep_alive_max_count - 1) {
  5337. EXPECT_EQ("close", result->get_header_value("Connection"));
  5338. } else {
  5339. EXPECT_FALSE(result->has_header("Connection"));
  5340. }
  5341. }
  5342. }
  5343. TEST(KeepAliveTest, Issue1041) {
  5344. Server svr;
  5345. svr.set_keep_alive_timeout(3);
  5346. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5347. res.set_content("Hello World!", "text/plain");
  5348. });
  5349. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5350. auto se = detail::scope_exit([&] {
  5351. svr.stop();
  5352. listen_thread.join();
  5353. ASSERT_FALSE(svr.is_running());
  5354. });
  5355. svr.wait_until_ready();
  5356. Client cli(HOST, PORT);
  5357. cli.set_keep_alive(true);
  5358. auto result = cli.Get("/hi");
  5359. ASSERT_TRUE(result);
  5360. EXPECT_EQ(StatusCode::OK_200, result->status);
  5361. std::this_thread::sleep_for(std::chrono::seconds(5));
  5362. result = cli.Get("/hi");
  5363. ASSERT_TRUE(result);
  5364. EXPECT_EQ(StatusCode::OK_200, result->status);
  5365. }
  5366. TEST(KeepAliveTest, Issue1959) {
  5367. Server svr;
  5368. svr.set_keep_alive_timeout(5);
  5369. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5370. res.set_content("a", "text/plain");
  5371. });
  5372. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5373. auto se = detail::scope_exit([&] {
  5374. if (!svr.is_running()) return;
  5375. svr.stop();
  5376. listen_thread.join();
  5377. ASSERT_FALSE(svr.is_running());
  5378. });
  5379. svr.wait_until_ready();
  5380. Client cli("localhost", PORT);
  5381. cli.set_keep_alive(true);
  5382. using namespace std::chrono;
  5383. auto start = steady_clock::now();
  5384. cli.Get("/a");
  5385. svr.stop();
  5386. listen_thread.join();
  5387. auto end = steady_clock::now();
  5388. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5389. EXPECT_LT(elapsed, 5000);
  5390. }
  5391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5392. TEST(KeepAliveTest, SSLClientReconnection) {
  5393. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5394. ASSERT_TRUE(svr.is_valid());
  5395. svr.set_keep_alive_timeout(1);
  5396. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5397. res.set_content("Hello World!", "text/plain");
  5398. });
  5399. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5400. auto se = detail::scope_exit([&] {
  5401. svr.stop();
  5402. listen_thread.join();
  5403. ASSERT_FALSE(svr.is_running());
  5404. });
  5405. svr.wait_until_ready();
  5406. SSLClient cli(HOST, PORT);
  5407. cli.enable_server_certificate_verification(false);
  5408. cli.set_keep_alive(true);
  5409. auto result = cli.Get("/hi");
  5410. ASSERT_TRUE(result);
  5411. EXPECT_EQ(StatusCode::OK_200, result->status);
  5412. result = cli.Get("/hi");
  5413. ASSERT_TRUE(result);
  5414. EXPECT_EQ(StatusCode::OK_200, result->status);
  5415. std::this_thread::sleep_for(std::chrono::seconds(2));
  5416. // Recoonect
  5417. result = cli.Get("/hi");
  5418. ASSERT_TRUE(result);
  5419. EXPECT_EQ(StatusCode::OK_200, result->status);
  5420. result = cli.Get("/hi");
  5421. ASSERT_TRUE(result);
  5422. EXPECT_EQ(StatusCode::OK_200, result->status);
  5423. }
  5424. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5425. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5426. ASSERT_TRUE(svr.is_valid());
  5427. svr.set_keep_alive_timeout(1);
  5428. std::string content = "reconnect";
  5429. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5430. res.set_content("Hello World!", "text/plain");
  5431. });
  5432. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5433. auto se = detail::scope_exit([&] {
  5434. svr.stop();
  5435. listen_thread.join();
  5436. ASSERT_FALSE(svr.is_running());
  5437. });
  5438. svr.wait_until_ready();
  5439. SSLClient cli(HOST, PORT);
  5440. cli.enable_server_certificate_verification(false);
  5441. cli.set_keep_alive(true);
  5442. auto result = cli.Post(
  5443. "/hi", content.size(),
  5444. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5445. sink.write(content.c_str(), content.size());
  5446. return true;
  5447. },
  5448. "text/plain");
  5449. ASSERT_TRUE(result);
  5450. EXPECT_EQ(200, result->status);
  5451. std::this_thread::sleep_for(std::chrono::seconds(2));
  5452. // Recoonect
  5453. result = cli.Post(
  5454. "/hi", content.size(),
  5455. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5456. sink.write(content.c_str(), content.size());
  5457. return true;
  5458. },
  5459. "text/plain");
  5460. ASSERT_TRUE(result);
  5461. EXPECT_EQ(200, result->status);
  5462. result = cli.Post(
  5463. "/hi", content.size(),
  5464. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5465. sink.write(content.c_str(), content.size());
  5466. return true;
  5467. },
  5468. "text/plain");
  5469. ASSERT_TRUE(result);
  5470. EXPECT_EQ(200, result->status);
  5471. }
  5472. #endif
  5473. TEST(ClientProblemDetectionTest, ContentProvider) {
  5474. Server svr;
  5475. size_t content_length = 1024 * 1024;
  5476. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5477. res.set_content_provider(
  5478. content_length, "text/plain",
  5479. [&](size_t offset, size_t length, DataSink &sink) {
  5480. auto out_len = std::min(length, static_cast<size_t>(1024));
  5481. std::string out(out_len, '@');
  5482. sink.write(out.data(), out_len);
  5483. return offset < 4096;
  5484. },
  5485. [](bool success) { ASSERT_FALSE(success); });
  5486. });
  5487. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5488. res.set_content_provider(
  5489. 0, "text/plain",
  5490. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5491. EXPECT_TRUE(false);
  5492. return true;
  5493. },
  5494. [](bool success) { ASSERT_FALSE(success); });
  5495. });
  5496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5497. auto se = detail::scope_exit([&] {
  5498. svr.stop();
  5499. listen_thread.join();
  5500. ASSERT_FALSE(svr.is_running());
  5501. });
  5502. svr.wait_until_ready();
  5503. Client cli("localhost", PORT);
  5504. {
  5505. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5506. size_t /*data_length*/) { return false; });
  5507. ASSERT_FALSE(res);
  5508. }
  5509. {
  5510. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5511. size_t /*data_length*/) { return false; });
  5512. ASSERT_TRUE(res);
  5513. }
  5514. }
  5515. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5516. Server svr;
  5517. svr.set_error_handler([](Request const &, Response &res) -> void {
  5518. res.set_chunked_content_provider(
  5519. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5520. sink.os << "hello";
  5521. sink.os << "world";
  5522. sink.done();
  5523. return true;
  5524. });
  5525. });
  5526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5527. auto se = detail::scope_exit([&] {
  5528. svr.stop();
  5529. listen_thread.join();
  5530. ASSERT_FALSE(svr.is_running());
  5531. });
  5532. svr.wait_until_ready();
  5533. Client cli("localhost", PORT);
  5534. auto res = cli.Get("/");
  5535. ASSERT_TRUE(res);
  5536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5537. EXPECT_EQ("helloworld", res->body);
  5538. }
  5539. TEST(LongPollingTest, ClientCloseDetection) {
  5540. Server svr;
  5541. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5542. res.set_chunked_content_provider(
  5543. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5544. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5545. sink.os << "hello";
  5546. auto count = 10;
  5547. while (count > 0 && sink.is_writable()) {
  5548. this_thread::sleep_for(chrono::milliseconds(10));
  5549. count--;
  5550. }
  5551. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5552. return true;
  5553. });
  5554. });
  5555. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. listen_thread.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. Client cli("localhost", PORT);
  5563. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5564. EXPECT_EQ("hello", string(data, data_length));
  5565. return false; // close the socket immediately.
  5566. });
  5567. ASSERT_FALSE(res);
  5568. }
  5569. TEST(GetWithParametersTest, GetWithParameters) {
  5570. Server svr;
  5571. svr.Get("/", [&](const Request &req, Response &) {
  5572. EXPECT_EQ("world", req.get_param_value("hello"));
  5573. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5574. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5575. });
  5576. svr.Get("/params", [&](const Request &req, Response &) {
  5577. EXPECT_EQ("world", req.get_param_value("hello"));
  5578. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5579. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5580. });
  5581. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5582. EXPECT_EQ("resource-id", req.matches[1]);
  5583. EXPECT_EQ("foo", req.get_param_value("param1"));
  5584. EXPECT_EQ("bar", req.get_param_value("param2"));
  5585. });
  5586. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5587. EXPECT_EQ("user-id", req.path_params.at("id"));
  5588. EXPECT_EQ("foo", req.get_param_value("param1"));
  5589. EXPECT_EQ("bar", req.get_param_value("param2"));
  5590. });
  5591. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5592. auto se = detail::scope_exit([&] {
  5593. svr.stop();
  5594. listen_thread.join();
  5595. ASSERT_FALSE(svr.is_running());
  5596. });
  5597. svr.wait_until_ready();
  5598. {
  5599. Client cli(HOST, PORT);
  5600. Params params;
  5601. params.emplace("hello", "world");
  5602. params.emplace("hello2", "world2");
  5603. params.emplace("hello3", "world3");
  5604. auto res = cli.Get("/", params, Headers{});
  5605. ASSERT_TRUE(res);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. }
  5608. {
  5609. Client cli(HOST, PORT);
  5610. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5611. ASSERT_TRUE(res);
  5612. EXPECT_EQ(StatusCode::OK_200, res->status);
  5613. }
  5614. {
  5615. Client cli(HOST, PORT);
  5616. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5617. ASSERT_TRUE(res);
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. }
  5620. {
  5621. Client cli(HOST, PORT);
  5622. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5623. ASSERT_TRUE(res);
  5624. EXPECT_EQ(StatusCode::OK_200, res->status);
  5625. }
  5626. }
  5627. TEST(GetWithParametersTest, GetWithParameters2) {
  5628. Server svr;
  5629. svr.Get("/", [&](const Request &req, Response &res) {
  5630. auto text = req.get_param_value("hello");
  5631. res.set_content(text, "text/plain");
  5632. });
  5633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5634. auto se = detail::scope_exit([&] {
  5635. svr.stop();
  5636. listen_thread.join();
  5637. ASSERT_FALSE(svr.is_running());
  5638. });
  5639. svr.wait_until_ready();
  5640. Client cli("localhost", PORT);
  5641. Params params;
  5642. params.emplace("hello", "world");
  5643. std::string body;
  5644. auto res = cli.Get("/", params, Headers{},
  5645. [&](const char *data, size_t data_length) {
  5646. body.append(data, data_length);
  5647. return true;
  5648. });
  5649. ASSERT_TRUE(res);
  5650. EXPECT_EQ(StatusCode::OK_200, res->status);
  5651. EXPECT_EQ("world", body);
  5652. }
  5653. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5655. auto host = "httpbin.org";
  5656. auto path = std::string{"/range/32"};
  5657. #else
  5658. auto host = "nghttp2.org";
  5659. auto path = std::string{"/httpbin/range/32"};
  5660. #endif
  5661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5662. SSLClient cli(host);
  5663. #else
  5664. Client cli(host);
  5665. #endif
  5666. cli.set_default_headers({make_range_header({{1, 10}})});
  5667. cli.set_connection_timeout(5);
  5668. {
  5669. auto res = cli.Get(path);
  5670. ASSERT_TRUE(res);
  5671. EXPECT_EQ("bcdefghijk", res->body);
  5672. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5673. }
  5674. {
  5675. auto res = cli.Get(path);
  5676. ASSERT_TRUE(res);
  5677. EXPECT_EQ("bcdefghijk", res->body);
  5678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5679. }
  5680. }
  5681. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5682. Server svr;
  5683. svr.set_default_headers({{"Hello", "World"}});
  5684. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5685. res.set_content("ok", "text/plain");
  5686. });
  5687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5688. auto se = detail::scope_exit([&] {
  5689. svr.stop();
  5690. listen_thread.join();
  5691. ASSERT_FALSE(svr.is_running());
  5692. });
  5693. svr.wait_until_ready();
  5694. Client cli("localhost", PORT);
  5695. auto res = cli.Get("/");
  5696. ASSERT_TRUE(res);
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. EXPECT_EQ("ok", res->body);
  5699. EXPECT_EQ("World", res->get_header_value("Hello"));
  5700. }
  5701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5702. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5704. ASSERT_TRUE(svr.is_valid());
  5705. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5706. std::this_thread::sleep_for(std::chrono::seconds(2));
  5707. res.set_content("a", "text/plain");
  5708. });
  5709. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5710. res.set_content("b", "text/plain");
  5711. });
  5712. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5713. auto se = detail::scope_exit([&] {
  5714. svr.stop();
  5715. listen_thread.join();
  5716. ASSERT_FALSE(svr.is_running());
  5717. });
  5718. svr.wait_until_ready();
  5719. SSLClient cli("localhost", PORT);
  5720. cli.enable_server_certificate_verification(false);
  5721. cli.set_keep_alive(true);
  5722. cli.set_read_timeout(std::chrono::seconds(1));
  5723. auto resa = cli.Get("/a");
  5724. ASSERT_TRUE(!resa);
  5725. EXPECT_EQ(Error::Read, resa.error());
  5726. auto resb = cli.Get("/b");
  5727. ASSERT_TRUE(resb);
  5728. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5729. EXPECT_EQ("b", resb->body);
  5730. }
  5731. #endif
  5732. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5733. protected:
  5734. ServerTestWithAI_PASSIVE()
  5735. : cli_(HOST, PORT)
  5736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5737. ,
  5738. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5739. #endif
  5740. {
  5741. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5742. cli_.enable_server_certificate_verification(false);
  5743. #endif
  5744. }
  5745. virtual void SetUp() {
  5746. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5747. res.set_content("Hello World!", "text/plain");
  5748. });
  5749. t_ = thread(
  5750. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5751. svr_.wait_until_ready();
  5752. }
  5753. virtual void TearDown() {
  5754. svr_.stop();
  5755. t_.join();
  5756. }
  5757. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5758. SSLClient cli_;
  5759. SSLServer svr_;
  5760. #else
  5761. Client cli_;
  5762. Server svr_;
  5763. #endif
  5764. thread t_;
  5765. };
  5766. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5767. auto res = cli_.Get("/hi");
  5768. ASSERT_TRUE(res);
  5769. EXPECT_EQ(StatusCode::OK_200, res->status);
  5770. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5771. EXPECT_EQ("Hello World!", res->body);
  5772. }
  5773. class ServerUpDownTest : public ::testing::Test {
  5774. protected:
  5775. ServerUpDownTest() : cli_(HOST, PORT) {}
  5776. virtual void SetUp() {
  5777. t_ = thread([&]() {
  5778. svr_.bind_to_any_port(HOST);
  5779. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5780. ASSERT_TRUE(svr_.listen_after_bind());
  5781. });
  5782. svr_.wait_until_ready();
  5783. }
  5784. virtual void TearDown() {
  5785. svr_.stop();
  5786. t_.join();
  5787. }
  5788. Client cli_;
  5789. Server svr_;
  5790. thread t_;
  5791. };
  5792. TEST_F(ServerUpDownTest, QuickStartStop) {
  5793. // Should not crash, especially when run with
  5794. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5795. }
  5796. class PayloadMaxLengthTest : public ::testing::Test {
  5797. protected:
  5798. PayloadMaxLengthTest()
  5799. : cli_(HOST, PORT)
  5800. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5801. ,
  5802. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5803. #endif
  5804. {
  5805. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5806. cli_.enable_server_certificate_verification(false);
  5807. #endif
  5808. }
  5809. virtual void SetUp() {
  5810. svr_.set_payload_max_length(8);
  5811. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5812. res.set_content("test", "text/plain");
  5813. });
  5814. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5815. svr_.wait_until_ready();
  5816. }
  5817. virtual void TearDown() {
  5818. svr_.stop();
  5819. t_.join();
  5820. }
  5821. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5822. SSLClient cli_;
  5823. SSLServer svr_;
  5824. #else
  5825. Client cli_;
  5826. Server svr_;
  5827. #endif
  5828. thread t_;
  5829. };
  5830. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5831. auto res = cli_.Post("/test", "123456789", "text/plain");
  5832. ASSERT_TRUE(res);
  5833. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5834. res = cli_.Post("/test", "12345678", "text/plain");
  5835. ASSERT_TRUE(res);
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST(HostAndPortPropertiesTest, NoSSL) {
  5839. httplib::Client cli("www.google.com", 1234);
  5840. ASSERT_EQ("www.google.com", cli.host());
  5841. ASSERT_EQ(1234, cli.port());
  5842. }
  5843. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5844. httplib::Client cli("www.google.com:1234");
  5845. ASSERT_EQ("www.google.com", cli.host());
  5846. ASSERT_EQ(1234, cli.port());
  5847. }
  5848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5849. TEST(HostAndPortPropertiesTest, SSL) {
  5850. httplib::SSLClient cli("www.google.com");
  5851. ASSERT_EQ("www.google.com", cli.host());
  5852. ASSERT_EQ(443, cli.port());
  5853. }
  5854. #endif
  5855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5856. TEST(SSLClientTest, UpdateCAStore) {
  5857. httplib::SSLClient httplib_client("www.google.com");
  5858. auto ca_store_1 = X509_STORE_new();
  5859. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5860. nullptr);
  5861. httplib_client.set_ca_cert_store(ca_store_1);
  5862. auto ca_store_2 = X509_STORE_new();
  5863. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5864. nullptr);
  5865. httplib_client.set_ca_cert_store(ca_store_2);
  5866. }
  5867. TEST(SSLClientTest, ServerNameIndication_Online) {
  5868. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5869. auto host = "httpbin.org";
  5870. auto path = std::string{"/get"};
  5871. #else
  5872. auto host = "nghttp2.org";
  5873. auto path = std::string{"/httpbin/get"};
  5874. #endif
  5875. SSLClient cli(host, 443);
  5876. auto res = cli.Get(path);
  5877. ASSERT_TRUE(res);
  5878. ASSERT_EQ(StatusCode::OK_200, res->status);
  5879. }
  5880. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5881. Client cli("https://google.com");
  5882. auto res = cli.Get("/");
  5883. ASSERT_TRUE(res);
  5884. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5885. }
  5886. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5887. SSLClient cli("google.com");
  5888. cli.enable_server_certificate_verification(true);
  5889. cli.set_ca_cert_path("hello");
  5890. auto res = cli.Get("/");
  5891. ASSERT_TRUE(!res);
  5892. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5893. }
  5894. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5895. SSLClient cli("google.com");
  5896. cli.set_ca_cert_path(CA_CERT_FILE);
  5897. auto res = cli.Get("/");
  5898. ASSERT_TRUE(res);
  5899. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5900. }
  5901. TEST(SSLClientTest, ServerCertificateVerification4) {
  5902. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5903. ASSERT_TRUE(svr.is_valid());
  5904. svr.Get("/test", [&](const Request &, Response &res) {
  5905. res.set_content("test", "text/plain");
  5906. svr.stop();
  5907. ASSERT_TRUE(true);
  5908. });
  5909. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5910. auto se = detail::scope_exit([&] {
  5911. t.join();
  5912. ASSERT_FALSE(svr.is_running());
  5913. });
  5914. svr.wait_until_ready();
  5915. SSLClient cli("127.0.0.1", PORT);
  5916. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5917. cli.enable_server_certificate_verification(true);
  5918. cli.set_connection_timeout(30);
  5919. auto res = cli.Get("/test");
  5920. ASSERT_TRUE(res);
  5921. ASSERT_EQ(StatusCode::OK_200, res->status);
  5922. }
  5923. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5924. std::string cert;
  5925. read_file(CA_CERT_FILE, cert);
  5926. SSLClient cli("google.com");
  5927. cli.load_ca_cert_store(cert.data(), cert.size());
  5928. const auto res = cli.Get("/");
  5929. ASSERT_TRUE(res);
  5930. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5931. }
  5932. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5933. // clang-format off
  5934. static constexpr char cert[] =
  5935. "GlobalSign Root CA\n"
  5936. "==================\n"
  5937. "-----BEGIN CERTIFICATE-----\n"
  5938. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5939. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5940. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5941. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5942. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5943. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5944. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5945. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5946. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5947. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5948. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5949. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5950. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5951. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5952. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5953. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5954. "-----END CERTIFICATE-----\n";
  5955. // clang-format on
  5956. SSLClient cli("google.com");
  5957. cli.load_ca_cert_store(cert, sizeof(cert));
  5958. const auto res = cli.Get("/");
  5959. ASSERT_TRUE(res);
  5960. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5961. }
  5962. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5963. SSLClient cli("www.youtube.com");
  5964. cli.set_ca_cert_path(CA_CERT_FILE);
  5965. cli.enable_server_certificate_verification(true);
  5966. cli.set_follow_location(true);
  5967. auto res = cli.Get("/");
  5968. ASSERT_TRUE(res);
  5969. ASSERT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST(SSLClientTest, Issue2004_Online) {
  5972. Client client("https://google.com");
  5973. client.set_follow_location(true);
  5974. auto res = client.Get("/");
  5975. ASSERT_TRUE(res);
  5976. ASSERT_EQ(StatusCode::OK_200, res->status);
  5977. auto body = res->body;
  5978. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5979. }
  5980. #if 0
  5981. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5982. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5983. ASSERT_TRUE(cli != nullptr);
  5984. cli->set_address_family(AF_INET6);
  5985. cli->set_interface("en0");
  5986. auto res = cli->Get("/get");
  5987. ASSERT_TRUE(res);
  5988. ASSERT_EQ(StatusCode::OK_200, res->status);
  5989. }
  5990. #endif
  5991. void ClientCertPresent(
  5992. const std::string &client_cert_file,
  5993. const std::string &client_private_key_file,
  5994. const std::string &client_encrypted_private_key_pass = std::string()) {
  5995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5996. CLIENT_CA_CERT_DIR);
  5997. ASSERT_TRUE(svr.is_valid());
  5998. svr.Get("/test", [&](const Request &req, Response &res) {
  5999. res.set_content("test", "text/plain");
  6000. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6001. ASSERT_TRUE(peer_cert != nullptr);
  6002. auto subject_name = X509_get_subject_name(peer_cert);
  6003. ASSERT_TRUE(subject_name != nullptr);
  6004. std::string common_name;
  6005. {
  6006. char name[BUFSIZ];
  6007. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6008. name, sizeof(name));
  6009. common_name.assign(name, static_cast<size_t>(name_len));
  6010. }
  6011. EXPECT_EQ("Common Name", common_name);
  6012. X509_free(peer_cert);
  6013. });
  6014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6015. auto se = detail::scope_exit([&] {
  6016. svr.stop();
  6017. t.join();
  6018. ASSERT_FALSE(svr.is_running());
  6019. });
  6020. svr.wait_until_ready();
  6021. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6022. client_encrypted_private_key_pass);
  6023. cli.enable_server_certificate_verification(false);
  6024. cli.set_connection_timeout(30);
  6025. auto res = cli.Get("/test");
  6026. ASSERT_TRUE(res);
  6027. ASSERT_EQ(StatusCode::OK_200, res->status);
  6028. }
  6029. TEST(SSLClientServerTest, ClientCertPresent) {
  6030. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6031. }
  6032. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6033. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6034. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6035. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6036. }
  6037. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6038. void MemoryClientCertPresent(
  6039. const std::string &client_cert_file,
  6040. const std::string &client_private_key_file,
  6041. const std::string &client_encrypted_private_key_pass = std::string()) {
  6042. auto f = fopen(SERVER_CERT_FILE, "r+");
  6043. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6044. fclose(f);
  6045. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6046. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6047. fclose(f);
  6048. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6049. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6050. auto client_ca_cert_store = X509_STORE_new();
  6051. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6052. X509_free(client_cert);
  6053. fclose(f);
  6054. f = fopen(client_cert_file.c_str(), "r+");
  6055. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6056. fclose(f);
  6057. f = fopen(client_private_key_file.c_str(), "r+");
  6058. auto client_private_key = PEM_read_PrivateKey(
  6059. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6060. fclose(f);
  6061. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6062. ASSERT_TRUE(svr.is_valid());
  6063. svr.Get("/test", [&](const Request &req, Response &res) {
  6064. res.set_content("test", "text/plain");
  6065. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6066. ASSERT_TRUE(peer_cert != nullptr);
  6067. auto subject_name = X509_get_subject_name(peer_cert);
  6068. ASSERT_TRUE(subject_name != nullptr);
  6069. std::string common_name;
  6070. {
  6071. char name[BUFSIZ];
  6072. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6073. name, sizeof(name));
  6074. common_name.assign(name, static_cast<size_t>(name_len));
  6075. }
  6076. EXPECT_EQ("Common Name", common_name);
  6077. X509_free(peer_cert);
  6078. });
  6079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6080. auto se = detail::scope_exit([&] {
  6081. svr.stop();
  6082. t.join();
  6083. ASSERT_FALSE(svr.is_running());
  6084. });
  6085. svr.wait_until_ready();
  6086. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6087. client_encrypted_private_key_pass);
  6088. cli.enable_server_certificate_verification(false);
  6089. cli.set_connection_timeout(30);
  6090. auto res = cli.Get("/test");
  6091. ASSERT_TRUE(res);
  6092. ASSERT_EQ(StatusCode::OK_200, res->status);
  6093. X509_free(server_cert);
  6094. EVP_PKEY_free(server_private_key);
  6095. X509_free(client_cert);
  6096. EVP_PKEY_free(client_private_key);
  6097. }
  6098. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6099. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6100. }
  6101. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6102. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6103. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6104. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6105. }
  6106. #endif
  6107. TEST(SSLClientServerTest, ClientCertMissing) {
  6108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6109. CLIENT_CA_CERT_DIR);
  6110. ASSERT_TRUE(svr.is_valid());
  6111. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6112. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6113. auto se = detail::scope_exit([&] {
  6114. svr.stop();
  6115. t.join();
  6116. ASSERT_FALSE(svr.is_running());
  6117. });
  6118. svr.wait_until_ready();
  6119. SSLClient cli(HOST, PORT);
  6120. auto res = cli.Get("/test");
  6121. cli.set_connection_timeout(30);
  6122. ASSERT_TRUE(!res);
  6123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6124. }
  6125. TEST(SSLClientServerTest, TrustDirOptional) {
  6126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6127. ASSERT_TRUE(svr.is_valid());
  6128. svr.Get("/test", [&](const Request &, Response &res) {
  6129. res.set_content("test", "text/plain");
  6130. });
  6131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6132. auto se = detail::scope_exit([&] {
  6133. svr.stop();
  6134. t.join();
  6135. ASSERT_FALSE(svr.is_running());
  6136. });
  6137. svr.wait_until_ready();
  6138. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6139. cli.enable_server_certificate_verification(false);
  6140. cli.set_connection_timeout(30);
  6141. auto res = cli.Get("/test");
  6142. ASSERT_TRUE(res);
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. }
  6145. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6146. class NoListenSSLServer : public SSLServer {
  6147. public:
  6148. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6149. const char *client_ca_cert_file_path,
  6150. const char *client_ca_cert_dir_path = nullptr)
  6151. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6152. client_ca_cert_dir_path),
  6153. stop_(false) {}
  6154. std::atomic_bool stop_;
  6155. private:
  6156. bool process_and_close_socket(socket_t /*sock*/) override {
  6157. // Don't create SSL context
  6158. while (!stop_.load()) {
  6159. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6160. }
  6161. return true;
  6162. }
  6163. };
  6164. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6165. CLIENT_CA_CERT_FILE);
  6166. ASSERT_TRUE(svr.is_valid());
  6167. svr.Get("/test", [&](const Request &, Response &res) {
  6168. res.set_content("test", "text/plain");
  6169. });
  6170. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6171. auto se = detail::scope_exit([&] {
  6172. svr.stop_ = true;
  6173. svr.stop();
  6174. t.join();
  6175. ASSERT_FALSE(svr.is_running());
  6176. });
  6177. svr.wait_until_ready();
  6178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6179. cli.enable_server_certificate_verification(false);
  6180. cli.set_connection_timeout(1);
  6181. auto res = cli.Get("/test");
  6182. ASSERT_TRUE(!res);
  6183. EXPECT_EQ(Error::SSLConnection, res.error());
  6184. }
  6185. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6186. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6187. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6188. SSL_CTX_set_options(&ssl_ctx,
  6189. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6190. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6191. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6192. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6193. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6194. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6195. "ECDHE-DSS-AES128-SHA256:"
  6196. "ECDHE-RSA-AES256-SHA256:"
  6197. "ECDHE-DSS-AES256-SHA256:";
  6198. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6199. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6200. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6201. SSL_FILETYPE_PEM) != 1) {
  6202. return false;
  6203. }
  6204. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6205. CLIENT_CA_CERT_DIR);
  6206. SSL_CTX_set_verify(
  6207. &ssl_ctx,
  6208. SSL_VERIFY_PEER |
  6209. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6210. nullptr);
  6211. return true;
  6212. };
  6213. SSLServer svr(setup_ssl_ctx_callback);
  6214. ASSERT_TRUE(svr.is_valid());
  6215. svr.Get("/test", [&](const Request &req, Response &res) {
  6216. res.set_content("test", "text/plain");
  6217. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6218. ASSERT_TRUE(peer_cert != nullptr);
  6219. auto subject_name = X509_get_subject_name(peer_cert);
  6220. ASSERT_TRUE(subject_name != nullptr);
  6221. std::string common_name;
  6222. {
  6223. char name[BUFSIZ];
  6224. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6225. name, sizeof(name));
  6226. common_name.assign(name, static_cast<size_t>(name_len));
  6227. }
  6228. EXPECT_EQ("Common Name", common_name);
  6229. X509_free(peer_cert);
  6230. });
  6231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6232. auto se = detail::scope_exit([&] {
  6233. svr.stop();
  6234. t.join();
  6235. ASSERT_FALSE(svr.is_running());
  6236. });
  6237. svr.wait_until_ready();
  6238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6239. cli.enable_server_certificate_verification(false);
  6240. cli.set_connection_timeout(30);
  6241. auto res = cli.Get("/test");
  6242. ASSERT_TRUE(res);
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. }
  6245. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6246. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6247. // prepare large data
  6248. std::random_device seed_gen;
  6249. std::mt19937 random(seed_gen());
  6250. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6251. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6252. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6253. // server
  6254. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6255. ASSERT_TRUE(svr.is_valid());
  6256. svr.Post("/binary", [&](const Request &req, Response &res) {
  6257. EXPECT_EQ(large_size_byte, req.body.size());
  6258. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6259. res.set_content(req.body, "application/octet-stream");
  6260. });
  6261. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6262. auto se = detail::scope_exit([&] {
  6263. svr.stop();
  6264. listen_thread.join();
  6265. ASSERT_FALSE(svr.is_running());
  6266. });
  6267. svr.wait_until_ready();
  6268. // client POST
  6269. SSLClient cli("localhost", PORT);
  6270. cli.enable_server_certificate_verification(false);
  6271. cli.set_read_timeout(std::chrono::seconds(100));
  6272. cli.set_write_timeout(std::chrono::seconds(100));
  6273. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6274. large_size_byte, "application/octet-stream");
  6275. // compare
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ(large_size_byte, res->body.size());
  6278. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6279. }
  6280. #endif
  6281. #ifdef _WIN32
  6282. TEST(CleanupTest, WSACleanup) {
  6283. int ret = WSACleanup();
  6284. ASSERT_EQ(0, ret);
  6285. }
  6286. #endif
  6287. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6288. TEST(NoSSLSupport, SimpleInterface) {
  6289. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6290. }
  6291. #endif
  6292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6293. TEST(InvalidScheme, SimpleInterface) {
  6294. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6295. }
  6296. #endif
  6297. TEST(NoScheme, SimpleInterface) {
  6298. Client cli("yahoo.com:80");
  6299. ASSERT_TRUE(cli.is_valid());
  6300. }
  6301. TEST(SendAPI, SimpleInterface_Online) {
  6302. Client cli("http://yahoo.com");
  6303. Request req;
  6304. req.method = "GET";
  6305. req.path = "/";
  6306. auto res = cli.send(req);
  6307. ASSERT_TRUE(res);
  6308. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6309. }
  6310. TEST(SendAPI, WithParamsInRequest) {
  6311. Server svr;
  6312. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6313. EXPECT_TRUE(req.has_param("test"));
  6314. EXPECT_EQ("test_value", req.get_param_value("test"));
  6315. });
  6316. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. t.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. Client cli(HOST, PORT);
  6324. {
  6325. Request req;
  6326. req.method = "GET";
  6327. req.path = "/";
  6328. req.params.emplace("test", "test_value");
  6329. auto res = cli.send(req);
  6330. ASSERT_TRUE(res);
  6331. }
  6332. {
  6333. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6334. ASSERT_TRUE(res);
  6335. }
  6336. }
  6337. TEST(ClientImplMethods, GetSocketTest) {
  6338. httplib::Server svr;
  6339. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6340. res.status = StatusCode::OK_200;
  6341. });
  6342. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6343. auto se = detail::scope_exit([&] {
  6344. svr.stop();
  6345. thread.join();
  6346. ASSERT_FALSE(svr.is_running());
  6347. });
  6348. svr.wait_until_ready();
  6349. {
  6350. httplib::Client cli("http://127.0.0.1:3333");
  6351. cli.set_keep_alive(true);
  6352. // Use the behavior of cpp-httplib of opening the connection
  6353. // only when the first request happens. If that changes,
  6354. // this test would be obsolete.
  6355. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6356. // This also implicitly tests the server. But other tests would fail much
  6357. // earlier than this one to be considered.
  6358. auto res = cli.Get("/");
  6359. ASSERT_TRUE(res);
  6360. EXPECT_EQ(StatusCode::OK_200, res->status);
  6361. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6362. }
  6363. }
  6364. // Disabled due to out-of-memory problem on GitHub Actions
  6365. #ifdef _WIN64
  6366. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6367. // allocate content size larger than 2GB in memory
  6368. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6369. char *content = (char *)malloc(content_size);
  6370. ASSERT_TRUE(content);
  6371. Server svr;
  6372. svr.Get("/foo",
  6373. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6374. res.set_content(content, content_size, "application/octet-stream");
  6375. });
  6376. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. if (content) free(content);
  6381. ASSERT_FALSE(svr.is_running());
  6382. });
  6383. svr.wait_until_ready();
  6384. Client cli(HOST, PORT);
  6385. auto res = cli.Get("/foo");
  6386. ASSERT_TRUE(res);
  6387. EXPECT_EQ(StatusCode::OK_200, res->status);
  6388. EXPECT_EQ(content_size, res->body.length());
  6389. }
  6390. #endif
  6391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6392. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6393. Client cli("http://yahoo.com");
  6394. auto res = cli.Get("/");
  6395. ASSERT_TRUE(res);
  6396. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6397. cli.set_follow_location(true);
  6398. res = cli.Get("/");
  6399. ASSERT_TRUE(res);
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6402. }
  6403. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6404. Client cli("https://yahoo.com");
  6405. auto res = cli.Get("/");
  6406. ASSERT_TRUE(res);
  6407. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6408. cli.set_follow_location(true);
  6409. res = cli.Get("/");
  6410. ASSERT_TRUE(res);
  6411. EXPECT_EQ(StatusCode::OK_200, res->status);
  6412. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6413. }
  6414. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6415. Client cli("https://yahoo.com");
  6416. auto res = cli.Get("/");
  6417. ASSERT_TRUE(res);
  6418. ASSERT_FALSE(!res);
  6419. ASSERT_TRUE(res);
  6420. ASSERT_FALSE(res == nullptr);
  6421. ASSERT_TRUE(res != nullptr);
  6422. EXPECT_EQ(Error::Success, res.error());
  6423. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6424. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6425. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6426. cli.set_follow_location(true);
  6427. res = cli.Get("/");
  6428. ASSERT_TRUE(res);
  6429. EXPECT_EQ(Error::Success, res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6431. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6432. EXPECT_EQ(StatusCode::OK_200, res->status);
  6433. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6434. }
  6435. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6436. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6437. Client cli("https://cdnjs.cloudflare.com");
  6438. auto res =
  6439. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ(287630U, res->body.size());
  6443. EXPECT_EQ("application/javascript; charset=utf-8",
  6444. res->get_header_value("Content-Type"));
  6445. }
  6446. #endif
  6447. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6448. #undef REDIR_HOST // Silence compiler warning
  6449. #define REDIR_HOST "https://httpbingo.org"
  6450. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6451. Client cli(REDIR_HOST);
  6452. cli.set_follow_location(true);
  6453. auto res =
  6454. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. }
  6458. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6459. Client cli(REDIR_HOST);
  6460. cli.set_follow_location(true);
  6461. Params params;
  6462. params.emplace("url", "http://example.com");
  6463. params.emplace("status_code", "302");
  6464. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6465. ASSERT_TRUE(res);
  6466. EXPECT_EQ(StatusCode::OK_200, res->status);
  6467. }
  6468. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6469. Client cli(REDIR_HOST);
  6470. cli.set_follow_location(true);
  6471. Params params;
  6472. params.emplace("url", "http://example.com");
  6473. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6474. ASSERT_TRUE(res);
  6475. EXPECT_EQ(StatusCode::OK_200, res->status);
  6476. }
  6477. TEST(HttpToHttpsRedirectTest, CertFile) {
  6478. Server svr;
  6479. ASSERT_TRUE(svr.is_valid());
  6480. svr.Get("/index", [&](const Request &, Response &res) {
  6481. res.set_redirect("https://127.0.0.1:1235/index");
  6482. svr.stop();
  6483. });
  6484. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6485. ASSERT_TRUE(ssl_svr.is_valid());
  6486. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6487. res.set_content("test", "text/plain");
  6488. ssl_svr.stop();
  6489. });
  6490. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6491. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6492. auto se = detail::scope_exit([&] {
  6493. t2.join();
  6494. t.join();
  6495. ASSERT_FALSE(svr.is_running());
  6496. });
  6497. svr.wait_until_ready();
  6498. ssl_svr.wait_until_ready();
  6499. Client cli("127.0.0.1", PORT);
  6500. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6501. cli.enable_server_certificate_verification(true);
  6502. cli.set_follow_location(true);
  6503. cli.set_connection_timeout(30);
  6504. auto res = cli.Get("/index");
  6505. ASSERT_TRUE(res);
  6506. ASSERT_EQ(StatusCode::OK_200, res->status);
  6507. }
  6508. TEST(MultipartFormDataTest, LargeData) {
  6509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6510. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6511. const ContentReader &content_reader) {
  6512. if (req.is_multipart_form_data()) {
  6513. MultipartFormDataItems files;
  6514. content_reader(
  6515. [&](const MultipartFormData &file) {
  6516. files.push_back(file);
  6517. return true;
  6518. },
  6519. [&](const char *data, size_t data_length) {
  6520. files.back().content.append(data, data_length);
  6521. return true;
  6522. });
  6523. EXPECT_TRUE(std::string(files[0].name) == "document");
  6524. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6525. EXPECT_TRUE(files[0].filename == "2MB_data");
  6526. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6527. EXPECT_TRUE(files[1].name == "hello");
  6528. EXPECT_TRUE(files[1].content == "world");
  6529. EXPECT_TRUE(files[1].filename == "");
  6530. EXPECT_TRUE(files[1].content_type == "");
  6531. } else {
  6532. std::string body;
  6533. content_reader([&](const char *data, size_t data_length) {
  6534. body.append(data, data_length);
  6535. return true;
  6536. });
  6537. }
  6538. });
  6539. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6540. auto se = detail::scope_exit([&] {
  6541. svr.stop();
  6542. t.join();
  6543. ASSERT_FALSE(svr.is_running());
  6544. });
  6545. svr.wait_until_ready();
  6546. {
  6547. std::string data(1024 * 1024 * 2, '.');
  6548. std::stringstream buffer;
  6549. buffer << data;
  6550. Client cli("https://localhost:8080");
  6551. cli.enable_server_certificate_verification(false);
  6552. MultipartFormDataItemsForClientInput items{
  6553. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6554. {"hello", "world", "", ""},
  6555. };
  6556. auto res = cli.Post("/post", items);
  6557. ASSERT_TRUE(res);
  6558. ASSERT_EQ(StatusCode::OK_200, res->status);
  6559. }
  6560. }
  6561. TEST(MultipartFormDataTest, DataProviderItems) {
  6562. std::random_device seed_gen;
  6563. std::mt19937 random(seed_gen());
  6564. std::string rand1;
  6565. rand1.resize(1000);
  6566. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6567. std::string rand2;
  6568. rand2.resize(3000);
  6569. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6571. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6572. const ContentReader &content_reader) {
  6573. ASSERT_FALSE(req.is_multipart_form_data());
  6574. std::string body;
  6575. content_reader([&](const char *data, size_t data_length) {
  6576. body.append(data, data_length);
  6577. return true;
  6578. });
  6579. EXPECT_EQ(body, "");
  6580. });
  6581. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6582. const ContentReader &content_reader) {
  6583. ASSERT_TRUE(req.is_multipart_form_data());
  6584. MultipartFormDataItems files;
  6585. content_reader(
  6586. [&](const MultipartFormData &file) {
  6587. files.push_back(file);
  6588. return true;
  6589. },
  6590. [&](const char *data, size_t data_length) {
  6591. files.back().content.append(data, data_length);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(files.size() == 2);
  6595. EXPECT_EQ(std::string(files[0].name), "name1");
  6596. EXPECT_EQ(files[0].content, "Testing123");
  6597. EXPECT_EQ(files[0].filename, "filename1");
  6598. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6599. EXPECT_EQ(files[1].name, "name2");
  6600. EXPECT_EQ(files[1].content, "Testing456");
  6601. EXPECT_EQ(files[1].filename, "");
  6602. EXPECT_EQ(files[1].content_type, "");
  6603. });
  6604. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6605. const ContentReader &content_reader) {
  6606. ASSERT_TRUE(req.is_multipart_form_data());
  6607. MultipartFormDataItems files;
  6608. content_reader(
  6609. [&](const MultipartFormData &file) {
  6610. files.push_back(file);
  6611. return true;
  6612. },
  6613. [&](const char *data, size_t data_length) {
  6614. files.back().content.append(data, data_length);
  6615. return true;
  6616. });
  6617. ASSERT_TRUE(files.size() == 2);
  6618. EXPECT_EQ(files[0].name, "name3");
  6619. EXPECT_EQ(files[0].content, rand1);
  6620. EXPECT_EQ(files[0].filename, "filename3");
  6621. EXPECT_EQ(files[0].content_type, "");
  6622. EXPECT_EQ(files[1].name, "name4");
  6623. EXPECT_EQ(files[1].content, rand2);
  6624. EXPECT_EQ(files[1].filename, "filename4");
  6625. EXPECT_EQ(files[1].content_type, "");
  6626. });
  6627. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6628. const ContentReader &content_reader) {
  6629. ASSERT_TRUE(req.is_multipart_form_data());
  6630. MultipartFormDataItems files;
  6631. content_reader(
  6632. [&](const MultipartFormData &file) {
  6633. files.push_back(file);
  6634. return true;
  6635. },
  6636. [&](const char *data, size_t data_length) {
  6637. files.back().content.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(files.size() == 4);
  6641. EXPECT_EQ(std::string(files[0].name), "name1");
  6642. EXPECT_EQ(files[0].content, "Testing123");
  6643. EXPECT_EQ(files[0].filename, "filename1");
  6644. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6645. EXPECT_EQ(files[1].name, "name2");
  6646. EXPECT_EQ(files[1].content, "Testing456");
  6647. EXPECT_EQ(files[1].filename, "");
  6648. EXPECT_EQ(files[1].content_type, "");
  6649. EXPECT_EQ(files[2].name, "name3");
  6650. EXPECT_EQ(files[2].content, rand1);
  6651. EXPECT_EQ(files[2].filename, "filename3");
  6652. EXPECT_EQ(files[2].content_type, "");
  6653. EXPECT_EQ(files[3].name, "name4");
  6654. EXPECT_EQ(files[3].content, rand2);
  6655. EXPECT_EQ(files[3].filename, "filename4");
  6656. EXPECT_EQ(files[3].content_type, "");
  6657. });
  6658. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6659. auto se = detail::scope_exit([&] {
  6660. svr.stop();
  6661. t.join();
  6662. ASSERT_FALSE(svr.is_running());
  6663. });
  6664. svr.wait_until_ready();
  6665. {
  6666. Client cli("https://localhost:8080");
  6667. cli.enable_server_certificate_verification(false);
  6668. MultipartFormDataItemsForClientInput items{
  6669. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6670. {"name2", "Testing456", "", ""}, // not a file
  6671. };
  6672. {
  6673. auto res = cli.Post("/post-none", {}, {}, {});
  6674. ASSERT_TRUE(res);
  6675. ASSERT_EQ(StatusCode::OK_200, res->status);
  6676. }
  6677. MultipartFormDataProviderItems providers;
  6678. {
  6679. auto res =
  6680. cli.Post("/post-items", {}, items, providers); // empty providers
  6681. ASSERT_TRUE(res);
  6682. ASSERT_EQ(StatusCode::OK_200, res->status);
  6683. }
  6684. providers.push_back({"name3",
  6685. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6686. // test the offset is given correctly at each step
  6687. if (!offset)
  6688. sink.os.write(rand1.data(), 30);
  6689. else if (offset == 30)
  6690. sink.os.write(rand1.data() + 30, 300);
  6691. else if (offset == 330)
  6692. sink.os.write(rand1.data() + 330, 670);
  6693. else if (offset == rand1.size())
  6694. sink.done();
  6695. return true;
  6696. },
  6697. "filename3",
  6698. {}});
  6699. providers.push_back({"name4",
  6700. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6701. // test the offset is given correctly at each step
  6702. if (!offset)
  6703. sink.os.write(rand2.data(), 2000);
  6704. else if (offset == 2000)
  6705. sink.os.write(rand2.data() + 2000, 1);
  6706. else if (offset == 2001)
  6707. sink.os.write(rand2.data() + 2001, 999);
  6708. else if (offset == rand2.size())
  6709. sink.done();
  6710. return true;
  6711. },
  6712. "filename4",
  6713. {}});
  6714. {
  6715. auto res = cli.Post("/post-providers", {}, {}, providers);
  6716. ASSERT_TRUE(res);
  6717. ASSERT_EQ(StatusCode::OK_200, res->status);
  6718. }
  6719. {
  6720. auto res = cli.Post("/post-both", {}, items, providers);
  6721. ASSERT_TRUE(res);
  6722. ASSERT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. }
  6725. }
  6726. TEST(MultipartFormDataTest, BadHeader) {
  6727. Server svr;
  6728. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6729. res.set_content("ok", "text/plain");
  6730. });
  6731. thread t = thread([&] { svr.listen(HOST, PORT); });
  6732. auto se = detail::scope_exit([&] {
  6733. svr.stop();
  6734. t.join();
  6735. ASSERT_FALSE(svr.is_running());
  6736. });
  6737. svr.wait_until_ready();
  6738. const std::string body =
  6739. "This is the preamble. It is to be ignored, though it\r\n"
  6740. "is a handy place for composition agents to include an\r\n"
  6741. "explanatory note to non-MIME conformant readers.\r\n"
  6742. "\r\n"
  6743. "\r\n"
  6744. "--simple boundary\r\n"
  6745. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6746. ": BAD...\r\n"
  6747. "\r\n"
  6748. "value1\r\n"
  6749. "--simple boundary\r\n"
  6750. "Content-Disposition: form-data; name=\"field2\"; "
  6751. "filename=\"example.txt\"\r\n"
  6752. "\r\n"
  6753. "value2\r\n"
  6754. "--simple boundary--\r\n"
  6755. "This is the epilogue. It is also to be ignored.\r\n";
  6756. std::string content_type =
  6757. R"(multipart/form-data; boundary="simple boundary")";
  6758. Client cli(HOST, PORT);
  6759. auto res = cli.Post("/post", body, content_type.c_str());
  6760. ASSERT_TRUE(res);
  6761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6762. }
  6763. TEST(MultipartFormDataTest, WithPreamble) {
  6764. Server svr;
  6765. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6766. res.set_content("ok", "text/plain");
  6767. });
  6768. thread t = thread([&] { svr.listen(HOST, PORT); });
  6769. auto se = detail::scope_exit([&] {
  6770. svr.stop();
  6771. t.join();
  6772. ASSERT_FALSE(svr.is_running());
  6773. });
  6774. svr.wait_until_ready();
  6775. const std::string body =
  6776. "This is the preamble. It is to be ignored, though it\r\n"
  6777. "is a handy place for composition agents to include an\r\n"
  6778. "explanatory note to non-MIME conformant readers.\r\n"
  6779. "\r\n"
  6780. "\r\n"
  6781. "--simple boundary\r\n"
  6782. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6783. "\r\n"
  6784. "value1\r\n"
  6785. "--simple boundary\r\n"
  6786. "Content-Disposition: form-data; name=\"field2\"; "
  6787. "filename=\"example.txt\"\r\n"
  6788. "\r\n"
  6789. "value2\r\n"
  6790. "--simple boundary--\r\n"
  6791. "This is the epilogue. It is also to be ignored.\r\n";
  6792. std::string content_type =
  6793. R"(multipart/form-data; boundary="simple boundary")";
  6794. Client cli(HOST, PORT);
  6795. auto res = cli.Post("/post", body, content_type.c_str());
  6796. ASSERT_TRUE(res);
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. }
  6799. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6801. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6802. const ContentReader &content_reader) {
  6803. if (req.is_multipart_form_data()) {
  6804. MultipartFormDataItems files;
  6805. content_reader(
  6806. [&](const MultipartFormData &file) {
  6807. files.push_back(file);
  6808. return true;
  6809. },
  6810. [&](const char *data, size_t data_length) {
  6811. files.back().content.append(data, data_length);
  6812. return true;
  6813. });
  6814. EXPECT_TRUE(std::string(files[0].name) == "document");
  6815. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6816. EXPECT_TRUE(files[0].filename == "2MB_data");
  6817. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6818. EXPECT_TRUE(files[1].name == "hello");
  6819. EXPECT_TRUE(files[1].content == "world");
  6820. EXPECT_TRUE(files[1].filename == "");
  6821. EXPECT_TRUE(files[1].content_type == "");
  6822. } else {
  6823. std::string body;
  6824. content_reader([&](const char *data, size_t data_length) {
  6825. body.append(data, data_length);
  6826. return true;
  6827. });
  6828. }
  6829. });
  6830. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6831. auto se = detail::scope_exit([&] {
  6832. svr.stop();
  6833. t.join();
  6834. ASSERT_FALSE(svr.is_running());
  6835. });
  6836. svr.wait_until_ready();
  6837. {
  6838. std::string data(1024 * 1024 * 2, '.');
  6839. std::stringstream buffer;
  6840. buffer << data;
  6841. Client cli("https://localhost:8080");
  6842. cli.enable_server_certificate_verification(false);
  6843. MultipartFormDataItemsForClientInput items{
  6844. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6845. {"hello", "world", "", ""},
  6846. };
  6847. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6848. ASSERT_TRUE(res);
  6849. ASSERT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. }
  6852. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6853. std::string data(1024 * 1024 * 2, '&');
  6854. std::stringstream buffer;
  6855. buffer << data;
  6856. Client cli("https://localhost:8080");
  6857. MultipartFormDataItemsForClientInput items{
  6858. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6859. {"hello", "world", "", ""},
  6860. };
  6861. for (const char &c : " \t\r\n") {
  6862. auto res =
  6863. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6864. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6865. ASSERT_FALSE(res);
  6866. }
  6867. }
  6868. TEST(MultipartFormDataTest, PutFormData) {
  6869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6870. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6871. const ContentReader &content_reader) {
  6872. if (req.is_multipart_form_data()) {
  6873. MultipartFormDataItems files;
  6874. content_reader(
  6875. [&](const MultipartFormData &file) {
  6876. files.push_back(file);
  6877. return true;
  6878. },
  6879. [&](const char *data, size_t data_length) {
  6880. files.back().content.append(data, data_length);
  6881. return true;
  6882. });
  6883. EXPECT_TRUE(std::string(files[0].name) == "document");
  6884. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6885. EXPECT_TRUE(files[0].filename == "2MB_data");
  6886. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6887. EXPECT_TRUE(files[1].name == "hello");
  6888. EXPECT_TRUE(files[1].content == "world");
  6889. EXPECT_TRUE(files[1].filename == "");
  6890. EXPECT_TRUE(files[1].content_type == "");
  6891. } else {
  6892. std::string body;
  6893. content_reader([&](const char *data, size_t data_length) {
  6894. body.append(data, data_length);
  6895. return true;
  6896. });
  6897. }
  6898. });
  6899. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6900. auto se = detail::scope_exit([&] {
  6901. svr.stop();
  6902. t.join();
  6903. ASSERT_FALSE(svr.is_running());
  6904. });
  6905. svr.wait_until_ready();
  6906. {
  6907. std::string data(1024 * 1024 * 2, '&');
  6908. std::stringstream buffer;
  6909. buffer << data;
  6910. Client cli("https://localhost:8080");
  6911. cli.enable_server_certificate_verification(false);
  6912. MultipartFormDataItemsForClientInput items{
  6913. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6914. {"hello", "world", "", ""},
  6915. };
  6916. auto res = cli.Put("/put", items);
  6917. ASSERT_TRUE(res);
  6918. ASSERT_EQ(StatusCode::OK_200, res->status);
  6919. }
  6920. }
  6921. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6923. svr.Put("/put_customboundary",
  6924. [&](const Request &req, const Response & /*res*/,
  6925. const ContentReader &content_reader) {
  6926. if (req.is_multipart_form_data()) {
  6927. MultipartFormDataItems files;
  6928. content_reader(
  6929. [&](const MultipartFormData &file) {
  6930. files.push_back(file);
  6931. return true;
  6932. },
  6933. [&](const char *data, size_t data_length) {
  6934. files.back().content.append(data, data_length);
  6935. return true;
  6936. });
  6937. EXPECT_TRUE(std::string(files[0].name) == "document");
  6938. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6939. EXPECT_TRUE(files[0].filename == "2MB_data");
  6940. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6941. EXPECT_TRUE(files[1].name == "hello");
  6942. EXPECT_TRUE(files[1].content == "world");
  6943. EXPECT_TRUE(files[1].filename == "");
  6944. EXPECT_TRUE(files[1].content_type == "");
  6945. } else {
  6946. std::string body;
  6947. content_reader([&](const char *data, size_t data_length) {
  6948. body.append(data, data_length);
  6949. return true;
  6950. });
  6951. }
  6952. });
  6953. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6954. auto se = detail::scope_exit([&] {
  6955. svr.stop();
  6956. t.join();
  6957. ASSERT_FALSE(svr.is_running());
  6958. });
  6959. svr.wait_until_ready();
  6960. {
  6961. std::string data(1024 * 1024 * 2, '&');
  6962. std::stringstream buffer;
  6963. buffer << data;
  6964. Client cli("https://localhost:8080");
  6965. cli.enable_server_certificate_verification(false);
  6966. MultipartFormDataItemsForClientInput items{
  6967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6968. {"hello", "world", "", ""},
  6969. };
  6970. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6971. ASSERT_TRUE(res);
  6972. ASSERT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. }
  6975. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6976. std::string data(1024 * 1024 * 2, '&');
  6977. std::stringstream buffer;
  6978. buffer << data;
  6979. Client cli("https://localhost:8080");
  6980. cli.enable_server_certificate_verification(false);
  6981. MultipartFormDataItemsForClientInput items{
  6982. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6983. {"hello", "world", "", ""},
  6984. };
  6985. for (const char &c : " \t\r\n") {
  6986. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6988. ASSERT_FALSE(res);
  6989. }
  6990. }
  6991. TEST(MultipartFormDataTest, AlternateFilename) {
  6992. auto handled = false;
  6993. Server svr;
  6994. svr.Post("/test", [&](const Request &req, Response &res) {
  6995. ASSERT_EQ(3u, req.files.size());
  6996. auto it = req.files.begin();
  6997. ASSERT_EQ("file1", it->second.name);
  6998. ASSERT_EQ("A.txt", it->second.filename);
  6999. ASSERT_EQ("text/plain", it->second.content_type);
  7000. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7001. ++it;
  7002. ASSERT_EQ("file2", it->second.name);
  7003. ASSERT_EQ("a.html", it->second.filename);
  7004. ASSERT_EQ("text/html", it->second.content_type);
  7005. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7006. it->second.content);
  7007. ++it;
  7008. ASSERT_EQ("text", it->second.name);
  7009. ASSERT_EQ("", it->second.filename);
  7010. ASSERT_EQ("", it->second.content_type);
  7011. ASSERT_EQ("text default", it->second.content);
  7012. res.set_content("ok", "text/plain");
  7013. handled = true;
  7014. });
  7015. thread t = thread([&] { svr.listen(HOST, PORT); });
  7016. auto se = detail::scope_exit([&] {
  7017. svr.stop();
  7018. t.join();
  7019. ASSERT_FALSE(svr.is_running());
  7020. ASSERT_TRUE(handled);
  7021. });
  7022. svr.wait_until_ready();
  7023. auto req = "POST /test HTTP/1.1\r\n"
  7024. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7025. "Content-Length: 399\r\n"
  7026. "\r\n"
  7027. "----------\r\n"
  7028. "Content-Disposition: form-data; name=\"text\"\r\n"
  7029. "\r\n"
  7030. "text default\r\n"
  7031. "----------\r\n"
  7032. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7033. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7034. "Content-Type: text/plain\r\n"
  7035. "\r\n"
  7036. "Content of a.txt.\r\n"
  7037. "\r\n"
  7038. "----------\r\n"
  7039. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7040. "\"a.html\"\r\n"
  7041. "Content-Type: text/html\r\n"
  7042. "\r\n"
  7043. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7044. "\r\n"
  7045. "------------\r\n";
  7046. ASSERT_TRUE(send_request(1, req));
  7047. }
  7048. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7049. auto handled = false;
  7050. Server svr;
  7051. svr.Post("/test", [&](const Request &req, Response &) {
  7052. ASSERT_EQ(2u, req.files.size());
  7053. auto it = req.files.begin();
  7054. ASSERT_EQ("text1", it->second.name);
  7055. ASSERT_EQ("text1", it->second.content);
  7056. ++it;
  7057. ASSERT_EQ("text2", it->second.name);
  7058. ASSERT_EQ("text2", it->second.content);
  7059. handled = true;
  7060. });
  7061. thread t = thread([&] { svr.listen(HOST, PORT); });
  7062. auto se = detail::scope_exit([&] {
  7063. svr.stop();
  7064. t.join();
  7065. ASSERT_FALSE(svr.is_running());
  7066. ASSERT_TRUE(handled);
  7067. });
  7068. svr.wait_until_ready();
  7069. auto req = "POST /test HTTP/1.1\r\n"
  7070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7071. "Content-Length: 146\r\n"
  7072. "\r\n----------\r\n"
  7073. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7074. "\r\n"
  7075. "text1"
  7076. "\r\n----------\r\n"
  7077. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7078. "\r\n"
  7079. "text2"
  7080. "\r\n------------";
  7081. std::string response;
  7082. ASSERT_TRUE(send_request(1, req, &response));
  7083. ASSERT_EQ("200", response.substr(9, 3));
  7084. }
  7085. TEST(MultipartFormDataTest, ContentLength) {
  7086. auto handled = false;
  7087. Server svr;
  7088. svr.Post("/test", [&](const Request &req, Response &) {
  7089. ASSERT_EQ(2u, req.files.size());
  7090. auto it = req.files.begin();
  7091. ASSERT_EQ("text1", it->second.name);
  7092. ASSERT_EQ("text1", it->second.content);
  7093. ++it;
  7094. ASSERT_EQ("text2", it->second.name);
  7095. ASSERT_EQ("text2", it->second.content);
  7096. handled = true;
  7097. });
  7098. thread t = thread([&] { svr.listen(HOST, PORT); });
  7099. auto se = detail::scope_exit([&] {
  7100. svr.stop();
  7101. t.join();
  7102. ASSERT_FALSE(svr.is_running());
  7103. ASSERT_TRUE(handled);
  7104. });
  7105. svr.wait_until_ready();
  7106. auto req = "POST /test HTTP/1.1\r\n"
  7107. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7108. "Content-Length: 167\r\n"
  7109. "\r\n----------\r\n"
  7110. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7111. "Content-Length: 5\r\n"
  7112. "\r\n"
  7113. "text1"
  7114. "\r\n----------\r\n"
  7115. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7116. "\r\n"
  7117. "text2"
  7118. "\r\n------------\r\n";
  7119. std::string response;
  7120. ASSERT_TRUE(send_request(1, req, &response));
  7121. ASSERT_EQ("200", response.substr(9, 3));
  7122. }
  7123. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7124. auto handled = false;
  7125. Server svr;
  7126. svr.Post("/test", [&](const Request &req, Response &) {
  7127. ASSERT_EQ(2u, req.files.size());
  7128. auto it = req.files.begin();
  7129. ASSERT_EQ("text1", it->second.name);
  7130. ASSERT_EQ("text1", it->second.content);
  7131. ASSERT_EQ(1, it->second.headers.count("Content-Length"));
  7132. auto content_length = it->second.headers.find("CONTENT-length");
  7133. ASSERT_EQ("5", content_length->second);
  7134. ASSERT_EQ(3, it->second.headers.size());
  7135. ++it;
  7136. ASSERT_EQ("text2", it->second.name);
  7137. ASSERT_EQ("text2", it->second.content);
  7138. auto &headers = it->second.headers;
  7139. ASSERT_EQ(3, headers.size());
  7140. auto custom_header = headers.find("x-whatever");
  7141. ASSERT_TRUE(custom_header != headers.end());
  7142. ASSERT_NE("customvalue", custom_header->second);
  7143. ASSERT_EQ("CustomValue", custom_header->second);
  7144. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7145. handled = true;
  7146. });
  7147. thread t = thread([&] { svr.listen(HOST, PORT); });
  7148. auto se = detail::scope_exit([&] {
  7149. svr.stop();
  7150. t.join();
  7151. ASSERT_FALSE(svr.is_running());
  7152. ASSERT_TRUE(handled);
  7153. });
  7154. svr.wait_until_ready();
  7155. auto req = "POST /test HTTP/1.1\r\n"
  7156. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7157. "Content-Length: 232\r\n"
  7158. "\r\n----------\r\n"
  7159. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7160. "Content-Length: 5\r\n"
  7161. "X-Test: 1\r\n"
  7162. "\r\n"
  7163. "text1"
  7164. "\r\n----------\r\n"
  7165. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7166. "Content-Type: text/plain\r\n"
  7167. "X-Whatever: CustomValue\r\n"
  7168. "\r\n"
  7169. "text2"
  7170. "\r\n------------\r\n"
  7171. "That should be disregarded. Not even read";
  7172. std::string response;
  7173. ASSERT_TRUE(send_request(1, req, &response));
  7174. ASSERT_EQ("200", response.substr(9, 3));
  7175. }
  7176. #endif
  7177. TEST(MultipartFormDataTest, LargeHeader) {
  7178. auto handled = false;
  7179. Server svr;
  7180. svr.Post("/test", [&](const Request &req, Response &) {
  7181. ASSERT_EQ(1u, req.files.size());
  7182. auto it = req.files.begin();
  7183. ASSERT_EQ("name1", it->second.name);
  7184. ASSERT_EQ("text1", it->second.content);
  7185. handled = true;
  7186. });
  7187. thread t = thread([&] { svr.listen(HOST, PORT); });
  7188. auto se = detail::scope_exit([&] {
  7189. svr.stop();
  7190. t.join();
  7191. ASSERT_FALSE(svr.is_running());
  7192. ASSERT_TRUE(handled);
  7193. });
  7194. svr.wait_until_ready();
  7195. auto boundary = std::string("cpp-httplib-multipart-data");
  7196. std::string content = "--" + boundary +
  7197. "\r\n"
  7198. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7199. "\r\n"
  7200. "text1\r\n"
  7201. "--" +
  7202. boundary + "--\r\n";
  7203. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7204. "Content-Type: multipart/form-data;boundary=" +
  7205. boundary +
  7206. "\r\n"
  7207. "Content-Length: " +
  7208. std::to_string(content.size()) +
  7209. "\r\n"
  7210. "Dummy-Header: ";
  7211. std::string header_suffix = "\r\n"
  7212. "\r\n";
  7213. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7214. size_t header_dummy_size =
  7215. read_buff_size -
  7216. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7217. auto header_dummy = std::string(header_dummy_size, '@');
  7218. auto req = header_prefix + header_dummy + header_suffix + content;
  7219. std::string response;
  7220. ASSERT_TRUE(send_request(1, req, &response));
  7221. ASSERT_EQ("200", response.substr(9, 3));
  7222. }
  7223. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7224. static constexpr unsigned int number_of_tasks{1000000};
  7225. std::atomic_uint count{0};
  7226. std::unique_ptr<TaskQueue> task_queue{
  7227. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7228. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7229. auto queued = task_queue->enqueue(
  7230. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7231. EXPECT_TRUE(queued);
  7232. }
  7233. EXPECT_NO_THROW(task_queue->shutdown());
  7234. EXPECT_EQ(number_of_tasks, count.load());
  7235. }
  7236. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7237. static constexpr unsigned int number_of_tasks{1000000};
  7238. static constexpr unsigned int qlimit{2};
  7239. unsigned int queued_count{0};
  7240. std::atomic_uint count{0};
  7241. std::unique_ptr<TaskQueue> task_queue{
  7242. new ThreadPool{/*num_threads=*/1, qlimit}};
  7243. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7244. if (task_queue->enqueue(
  7245. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7246. queued_count++;
  7247. }
  7248. }
  7249. EXPECT_NO_THROW(task_queue->shutdown());
  7250. EXPECT_EQ(queued_count, count.load());
  7251. EXPECT_TRUE(queued_count <= number_of_tasks);
  7252. EXPECT_TRUE(queued_count >= qlimit);
  7253. }
  7254. TEST(TaskQueueTest, MaxQueuedRequests) {
  7255. static constexpr unsigned int qlimit{3};
  7256. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7257. std::condition_variable sem_cv;
  7258. std::mutex sem_mtx;
  7259. int credits = 0;
  7260. bool queued;
  7261. /* Fill up the queue with tasks that will block until we give them credits to
  7262. * complete. */
  7263. for (unsigned int n = 0; n <= qlimit;) {
  7264. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7265. std::unique_lock<std::mutex> lock(sem_mtx);
  7266. while (credits <= 0) {
  7267. sem_cv.wait(lock);
  7268. }
  7269. /* Consume the credit and signal the test code if they are all gone. */
  7270. if (--credits == 0) { sem_cv.notify_one(); }
  7271. });
  7272. if (n < qlimit) {
  7273. /* The first qlimit enqueues must succeed. */
  7274. EXPECT_TRUE(queued);
  7275. } else {
  7276. /* The last one will succeed only when the worker thread
  7277. * starts and dequeues the first blocking task. Although
  7278. * not necessary for the correctness of this test, we sleep for
  7279. * a short while to avoid busy waiting. */
  7280. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7281. }
  7282. if (queued) { n++; }
  7283. }
  7284. /* Further enqueues must fail since the queue is full. */
  7285. for (auto i = 0; i < 4; i++) {
  7286. queued = task_queue->enqueue([] {});
  7287. EXPECT_FALSE(queued);
  7288. }
  7289. /* Give the credits to allow the previous tasks to complete. */
  7290. {
  7291. std::unique_lock<std::mutex> lock(sem_mtx);
  7292. credits += qlimit + 1;
  7293. }
  7294. sem_cv.notify_all();
  7295. /* Wait for all the credits to be consumed. */
  7296. {
  7297. std::unique_lock<std::mutex> lock(sem_mtx);
  7298. while (credits > 0) {
  7299. sem_cv.wait(lock);
  7300. }
  7301. }
  7302. /* Check that we are able again to enqueue at least qlimit tasks. */
  7303. for (unsigned int i = 0; i < qlimit; i++) {
  7304. queued = task_queue->enqueue([] {});
  7305. EXPECT_TRUE(queued);
  7306. }
  7307. EXPECT_NO_THROW(task_queue->shutdown());
  7308. }
  7309. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7310. Server svr;
  7311. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7312. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7313. });
  7314. svr.Get("/hello", [](const Request &req, Response &res) {
  7315. res.set_content(req.get_param_value("key"), "text/plain");
  7316. });
  7317. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7318. auto se = detail::scope_exit([&] {
  7319. svr.stop();
  7320. thread.join();
  7321. ASSERT_FALSE(svr.is_running());
  7322. });
  7323. svr.wait_until_ready();
  7324. {
  7325. Client cli(HOST, PORT);
  7326. cli.set_follow_location(true);
  7327. auto res = cli.Get("/");
  7328. ASSERT_TRUE(res);
  7329. EXPECT_EQ(StatusCode::OK_200, res->status);
  7330. EXPECT_EQ("val&key2=val2", res->body);
  7331. }
  7332. }
  7333. TEST(VulnerabilityTest, CRLFInjection) {
  7334. Server svr;
  7335. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7336. res.set_content("Hello 1", "text/plain");
  7337. });
  7338. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7339. res.set_content("Hello 2", "text/plain");
  7340. });
  7341. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7342. res.set_content("Hello 3", "text/plain");
  7343. });
  7344. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7345. res.set_content("Hello 4", "text/plain");
  7346. });
  7347. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7348. for (const auto &x : req.headers) {
  7349. auto key = x.first;
  7350. EXPECT_STRNE("evil", key.c_str());
  7351. }
  7352. });
  7353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7354. auto se = detail::scope_exit([&] {
  7355. svr.stop();
  7356. thread.join();
  7357. ASSERT_FALSE(svr.is_running());
  7358. });
  7359. svr.wait_until_ready();
  7360. {
  7361. Client cli(HOST, PORT);
  7362. cli.Post("/test1", "A=B",
  7363. "application/x-www-form-urlencoded\r\nevil: hello1");
  7364. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7365. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7366. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7367. }
  7368. }
  7369. TEST(PathParamsTest, StaticMatch) {
  7370. const auto pattern = "/users/all";
  7371. detail::PathParamsMatcher matcher(pattern);
  7372. Request request;
  7373. request.path = "/users/all";
  7374. ASSERT_TRUE(matcher.match(request));
  7375. std::unordered_map<std::string, std::string> expected_params = {};
  7376. EXPECT_EQ(request.path_params, expected_params);
  7377. }
  7378. TEST(PathParamsTest, StaticMismatch) {
  7379. const auto pattern = "/users/all";
  7380. detail::PathParamsMatcher matcher(pattern);
  7381. Request request;
  7382. request.path = "/users/1";
  7383. ASSERT_FALSE(matcher.match(request));
  7384. }
  7385. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7386. const auto pattern = "/users/:id/subscriptions";
  7387. detail::PathParamsMatcher matcher(pattern);
  7388. Request request;
  7389. request.path = "/users/42/subscriptions";
  7390. ASSERT_TRUE(matcher.match(request));
  7391. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7392. EXPECT_EQ(request.path_params, expected_params);
  7393. }
  7394. TEST(PathParamsTest, SingleParamInTheEnd) {
  7395. const auto pattern = "/users/:id";
  7396. detail::PathParamsMatcher matcher(pattern);
  7397. Request request;
  7398. request.path = "/users/24";
  7399. ASSERT_TRUE(matcher.match(request));
  7400. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7401. EXPECT_EQ(request.path_params, expected_params);
  7402. }
  7403. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7404. const auto pattern = "/users/:id/";
  7405. detail::PathParamsMatcher matcher(pattern);
  7406. Request request;
  7407. request.path = "/users/42/";
  7408. ASSERT_TRUE(matcher.match(request));
  7409. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7410. EXPECT_EQ(request.path_params, expected_params);
  7411. }
  7412. TEST(PathParamsTest, EmptyParam) {
  7413. const auto pattern = "/users/:id/";
  7414. detail::PathParamsMatcher matcher(pattern);
  7415. Request request;
  7416. request.path = "/users//";
  7417. ASSERT_TRUE(matcher.match(request));
  7418. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  7419. EXPECT_EQ(request.path_params, expected_params);
  7420. }
  7421. TEST(PathParamsTest, FragmentMismatch) {
  7422. const auto pattern = "/users/:id/";
  7423. detail::PathParamsMatcher matcher(pattern);
  7424. Request request;
  7425. request.path = "/admins/24/";
  7426. ASSERT_FALSE(matcher.match(request));
  7427. }
  7428. TEST(PathParamsTest, ExtraFragments) {
  7429. const auto pattern = "/users/:id";
  7430. detail::PathParamsMatcher matcher(pattern);
  7431. Request request;
  7432. request.path = "/users/42/subscriptions";
  7433. ASSERT_FALSE(matcher.match(request));
  7434. }
  7435. TEST(PathParamsTest, MissingTrailingParam) {
  7436. const auto pattern = "/users/:id";
  7437. detail::PathParamsMatcher matcher(pattern);
  7438. Request request;
  7439. request.path = "/users";
  7440. ASSERT_FALSE(matcher.match(request));
  7441. }
  7442. TEST(PathParamsTest, MissingParamInTheMiddle) {
  7443. const auto pattern = "/users/:id/subscriptions";
  7444. detail::PathParamsMatcher matcher(pattern);
  7445. Request request;
  7446. request.path = "/users/subscriptions";
  7447. ASSERT_FALSE(matcher.match(request));
  7448. }
  7449. TEST(PathParamsTest, MultipleParams) {
  7450. const auto pattern = "/users/:userid/subscriptions/:subid";
  7451. detail::PathParamsMatcher matcher(pattern);
  7452. Request request;
  7453. request.path = "/users/42/subscriptions/2";
  7454. ASSERT_TRUE(matcher.match(request));
  7455. std::unordered_map<std::string, std::string> expected_params = {
  7456. {"userid", "42"}, {"subid", "2"}};
  7457. EXPECT_EQ(request.path_params, expected_params);
  7458. }
  7459. TEST(PathParamsTest, SequenceOfParams) {
  7460. const auto pattern = "/values/:x/:y/:z";
  7461. detail::PathParamsMatcher matcher(pattern);
  7462. Request request;
  7463. request.path = "/values/1/2/3";
  7464. ASSERT_TRUE(matcher.match(request));
  7465. std::unordered_map<std::string, std::string> expected_params = {
  7466. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  7467. EXPECT_EQ(request.path_params, expected_params);
  7468. }
  7469. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  7470. const auto pattern = "/prefix:suffix";
  7471. detail::PathParamsMatcher matcher(pattern);
  7472. Request request;
  7473. request.path = "/prefix:suffix";
  7474. ASSERT_TRUE(matcher.match(request));
  7475. const std::unordered_map<std::string, std::string> expected_params = {};
  7476. EXPECT_EQ(request.path_params, expected_params);
  7477. }
  7478. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  7479. // If ipv6 regex working, regex match codepath is taken.
  7480. // else port will default to 80 in Client impl
  7481. int clientImplMagicPort = 80;
  7482. int port = 4321;
  7483. // above ports must be different to avoid false negative
  7484. EXPECT_NE(clientImplMagicPort, port);
  7485. std::string ipV6TestURL = "http://[ff06::c3]";
  7486. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  7487. CLIENT_PRIVATE_KEY_FILE);
  7488. EXPECT_EQ(cli.port(), port);
  7489. }
  7490. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  7491. auto file_path = "./www/dir/index.html";
  7492. auto dir_path = "./www/dir";
  7493. detail::FileStat stat_file(file_path);
  7494. EXPECT_TRUE(stat_file.is_file());
  7495. EXPECT_FALSE(stat_file.is_dir());
  7496. detail::FileStat stat_dir(dir_path);
  7497. EXPECT_FALSE(stat_dir.is_file());
  7498. EXPECT_TRUE(stat_dir.is_dir());
  7499. }
  7500. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  7501. Server svr;
  7502. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7503. EXPECT_EQ(res.status, 400);
  7504. });
  7505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7506. auto se = detail::scope_exit([&] {
  7507. svr.stop();
  7508. thread.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.wait_until_ready();
  7512. Client cli(HOST, PORT);
  7513. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  7514. }
  7515. TEST(InvalidHeaderCharsTest, is_field_name) {
  7516. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  7517. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  7518. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  7519. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  7520. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  7521. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  7522. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  7523. EXPECT_FALSE(detail::fields::is_field_name(""));
  7524. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  7525. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  7526. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  7527. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  7528. }
  7529. TEST(InvalidHeaderCharsTest, is_field_value) {
  7530. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  7531. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  7532. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  7533. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  7534. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  7535. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  7536. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  7537. EXPECT_TRUE(detail::fields::is_field_value(""));
  7538. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  7539. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  7540. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  7541. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  7542. EXPECT_TRUE(detail::fields::is_field_value("0"));
  7543. }
  7544. TEST(InvalidHeaderCharsTest, OnServer) {
  7545. Server svr;
  7546. svr.Get("/test_name", [&](const Request &req, Response &res) {
  7547. std::string header = "Not Set";
  7548. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7549. res.set_header(header, "value");
  7550. res.set_content("Page Content Page Content", "text/plain");
  7551. });
  7552. svr.Get("/test_value", [&](const Request &req, Response &res) {
  7553. std::string header = "Not Set";
  7554. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7555. res.set_header("X-Test", header);
  7556. res.set_content("Page Content Page Content", "text/plain");
  7557. });
  7558. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7559. auto se = detail::scope_exit([&] {
  7560. svr.stop();
  7561. thread.join();
  7562. ASSERT_FALSE(svr.is_running());
  7563. });
  7564. svr.wait_until_ready();
  7565. Client cli(HOST, PORT);
  7566. {
  7567. auto res = cli.Get(
  7568. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7569. ASSERT_TRUE(res);
  7570. EXPECT_EQ("Page Content Page Content", res->body);
  7571. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7572. }
  7573. {
  7574. auto res = cli.Get(
  7575. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7576. ASSERT_TRUE(res);
  7577. EXPECT_EQ("Page Content Page Content", res->body);
  7578. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7579. }
  7580. }
  7581. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  7582. auto handled = false;
  7583. Server svr;
  7584. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  7585. thread t = thread([&] { svr.listen(HOST, PORT); });
  7586. auto se = detail::scope_exit([&] {
  7587. svr.stop();
  7588. t.join();
  7589. ASSERT_FALSE(svr.is_running());
  7590. ASSERT_FALSE(handled);
  7591. });
  7592. svr.wait_until_ready();
  7593. auto req = "POST /test HTTP/1.1\r\n"
  7594. "Content-Length: x\r\n"
  7595. "\r\n";
  7596. std::string response;
  7597. ASSERT_TRUE(send_request(1, req, &response));
  7598. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7599. response.substr(0, response.find("\r\n")));
  7600. }
  7601. #ifndef _WIN32
  7602. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7603. static constexpr char reject[] = "Unauthorized";
  7604. static constexpr char accept[] = "Upload accepted";
  7605. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7606. Server svr;
  7607. svr.set_expect_100_continue_handler(
  7608. [](const Request & /*req*/, Response &res) {
  7609. res.status = StatusCode::Unauthorized_401;
  7610. res.set_content(reject, "text/plain");
  7611. return res.status;
  7612. });
  7613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7614. res.set_content(accept, "text/plain");
  7615. });
  7616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7617. auto se = detail::scope_exit([&] {
  7618. svr.stop();
  7619. thread.join();
  7620. ASSERT_FALSE(svr.is_running());
  7621. });
  7622. svr.wait_until_ready();
  7623. {
  7624. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7625. curl_easy_init(), &curl_easy_cleanup};
  7626. ASSERT_NE(curl, nullptr);
  7627. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7628. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7629. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7630. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7631. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7632. &curl_slist_free_all};
  7633. ASSERT_NE(list, nullptr);
  7634. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7635. struct read_data {
  7636. size_t read_size;
  7637. size_t total_size;
  7638. } data = {0, total_size};
  7639. using read_callback_t =
  7640. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7641. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7642. void *userdata) -> size_t {
  7643. read_data *data = (read_data *)userdata;
  7644. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7645. std::fill_n(ptr, size * nmemb, 'A');
  7646. data->read_size += size * nmemb;
  7647. return size * nmemb;
  7648. };
  7649. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7650. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7651. std::vector<char> buffer;
  7652. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7653. using write_callback_t =
  7654. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7655. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7656. void *userdata) -> size_t {
  7657. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7658. buffer->reserve(buffer->size() + size * nmemb + 1);
  7659. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7660. return size * nmemb;
  7661. };
  7662. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7663. {
  7664. const auto res = curl_easy_perform(curl.get());
  7665. ASSERT_EQ(res, CURLE_OK);
  7666. }
  7667. {
  7668. auto response_code = long{};
  7669. const auto res =
  7670. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7671. ASSERT_EQ(res, CURLE_OK);
  7672. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7673. }
  7674. {
  7675. auto dl = curl_off_t{};
  7676. const auto res =
  7677. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7678. ASSERT_EQ(res, CURLE_OK);
  7679. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7680. }
  7681. {
  7682. buffer.push_back('\0');
  7683. ASSERT_STRCASEEQ(buffer.data(), reject);
  7684. }
  7685. }
  7686. }
  7687. #endif
  7688. template <typename S, typename C>
  7689. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7690. svr.Get("/stream", [&](const Request &, Response &res) {
  7691. auto data = new std::string("01234567890123456789");
  7692. res.set_content_provider(
  7693. data->size(), "text/plain",
  7694. [&, data](size_t offset, size_t length, DataSink &sink) {
  7695. const size_t DATA_CHUNK_SIZE = 4;
  7696. const auto &d = *data;
  7697. std::this_thread::sleep_for(std::chrono::seconds(1));
  7698. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7699. return true;
  7700. },
  7701. [data](bool success) {
  7702. EXPECT_FALSE(success);
  7703. delete data;
  7704. });
  7705. });
  7706. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7707. auto i = new size_t(0);
  7708. res.set_content_provider(
  7709. "text/plain",
  7710. [i](size_t, DataSink &sink) {
  7711. if (*i < 5) {
  7712. std::this_thread::sleep_for(std::chrono::seconds(1));
  7713. sink.write("abcd", 4);
  7714. (*i)++;
  7715. } else {
  7716. sink.done();
  7717. }
  7718. return true;
  7719. },
  7720. [i](bool success) {
  7721. EXPECT_FALSE(success);
  7722. delete i;
  7723. });
  7724. });
  7725. svr.Get("/chunked", [&](const Request &, Response &res) {
  7726. auto i = new size_t(0);
  7727. res.set_chunked_content_provider(
  7728. "text/plain",
  7729. [i](size_t, DataSink &sink) {
  7730. if (*i < 5) {
  7731. std::this_thread::sleep_for(std::chrono::seconds(1));
  7732. sink.os << "abcd";
  7733. (*i)++;
  7734. } else {
  7735. sink.done();
  7736. }
  7737. return true;
  7738. },
  7739. [i](bool success) {
  7740. EXPECT_FALSE(success);
  7741. delete i;
  7742. });
  7743. });
  7744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7745. auto se = detail::scope_exit([&] {
  7746. svr.stop();
  7747. listen_thread.join();
  7748. ASSERT_FALSE(svr.is_running());
  7749. });
  7750. svr.wait_until_ready();
  7751. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7752. {
  7753. auto start = std::chrono::steady_clock::now();
  7754. auto res = cli.Get("/stream");
  7755. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7756. std::chrono::steady_clock::now() - start)
  7757. .count();
  7758. ASSERT_FALSE(res);
  7759. EXPECT_EQ(Error::Read, res.error());
  7760. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7761. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7762. }
  7763. {
  7764. auto start = std::chrono::steady_clock::now();
  7765. auto res = cli.Get("/stream_without_length");
  7766. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7767. std::chrono::steady_clock::now() - start)
  7768. .count();
  7769. ASSERT_FALSE(res);
  7770. EXPECT_EQ(Error::Read, res.error());
  7771. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7772. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7773. }
  7774. {
  7775. auto start = std::chrono::steady_clock::now();
  7776. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  7777. EXPECT_EQ("abcd", string(data, data_length));
  7778. return true;
  7779. });
  7780. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7781. std::chrono::steady_clock::now() - start)
  7782. .count();
  7783. ASSERT_FALSE(res);
  7784. EXPECT_EQ(Error::Read, res.error());
  7785. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7786. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7787. }
  7788. }
  7789. TEST(MaxTimeoutTest, ContentStream) {
  7790. time_t timeout = 2000;
  7791. time_t threshold = 200;
  7792. Server svr;
  7793. Client cli("localhost", PORT);
  7794. max_timeout_test(svr, cli, timeout, threshold);
  7795. }
  7796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7797. TEST(MaxTimeoutTest, ContentStreamSSL) {
  7798. time_t timeout = 2000;
  7799. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  7800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7801. SSLClient cli("localhost", PORT);
  7802. cli.enable_server_certificate_verification(false);
  7803. max_timeout_test(svr, cli, timeout, threshold);
  7804. }
  7805. #endif
  7806. class EventDispatcher {
  7807. public:
  7808. EventDispatcher() {}
  7809. void wait_event(DataSink *sink) {
  7810. unique_lock<mutex> lk(m_);
  7811. int id = id_;
  7812. cv_.wait(lk, [&] { return cid_ == id; });
  7813. sink->write(message_.data(), message_.size());
  7814. }
  7815. void send_event(const string &message) {
  7816. lock_guard<mutex> lk(m_);
  7817. cid_ = id_++;
  7818. message_ = message;
  7819. cv_.notify_all();
  7820. }
  7821. private:
  7822. mutex m_;
  7823. condition_variable cv_;
  7824. atomic_int id_{0};
  7825. atomic_int cid_{-1};
  7826. string message_;
  7827. };
  7828. TEST(ClientInThreadTest, Issue2068) {
  7829. EventDispatcher ed;
  7830. Server svr;
  7831. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  7832. res.set_chunked_content_provider("text/event-stream",
  7833. [&](size_t /*offset*/, DataSink &sink) {
  7834. ed.wait_event(&sink);
  7835. return true;
  7836. });
  7837. });
  7838. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7839. svr.wait_until_ready();
  7840. thread event_thread([&] {
  7841. int id = 0;
  7842. while (svr.is_running()) {
  7843. this_thread::sleep_for(chrono::milliseconds(500));
  7844. std::stringstream ss;
  7845. ss << "data: " << id << "\n\n";
  7846. ed.send_event(ss.str());
  7847. id++;
  7848. }
  7849. });
  7850. auto se = detail::scope_exit([&] {
  7851. svr.stop();
  7852. listen_thread.join();
  7853. event_thread.join();
  7854. ASSERT_FALSE(svr.is_running());
  7855. });
  7856. {
  7857. auto client = detail::make_unique<Client>(HOST, PORT);
  7858. client->set_read_timeout(std::chrono::minutes(10));
  7859. std::atomic<bool> stop{false};
  7860. std::thread t([&] {
  7861. client->Get("/event1",
  7862. [&](const char *, size_t) -> bool { return !stop; });
  7863. });
  7864. std::this_thread::sleep_for(std::chrono::seconds(2));
  7865. stop = true;
  7866. client->stop();
  7867. client.reset();
  7868. t.join();
  7869. }
  7870. }