test.cc 264 KB

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