1
0

test.cc 265 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826
  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, PreAndPostRoutingHandlers) {
  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(RequestHandlerTest, PreRequestHandler) {
  1928. auto route_path = "/user/:user";
  1929. Server svr;
  1930. svr.Get("/hi", [](const Request &, Response &res) {
  1931. res.set_content("hi", "text/plain");
  1932. });
  1933. svr.Get(route_path, [](const Request &req, Response &res) {
  1934. res.set_content(req.path_params.at("user"), "text/plain");
  1935. });
  1936. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  1937. if (req.matched_route == route_path) {
  1938. auto user = req.path_params.at("user");
  1939. if (user != "john") {
  1940. res.status = StatusCode::Forbidden_403;
  1941. res.set_content("error", "text/html");
  1942. return Server::HandlerResponse::Handled;
  1943. }
  1944. }
  1945. return Server::HandlerResponse::Unhandled;
  1946. });
  1947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1948. auto se = detail::scope_exit([&] {
  1949. svr.stop();
  1950. thread.join();
  1951. ASSERT_FALSE(svr.is_running());
  1952. });
  1953. svr.wait_until_ready();
  1954. Client cli(HOST, PORT);
  1955. {
  1956. auto res = cli.Get("/hi");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("hi", res->body);
  1960. }
  1961. {
  1962. auto res = cli.Get("/user/john");
  1963. ASSERT_TRUE(res);
  1964. EXPECT_EQ(StatusCode::OK_200, res->status);
  1965. EXPECT_EQ("john", res->body);
  1966. }
  1967. {
  1968. auto res = cli.Get("/user/invalid-user");
  1969. ASSERT_TRUE(res);
  1970. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  1971. EXPECT_EQ("error", res->body);
  1972. }
  1973. }
  1974. TEST(InvalidFormatTest, StatusCode) {
  1975. Server svr;
  1976. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1977. res.set_content("Hello World!\n", "text/plain");
  1978. res.status = 9999; // Status should be a three-digit code...
  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. auto res = cli.Get("/hi");
  1990. ASSERT_FALSE(res);
  1991. }
  1992. }
  1993. TEST(URLFragmentTest, WithFragment) {
  1994. Server svr;
  1995. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1996. EXPECT_TRUE(req.target == "/hi");
  1997. });
  1998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1999. auto se = detail::scope_exit([&] {
  2000. svr.stop();
  2001. thread.join();
  2002. ASSERT_FALSE(svr.is_running());
  2003. });
  2004. svr.wait_until_ready();
  2005. {
  2006. Client cli(HOST, PORT);
  2007. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2008. EXPECT_TRUE(res);
  2009. EXPECT_EQ(StatusCode::OK_200, res->status);
  2010. res = cli.Get("/hi%23key1=val1=key2=val2");
  2011. EXPECT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2013. }
  2014. }
  2015. TEST(HeaderWriter, SetHeaderWriter) {
  2016. Server svr;
  2017. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2018. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2019. return detail::write_headers(strm, hdrs);
  2020. });
  2021. svr.Get("/hi", [](const Request &req, Response &res) {
  2022. auto it = req.headers.find("CustomClientHeader");
  2023. EXPECT_TRUE(it != req.headers.end());
  2024. EXPECT_EQ(it->second, "CustomClientValue");
  2025. res.set_content("Hello World!\n", "text/plain");
  2026. });
  2027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2028. auto se = detail::scope_exit([&] {
  2029. svr.stop();
  2030. thread.join();
  2031. ASSERT_FALSE(svr.is_running());
  2032. });
  2033. svr.wait_until_ready();
  2034. {
  2035. Client cli(HOST, PORT);
  2036. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2037. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2038. return detail::write_headers(strm, hdrs);
  2039. });
  2040. auto res = cli.Get("/hi");
  2041. EXPECT_TRUE(res);
  2042. EXPECT_EQ(StatusCode::OK_200, res->status);
  2043. auto it = res->headers.find("CustomServerHeader");
  2044. EXPECT_TRUE(it != res->headers.end());
  2045. EXPECT_EQ(it->second, "CustomServerValue");
  2046. }
  2047. }
  2048. class ServerTest : public ::testing::Test {
  2049. protected:
  2050. ServerTest()
  2051. : cli_(HOST, PORT)
  2052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2053. ,
  2054. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2055. #endif
  2056. {
  2057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2058. cli_.enable_server_certificate_verification(false);
  2059. #endif
  2060. }
  2061. virtual void SetUp() {
  2062. svr_.set_mount_point("/", "./www");
  2063. svr_.set_mount_point("/mount", "./www2");
  2064. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2065. svr_.Get("/hi",
  2066. [&](const Request & /*req*/, Response &res) {
  2067. res.set_content("Hello World!", "text/plain");
  2068. })
  2069. .Get("/file_content",
  2070. [&](const Request & /*req*/, Response &res) {
  2071. res.set_file_content("./www/dir/test.html");
  2072. })
  2073. .Get("/file_content_with_content_type",
  2074. [&](const Request & /*req*/, Response &res) {
  2075. res.set_file_content("./www/file", "text/plain");
  2076. })
  2077. .Get("/invalid_file_content",
  2078. [&](const Request & /*req*/, Response &res) {
  2079. res.set_file_content("./www/dir/invalid_file_path");
  2080. })
  2081. .Get("/http_response_splitting",
  2082. [&](const Request & /*req*/, Response &res) {
  2083. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2084. EXPECT_EQ(0U, res.headers.size());
  2085. EXPECT_FALSE(res.has_header("a"));
  2086. res.set_header("a", "1\nSet-Cookie: a=1");
  2087. EXPECT_EQ(0U, res.headers.size());
  2088. EXPECT_FALSE(res.has_header("a"));
  2089. res.set_header("a", "1\rSet-Cookie: a=1");
  2090. EXPECT_EQ(0U, res.headers.size());
  2091. EXPECT_FALSE(res.has_header("a"));
  2092. res.set_header("a\r\nb", "0");
  2093. EXPECT_EQ(0U, res.headers.size());
  2094. EXPECT_FALSE(res.has_header("a"));
  2095. res.set_header("a\rb", "0");
  2096. EXPECT_EQ(0U, res.headers.size());
  2097. EXPECT_FALSE(res.has_header("a"));
  2098. res.set_header("a\nb", "0");
  2099. EXPECT_EQ(0U, res.headers.size());
  2100. EXPECT_FALSE(res.has_header("a"));
  2101. res.set_redirect("1\r\nSet-Cookie: a=1");
  2102. EXPECT_EQ(0U, res.headers.size());
  2103. EXPECT_FALSE(res.has_header("Location"));
  2104. })
  2105. .Get("/slow",
  2106. [&](const Request & /*req*/, Response &res) {
  2107. std::this_thread::sleep_for(std::chrono::seconds(2));
  2108. res.set_content("slow", "text/plain");
  2109. })
  2110. #if 0
  2111. .Post("/slowpost",
  2112. [&](const Request & /*req*/, Response &res) {
  2113. std::this_thread::sleep_for(std::chrono::seconds(2));
  2114. res.set_content("slow", "text/plain");
  2115. })
  2116. #endif
  2117. .Get("/remote_addr",
  2118. [&](const Request &req, Response &res) {
  2119. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2120. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2121. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2122. EXPECT_EQ(req.remote_port,
  2123. std::stoi(req.get_header_value("REMOTE_PORT")));
  2124. res.set_content(remote_addr.c_str(), "text/plain");
  2125. })
  2126. .Get("/local_addr",
  2127. [&](const Request &req, Response &res) {
  2128. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2129. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2130. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2131. auto local_port = req.get_header_value("LOCAL_PORT");
  2132. EXPECT_EQ(req.local_addr, local_addr);
  2133. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2134. res.set_content(local_addr.append(":").append(local_port),
  2135. "text/plain");
  2136. })
  2137. .Get("/endwith%",
  2138. [&](const Request & /*req*/, Response &res) {
  2139. res.set_content("Hello World!", "text/plain");
  2140. })
  2141. .Get("/a\\+\\+b",
  2142. [&](const Request &req, Response &res) {
  2143. ASSERT_TRUE(req.has_param("a +b"));
  2144. auto val = req.get_param_value("a +b");
  2145. res.set_content(val, "text/plain");
  2146. })
  2147. .Get("/", [&](const Request & /*req*/,
  2148. Response &res) { res.set_redirect("/hi"); })
  2149. .Post("/1",
  2150. [](const Request & /*req*/, Response &res) {
  2151. res.set_redirect("/2", StatusCode::SeeOther_303);
  2152. })
  2153. .Get("/2",
  2154. [](const Request & /*req*/, Response &res) {
  2155. res.set_content("redirected.", "text/plain");
  2156. res.status = StatusCode::OK_200;
  2157. })
  2158. .Post("/person",
  2159. [&](const Request &req, Response &res) {
  2160. if (req.has_param("name") && req.has_param("note")) {
  2161. persons_[req.get_param_value("name")] =
  2162. req.get_param_value("note");
  2163. } else {
  2164. res.status = StatusCode::BadRequest_400;
  2165. }
  2166. })
  2167. .Put("/person",
  2168. [&](const Request &req, Response &res) {
  2169. if (req.has_param("name") && req.has_param("note")) {
  2170. persons_[req.get_param_value("name")] =
  2171. req.get_param_value("note");
  2172. } else {
  2173. res.status = StatusCode::BadRequest_400;
  2174. }
  2175. })
  2176. .Get("/person/(.*)",
  2177. [&](const Request &req, Response &res) {
  2178. string name = req.matches[1];
  2179. if (persons_.find(name) != persons_.end()) {
  2180. auto note = persons_[name];
  2181. res.set_content(note, "text/plain");
  2182. } else {
  2183. res.status = StatusCode::NotFound_404;
  2184. }
  2185. })
  2186. .Post("/x-www-form-urlencoded-json",
  2187. [&](const Request &req, Response &res) {
  2188. auto json = req.get_param_value("json");
  2189. ASSERT_EQ(JSON_DATA, json);
  2190. res.set_content(json, "appliation/json");
  2191. res.status = StatusCode::OK_200;
  2192. })
  2193. .Get("/streamed-chunked",
  2194. [&](const Request & /*req*/, Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2197. sink.os << "123";
  2198. sink.os << "456";
  2199. sink.os << "789";
  2200. sink.done();
  2201. return true;
  2202. });
  2203. })
  2204. .Get("/streamed-chunked2",
  2205. [&](const Request & /*req*/, Response &res) {
  2206. auto i = new int(0);
  2207. res.set_chunked_content_provider(
  2208. "text/plain",
  2209. [i](size_t /*offset*/, DataSink &sink) {
  2210. switch (*i) {
  2211. case 0: sink.os << "123"; break;
  2212. case 1: sink.os << "456"; break;
  2213. case 2: sink.os << "789"; break;
  2214. case 3: sink.done(); break;
  2215. }
  2216. (*i)++;
  2217. return true;
  2218. },
  2219. [i](bool success) {
  2220. EXPECT_TRUE(success);
  2221. delete i;
  2222. });
  2223. })
  2224. .Get("/streamed-chunked-with-trailer",
  2225. [&](const Request & /*req*/, Response &res) {
  2226. auto i = new int(0);
  2227. res.set_header("Trailer", "Dummy1, Dummy2");
  2228. res.set_chunked_content_provider(
  2229. "text/plain",
  2230. [i](size_t /*offset*/, DataSink &sink) {
  2231. switch (*i) {
  2232. case 0: sink.os << "123"; break;
  2233. case 1: sink.os << "456"; break;
  2234. case 2: sink.os << "789"; break;
  2235. case 3: {
  2236. sink.done_with_trailer(
  2237. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2238. } break;
  2239. }
  2240. (*i)++;
  2241. return true;
  2242. },
  2243. [i](bool success) {
  2244. EXPECT_TRUE(success);
  2245. delete i;
  2246. });
  2247. })
  2248. .Get("/streamed",
  2249. [&](const Request & /*req*/, Response &res) {
  2250. res.set_content_provider(
  2251. 6, "text/plain",
  2252. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2253. sink.os << (offset < 3 ? "a" : "b");
  2254. return true;
  2255. });
  2256. })
  2257. .Get("/streamed-with-range",
  2258. [&](const Request &req, Response &res) {
  2259. auto data = new std::string("abcdefg");
  2260. res.set_content_provider(
  2261. data->size(), "text/plain",
  2262. [data](size_t offset, size_t length, DataSink &sink) {
  2263. size_t DATA_CHUNK_SIZE = 4;
  2264. const auto &d = *data;
  2265. auto out_len =
  2266. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2267. auto ret =
  2268. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2269. EXPECT_TRUE(ret);
  2270. return true;
  2271. },
  2272. [data, &req](bool success) {
  2273. EXPECT_EQ(success, !req.has_param("error"));
  2274. delete data;
  2275. });
  2276. })
  2277. .Get("/streamed-cancel",
  2278. [&](const Request & /*req*/, Response &res) {
  2279. res.set_content_provider(
  2280. size_t(-1), "text/plain",
  2281. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2282. sink.os << "data_chunk";
  2283. return true;
  2284. });
  2285. })
  2286. .Get("/regex-with-delimiter",
  2287. [&](const Request &req, Response & /*res*/) {
  2288. ASSERT_TRUE(req.has_param("key"));
  2289. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2290. })
  2291. .Get("/with-range",
  2292. [&](const Request & /*req*/, Response &res) {
  2293. res.set_content("abcdefg", "text/plain");
  2294. })
  2295. .Get("/with-range-customized-response",
  2296. [&](const Request & /*req*/, Response &res) {
  2297. res.status = StatusCode::BadRequest_400;
  2298. res.set_content(JSON_DATA, "application/json");
  2299. })
  2300. .Post("/chunked",
  2301. [&](const Request &req, Response & /*res*/) {
  2302. EXPECT_EQ(req.body, "dechunked post body");
  2303. })
  2304. .Post("/large-chunked",
  2305. [&](const Request &req, Response & /*res*/) {
  2306. std::string expected(6 * 30 * 1024u, 'a');
  2307. EXPECT_EQ(req.body, expected);
  2308. })
  2309. .Post("/multipart",
  2310. [&](const Request &req, Response & /*res*/) {
  2311. EXPECT_EQ(6u, req.files.size());
  2312. ASSERT_TRUE(!req.has_file("???"));
  2313. ASSERT_TRUE(req.body.empty());
  2314. {
  2315. const auto &file = req.get_file_value("text1");
  2316. EXPECT_TRUE(file.filename.empty());
  2317. EXPECT_EQ("text default", file.content);
  2318. }
  2319. {
  2320. const auto &file = req.get_file_value("text2");
  2321. EXPECT_TRUE(file.filename.empty());
  2322. EXPECT_EQ("aωb", file.content);
  2323. }
  2324. {
  2325. const auto &file = req.get_file_value("file1");
  2326. EXPECT_EQ("hello.txt", file.filename);
  2327. EXPECT_EQ("text/plain", file.content_type);
  2328. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2329. }
  2330. {
  2331. const auto &file = req.get_file_value("file3");
  2332. EXPECT_TRUE(file.filename.empty());
  2333. EXPECT_EQ("application/octet-stream", file.content_type);
  2334. EXPECT_EQ(0u, file.content.size());
  2335. }
  2336. {
  2337. const auto &file = req.get_file_value("file4");
  2338. EXPECT_TRUE(file.filename.empty());
  2339. EXPECT_EQ(0u, file.content.size());
  2340. EXPECT_EQ("application/json tmp-string", file.content_type);
  2341. }
  2342. })
  2343. .Post("/multipart/multi_file_values",
  2344. [&](const Request &req, Response & /*res*/) {
  2345. EXPECT_EQ(5u, req.files.size());
  2346. ASSERT_TRUE(!req.has_file("???"));
  2347. ASSERT_TRUE(req.body.empty());
  2348. {
  2349. const auto &text_value = req.get_file_values("text");
  2350. EXPECT_EQ(1u, text_value.size());
  2351. auto &text = text_value[0];
  2352. EXPECT_TRUE(text.filename.empty());
  2353. EXPECT_EQ("default text", text.content);
  2354. }
  2355. {
  2356. const auto &text1_values = req.get_file_values("multi_text1");
  2357. EXPECT_EQ(2u, text1_values.size());
  2358. EXPECT_EQ("aaaaa", text1_values[0].content);
  2359. EXPECT_EQ("bbbbb", text1_values[1].content);
  2360. }
  2361. {
  2362. const auto &file1_values = req.get_file_values("multi_file1");
  2363. EXPECT_EQ(2u, file1_values.size());
  2364. auto file1 = file1_values[0];
  2365. EXPECT_EQ(file1.filename, "hello.txt");
  2366. EXPECT_EQ(file1.content_type, "text/plain");
  2367. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2368. auto file2 = file1_values[1];
  2369. EXPECT_EQ(file2.filename, "world.json");
  2370. EXPECT_EQ(file2.content_type, "application/json");
  2371. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2372. }
  2373. })
  2374. .Post("/empty",
  2375. [&](const Request &req, Response &res) {
  2376. EXPECT_EQ(req.body, "");
  2377. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2378. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2379. res.set_content("empty", "text/plain");
  2380. })
  2381. .Post("/empty-no-content-type",
  2382. [&](const Request &req, Response &res) {
  2383. EXPECT_EQ(req.body, "");
  2384. EXPECT_FALSE(req.has_header("Content-Type"));
  2385. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2386. res.set_content("empty-no-content-type", "text/plain");
  2387. })
  2388. .Post("/path-only",
  2389. [&](const Request &req, Response &res) {
  2390. EXPECT_EQ(req.body, "");
  2391. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2392. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2393. res.set_content("path-only", "text/plain");
  2394. })
  2395. .Post("/path-headers-only",
  2396. [&](const Request &req, Response &res) {
  2397. EXPECT_EQ(req.body, "");
  2398. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2399. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2400. EXPECT_EQ("world", req.get_header_value("hello"));
  2401. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2402. res.set_content("path-headers-only", "text/plain");
  2403. })
  2404. .Post("/post-large",
  2405. [&](const Request &req, Response &res) {
  2406. EXPECT_EQ(req.body, LARGE_DATA);
  2407. res.set_content(req.body, "text/plain");
  2408. })
  2409. .Put("/empty-no-content-type",
  2410. [&](const Request &req, Response &res) {
  2411. EXPECT_EQ(req.body, "");
  2412. EXPECT_FALSE(req.has_header("Content-Type"));
  2413. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2414. res.set_content("empty-no-content-type", "text/plain");
  2415. })
  2416. .Put("/put",
  2417. [&](const Request &req, Response &res) {
  2418. EXPECT_EQ(req.body, "PUT");
  2419. res.set_content(req.body, "text/plain");
  2420. })
  2421. .Put("/put-large",
  2422. [&](const Request &req, Response &res) {
  2423. EXPECT_EQ(req.body, LARGE_DATA);
  2424. res.set_content(req.body, "text/plain");
  2425. })
  2426. .Patch("/patch",
  2427. [&](const Request &req, Response &res) {
  2428. EXPECT_EQ(req.body, "PATCH");
  2429. res.set_content(req.body, "text/plain");
  2430. })
  2431. .Delete("/delete",
  2432. [&](const Request & /*req*/, Response &res) {
  2433. res.set_content("DELETE", "text/plain");
  2434. })
  2435. .Delete("/delete-body",
  2436. [&](const Request &req, Response &res) {
  2437. EXPECT_EQ(req.body, "content");
  2438. res.set_content(req.body, "text/plain");
  2439. })
  2440. .Options(R"(\*)",
  2441. [&](const Request & /*req*/, Response &res) {
  2442. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2443. })
  2444. .Get("/request-target",
  2445. [&](const Request &req, Response & /*res*/) {
  2446. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2447. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2448. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2449. })
  2450. .Get("/long-query-value",
  2451. [&](const Request &req, Response & /*res*/) {
  2452. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2453. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2454. })
  2455. .Get("/too-long-query-value",
  2456. [&](const Request &req, Response & /*res*/) {
  2457. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2458. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2459. })
  2460. .Get("/array-param",
  2461. [&](const Request &req, Response & /*res*/) {
  2462. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2463. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2464. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2465. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2466. })
  2467. .Post("/validate-no-multiple-headers",
  2468. [&](const Request &req, Response & /*res*/) {
  2469. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2470. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2471. })
  2472. .Post("/content_receiver",
  2473. [&](const Request &req, Response &res,
  2474. const ContentReader &content_reader) {
  2475. if (req.is_multipart_form_data()) {
  2476. MultipartFormDataItems files;
  2477. content_reader(
  2478. [&](const MultipartFormData &file) {
  2479. files.push_back(file);
  2480. return true;
  2481. },
  2482. [&](const char *data, size_t data_length) {
  2483. files.back().content.append(data, data_length);
  2484. return true;
  2485. });
  2486. EXPECT_EQ(5u, files.size());
  2487. {
  2488. const auto &file = get_file_value(files, "text1");
  2489. EXPECT_TRUE(file.filename.empty());
  2490. EXPECT_EQ("text default", file.content);
  2491. }
  2492. {
  2493. const auto &file = get_file_value(files, "text2");
  2494. EXPECT_TRUE(file.filename.empty());
  2495. EXPECT_EQ("aωb", file.content);
  2496. }
  2497. {
  2498. const auto &file = get_file_value(files, "file1");
  2499. EXPECT_EQ("hello.txt", file.filename);
  2500. EXPECT_EQ("text/plain", file.content_type);
  2501. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2502. }
  2503. {
  2504. const auto &file = get_file_value(files, "file3");
  2505. EXPECT_TRUE(file.filename.empty());
  2506. EXPECT_EQ("application/octet-stream", file.content_type);
  2507. EXPECT_EQ(0u, file.content.size());
  2508. }
  2509. } else {
  2510. std::string body;
  2511. content_reader([&](const char *data, size_t data_length) {
  2512. EXPECT_EQ(7U, data_length);
  2513. body.append(data, data_length);
  2514. return true;
  2515. });
  2516. EXPECT_EQ(body, "content");
  2517. res.set_content(body, "text/plain");
  2518. }
  2519. })
  2520. .Put("/content_receiver",
  2521. [&](const Request & /*req*/, Response &res,
  2522. const ContentReader &content_reader) {
  2523. std::string body;
  2524. content_reader([&](const char *data, size_t data_length) {
  2525. body.append(data, data_length);
  2526. return true;
  2527. });
  2528. EXPECT_EQ(body, "content");
  2529. res.set_content(body, "text/plain");
  2530. })
  2531. .Patch("/content_receiver",
  2532. [&](const Request & /*req*/, Response &res,
  2533. const ContentReader &content_reader) {
  2534. std::string body;
  2535. content_reader([&](const char *data, size_t data_length) {
  2536. body.append(data, data_length);
  2537. return true;
  2538. });
  2539. EXPECT_EQ(body, "content");
  2540. res.set_content(body, "text/plain");
  2541. })
  2542. .Post("/query-string-and-body",
  2543. [&](const Request &req, Response & /*res*/) {
  2544. ASSERT_TRUE(req.has_param("key"));
  2545. EXPECT_EQ(req.get_param_value("key"), "value");
  2546. EXPECT_EQ(req.body, "content");
  2547. })
  2548. .Get("/last-request",
  2549. [&](const Request &req, Response & /*res*/) {
  2550. EXPECT_EQ("close", req.get_header_value("Connection"));
  2551. })
  2552. .Get(R"(/redirect/(\d+))",
  2553. [&](const Request &req, Response &res) {
  2554. auto num = std::stoi(req.matches[1]) + 1;
  2555. std::string url = "/redirect/" + std::to_string(num);
  2556. res.set_redirect(url);
  2557. })
  2558. .Post("/binary",
  2559. [&](const Request &req, Response &res) {
  2560. EXPECT_EQ(4U, req.body.size());
  2561. EXPECT_EQ("application/octet-stream",
  2562. req.get_header_value("Content-Type"));
  2563. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2564. res.set_content(req.body, "application/octet-stream");
  2565. })
  2566. .Put("/binary",
  2567. [&](const Request &req, Response &res) {
  2568. EXPECT_EQ(4U, req.body.size());
  2569. EXPECT_EQ("application/octet-stream",
  2570. req.get_header_value("Content-Type"));
  2571. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2572. res.set_content(req.body, "application/octet-stream");
  2573. })
  2574. .Patch("/binary",
  2575. [&](const Request &req, Response &res) {
  2576. EXPECT_EQ(4U, req.body.size());
  2577. EXPECT_EQ("application/octet-stream",
  2578. req.get_header_value("Content-Type"));
  2579. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2580. res.set_content(req.body, "application/octet-stream");
  2581. })
  2582. .Delete("/binary",
  2583. [&](const Request &req, Response &res) {
  2584. EXPECT_EQ(4U, req.body.size());
  2585. EXPECT_EQ("application/octet-stream",
  2586. req.get_header_value("Content-Type"));
  2587. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2588. res.set_content(req.body, "application/octet-stream");
  2589. })
  2590. .Get("/issue1772",
  2591. [&](const Request & /*req*/, Response &res) {
  2592. res.status = 401;
  2593. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2594. })
  2595. .Delete("/issue609",
  2596. [](const httplib::Request &, httplib::Response &res,
  2597. const httplib::ContentReader &) {
  2598. res.set_content("ok", "text/plain");
  2599. })
  2600. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2601. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2602. .Get("/compress",
  2603. [&](const Request & /*req*/, Response &res) {
  2604. res.set_content(
  2605. "12345678901234567890123456789012345678901234567890123456789"
  2606. "01234567890123456789012345678901234567890",
  2607. "text/plain");
  2608. })
  2609. .Get("/nocompress",
  2610. [&](const Request & /*req*/, Response &res) {
  2611. res.set_content(
  2612. "12345678901234567890123456789012345678901234567890123456789"
  2613. "01234567890123456789012345678901234567890",
  2614. "application/octet-stream");
  2615. })
  2616. .Post("/compress-multipart",
  2617. [&](const Request &req, Response & /*res*/) {
  2618. EXPECT_EQ(2u, req.files.size());
  2619. ASSERT_TRUE(!req.has_file("???"));
  2620. {
  2621. const auto &file = req.get_file_value("key1");
  2622. EXPECT_TRUE(file.filename.empty());
  2623. EXPECT_EQ("test", file.content);
  2624. }
  2625. {
  2626. const auto &file = req.get_file_value("key2");
  2627. EXPECT_TRUE(file.filename.empty());
  2628. EXPECT_EQ("--abcdefg123", file.content);
  2629. }
  2630. })
  2631. #endif
  2632. ;
  2633. persons_["john"] = "programmer";
  2634. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2635. svr_.wait_until_ready();
  2636. }
  2637. virtual void TearDown() {
  2638. svr_.stop();
  2639. if (!request_threads_.empty()) {
  2640. std::this_thread::sleep_for(std::chrono::seconds(1));
  2641. for (auto &t : request_threads_) {
  2642. t.join();
  2643. }
  2644. }
  2645. t_.join();
  2646. }
  2647. map<string, string> persons_;
  2648. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2649. SSLClient cli_;
  2650. SSLServer svr_;
  2651. #else
  2652. Client cli_;
  2653. Server svr_;
  2654. #endif
  2655. thread t_;
  2656. std::vector<thread> request_threads_;
  2657. };
  2658. TEST_F(ServerTest, GetMethod200) {
  2659. auto res = cli_.Get("/hi");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ("HTTP/1.1", res->version);
  2662. EXPECT_EQ(StatusCode::OK_200, res->status);
  2663. EXPECT_EQ("OK", res->reason);
  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, GetEmptyFile) {
  2669. auto res = cli_.Get("/empty_file");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(StatusCode::OK_200, res->status);
  2672. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2673. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2674. EXPECT_EQ("", res->body);
  2675. }
  2676. TEST_F(ServerTest, GetFileContent) {
  2677. auto res = cli_.Get("/file_content");
  2678. ASSERT_TRUE(res);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2681. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2682. EXPECT_EQ("test.html", res->body);
  2683. }
  2684. TEST_F(ServerTest, GetFileContentWithRange) {
  2685. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2686. ASSERT_TRUE(res);
  2687. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2688. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2689. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2690. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2691. EXPECT_EQ("est", res->body);
  2692. }
  2693. TEST_F(ServerTest, GetFileContentWithContentType) {
  2694. auto res = cli_.Get("/file_content_with_content_type");
  2695. ASSERT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2698. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2699. EXPECT_EQ("file\n", res->body);
  2700. }
  2701. TEST_F(ServerTest, GetInvalidFileContent) {
  2702. auto res = cli_.Get("/invalid_file_content");
  2703. ASSERT_TRUE(res);
  2704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2705. }
  2706. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2707. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2708. ASSERT_TRUE(res);
  2709. EXPECT_EQ("HTTP/1.1", res->version);
  2710. EXPECT_EQ(StatusCode::OK_200, res->status);
  2711. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2712. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2713. EXPECT_EQ("Hello World!", res->body);
  2714. }
  2715. TEST_F(ServerTest, GetMethod302) {
  2716. auto res = cli_.Get("/");
  2717. ASSERT_TRUE(res);
  2718. EXPECT_EQ(StatusCode::Found_302, res->status);
  2719. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2720. }
  2721. TEST_F(ServerTest, GetMethod302Redirect) {
  2722. cli_.set_follow_location(true);
  2723. auto res = cli_.Get("/");
  2724. ASSERT_TRUE(res);
  2725. EXPECT_EQ(StatusCode::OK_200, res->status);
  2726. EXPECT_EQ("Hello World!", res->body);
  2727. EXPECT_EQ("/hi", res->location);
  2728. }
  2729. TEST_F(ServerTest, GetMethod404) {
  2730. auto res = cli_.Get("/invalid");
  2731. ASSERT_TRUE(res);
  2732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2733. }
  2734. TEST_F(ServerTest, HeadMethod200) {
  2735. auto res = cli_.Head("/hi");
  2736. ASSERT_TRUE(res);
  2737. EXPECT_EQ(StatusCode::OK_200, res->status);
  2738. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2739. EXPECT_TRUE(res->body.empty());
  2740. }
  2741. TEST_F(ServerTest, HeadMethod200Static) {
  2742. auto res = cli_.Head("/mount/dir/index.html");
  2743. ASSERT_TRUE(res);
  2744. EXPECT_EQ(StatusCode::OK_200, res->status);
  2745. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2746. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2747. EXPECT_TRUE(res->body.empty());
  2748. }
  2749. TEST_F(ServerTest, HeadMethod404) {
  2750. auto res = cli_.Head("/invalid");
  2751. ASSERT_TRUE(res);
  2752. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2753. EXPECT_TRUE(res->body.empty());
  2754. }
  2755. TEST_F(ServerTest, GetMethodPersonJohn) {
  2756. auto res = cli_.Get("/person/john");
  2757. ASSERT_TRUE(res);
  2758. EXPECT_EQ(StatusCode::OK_200, res->status);
  2759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2760. EXPECT_EQ("programmer", res->body);
  2761. }
  2762. TEST_F(ServerTest, PostMethod1) {
  2763. auto res = cli_.Get("/person/john1");
  2764. ASSERT_TRUE(res);
  2765. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2766. res = cli_.Post("/person", "name=john1&note=coder",
  2767. "application/x-www-form-urlencoded");
  2768. ASSERT_TRUE(res);
  2769. ASSERT_EQ(StatusCode::OK_200, res->status);
  2770. res = cli_.Get("/person/john1");
  2771. ASSERT_TRUE(res);
  2772. ASSERT_EQ(StatusCode::OK_200, res->status);
  2773. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2774. ASSERT_EQ("coder", res->body);
  2775. }
  2776. TEST_F(ServerTest, PostMethod2) {
  2777. auto res = cli_.Get("/person/john2");
  2778. ASSERT_TRUE(res);
  2779. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2780. Params params;
  2781. params.emplace("name", "john2");
  2782. params.emplace("note", "coder");
  2783. res = cli_.Post("/person", params);
  2784. ASSERT_TRUE(res);
  2785. ASSERT_EQ(StatusCode::OK_200, res->status);
  2786. res = cli_.Get("/person/john2");
  2787. ASSERT_TRUE(res);
  2788. ASSERT_EQ(StatusCode::OK_200, res->status);
  2789. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2790. ASSERT_EQ("coder", res->body);
  2791. }
  2792. TEST_F(ServerTest, PutMethod3) {
  2793. auto res = cli_.Get("/person/john3");
  2794. ASSERT_TRUE(res);
  2795. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2796. Params params;
  2797. params.emplace("name", "john3");
  2798. params.emplace("note", "coder");
  2799. res = cli_.Put("/person", params);
  2800. ASSERT_TRUE(res);
  2801. ASSERT_EQ(StatusCode::OK_200, res->status);
  2802. res = cli_.Get("/person/john3");
  2803. ASSERT_TRUE(res);
  2804. ASSERT_EQ(StatusCode::OK_200, res->status);
  2805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2806. ASSERT_EQ("coder", res->body);
  2807. }
  2808. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2809. Params params;
  2810. params.emplace("json", JSON_DATA);
  2811. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2812. ASSERT_TRUE(res);
  2813. ASSERT_EQ(StatusCode::OK_200, res->status);
  2814. ASSERT_EQ(JSON_DATA, res->body);
  2815. }
  2816. TEST_F(ServerTest, PostEmptyContent) {
  2817. auto res = cli_.Post("/empty", "", "text/plain");
  2818. ASSERT_TRUE(res);
  2819. ASSERT_EQ(StatusCode::OK_200, res->status);
  2820. ASSERT_EQ("empty", res->body);
  2821. }
  2822. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2823. auto res = cli_.Post("/empty-no-content-type");
  2824. ASSERT_TRUE(res);
  2825. ASSERT_EQ(StatusCode::OK_200, res->status);
  2826. ASSERT_EQ("empty-no-content-type", res->body);
  2827. }
  2828. TEST_F(ServerTest, PostPathOnly) {
  2829. auto res = cli_.Post("/path-only");
  2830. ASSERT_TRUE(res);
  2831. ASSERT_EQ(StatusCode::OK_200, res->status);
  2832. ASSERT_EQ("path-only", res->body);
  2833. }
  2834. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2835. auto res = cli_.Post("/path-headers-only",
  2836. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2837. ASSERT_TRUE(res);
  2838. ASSERT_EQ(StatusCode::OK_200, res->status);
  2839. ASSERT_EQ("path-headers-only", res->body);
  2840. }
  2841. TEST_F(ServerTest, PostLarge) {
  2842. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2843. ASSERT_TRUE(res);
  2844. ASSERT_EQ(StatusCode::OK_200, res->status);
  2845. EXPECT_EQ(LARGE_DATA, res->body);
  2846. }
  2847. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2848. auto res = cli_.Put("/empty-no-content-type");
  2849. ASSERT_TRUE(res);
  2850. ASSERT_EQ(StatusCode::OK_200, res->status);
  2851. ASSERT_EQ("empty-no-content-type", res->body);
  2852. }
  2853. TEST_F(ServerTest, GetMethodDir) {
  2854. auto res = cli_.Get("/dir/");
  2855. ASSERT_TRUE(res);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2858. auto body = R"(<html>
  2859. <head>
  2860. </head>
  2861. <body>
  2862. <a href="/dir/test.html">Test</a>
  2863. <a href="/hi">hi</a>
  2864. </body>
  2865. </html>
  2866. )";
  2867. EXPECT_EQ(body, res->body);
  2868. }
  2869. TEST_F(ServerTest, GetMethodDirTest) {
  2870. auto res = cli_.Get("/dir/test.html");
  2871. ASSERT_TRUE(res);
  2872. EXPECT_EQ(StatusCode::OK_200, res->status);
  2873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2874. EXPECT_EQ("test.html", res->body);
  2875. }
  2876. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2877. auto res = cli_.Get("/dir/../dir/test.html");
  2878. ASSERT_TRUE(res);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2881. EXPECT_EQ("test.html", res->body);
  2882. }
  2883. TEST_F(ServerTest, GetMethodInvalidPath) {
  2884. auto res = cli_.Get("/dir/../test.html");
  2885. ASSERT_TRUE(res);
  2886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2887. }
  2888. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2889. auto res = cli_.Get("/../www/dir/test.html");
  2890. ASSERT_TRUE(res);
  2891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2892. }
  2893. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2894. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2895. ASSERT_TRUE(res);
  2896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2897. }
  2898. TEST_F(ServerTest, GetMethodDirMountTest) {
  2899. auto res = cli_.Get("/mount/dir/test.html");
  2900. ASSERT_TRUE(res);
  2901. EXPECT_EQ(StatusCode::OK_200, res->status);
  2902. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2903. EXPECT_EQ("test.html", res->body);
  2904. }
  2905. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2906. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2907. ASSERT_TRUE(res);
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2910. EXPECT_EQ("test.html", res->body);
  2911. }
  2912. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2913. auto res = cli_.Get("/mount/dir/../test.html");
  2914. ASSERT_TRUE(res);
  2915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2916. }
  2917. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2918. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2919. ASSERT_TRUE(res);
  2920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2921. }
  2922. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2923. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2924. ASSERT_TRUE(res);
  2925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2926. }
  2927. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2928. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2929. ASSERT_TRUE(res);
  2930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2931. }
  2932. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2933. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2936. }
  2937. TEST_F(ServerTest, PostMethod303) {
  2938. auto res = cli_.Post("/1", "body", "text/plain");
  2939. ASSERT_TRUE(res);
  2940. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2941. EXPECT_EQ("/2", res->get_header_value("Location"));
  2942. }
  2943. TEST_F(ServerTest, PostMethod303Redirect) {
  2944. cli_.set_follow_location(true);
  2945. auto res = cli_.Post("/1", "body", "text/plain");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::OK_200, res->status);
  2948. EXPECT_EQ("redirected.", res->body);
  2949. EXPECT_EQ("/2", res->location);
  2950. }
  2951. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2952. auto res = cli_.Get("/dir/test.abcde");
  2953. ASSERT_TRUE(res);
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2956. EXPECT_EQ("abcde", res->body);
  2957. }
  2958. TEST_F(ServerTest, StaticFileRange) {
  2959. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2960. ASSERT_TRUE(res);
  2961. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2962. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2963. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2964. EXPECT_EQ(true, res->has_header("Content-Range"));
  2965. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2966. EXPECT_EQ(std::string("cd"), res->body);
  2967. }
  2968. TEST_F(ServerTest, StaticFileRanges) {
  2969. auto res =
  2970. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2971. ASSERT_TRUE(res);
  2972. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2973. EXPECT_TRUE(
  2974. res->get_header_value("Content-Type")
  2975. .find(
  2976. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2977. 0);
  2978. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2979. }
  2980. TEST_F(ServerTest, StaticFileRangeHead) {
  2981. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2982. ASSERT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2984. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2986. EXPECT_EQ(true, res->has_header("Content-Range"));
  2987. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2988. }
  2989. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2990. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2991. ASSERT_TRUE(res);
  2992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2994. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2995. EXPECT_EQ(true, res->has_header("Content-Range"));
  2996. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2997. res->get_header_value("Content-Range"));
  2998. EXPECT_EQ("LAST\n", res->body);
  2999. }
  3000. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3001. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3002. ASSERT_TRUE(res);
  3003. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3005. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3006. EXPECT_EQ(true, res->has_header("Content-Range"));
  3007. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3008. }
  3009. TEST_F(ServerTest, StaticFileBigFile) {
  3010. auto res = cli_.Get("/dir/1MB.txt");
  3011. ASSERT_TRUE(res);
  3012. EXPECT_EQ(StatusCode::OK_200, res->status);
  3013. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3014. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3015. }
  3016. TEST_F(ServerTest, InvalidBaseDirMount) {
  3017. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3018. }
  3019. TEST_F(ServerTest, Binary) {
  3020. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3021. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3022. "application/octet-stream");
  3023. ASSERT_TRUE(res);
  3024. ASSERT_EQ(StatusCode::OK_200, res->status);
  3025. ASSERT_EQ(4U, res->body.size());
  3026. res = cli_.Put("/binary", binary.data(), binary.size(),
  3027. "application/octet-stream");
  3028. ASSERT_TRUE(res);
  3029. ASSERT_EQ(StatusCode::OK_200, res->status);
  3030. ASSERT_EQ(4U, res->body.size());
  3031. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3032. "application/octet-stream");
  3033. ASSERT_TRUE(res);
  3034. ASSERT_EQ(StatusCode::OK_200, res->status);
  3035. ASSERT_EQ(4U, res->body.size());
  3036. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3037. "application/octet-stream");
  3038. ASSERT_TRUE(res);
  3039. ASSERT_EQ(StatusCode::OK_200, res->status);
  3040. ASSERT_EQ(4U, res->body.size());
  3041. }
  3042. TEST_F(ServerTest, BinaryString) {
  3043. auto binary = std::string("\x00\x01\x02\x03", 4);
  3044. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3045. ASSERT_TRUE(res);
  3046. ASSERT_EQ(StatusCode::OK_200, res->status);
  3047. ASSERT_EQ(4U, res->body.size());
  3048. res = cli_.Put("/binary", binary, "application/octet-stream");
  3049. ASSERT_TRUE(res);
  3050. ASSERT_EQ(StatusCode::OK_200, res->status);
  3051. ASSERT_EQ(4U, res->body.size());
  3052. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3053. ASSERT_TRUE(res);
  3054. ASSERT_EQ(StatusCode::OK_200, res->status);
  3055. ASSERT_EQ(4U, res->body.size());
  3056. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3057. ASSERT_TRUE(res);
  3058. ASSERT_EQ(StatusCode::OK_200, res->status);
  3059. ASSERT_EQ(4U, res->body.size());
  3060. }
  3061. TEST_F(ServerTest, EmptyRequest) {
  3062. auto res = cli_.Get("");
  3063. ASSERT_TRUE(!res);
  3064. EXPECT_EQ(Error::Connection, res.error());
  3065. }
  3066. TEST_F(ServerTest, LongRequest) {
  3067. std::string request;
  3068. for (size_t i = 0; i < 545; i++) {
  3069. request += "/TooLongRequest";
  3070. }
  3071. request += "OK";
  3072. auto res = cli_.Get(request.c_str());
  3073. ASSERT_TRUE(res);
  3074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3075. }
  3076. TEST_F(ServerTest, TooLongRequest) {
  3077. std::string request;
  3078. for (size_t i = 0; i < 546; i++) {
  3079. request += "/TooLongRequest";
  3080. }
  3081. request += "_NG";
  3082. auto res = cli_.Get(request.c_str());
  3083. ASSERT_TRUE(res);
  3084. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3085. }
  3086. TEST_F(ServerTest, AlmostTooLongRequest) {
  3087. // test for #2046 - URI length check shouldn't include other content on req
  3088. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3089. // leading /, space, HTTP/1.1)
  3090. std::string request =
  3091. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3092. auto res = cli_.Get(request.c_str());
  3093. ASSERT_TRUE(res);
  3094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3095. }
  3096. TEST_F(ServerTest, LongHeader) {
  3097. Request req;
  3098. req.method = "GET";
  3099. req.path = "/hi";
  3100. std::string host_and_port;
  3101. host_and_port += HOST;
  3102. host_and_port += ":";
  3103. host_and_port += std::to_string(PORT);
  3104. req.headers.emplace("Host", host_and_port.c_str());
  3105. req.headers.emplace("Accept", "*/*");
  3106. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3107. req.headers.emplace(
  3108. "Header-Name",
  3109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3137. "@@@@@@@@@@@@@@@@");
  3138. auto res = std::make_shared<Response>();
  3139. auto error = Error::Success;
  3140. auto ret = cli_.send(req, *res, error);
  3141. ASSERT_TRUE(ret);
  3142. EXPECT_EQ(StatusCode::OK_200, res->status);
  3143. }
  3144. TEST_F(ServerTest, LongQueryValue) {
  3145. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3146. ASSERT_TRUE(res);
  3147. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3148. }
  3149. TEST_F(ServerTest, TooLongQueryValue) {
  3150. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3151. ASSERT_FALSE(res);
  3152. EXPECT_EQ(Error::Read, res.error());
  3153. }
  3154. TEST_F(ServerTest, TooLongHeader) {
  3155. Request req;
  3156. req.method = "GET";
  3157. req.path = "/hi";
  3158. std::string host_and_port;
  3159. host_and_port += HOST;
  3160. host_and_port += ":";
  3161. host_and_port += std::to_string(PORT);
  3162. req.headers.emplace("Host", host_and_port.c_str());
  3163. req.headers.emplace("Accept", "*/*");
  3164. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3165. req.headers.emplace(
  3166. "Header-Name",
  3167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3195. "@@@@@@@@@@@@@@@@@");
  3196. auto res = std::make_shared<Response>();
  3197. auto error = Error::Success;
  3198. auto ret = cli_.send(req, *res, error);
  3199. ASSERT_TRUE(ret);
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST_F(ServerTest, PercentEncoding) {
  3203. auto res = cli_.Get("/e%6edwith%");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST_F(ServerTest, PercentEncodingUnicode) {
  3208. auto res = cli_.Get("/e%u006edwith%");
  3209. ASSERT_TRUE(res);
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST_F(ServerTest, InvalidPercentEncoding) {
  3213. auto res = cli_.Get("/%endwith%");
  3214. ASSERT_TRUE(res);
  3215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3216. }
  3217. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3218. auto res = cli_.Get("/%uendwith%");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3221. }
  3222. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3223. auto res = cli_.Get("/hello?aaa=bbb%");
  3224. ASSERT_TRUE(res);
  3225. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3226. }
  3227. TEST_F(ServerTest, PlusSignEncoding) {
  3228. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3229. ASSERT_TRUE(res);
  3230. EXPECT_EQ(StatusCode::OK_200, res->status);
  3231. EXPECT_EQ("a +b", res->body);
  3232. }
  3233. TEST_F(ServerTest, MultipartFormData) {
  3234. MultipartFormDataItems items = {
  3235. {"text1", "text default", "", ""},
  3236. {"text2", "aωb", "", ""},
  3237. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3238. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3239. {"file3", "", "", "application/octet-stream"},
  3240. {"file4", "", "", " application/json tmp-string "}};
  3241. auto res = cli_.Post("/multipart", items);
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. }
  3245. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3246. MultipartFormDataItems items = {
  3247. {"text", "default text", "", ""},
  3248. {"multi_text1", "aaaaa", "", ""},
  3249. {"multi_text1", "bbbbb", "", ""},
  3250. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3251. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3252. "application/json"},
  3253. };
  3254. auto res = cli_.Post("/multipart/multi_file_values", items);
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. }
  3258. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3259. auto res = cli_.Get("/hi");
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3263. EXPECT_EQ("Hello World!", res->body);
  3264. }
  3265. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3266. Request req;
  3267. req.method = "POST";
  3268. req.path = "/chunked";
  3269. std::string host_and_port;
  3270. host_and_port += HOST;
  3271. host_and_port += ":";
  3272. host_and_port += std::to_string(PORT);
  3273. req.headers.emplace("Host", host_and_port.c_str());
  3274. req.headers.emplace("Accept", "*/*");
  3275. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3276. req.headers.emplace("Content-Type", "text/plain");
  3277. req.headers.emplace("Content-Length", "0");
  3278. req.headers.emplace(
  3279. "Transfer-Encoding",
  3280. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3281. // Client does not chunk, so make a chunked body manually.
  3282. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3283. auto res = std::make_shared<Response>();
  3284. auto error = Error::Success;
  3285. auto ret = cli_.send(req, *res, error);
  3286. ASSERT_TRUE(ret);
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST_F(ServerTest, GetStreamed2) {
  3290. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3291. ASSERT_TRUE(res);
  3292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3294. EXPECT_EQ(true, res->has_header("Content-Range"));
  3295. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3296. EXPECT_EQ(std::string("ab"), res->body);
  3297. }
  3298. TEST_F(ServerTest, GetStreamed) {
  3299. auto res = cli_.Get("/streamed");
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3303. EXPECT_EQ(std::string("aaabbb"), res->body);
  3304. }
  3305. TEST_F(ServerTest, GetStreamedWithRange1) {
  3306. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3309. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3310. EXPECT_EQ(true, res->has_header("Content-Range"));
  3311. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3312. EXPECT_EQ(std::string("def"), res->body);
  3313. }
  3314. TEST_F(ServerTest, GetStreamedWithRange2) {
  3315. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3316. ASSERT_TRUE(res);
  3317. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3318. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3319. EXPECT_EQ(true, res->has_header("Content-Range"));
  3320. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3321. EXPECT_EQ(std::string("bcdefg"), res->body);
  3322. }
  3323. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3324. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3325. ASSERT_TRUE(res);
  3326. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3327. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3328. EXPECT_EQ(true, res->has_header("Content-Range"));
  3329. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3330. EXPECT_EQ(std::string("efg"), res->body);
  3331. }
  3332. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3333. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3334. ASSERT_TRUE(res);
  3335. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3336. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3337. EXPECT_EQ(false, res->has_header("Content-Range"));
  3338. EXPECT_EQ(0U, res->body.size());
  3339. }
  3340. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3341. auto res = cli_.Get("/streamed-with-range",
  3342. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3343. "92233720368547758079223372036854775807"}});
  3344. ASSERT_TRUE(res);
  3345. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3346. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3347. EXPECT_EQ(false, res->has_header("Content-Range"));
  3348. EXPECT_EQ(0U, res->body.size());
  3349. }
  3350. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3351. auto res = cli_.Get(
  3352. "/with-range",
  3353. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3354. {"Accept-Encoding", ""}});
  3355. ASSERT_TRUE(res);
  3356. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3357. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3358. EXPECT_EQ(true, res->has_header("Content-Range"));
  3359. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3360. EXPECT_EQ(std::string("abcdefg"), res->body);
  3361. }
  3362. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3363. auto res = cli_.Get("/with-range", {
  3364. {"Range", "bytes=0-"},
  3365. {"Accept-Encoding", ""},
  3366. });
  3367. ASSERT_TRUE(res);
  3368. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3369. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3370. EXPECT_EQ(true, res->has_header("Content-Range"));
  3371. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3372. EXPECT_EQ(std::string("abcdefg"), res->body);
  3373. }
  3374. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3375. auto res =
  3376. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3377. ASSERT_TRUE(res);
  3378. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3379. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3380. EXPECT_EQ(false, res->has_header("Content-Range"));
  3381. EXPECT_EQ(267U, res->body.size());
  3382. }
  3383. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3384. Ranges ranges;
  3385. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3386. ranges.emplace_back(0, -1);
  3387. }
  3388. auto res =
  3389. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3392. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3393. EXPECT_EQ(false, res->has_header("Content-Range"));
  3394. EXPECT_EQ(0U, res->body.size());
  3395. }
  3396. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3397. auto res = cli_.Get("/streamed-with-range?error",
  3398. {{make_range_header({{0, -1}, {0, -1}})}});
  3399. ASSERT_TRUE(res);
  3400. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3401. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3402. EXPECT_EQ(false, res->has_header("Content-Range"));
  3403. EXPECT_EQ(0U, res->body.size());
  3404. }
  3405. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3406. auto res = cli_.Get("/streamed-with-range?error",
  3407. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3408. ASSERT_TRUE(res);
  3409. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3410. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3411. EXPECT_EQ(false, res->has_header("Content-Range"));
  3412. EXPECT_EQ(0U, res->body.size());
  3413. }
  3414. TEST_F(ServerTest, GetStreamedEndless) {
  3415. uint64_t offset = 0;
  3416. auto res = cli_.Get("/streamed-cancel",
  3417. [&](const char * /*data*/, uint64_t data_length) {
  3418. if (offset < 100) {
  3419. offset += data_length;
  3420. return true;
  3421. }
  3422. return false;
  3423. });
  3424. ASSERT_TRUE(!res);
  3425. EXPECT_EQ(Error::Canceled, res.error());
  3426. }
  3427. TEST_F(ServerTest, ClientStop) {
  3428. std::atomic_size_t count{4};
  3429. std::vector<std::thread> threads;
  3430. for (auto i = count.load(); i != 0; --i) {
  3431. threads.emplace_back([&]() {
  3432. auto res = cli_.Get("/streamed-cancel",
  3433. [&](const char *, uint64_t) { return true; });
  3434. --count;
  3435. ASSERT_TRUE(!res);
  3436. EXPECT_TRUE(res.error() == Error::Canceled ||
  3437. res.error() == Error::Read || res.error() == Error::Write);
  3438. });
  3439. }
  3440. std::this_thread::sleep_for(std::chrono::seconds(2));
  3441. while (count != 0) {
  3442. cli_.stop();
  3443. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3444. }
  3445. for (auto &t : threads) {
  3446. t.join();
  3447. }
  3448. }
  3449. TEST_F(ServerTest, GetWithRange1) {
  3450. auto res = cli_.Get("/with-range", {
  3451. make_range_header({{3, 5}}),
  3452. {"Accept-Encoding", ""},
  3453. });
  3454. ASSERT_TRUE(res);
  3455. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3456. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3457. EXPECT_EQ(true, res->has_header("Content-Range"));
  3458. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3459. EXPECT_EQ(std::string("def"), res->body);
  3460. }
  3461. TEST_F(ServerTest, GetWithRange2) {
  3462. auto res = cli_.Get("/with-range", {
  3463. make_range_header({{1, -1}}),
  3464. {"Accept-Encoding", ""},
  3465. });
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3469. EXPECT_EQ(true, res->has_header("Content-Range"));
  3470. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3471. EXPECT_EQ(std::string("bcdefg"), res->body);
  3472. }
  3473. TEST_F(ServerTest, GetWithRange3) {
  3474. auto res = cli_.Get("/with-range", {
  3475. make_range_header({{0, 0}}),
  3476. {"Accept-Encoding", ""},
  3477. });
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3480. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3481. EXPECT_EQ(true, res->has_header("Content-Range"));
  3482. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3483. EXPECT_EQ(std::string("a"), res->body);
  3484. }
  3485. TEST_F(ServerTest, GetWithRange4) {
  3486. auto res = cli_.Get("/with-range", {
  3487. make_range_header({{-1, 2}}),
  3488. {"Accept-Encoding", ""},
  3489. });
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3492. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3493. EXPECT_EQ(true, res->has_header("Content-Range"));
  3494. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3495. EXPECT_EQ(std::string("fg"), res->body);
  3496. }
  3497. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3498. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3501. }
  3502. TEST_F(ServerTest, GetWithRangeMultipart) {
  3503. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3506. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3507. EXPECT_EQ(false, res->has_header("Content-Range"));
  3508. EXPECT_EQ(267U, res->body.size());
  3509. }
  3510. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3511. auto res =
  3512. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3515. }
  3516. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3517. auto res = cli_.Get("/with-range-customized-response",
  3518. {{make_range_header({{1, 2}})}});
  3519. ASSERT_TRUE(res);
  3520. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3521. EXPECT_EQ(true, res->has_header("Content-Length"));
  3522. EXPECT_EQ(false, res->has_header("Content-Range"));
  3523. EXPECT_EQ(JSON_DATA, res->body);
  3524. }
  3525. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3526. auto res = cli_.Get("/with-range-customized-response",
  3527. {{make_range_header({{1, 2}, {4, 5}})}});
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3530. EXPECT_EQ(true, res->has_header("Content-Length"));
  3531. EXPECT_EQ(false, res->has_header("Content-Range"));
  3532. EXPECT_EQ(JSON_DATA, res->body);
  3533. }
  3534. TEST_F(ServerTest, Issue1772) {
  3535. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3536. ASSERT_TRUE(res);
  3537. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3538. }
  3539. TEST_F(ServerTest, Issue609) {
  3540. auto res = cli_.Delete("/issue609");
  3541. ASSERT_TRUE(res);
  3542. EXPECT_EQ(StatusCode::OK_200, res->status);
  3543. EXPECT_EQ(std::string("ok"), res->body);
  3544. }
  3545. TEST_F(ServerTest, GetStreamedChunked) {
  3546. auto res = cli_.Get("/streamed-chunked");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::OK_200, res->status);
  3549. EXPECT_EQ(std::string("123456789"), res->body);
  3550. }
  3551. TEST_F(ServerTest, GetStreamedChunked2) {
  3552. auto res = cli_.Get("/streamed-chunked2");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. EXPECT_EQ(std::string("123456789"), res->body);
  3556. }
  3557. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3558. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ(std::string("123456789"), res->body);
  3562. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3563. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3564. }
  3565. TEST_F(ServerTest, LargeChunkedPost) {
  3566. Request req;
  3567. req.method = "POST";
  3568. req.path = "/large-chunked";
  3569. std::string host_and_port;
  3570. host_and_port += HOST;
  3571. host_and_port += ":";
  3572. host_and_port += std::to_string(PORT);
  3573. req.headers.emplace("Host", host_and_port.c_str());
  3574. req.headers.emplace("Accept", "*/*");
  3575. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3576. req.headers.emplace("Content-Type", "text/plain");
  3577. req.headers.emplace("Content-Length", "0");
  3578. req.headers.emplace("Transfer-Encoding", "chunked");
  3579. std::string long_string(30 * 1024u, 'a');
  3580. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3581. // Attempt to make a large enough post to exceed OS buffers, to test that
  3582. // the server handles short reads if the full chunk data isn't available.
  3583. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3584. auto res = std::make_shared<Response>();
  3585. auto error = Error::Success;
  3586. auto ret = cli_.send(req, *res, error);
  3587. ASSERT_TRUE(ret);
  3588. EXPECT_EQ(StatusCode::OK_200, res->status);
  3589. }
  3590. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3591. auto res = cli_.Get("/remote_addr");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::OK_200, res->status);
  3594. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3595. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3596. }
  3597. TEST_F(ServerTest, GetMethodLocalAddr) {
  3598. auto res = cli_.Get("/local_addr");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::OK_200, res->status);
  3601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3602. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3603. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3604. }
  3605. TEST_F(ServerTest, HTTPResponseSplitting) {
  3606. auto res = cli_.Get("/http_response_splitting");
  3607. ASSERT_TRUE(res);
  3608. EXPECT_EQ(StatusCode::OK_200, res->status);
  3609. }
  3610. TEST_F(ServerTest, SlowRequest) {
  3611. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3612. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3613. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3614. }
  3615. #if 0
  3616. TEST_F(ServerTest, SlowPost) {
  3617. char buffer[64 * 1024];
  3618. memset(buffer, 0x42, sizeof(buffer));
  3619. auto res = cli_.Post(
  3620. "/slowpost", 64 * 1024 * 1024,
  3621. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3622. auto ret = sink.write(buffer, sizeof(buffer));
  3623. EXPECT_TRUE(ret);
  3624. return true;
  3625. },
  3626. "text/plain");
  3627. ASSERT_TRUE(res);
  3628. EXPECT_EQ(StatusCode::OK_200, res->status);
  3629. }
  3630. TEST_F(ServerTest, SlowPostFail) {
  3631. char buffer[64 * 1024];
  3632. memset(buffer, 0x42, sizeof(buffer));
  3633. cli_.set_write_timeout(std::chrono::seconds(0));
  3634. auto res = cli_.Post(
  3635. "/slowpost", 64 * 1024 * 1024,
  3636. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3637. sink.write(buffer, sizeof(buffer));
  3638. return true;
  3639. },
  3640. "text/plain");
  3641. ASSERT_TRUE(!res);
  3642. EXPECT_EQ(Error::Write, res.error());
  3643. }
  3644. #endif
  3645. TEST_F(ServerTest, Put) {
  3646. auto res = cli_.Put("/put", "PUT", "text/plain");
  3647. ASSERT_TRUE(res);
  3648. EXPECT_EQ(StatusCode::OK_200, res->status);
  3649. EXPECT_EQ("PUT", res->body);
  3650. }
  3651. TEST_F(ServerTest, PutWithContentProvider) {
  3652. auto res = cli_.Put(
  3653. "/put", 3,
  3654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3655. sink.os << "PUT";
  3656. return true;
  3657. },
  3658. "text/plain");
  3659. ASSERT_TRUE(res);
  3660. EXPECT_EQ(StatusCode::OK_200, res->status);
  3661. EXPECT_EQ("PUT", res->body);
  3662. }
  3663. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3664. auto res = cli_.Post(
  3665. "/post", 42,
  3666. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3667. return false;
  3668. },
  3669. "text/plain");
  3670. ASSERT_TRUE(!res);
  3671. EXPECT_EQ(Error::Canceled, res.error());
  3672. }
  3673. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3674. auto res = cli_.Put(
  3675. "/put",
  3676. [](size_t /*offset*/, DataSink &sink) {
  3677. sink.os << "PUT";
  3678. sink.done();
  3679. return true;
  3680. },
  3681. "text/plain");
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::OK_200, res->status);
  3684. EXPECT_EQ("PUT", res->body);
  3685. }
  3686. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  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. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3694. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3695. cli_.set_compress(true);
  3696. auto res = cli_.Put(
  3697. "/put", 3,
  3698. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3699. sink.os << "PUT";
  3700. return true;
  3701. },
  3702. "text/plain");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("PUT", res->body);
  3706. }
  3707. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3708. cli_.set_compress(true);
  3709. auto res = cli_.Post(
  3710. "/post", 42,
  3711. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3712. return false;
  3713. },
  3714. "text/plain");
  3715. ASSERT_TRUE(!res);
  3716. EXPECT_EQ(Error::Canceled, res.error());
  3717. }
  3718. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3719. cli_.set_compress(true);
  3720. auto res = cli_.Put(
  3721. "/put",
  3722. [](size_t /*offset*/, DataSink &sink) {
  3723. sink.os << "PUT";
  3724. sink.done();
  3725. return true;
  3726. },
  3727. "text/plain");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. EXPECT_EQ("PUT", res->body);
  3731. }
  3732. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3733. cli_.set_compress(true);
  3734. auto res = cli_.Post(
  3735. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3736. "text/plain");
  3737. ASSERT_TRUE(!res);
  3738. EXPECT_EQ(Error::Canceled, res.error());
  3739. }
  3740. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3741. cli_.set_compress(true);
  3742. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3743. ASSERT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. EXPECT_EQ(LARGE_DATA, res->body);
  3746. }
  3747. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3748. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3749. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3750. Client cli(s.c_str());
  3751. cli.enable_server_certificate_verification(false);
  3752. #else
  3753. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3754. Client cli(s.c_str());
  3755. #endif
  3756. cli.set_compress(true);
  3757. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3758. ASSERT_TRUE(res);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ(LARGE_DATA, res->body);
  3761. // The compressed size should be less than a 10th of the original. May vary
  3762. // depending on the zlib library.
  3763. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  3764. static_cast<uint64_t>(10 * 1024 * 1024));
  3765. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3766. }
  3767. TEST_F(ServerTest, PutContentWithDeflate) {
  3768. cli_.set_compress(false);
  3769. Headers headers;
  3770. headers.emplace("Content-Encoding", "deflate");
  3771. // PUT in deflate format:
  3772. auto res = cli_.Put("/put", headers,
  3773. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. EXPECT_EQ("PUT", res->body);
  3777. }
  3778. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3779. Headers headers;
  3780. headers.emplace("Accept-Encoding", "gzip, deflate");
  3781. auto res = cli_.Get("/streamed-chunked", headers);
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::OK_200, res->status);
  3784. EXPECT_EQ(std::string("123456789"), res->body);
  3785. }
  3786. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3787. Headers headers;
  3788. headers.emplace("Accept-Encoding", "gzip, deflate");
  3789. auto res = cli_.Get("/streamed-chunked2", headers);
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ(std::string("123456789"), res->body);
  3793. }
  3794. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3795. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::OK_200, res->status);
  3798. }
  3799. TEST(GzipDecompressor, ChunkedDecompression) {
  3800. std::string data;
  3801. for (size_t i = 0; i < 32 * 1024; ++i) {
  3802. data.push_back(static_cast<char>('a' + i % 26));
  3803. }
  3804. std::string compressed_data;
  3805. {
  3806. httplib::detail::gzip_compressor compressor;
  3807. bool result = compressor.compress(
  3808. data.data(), data.size(),
  3809. /*last=*/true,
  3810. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3811. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3812. compressed_data_size);
  3813. return true;
  3814. });
  3815. ASSERT_TRUE(result);
  3816. }
  3817. std::string decompressed_data;
  3818. {
  3819. httplib::detail::gzip_decompressor decompressor;
  3820. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3821. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3822. size_t chunk_size = 130;
  3823. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3824. chunk_begin += chunk_size) {
  3825. size_t current_chunk_size =
  3826. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3827. bool result = decompressor.decompress(
  3828. compressed_data.data() + chunk_begin, current_chunk_size,
  3829. [&](const char *decompressed_data_chunk,
  3830. size_t decompressed_data_chunk_size) {
  3831. decompressed_data.insert(decompressed_data.size(),
  3832. decompressed_data_chunk,
  3833. decompressed_data_chunk_size);
  3834. return true;
  3835. });
  3836. ASSERT_TRUE(result);
  3837. }
  3838. }
  3839. ASSERT_EQ(data, decompressed_data);
  3840. }
  3841. TEST(GzipDecompressor, DeflateDecompression) {
  3842. std::string original_text = "Raw deflate without gzip";
  3843. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3844. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3845. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3846. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3847. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3848. std::string decompressed_data;
  3849. {
  3850. httplib::detail::gzip_decompressor decompressor;
  3851. bool result = decompressor.decompress(
  3852. compressed_data.data(), compressed_data.size(),
  3853. [&](const char *decompressed_data_chunk,
  3854. size_t decompressed_data_chunk_size) {
  3855. decompressed_data.insert(decompressed_data.size(),
  3856. decompressed_data_chunk,
  3857. decompressed_data_chunk_size);
  3858. return true;
  3859. });
  3860. ASSERT_TRUE(result);
  3861. }
  3862. ASSERT_EQ(original_text, decompressed_data);
  3863. }
  3864. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3865. std::string original_text = "Raw deflate without gzip";
  3866. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3867. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3868. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3869. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3870. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3871. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3872. std::string decompressed_data;
  3873. {
  3874. httplib::detail::gzip_decompressor decompressor;
  3875. bool result = decompressor.decompress(
  3876. compressed_data.data(), compressed_data.size(),
  3877. [&](const char *decompressed_data_chunk,
  3878. size_t decompressed_data_chunk_size) {
  3879. decompressed_data.insert(decompressed_data.size(),
  3880. decompressed_data_chunk,
  3881. decompressed_data_chunk_size);
  3882. return true;
  3883. });
  3884. ASSERT_TRUE(result);
  3885. }
  3886. ASSERT_EQ(original_text, decompressed_data);
  3887. }
  3888. #ifdef _WIN32
  3889. TEST(GzipDecompressor, LargeRandomData) {
  3890. // prepare large random data that is difficult to be compressed and is
  3891. // expected to have large size even when compressed
  3892. std::random_device seed_gen;
  3893. std::mt19937 random(seed_gen());
  3894. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3895. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3896. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3897. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3898. // compress data over 4GiB
  3899. std::string compressed_data;
  3900. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3901. httplib::detail::gzip_compressor compressor;
  3902. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3903. data.size() * sizeof(std::uint32_t), true,
  3904. [&](const char *data, size_t size) {
  3905. compressed_data.insert(
  3906. compressed_data.size(), data, size);
  3907. return true;
  3908. });
  3909. ASSERT_TRUE(result);
  3910. // FIXME: compressed data size is expected to be greater than 4GiB,
  3911. // but there is no guarantee
  3912. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3913. // decompress data over 4GiB
  3914. std::string decompressed_data;
  3915. decompressed_data.reserve(data_size);
  3916. httplib::detail::gzip_decompressor decompressor;
  3917. result = decompressor.decompress(
  3918. compressed_data.data(), compressed_data.size(),
  3919. [&](const char *data, size_t size) {
  3920. decompressed_data.insert(decompressed_data.size(), data, size);
  3921. return true;
  3922. });
  3923. ASSERT_TRUE(result);
  3924. // compare
  3925. ASSERT_EQ(data_size, decompressed_data.size());
  3926. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3927. 0);
  3928. }
  3929. #endif
  3930. #endif
  3931. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3932. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3933. Headers headers;
  3934. headers.emplace("Accept-Encoding", "br");
  3935. auto res = cli_.Get("/streamed-chunked", headers);
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ(StatusCode::OK_200, res->status);
  3938. EXPECT_EQ(std::string("123456789"), res->body);
  3939. }
  3940. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3941. Headers headers;
  3942. headers.emplace("Accept-Encoding", "br");
  3943. auto res = cli_.Get("/streamed-chunked2", headers);
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ(std::string("123456789"), res->body);
  3947. }
  3948. #endif
  3949. TEST_F(ServerTest, Patch) {
  3950. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. EXPECT_EQ("PATCH", res->body);
  3954. }
  3955. TEST_F(ServerTest, Delete) {
  3956. auto res = cli_.Delete("/delete");
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::OK_200, res->status);
  3959. EXPECT_EQ("DELETE", res->body);
  3960. }
  3961. TEST_F(ServerTest, DeleteContentReceiver) {
  3962. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3963. ASSERT_TRUE(res);
  3964. EXPECT_EQ(StatusCode::OK_200, res->status);
  3965. EXPECT_EQ("content", res->body);
  3966. }
  3967. TEST_F(ServerTest, Options) {
  3968. auto res = cli_.Options("*");
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3972. EXPECT_TRUE(res->body.empty());
  3973. }
  3974. TEST_F(ServerTest, URL) {
  3975. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::OK_200, res->status);
  3978. }
  3979. TEST_F(ServerTest, ArrayParam) {
  3980. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3981. ASSERT_TRUE(res);
  3982. EXPECT_EQ(StatusCode::OK_200, res->status);
  3983. }
  3984. TEST_F(ServerTest, NoMultipleHeaders) {
  3985. Headers headers = {{"Content-Length", "5"}};
  3986. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3987. "text/plain");
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. }
  3991. TEST_F(ServerTest, PostContentReceiver) {
  3992. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3993. ASSERT_TRUE(res);
  3994. ASSERT_EQ(StatusCode::OK_200, res->status);
  3995. ASSERT_EQ("content", res->body);
  3996. }
  3997. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3998. MultipartFormDataItems items = {
  3999. {"text1", "text default", "", ""},
  4000. {"text2", "aωb", "", ""},
  4001. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4002. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4003. {"file3", "", "", "application/octet-stream"},
  4004. };
  4005. auto res = cli_.Post("/content_receiver", items);
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::OK_200, res->status);
  4008. }
  4009. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4010. MultipartFormDataItems items = {
  4011. {"text1", "text default", "", ""},
  4012. {"text2", "aωb", "", ""},
  4013. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4014. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4015. {"file3", "", "", "application/octet-stream"},
  4016. };
  4017. auto boundary = std::string("+++++");
  4018. std::string body;
  4019. for (const auto &item : items) {
  4020. body += "--" + boundary + "\r\n";
  4021. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4022. if (!item.filename.empty()) {
  4023. body += "; filename=\"" + item.filename + "\"";
  4024. }
  4025. body += "\r\n";
  4026. if (!item.content_type.empty()) {
  4027. body += "Content-Type: " + item.content_type + "\r\n";
  4028. }
  4029. body += "\r\n";
  4030. body += item.content + "\r\n";
  4031. }
  4032. body += "--" + boundary + "--\r\n";
  4033. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4034. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::OK_200, res->status);
  4037. }
  4038. TEST_F(ServerTest, PostContentReceiverGzip) {
  4039. cli_.set_compress(true);
  4040. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4041. ASSERT_TRUE(res);
  4042. ASSERT_EQ(StatusCode::OK_200, res->status);
  4043. ASSERT_EQ("content", res->body);
  4044. }
  4045. TEST_F(ServerTest, PutContentReceiver) {
  4046. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4047. ASSERT_TRUE(res);
  4048. ASSERT_EQ(StatusCode::OK_200, res->status);
  4049. ASSERT_EQ("content", res->body);
  4050. }
  4051. TEST_F(ServerTest, PatchContentReceiver) {
  4052. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4053. ASSERT_TRUE(res);
  4054. ASSERT_EQ(StatusCode::OK_200, res->status);
  4055. ASSERT_EQ("content", res->body);
  4056. }
  4057. TEST_F(ServerTest, PostQueryStringAndBody) {
  4058. auto res =
  4059. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4060. ASSERT_TRUE(res);
  4061. ASSERT_EQ(StatusCode::OK_200, res->status);
  4062. }
  4063. TEST_F(ServerTest, HTTP2Magic) {
  4064. Request req;
  4065. req.method = "PRI";
  4066. req.path = "*";
  4067. req.body = "SM";
  4068. auto res = std::make_shared<Response>();
  4069. auto error = Error::Success;
  4070. auto ret = cli_.send(req, *res, error);
  4071. ASSERT_TRUE(ret);
  4072. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4073. }
  4074. TEST_F(ServerTest, KeepAlive) {
  4075. auto res = cli_.Get("/hi");
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4079. EXPECT_EQ("Hello World!", res->body);
  4080. res = cli_.Get("/hi");
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::OK_200, res->status);
  4083. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4084. EXPECT_EQ("Hello World!", res->body);
  4085. res = cli_.Get("/hi");
  4086. ASSERT_TRUE(res);
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4089. EXPECT_EQ("Hello World!", res->body);
  4090. res = cli_.Get("/not-exist");
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4093. res = cli_.Post("/empty", "", "text/plain");
  4094. ASSERT_TRUE(res);
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4097. EXPECT_EQ("empty", res->body);
  4098. EXPECT_EQ("close", res->get_header_value("Connection"));
  4099. res = cli_.Post(
  4100. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4101. "text/plain");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4105. EXPECT_EQ("empty", res->body);
  4106. cli_.set_keep_alive(false);
  4107. res = cli_.Get("/last-request");
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::OK_200, res->status);
  4110. EXPECT_EQ("close", res->get_header_value("Connection"));
  4111. }
  4112. TEST_F(ServerTest, TooManyRedirect) {
  4113. cli_.set_follow_location(true);
  4114. auto res = cli_.Get("/redirect/0");
  4115. ASSERT_TRUE(!res);
  4116. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4117. }
  4118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4119. TEST_F(ServerTest, Gzip) {
  4120. Headers headers;
  4121. headers.emplace("Accept-Encoding", "gzip, deflate");
  4122. auto res = cli_.Get("/compress", headers);
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4126. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4127. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4128. "7890123456789012345678901234567890",
  4129. res->body);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. }
  4132. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4133. Headers headers;
  4134. headers.emplace("Accept-Encoding", "");
  4135. auto res = cli_.Get("/compress", headers);
  4136. ASSERT_TRUE(res);
  4137. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4139. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4141. "7890123456789012345678901234567890",
  4142. res->body);
  4143. EXPECT_EQ(StatusCode::OK_200, res->status);
  4144. }
  4145. TEST_F(ServerTest, GzipWithContentReceiver) {
  4146. Headers headers;
  4147. headers.emplace("Accept-Encoding", "gzip, deflate");
  4148. std::string body;
  4149. auto res = cli_.Get("/compress", headers,
  4150. [&](const char *data, uint64_t data_length) {
  4151. EXPECT_EQ(100U, data_length);
  4152. body.append(data, data_length);
  4153. return true;
  4154. });
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4158. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4159. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4160. "7890123456789012345678901234567890",
  4161. body);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. }
  4164. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4165. Headers headers;
  4166. headers.emplace("Accept-Encoding", "gzip, deflate");
  4167. cli_.set_decompress(false);
  4168. auto res = cli_.Get("/compress", headers);
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4172. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4173. EXPECT_EQ(33U, res->body.size());
  4174. EXPECT_EQ(StatusCode::OK_200, res->status);
  4175. }
  4176. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4177. Headers headers;
  4178. headers.emplace("Accept-Encoding", "");
  4179. std::string body;
  4180. auto res = cli_.Get("/compress", headers,
  4181. [&](const char *data, uint64_t data_length) {
  4182. EXPECT_EQ(100U, data_length);
  4183. body.append(data, data_length);
  4184. return true;
  4185. });
  4186. ASSERT_TRUE(res);
  4187. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4189. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4190. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4191. "7890123456789012345678901234567890",
  4192. body);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. }
  4195. TEST_F(ServerTest, NoGzip) {
  4196. Headers headers;
  4197. headers.emplace("Accept-Encoding", "gzip, deflate");
  4198. auto res = cli_.Get("/nocompress", headers);
  4199. ASSERT_TRUE(res);
  4200. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4201. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4202. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4203. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4204. "7890123456789012345678901234567890",
  4205. res->body);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. }
  4208. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4209. Headers headers;
  4210. headers.emplace("Accept-Encoding", "gzip, deflate");
  4211. std::string body;
  4212. auto res = cli_.Get("/nocompress", headers,
  4213. [&](const char *data, uint64_t data_length) {
  4214. EXPECT_EQ(100U, data_length);
  4215. body.append(data, data_length);
  4216. return true;
  4217. });
  4218. ASSERT_TRUE(res);
  4219. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4220. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4221. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4223. "7890123456789012345678901234567890",
  4224. body);
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. }
  4227. TEST_F(ServerTest, MultipartFormDataGzip) {
  4228. MultipartFormDataItems items = {
  4229. {"key1", "test", "", ""},
  4230. {"key2", "--abcdefg123", "", ""},
  4231. };
  4232. cli_.set_compress(true);
  4233. auto res = cli_.Post("/compress-multipart", items);
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. }
  4237. #endif
  4238. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4239. TEST_F(ServerTest, Brotli) {
  4240. Headers headers;
  4241. headers.emplace("Accept-Encoding", "br");
  4242. auto res = cli_.Get("/compress", headers);
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4246. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4247. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4248. "7890123456789012345678901234567890",
  4249. res->body);
  4250. EXPECT_EQ(StatusCode::OK_200, res->status);
  4251. }
  4252. #endif
  4253. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4254. TEST_F(ServerTest, Zstd) {
  4255. Headers headers;
  4256. headers.emplace("Accept-Encoding", "zstd");
  4257. auto res = cli_.Get("/compress", headers);
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4261. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4262. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4263. "7890123456789012345678901234567890",
  4264. res->body);
  4265. EXPECT_EQ(StatusCode::OK_200, res->status);
  4266. }
  4267. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4268. Headers headers;
  4269. headers.emplace("Accept-Encoding", "");
  4270. auto res = cli_.Get("/compress", headers);
  4271. ASSERT_TRUE(res);
  4272. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4276. "7890123456789012345678901234567890",
  4277. res->body);
  4278. EXPECT_EQ(StatusCode::OK_200, res->status);
  4279. }
  4280. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4281. Headers headers;
  4282. headers.emplace("Accept-Encoding", "zstd");
  4283. std::string body;
  4284. auto res = cli_.Get("/compress", headers,
  4285. [&](const char *data, uint64_t data_length) {
  4286. EXPECT_EQ(100U, data_length);
  4287. body.append(data, data_length);
  4288. return true;
  4289. });
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4293. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4294. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4295. "7890123456789012345678901234567890",
  4296. body);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4300. Headers headers;
  4301. headers.emplace("Accept-Encoding", "zstd");
  4302. cli_.set_decompress(false);
  4303. auto res = cli_.Get("/compress", headers);
  4304. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4305. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4306. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4307. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4311. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4312. EXPECT_EQ(StatusCode::OK_200, res->status);
  4313. ASSERT_EQ(26U, res->body.size());
  4314. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4315. 0);
  4316. }
  4317. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4318. Headers headers;
  4319. headers.emplace("Accept-Encoding", "");
  4320. std::string body;
  4321. auto res = cli_.Get("/compress", headers,
  4322. [&](const char *data, uint64_t data_length) {
  4323. EXPECT_EQ(100U, data_length);
  4324. body.append(data, data_length);
  4325. return true;
  4326. });
  4327. ASSERT_TRUE(res);
  4328. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4330. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4331. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4332. "7890123456789012345678901234567890",
  4333. body);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. }
  4336. TEST_F(ServerTest, NoZstd) {
  4337. Headers headers;
  4338. headers.emplace("Accept-Encoding", "zstd");
  4339. auto res = cli_.Get("/nocompress", headers);
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4342. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4343. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4345. "7890123456789012345678901234567890",
  4346. res->body);
  4347. EXPECT_EQ(StatusCode::OK_200, res->status);
  4348. }
  4349. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4350. Headers headers;
  4351. headers.emplace("Accept-Encoding", "zstd");
  4352. std::string body;
  4353. auto res = cli_.Get("/nocompress", headers,
  4354. [&](const char *data, uint64_t data_length) {
  4355. EXPECT_EQ(100U, data_length);
  4356. body.append(data, data_length);
  4357. return true;
  4358. });
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4361. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4362. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4363. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4364. "7890123456789012345678901234567890",
  4365. body);
  4366. EXPECT_EQ(StatusCode::OK_200, res->status);
  4367. }
  4368. // TODO: How to enable zstd ??
  4369. TEST_F(ServerTest, MultipartFormDataZstd) {
  4370. MultipartFormDataItems items = {
  4371. {"key1", "test", "", ""},
  4372. {"key2", "--abcdefg123", "", ""},
  4373. };
  4374. Headers headers;
  4375. headers.emplace("Accept-Encoding", "zstd");
  4376. cli_.set_compress(true);
  4377. auto res = cli_.Post("/compress-multipart", headers, items);
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(StatusCode::OK_200, res->status);
  4380. }
  4381. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4382. Headers headers;
  4383. headers.emplace("Accept-Encoding", "zstd");
  4384. cli_.set_compress(true);
  4385. auto res = cli_.Put(
  4386. "/put", headers, 3,
  4387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4388. sink.os << "PUT";
  4389. return true;
  4390. },
  4391. "text/plain");
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::OK_200, res->status);
  4394. EXPECT_EQ("PUT", res->body);
  4395. }
  4396. TEST(ZstdDecompressor, ChunkedDecompression) {
  4397. std::string data;
  4398. for (size_t i = 0; i < 32 * 1024; ++i) {
  4399. data.push_back(static_cast<char>('a' + i % 26));
  4400. }
  4401. std::string compressed_data;
  4402. {
  4403. httplib::detail::zstd_compressor compressor;
  4404. bool result = compressor.compress(
  4405. data.data(), data.size(),
  4406. /*last=*/true,
  4407. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4408. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4409. compressed_data_size);
  4410. return true;
  4411. });
  4412. ASSERT_TRUE(result);
  4413. }
  4414. std::string decompressed_data;
  4415. {
  4416. httplib::detail::zstd_decompressor decompressor;
  4417. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4418. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4419. size_t chunk_size = 130;
  4420. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4421. chunk_begin += chunk_size) {
  4422. size_t current_chunk_size =
  4423. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4424. bool result = decompressor.decompress(
  4425. compressed_data.data() + chunk_begin, current_chunk_size,
  4426. [&](const char *decompressed_data_chunk,
  4427. size_t decompressed_data_chunk_size) {
  4428. decompressed_data.insert(decompressed_data.size(),
  4429. decompressed_data_chunk,
  4430. decompressed_data_chunk_size);
  4431. return true;
  4432. });
  4433. ASSERT_TRUE(result);
  4434. }
  4435. }
  4436. ASSERT_EQ(data, decompressed_data);
  4437. }
  4438. TEST(ZstdDecompressor, Decompress) {
  4439. std::string original_text = "Compressed with ZSTD";
  4440. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4441. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4442. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4443. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4444. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4445. std::string decompressed_data;
  4446. {
  4447. httplib::detail::zstd_decompressor decompressor;
  4448. bool result = decompressor.decompress(
  4449. compressed_data.data(), compressed_data.size(),
  4450. [&](const char *decompressed_data_chunk,
  4451. size_t decompressed_data_chunk_size) {
  4452. decompressed_data.insert(decompressed_data.size(),
  4453. decompressed_data_chunk,
  4454. decompressed_data_chunk_size);
  4455. return true;
  4456. });
  4457. ASSERT_TRUE(result);
  4458. }
  4459. ASSERT_EQ(original_text, decompressed_data);
  4460. }
  4461. #endif
  4462. // Sends a raw request to a server listening at HOST:PORT.
  4463. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4464. std::string *resp = nullptr) {
  4465. auto error = Error::Success;
  4466. auto client_sock = detail::create_client_socket(
  4467. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4468. /*connection_timeout_sec=*/5, 0,
  4469. /*read_timeout_sec=*/5, 0,
  4470. /*write_timeout_sec=*/5, 0, std::string(), error);
  4471. if (client_sock == INVALID_SOCKET) { return false; }
  4472. auto ret = detail::process_client_socket(
  4473. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4474. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4475. if (req.size() !=
  4476. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4477. return false;
  4478. }
  4479. char buf[512];
  4480. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4481. while (line_reader.getline()) {
  4482. if (resp) { *resp += line_reader.ptr(); }
  4483. }
  4484. return true;
  4485. });
  4486. detail::close_socket(client_sock);
  4487. return ret;
  4488. }
  4489. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4490. Server svr;
  4491. std::string header_value;
  4492. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4493. header_value = req.get_header_value("foo");
  4494. res.set_content("ok", "text/plain");
  4495. });
  4496. thread t = thread([&] { svr.listen(HOST, PORT); });
  4497. auto se = detail::scope_exit([&] {
  4498. svr.stop();
  4499. t.join();
  4500. ASSERT_FALSE(svr.is_running());
  4501. });
  4502. svr.wait_until_ready();
  4503. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4504. // like characters are not treated the same - use vertical tab and escape.
  4505. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4506. "foo: \t \v bar \x1B\t \r\n"
  4507. "Connection: close\r\n"
  4508. "\r\n";
  4509. std::string res;
  4510. ASSERT_TRUE(send_request(5, req, &res));
  4511. EXPECT_EQ(header_value, "");
  4512. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4513. }
  4514. // Sends a raw request and verifies that there isn't a crash or exception.
  4515. static void test_raw_request(const std::string &req,
  4516. std::string *out = nullptr) {
  4517. Server svr;
  4518. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4519. res.set_content("ok", "text/plain");
  4520. });
  4521. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4522. res.set_content("ok", "text/plain");
  4523. });
  4524. svr.Get("/header_field_value_check",
  4525. [&](const Request & /*req*/, Response &res) {
  4526. res.set_content("ok", "text/plain");
  4527. });
  4528. // Server read timeout must be longer than the client read timeout for the
  4529. // bug to reproduce, probably to force the server to process a request
  4530. // without a trailing blank line.
  4531. const time_t client_read_timeout_sec = 1;
  4532. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4533. bool listen_thread_ok = false;
  4534. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4535. auto se = detail::scope_exit([&] {
  4536. svr.stop();
  4537. t.join();
  4538. ASSERT_FALSE(svr.is_running());
  4539. EXPECT_TRUE(listen_thread_ok);
  4540. });
  4541. svr.wait_until_ready();
  4542. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4543. }
  4544. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4545. // A certain header line causes an exception if the header property is parsed
  4546. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4547. test_raw_request(
  4548. "GET /hi HTTP/1.1\r\n"
  4549. " : "
  4550. " "
  4551. " ");
  4552. }
  4553. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4554. // A certain header line causes an exception if the header property *name* is
  4555. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4556. // greedy matcher and requires backtracking when there are a lot of ":"
  4557. // characters.
  4558. // This occurs with libc++ but not libstdc++.
  4559. test_raw_request(
  4560. "GET /hi HTTP/1.1\r\n"
  4561. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4562. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4563. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4564. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4565. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4566. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4567. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4568. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4569. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4570. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4571. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4572. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4573. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4574. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4575. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4576. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4577. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4578. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4579. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4580. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4581. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4582. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4583. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4584. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4585. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4586. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4587. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4588. "&&&%%%");
  4589. }
  4590. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4591. // Make sure this doesn't crash the server.
  4592. // In a previous version of the header line regex, the "\r" rendered the line
  4593. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4594. // a new position where the leading white space ended and the field value
  4595. // began.
  4596. // The crash occurs with libc++ but not libstdc++.
  4597. test_raw_request("GET /hi HTTP/1.1\r\n"
  4598. "a:" +
  4599. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4600. "\r\n"
  4601. "\r\n");
  4602. }
  4603. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4604. std::string out;
  4605. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4606. "Content-Type: text/plain\r\n"
  4607. "Transfer-Encoding: chunked\r\n"
  4608. "\r\n"
  4609. "nothex\r\n",
  4610. &out);
  4611. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4612. }
  4613. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4614. std::string out;
  4615. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4616. "Content-Type: text/plain\r\n"
  4617. "Transfer-Encoding: chunked\r\n"
  4618. "\r\n"
  4619. "3\r\n"
  4620. "xyz\r\n"
  4621. "NaN\r\n",
  4622. &out);
  4623. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4624. }
  4625. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4626. std::string out;
  4627. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4628. "Content-Type: text/plain\r\n"
  4629. "Transfer-Encoding: chunked\r\n"
  4630. "\r\n"
  4631. // Length is too large for 64 bits.
  4632. "1ffffffffffffffff\r\n"
  4633. "xyz\r\n",
  4634. &out);
  4635. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4636. }
  4637. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4638. test_raw_request("GET /hi HTTP/1.1\r\n"
  4639. "Content-Type: text/plain\r\n\r");
  4640. }
  4641. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4642. std::string out;
  4643. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4644. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4645. }
  4646. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4647. std::string out;
  4648. std::string request(
  4649. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4650. test_raw_request(request, &out);
  4651. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4652. }
  4653. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  4654. std::string out;
  4655. std::string request(
  4656. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  4657. test_raw_request(request, &out);
  4658. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4659. }
  4660. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  4661. std::string out;
  4662. std::string request(
  4663. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  4664. test_raw_request(request, &out);
  4665. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4666. }
  4667. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  4668. std::string out;
  4669. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  4670. "Test: \r\n\r\n",
  4671. &out);
  4672. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  4673. }
  4674. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4675. Server svr;
  4676. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4677. res.set_header("Cache-Control", "no-cache");
  4678. res.set_chunked_content_provider(
  4679. "text/event-stream", [](size_t offset, DataSink &sink) {
  4680. std::string s = "data:";
  4681. s += std::to_string(offset);
  4682. s += "\n\n";
  4683. auto ret = sink.write(s.data(), s.size());
  4684. EXPECT_TRUE(ret);
  4685. std::this_thread::sleep_for(std::chrono::seconds(1));
  4686. return true;
  4687. });
  4688. });
  4689. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4690. svr.wait_until_ready();
  4691. Client client(HOST, PORT);
  4692. const Headers headers = {{"Accept", "text/event-stream"}};
  4693. auto get_thread = std::thread([&client, &headers]() {
  4694. auto res = client.Get(
  4695. "/events", headers,
  4696. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4697. });
  4698. auto se = detail::scope_exit([&] {
  4699. svr.stop();
  4700. get_thread.join();
  4701. listen_thread.join();
  4702. ASSERT_FALSE(svr.is_running());
  4703. });
  4704. // Give GET time to get a few messages.
  4705. std::this_thread::sleep_for(std::chrono::seconds(2));
  4706. }
  4707. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4708. httplib::Server svr;
  4709. svr.Post("/hi",
  4710. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4711. res.status = StatusCode::OK_200;
  4712. });
  4713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4714. svr.wait_until_ready();
  4715. Client cli(HOST, PORT);
  4716. auto res = cli.Post("/hi", "data", "text/plain");
  4717. ASSERT_TRUE(res);
  4718. EXPECT_EQ(StatusCode::OK_200, res->status);
  4719. svr.stop();
  4720. thread.join();
  4721. ASSERT_FALSE(svr.is_running());
  4722. res = cli.Post("/hi", "data", "text/plain");
  4723. ASSERT_FALSE(res);
  4724. }
  4725. TEST(ServerStopTest, ListenFailure) {
  4726. Server svr;
  4727. auto t = thread([&]() {
  4728. auto ret = svr.listen("????", PORT);
  4729. EXPECT_FALSE(ret);
  4730. });
  4731. svr.wait_until_ready();
  4732. svr.stop();
  4733. t.join();
  4734. }
  4735. TEST(ServerStopTest, Decommision) {
  4736. Server svr;
  4737. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4738. for (int i = 0; i < 4; i++) {
  4739. auto is_even = !(i % 2);
  4740. std::thread t{[&] {
  4741. try {
  4742. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4743. if (is_even) {
  4744. throw std::runtime_error("Some thing that happens to go wrong.");
  4745. }
  4746. svr.listen(HOST, PORT);
  4747. } catch (...) { svr.decommission(); }
  4748. }};
  4749. svr.wait_until_ready();
  4750. // Server is up
  4751. {
  4752. Client cli(HOST, PORT);
  4753. auto res = cli.Get("/hi");
  4754. if (is_even) {
  4755. EXPECT_FALSE(res);
  4756. } else {
  4757. EXPECT_TRUE(res);
  4758. EXPECT_EQ("hi...", res->body);
  4759. }
  4760. }
  4761. svr.stop();
  4762. t.join();
  4763. // Server is down...
  4764. {
  4765. Client cli(HOST, PORT);
  4766. auto res = cli.Get("/hi");
  4767. EXPECT_FALSE(res);
  4768. }
  4769. }
  4770. }
  4771. TEST(StreamingTest, NoContentLengthStreaming) {
  4772. Server svr;
  4773. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4774. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4775. if (offset < 6) {
  4776. sink.os << (offset < 3 ? "a" : "b");
  4777. } else {
  4778. sink.done();
  4779. }
  4780. return true;
  4781. });
  4782. });
  4783. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4784. auto listen_se = detail::scope_exit([&] {
  4785. svr.stop();
  4786. listen_thread.join();
  4787. ASSERT_FALSE(svr.is_running());
  4788. });
  4789. svr.wait_until_ready();
  4790. Client client(HOST, PORT);
  4791. auto get_thread = std::thread([&client]() {
  4792. std::string s;
  4793. auto res =
  4794. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4795. s += std::string(data, len);
  4796. return true;
  4797. });
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::OK_200, res->status);
  4800. EXPECT_EQ("aaabbb", s);
  4801. });
  4802. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4803. // Give GET time to get a few messages.
  4804. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4805. }
  4806. TEST(MountTest, Unmount) {
  4807. Server svr;
  4808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4809. auto se = detail::scope_exit([&] {
  4810. svr.stop();
  4811. listen_thread.join();
  4812. ASSERT_FALSE(svr.is_running());
  4813. });
  4814. svr.wait_until_ready();
  4815. Client cli("localhost", PORT);
  4816. svr.set_mount_point("/mount2", "./www2");
  4817. auto res = cli.Get("/");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4820. res = cli.Get("/mount2/dir/test.html");
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. svr.set_mount_point("/", "./www");
  4824. res = cli.Get("/dir/");
  4825. ASSERT_TRUE(res);
  4826. EXPECT_EQ(StatusCode::OK_200, res->status);
  4827. svr.remove_mount_point("/");
  4828. res = cli.Get("/dir/");
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4831. svr.remove_mount_point("/mount2");
  4832. res = cli.Get("/mount2/dir/test.html");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4835. }
  4836. TEST(MountTest, Redicect) {
  4837. Server svr;
  4838. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4839. auto se = detail::scope_exit([&] {
  4840. svr.stop();
  4841. listen_thread.join();
  4842. ASSERT_FALSE(svr.is_running());
  4843. });
  4844. svr.set_mount_point("/", "./www");
  4845. svr.wait_until_ready();
  4846. Client cli("localhost", PORT);
  4847. auto res = cli.Get("/dir/");
  4848. ASSERT_TRUE(res);
  4849. EXPECT_EQ(StatusCode::OK_200, res->status);
  4850. res = cli.Get("/dir");
  4851. ASSERT_TRUE(res);
  4852. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4853. res = cli.Get("/file");
  4854. ASSERT_TRUE(res);
  4855. EXPECT_EQ(StatusCode::OK_200, res->status);
  4856. res = cli.Get("/file/");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4859. cli.set_follow_location(true);
  4860. res = cli.Get("/dir");
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ(StatusCode::OK_200, res->status);
  4863. }
  4864. TEST(MountTest, MultibytesPathName) {
  4865. Server svr;
  4866. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4867. auto se = detail::scope_exit([&] {
  4868. svr.stop();
  4869. listen_thread.join();
  4870. ASSERT_FALSE(svr.is_running());
  4871. });
  4872. svr.set_mount_point("/", "./www");
  4873. svr.wait_until_ready();
  4874. Client cli("localhost", PORT);
  4875. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  4879. }
  4880. TEST(KeepAliveTest, ReadTimeout) {
  4881. Server svr;
  4882. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4883. std::this_thread::sleep_for(std::chrono::seconds(2));
  4884. res.set_content("a", "text/plain");
  4885. });
  4886. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4887. res.set_content("b", "text/plain");
  4888. });
  4889. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4890. auto se = detail::scope_exit([&] {
  4891. svr.stop();
  4892. listen_thread.join();
  4893. ASSERT_FALSE(svr.is_running());
  4894. });
  4895. svr.wait_until_ready();
  4896. Client cli("localhost", PORT);
  4897. cli.set_keep_alive(true);
  4898. cli.set_read_timeout(std::chrono::seconds(1));
  4899. auto resa = cli.Get("/a");
  4900. ASSERT_FALSE(resa);
  4901. EXPECT_EQ(Error::Read, resa.error());
  4902. auto resb = cli.Get("/b");
  4903. ASSERT_TRUE(resb);
  4904. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4905. EXPECT_EQ("b", resb->body);
  4906. }
  4907. TEST(KeepAliveTest, MaxCount) {
  4908. size_t keep_alive_max_count = 3;
  4909. Server svr;
  4910. svr.set_keep_alive_max_count(keep_alive_max_count);
  4911. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4912. res.set_content("Hello World!", "text/plain");
  4913. });
  4914. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4915. auto se = detail::scope_exit([&] {
  4916. svr.stop();
  4917. listen_thread.join();
  4918. ASSERT_FALSE(svr.is_running());
  4919. });
  4920. svr.wait_until_ready();
  4921. Client cli(HOST, PORT);
  4922. cli.set_keep_alive(true);
  4923. for (size_t i = 0; i < 5; i++) {
  4924. auto result = cli.Get("/hi");
  4925. ASSERT_TRUE(result);
  4926. EXPECT_EQ(StatusCode::OK_200, result->status);
  4927. if (i == keep_alive_max_count - 1) {
  4928. EXPECT_EQ("close", result->get_header_value("Connection"));
  4929. } else {
  4930. EXPECT_FALSE(result->has_header("Connection"));
  4931. }
  4932. }
  4933. }
  4934. TEST(KeepAliveTest, Issue1041) {
  4935. Server svr;
  4936. svr.set_keep_alive_timeout(3);
  4937. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4938. res.set_content("Hello World!", "text/plain");
  4939. });
  4940. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4941. auto se = detail::scope_exit([&] {
  4942. svr.stop();
  4943. listen_thread.join();
  4944. ASSERT_FALSE(svr.is_running());
  4945. });
  4946. svr.wait_until_ready();
  4947. Client cli(HOST, PORT);
  4948. cli.set_keep_alive(true);
  4949. auto result = cli.Get("/hi");
  4950. ASSERT_TRUE(result);
  4951. EXPECT_EQ(StatusCode::OK_200, result->status);
  4952. std::this_thread::sleep_for(std::chrono::seconds(5));
  4953. result = cli.Get("/hi");
  4954. ASSERT_TRUE(result);
  4955. EXPECT_EQ(StatusCode::OK_200, result->status);
  4956. }
  4957. TEST(KeepAliveTest, Issue1959) {
  4958. Server svr;
  4959. svr.set_keep_alive_timeout(5);
  4960. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4961. res.set_content("a", "text/plain");
  4962. });
  4963. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4964. auto se = detail::scope_exit([&] {
  4965. if (!svr.is_running()) return;
  4966. svr.stop();
  4967. listen_thread.join();
  4968. ASSERT_FALSE(svr.is_running());
  4969. });
  4970. svr.wait_until_ready();
  4971. Client cli("localhost", PORT);
  4972. cli.set_keep_alive(true);
  4973. using namespace std::chrono;
  4974. auto start = steady_clock::now();
  4975. cli.Get("/a");
  4976. svr.stop();
  4977. listen_thread.join();
  4978. auto end = steady_clock::now();
  4979. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4980. EXPECT_LT(elapsed, 5000);
  4981. }
  4982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4983. TEST(KeepAliveTest, SSLClientReconnection) {
  4984. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4985. ASSERT_TRUE(svr.is_valid());
  4986. svr.set_keep_alive_timeout(1);
  4987. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4988. res.set_content("Hello World!", "text/plain");
  4989. });
  4990. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4991. auto se = detail::scope_exit([&] {
  4992. svr.stop();
  4993. listen_thread.join();
  4994. ASSERT_FALSE(svr.is_running());
  4995. });
  4996. svr.wait_until_ready();
  4997. SSLClient cli(HOST, PORT);
  4998. cli.enable_server_certificate_verification(false);
  4999. cli.set_keep_alive(true);
  5000. auto result = cli.Get("/hi");
  5001. ASSERT_TRUE(result);
  5002. EXPECT_EQ(StatusCode::OK_200, result->status);
  5003. result = cli.Get("/hi");
  5004. ASSERT_TRUE(result);
  5005. EXPECT_EQ(StatusCode::OK_200, result->status);
  5006. std::this_thread::sleep_for(std::chrono::seconds(2));
  5007. // Recoonect
  5008. result = cli.Get("/hi");
  5009. ASSERT_TRUE(result);
  5010. EXPECT_EQ(StatusCode::OK_200, result->status);
  5011. result = cli.Get("/hi");
  5012. ASSERT_TRUE(result);
  5013. EXPECT_EQ(StatusCode::OK_200, result->status);
  5014. }
  5015. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5017. ASSERT_TRUE(svr.is_valid());
  5018. svr.set_keep_alive_timeout(1);
  5019. std::string content = "reconnect";
  5020. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5021. res.set_content("Hello World!", "text/plain");
  5022. });
  5023. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5024. auto se = detail::scope_exit([&] {
  5025. svr.stop();
  5026. listen_thread.join();
  5027. ASSERT_FALSE(svr.is_running());
  5028. });
  5029. svr.wait_until_ready();
  5030. SSLClient cli(HOST, PORT);
  5031. cli.enable_server_certificate_verification(false);
  5032. cli.set_keep_alive(true);
  5033. auto result = cli.Post(
  5034. "/hi", content.size(),
  5035. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5036. sink.write(content.c_str(), content.size());
  5037. return true;
  5038. },
  5039. "text/plain");
  5040. ASSERT_TRUE(result);
  5041. EXPECT_EQ(200, result->status);
  5042. std::this_thread::sleep_for(std::chrono::seconds(2));
  5043. // Recoonect
  5044. result = cli.Post(
  5045. "/hi", content.size(),
  5046. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5047. sink.write(content.c_str(), content.size());
  5048. return true;
  5049. },
  5050. "text/plain");
  5051. ASSERT_TRUE(result);
  5052. EXPECT_EQ(200, result->status);
  5053. result = cli.Post(
  5054. "/hi", content.size(),
  5055. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5056. sink.write(content.c_str(), content.size());
  5057. return true;
  5058. },
  5059. "text/plain");
  5060. ASSERT_TRUE(result);
  5061. EXPECT_EQ(200, result->status);
  5062. }
  5063. #endif
  5064. TEST(ClientProblemDetectionTest, ContentProvider) {
  5065. Server svr;
  5066. size_t content_length = 1024 * 1024;
  5067. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5068. res.set_content_provider(
  5069. content_length, "text/plain",
  5070. [&](size_t offset, size_t length, DataSink &sink) {
  5071. auto out_len = std::min(length, static_cast<size_t>(1024));
  5072. std::string out(out_len, '@');
  5073. sink.write(out.data(), out_len);
  5074. return offset < 4096;
  5075. },
  5076. [](bool success) { ASSERT_FALSE(success); });
  5077. });
  5078. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5079. res.set_content_provider(
  5080. 0, "text/plain",
  5081. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5082. EXPECT_TRUE(false);
  5083. return true;
  5084. },
  5085. [](bool success) { ASSERT_FALSE(success); });
  5086. });
  5087. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5088. auto se = detail::scope_exit([&] {
  5089. svr.stop();
  5090. listen_thread.join();
  5091. ASSERT_FALSE(svr.is_running());
  5092. });
  5093. svr.wait_until_ready();
  5094. Client cli("localhost", PORT);
  5095. {
  5096. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5097. size_t /*data_length*/) { return false; });
  5098. ASSERT_FALSE(res);
  5099. }
  5100. {
  5101. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5102. size_t /*data_length*/) { return false; });
  5103. ASSERT_TRUE(res);
  5104. }
  5105. }
  5106. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5107. Server svr;
  5108. svr.set_error_handler([](Request const &, Response &res) -> void {
  5109. res.set_chunked_content_provider(
  5110. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5111. sink.os << "hello";
  5112. sink.os << "world";
  5113. sink.done();
  5114. return true;
  5115. });
  5116. });
  5117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5118. auto se = detail::scope_exit([&] {
  5119. svr.stop();
  5120. listen_thread.join();
  5121. ASSERT_FALSE(svr.is_running());
  5122. });
  5123. svr.wait_until_ready();
  5124. Client cli("localhost", PORT);
  5125. auto res = cli.Get("/");
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5128. EXPECT_EQ("helloworld", res->body);
  5129. }
  5130. TEST(LongPollingTest, ClientCloseDetection) {
  5131. Server svr;
  5132. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5133. res.set_chunked_content_provider(
  5134. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5135. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5136. sink.os << "hello";
  5137. auto count = 10;
  5138. while (count > 0 && sink.is_writable()) {
  5139. this_thread::sleep_for(chrono::milliseconds(10));
  5140. count--;
  5141. }
  5142. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5143. return true;
  5144. });
  5145. });
  5146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5147. auto se = detail::scope_exit([&] {
  5148. svr.stop();
  5149. listen_thread.join();
  5150. ASSERT_FALSE(svr.is_running());
  5151. });
  5152. svr.wait_until_ready();
  5153. Client cli("localhost", PORT);
  5154. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5155. EXPECT_EQ("hello", string(data, data_length));
  5156. return false; // close the socket immediately.
  5157. });
  5158. ASSERT_FALSE(res);
  5159. }
  5160. TEST(GetWithParametersTest, GetWithParameters) {
  5161. Server svr;
  5162. svr.Get("/", [&](const Request &req, Response &) {
  5163. EXPECT_EQ("world", req.get_param_value("hello"));
  5164. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5165. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5166. });
  5167. svr.Get("/params", [&](const Request &req, Response &) {
  5168. EXPECT_EQ("world", req.get_param_value("hello"));
  5169. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5170. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5171. });
  5172. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5173. EXPECT_EQ("resource-id", req.matches[1]);
  5174. EXPECT_EQ("foo", req.get_param_value("param1"));
  5175. EXPECT_EQ("bar", req.get_param_value("param2"));
  5176. });
  5177. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5178. EXPECT_EQ("user-id", req.path_params.at("id"));
  5179. EXPECT_EQ("foo", req.get_param_value("param1"));
  5180. EXPECT_EQ("bar", req.get_param_value("param2"));
  5181. });
  5182. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5183. auto se = detail::scope_exit([&] {
  5184. svr.stop();
  5185. listen_thread.join();
  5186. ASSERT_FALSE(svr.is_running());
  5187. });
  5188. svr.wait_until_ready();
  5189. {
  5190. Client cli(HOST, PORT);
  5191. Params params;
  5192. params.emplace("hello", "world");
  5193. params.emplace("hello2", "world2");
  5194. params.emplace("hello3", "world3");
  5195. auto res = cli.Get("/", params, Headers{});
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. {
  5200. Client cli(HOST, PORT);
  5201. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. {
  5206. Client cli(HOST, PORT);
  5207. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. }
  5211. {
  5212. Client cli(HOST, PORT);
  5213. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5214. ASSERT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. }
  5217. }
  5218. TEST(GetWithParametersTest, GetWithParameters2) {
  5219. Server svr;
  5220. svr.Get("/", [&](const Request &req, Response &res) {
  5221. auto text = req.get_param_value("hello");
  5222. res.set_content(text, "text/plain");
  5223. });
  5224. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5225. auto se = detail::scope_exit([&] {
  5226. svr.stop();
  5227. listen_thread.join();
  5228. ASSERT_FALSE(svr.is_running());
  5229. });
  5230. svr.wait_until_ready();
  5231. Client cli("localhost", PORT);
  5232. Params params;
  5233. params.emplace("hello", "world");
  5234. std::string body;
  5235. auto res = cli.Get("/", params, Headers{},
  5236. [&](const char *data, size_t data_length) {
  5237. body.append(data, data_length);
  5238. return true;
  5239. });
  5240. ASSERT_TRUE(res);
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("world", body);
  5243. }
  5244. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5245. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5246. auto host = "httpbin.org";
  5247. auto path = std::string{"/range/32"};
  5248. #else
  5249. auto host = "nghttp2.org";
  5250. auto path = std::string{"/httpbin/range/32"};
  5251. #endif
  5252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5253. SSLClient cli(host);
  5254. #else
  5255. Client cli(host);
  5256. #endif
  5257. cli.set_default_headers({make_range_header({{1, 10}})});
  5258. cli.set_connection_timeout(5);
  5259. {
  5260. auto res = cli.Get(path);
  5261. ASSERT_TRUE(res);
  5262. EXPECT_EQ("bcdefghijk", res->body);
  5263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5264. }
  5265. {
  5266. auto res = cli.Get(path);
  5267. ASSERT_TRUE(res);
  5268. EXPECT_EQ("bcdefghijk", res->body);
  5269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5270. }
  5271. }
  5272. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5273. Server svr;
  5274. svr.set_default_headers({{"Hello", "World"}});
  5275. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5276. res.set_content("ok", "text/plain");
  5277. });
  5278. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5279. auto se = detail::scope_exit([&] {
  5280. svr.stop();
  5281. listen_thread.join();
  5282. ASSERT_FALSE(svr.is_running());
  5283. });
  5284. svr.wait_until_ready();
  5285. Client cli("localhost", PORT);
  5286. auto res = cli.Get("/");
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. EXPECT_EQ("ok", res->body);
  5290. EXPECT_EQ("World", res->get_header_value("Hello"));
  5291. }
  5292. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5293. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5295. ASSERT_TRUE(svr.is_valid());
  5296. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5297. std::this_thread::sleep_for(std::chrono::seconds(2));
  5298. res.set_content("a", "text/plain");
  5299. });
  5300. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5301. res.set_content("b", "text/plain");
  5302. });
  5303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5304. auto se = detail::scope_exit([&] {
  5305. svr.stop();
  5306. listen_thread.join();
  5307. ASSERT_FALSE(svr.is_running());
  5308. });
  5309. svr.wait_until_ready();
  5310. SSLClient cli("localhost", PORT);
  5311. cli.enable_server_certificate_verification(false);
  5312. cli.set_keep_alive(true);
  5313. cli.set_read_timeout(std::chrono::seconds(1));
  5314. auto resa = cli.Get("/a");
  5315. ASSERT_TRUE(!resa);
  5316. EXPECT_EQ(Error::Read, resa.error());
  5317. auto resb = cli.Get("/b");
  5318. ASSERT_TRUE(resb);
  5319. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5320. EXPECT_EQ("b", resb->body);
  5321. }
  5322. #endif
  5323. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5324. protected:
  5325. ServerTestWithAI_PASSIVE()
  5326. : cli_(HOST, PORT)
  5327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5328. ,
  5329. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5330. #endif
  5331. {
  5332. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5333. cli_.enable_server_certificate_verification(false);
  5334. #endif
  5335. }
  5336. virtual void SetUp() {
  5337. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5338. res.set_content("Hello World!", "text/plain");
  5339. });
  5340. t_ = thread(
  5341. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5342. svr_.wait_until_ready();
  5343. }
  5344. virtual void TearDown() {
  5345. svr_.stop();
  5346. t_.join();
  5347. }
  5348. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5349. SSLClient cli_;
  5350. SSLServer svr_;
  5351. #else
  5352. Client cli_;
  5353. Server svr_;
  5354. #endif
  5355. thread t_;
  5356. };
  5357. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5358. auto res = cli_.Get("/hi");
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5362. EXPECT_EQ("Hello World!", res->body);
  5363. }
  5364. class ServerUpDownTest : public ::testing::Test {
  5365. protected:
  5366. ServerUpDownTest() : cli_(HOST, PORT) {}
  5367. virtual void SetUp() {
  5368. t_ = thread([&]() {
  5369. svr_.bind_to_any_port(HOST);
  5370. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5371. ASSERT_TRUE(svr_.listen_after_bind());
  5372. });
  5373. svr_.wait_until_ready();
  5374. }
  5375. virtual void TearDown() {
  5376. svr_.stop();
  5377. t_.join();
  5378. }
  5379. Client cli_;
  5380. Server svr_;
  5381. thread t_;
  5382. };
  5383. TEST_F(ServerUpDownTest, QuickStartStop) {
  5384. // Should not crash, especially when run with
  5385. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5386. }
  5387. class PayloadMaxLengthTest : public ::testing::Test {
  5388. protected:
  5389. PayloadMaxLengthTest()
  5390. : cli_(HOST, PORT)
  5391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5392. ,
  5393. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5394. #endif
  5395. {
  5396. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5397. cli_.enable_server_certificate_verification(false);
  5398. #endif
  5399. }
  5400. virtual void SetUp() {
  5401. svr_.set_payload_max_length(8);
  5402. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5403. res.set_content("test", "text/plain");
  5404. });
  5405. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5406. svr_.wait_until_ready();
  5407. }
  5408. virtual void TearDown() {
  5409. svr_.stop();
  5410. t_.join();
  5411. }
  5412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5413. SSLClient cli_;
  5414. SSLServer svr_;
  5415. #else
  5416. Client cli_;
  5417. Server svr_;
  5418. #endif
  5419. thread t_;
  5420. };
  5421. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5422. auto res = cli_.Post("/test", "123456789", "text/plain");
  5423. ASSERT_TRUE(res);
  5424. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5425. res = cli_.Post("/test", "12345678", "text/plain");
  5426. ASSERT_TRUE(res);
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. }
  5429. TEST(HostAndPortPropertiesTest, NoSSL) {
  5430. httplib::Client cli("www.google.com", 1234);
  5431. ASSERT_EQ("www.google.com", cli.host());
  5432. ASSERT_EQ(1234, cli.port());
  5433. }
  5434. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5435. httplib::Client cli("www.google.com:1234");
  5436. ASSERT_EQ("www.google.com", cli.host());
  5437. ASSERT_EQ(1234, cli.port());
  5438. }
  5439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5440. TEST(HostAndPortPropertiesTest, SSL) {
  5441. httplib::SSLClient cli("www.google.com");
  5442. ASSERT_EQ("www.google.com", cli.host());
  5443. ASSERT_EQ(443, cli.port());
  5444. }
  5445. #endif
  5446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5447. TEST(SSLClientTest, UpdateCAStore) {
  5448. httplib::SSLClient httplib_client("www.google.com");
  5449. auto ca_store_1 = X509_STORE_new();
  5450. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5451. nullptr);
  5452. httplib_client.set_ca_cert_store(ca_store_1);
  5453. auto ca_store_2 = X509_STORE_new();
  5454. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5455. nullptr);
  5456. httplib_client.set_ca_cert_store(ca_store_2);
  5457. }
  5458. TEST(SSLClientTest, ServerNameIndication_Online) {
  5459. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5460. auto host = "httpbin.org";
  5461. auto path = std::string{"/get"};
  5462. #else
  5463. auto host = "nghttp2.org";
  5464. auto path = std::string{"/httpbin/get"};
  5465. #endif
  5466. SSLClient cli(host, 443);
  5467. auto res = cli.Get(path);
  5468. ASSERT_TRUE(res);
  5469. ASSERT_EQ(StatusCode::OK_200, res->status);
  5470. }
  5471. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5472. Client cli("https://google.com");
  5473. auto res = cli.Get("/");
  5474. ASSERT_TRUE(res);
  5475. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5476. }
  5477. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5478. SSLClient cli("google.com");
  5479. cli.enable_server_certificate_verification(true);
  5480. cli.set_ca_cert_path("hello");
  5481. auto res = cli.Get("/");
  5482. ASSERT_TRUE(!res);
  5483. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5484. }
  5485. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5486. SSLClient cli("google.com");
  5487. cli.set_ca_cert_path(CA_CERT_FILE);
  5488. auto res = cli.Get("/");
  5489. ASSERT_TRUE(res);
  5490. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5491. }
  5492. TEST(SSLClientTest, ServerCertificateVerification4) {
  5493. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5494. ASSERT_TRUE(svr.is_valid());
  5495. svr.Get("/test", [&](const Request &, Response &res) {
  5496. res.set_content("test", "text/plain");
  5497. svr.stop();
  5498. ASSERT_TRUE(true);
  5499. });
  5500. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5501. auto se = detail::scope_exit([&] {
  5502. t.join();
  5503. ASSERT_FALSE(svr.is_running());
  5504. });
  5505. svr.wait_until_ready();
  5506. SSLClient cli("127.0.0.1", PORT);
  5507. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5508. cli.enable_server_certificate_verification(true);
  5509. cli.set_connection_timeout(30);
  5510. auto res = cli.Get("/test");
  5511. ASSERT_TRUE(res);
  5512. ASSERT_EQ(StatusCode::OK_200, res->status);
  5513. }
  5514. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5515. std::string cert;
  5516. read_file(CA_CERT_FILE, cert);
  5517. SSLClient cli("google.com");
  5518. cli.load_ca_cert_store(cert.data(), cert.size());
  5519. const auto res = cli.Get("/");
  5520. ASSERT_TRUE(res);
  5521. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5522. }
  5523. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5524. // clang-format off
  5525. static constexpr char cert[] =
  5526. "GlobalSign Root CA\n"
  5527. "==================\n"
  5528. "-----BEGIN CERTIFICATE-----\n"
  5529. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5530. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5531. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5532. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5533. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5534. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5535. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5536. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5537. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5538. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5539. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5540. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5541. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5542. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5543. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5544. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5545. "-----END CERTIFICATE-----\n";
  5546. // clang-format on
  5547. SSLClient cli("google.com");
  5548. cli.load_ca_cert_store(cert, sizeof(cert));
  5549. const auto res = cli.Get("/");
  5550. ASSERT_TRUE(res);
  5551. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5552. }
  5553. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5554. SSLClient cli("www.youtube.com");
  5555. cli.set_ca_cert_path(CA_CERT_FILE);
  5556. cli.enable_server_certificate_verification(true);
  5557. cli.set_follow_location(true);
  5558. auto res = cli.Get("/");
  5559. ASSERT_TRUE(res);
  5560. ASSERT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST(SSLClientTest, Issue2004_Online) {
  5563. Client client("https://google.com");
  5564. client.set_follow_location(true);
  5565. auto res = client.Get("/");
  5566. ASSERT_TRUE(res);
  5567. ASSERT_EQ(StatusCode::OK_200, res->status);
  5568. auto body = res->body;
  5569. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5570. }
  5571. #if 0
  5572. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5573. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5574. ASSERT_TRUE(cli != nullptr);
  5575. cli->set_address_family(AF_INET6);
  5576. cli->set_interface("en0");
  5577. auto res = cli->Get("/get");
  5578. ASSERT_TRUE(res);
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. }
  5581. #endif
  5582. void ClientCertPresent(
  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. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5587. CLIENT_CA_CERT_DIR);
  5588. ASSERT_TRUE(svr.is_valid());
  5589. svr.Get("/test", [&](const Request &req, Response &res) {
  5590. res.set_content("test", "text/plain");
  5591. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5592. ASSERT_TRUE(peer_cert != nullptr);
  5593. auto subject_name = X509_get_subject_name(peer_cert);
  5594. ASSERT_TRUE(subject_name != nullptr);
  5595. std::string common_name;
  5596. {
  5597. char name[BUFSIZ];
  5598. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5599. name, sizeof(name));
  5600. common_name.assign(name, static_cast<size_t>(name_len));
  5601. }
  5602. EXPECT_EQ("Common Name", common_name);
  5603. X509_free(peer_cert);
  5604. });
  5605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5606. auto se = detail::scope_exit([&] {
  5607. svr.stop();
  5608. t.join();
  5609. ASSERT_FALSE(svr.is_running());
  5610. });
  5611. svr.wait_until_ready();
  5612. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5613. client_encrypted_private_key_pass);
  5614. cli.enable_server_certificate_verification(false);
  5615. cli.set_connection_timeout(30);
  5616. auto res = cli.Get("/test");
  5617. ASSERT_TRUE(res);
  5618. ASSERT_EQ(StatusCode::OK_200, res->status);
  5619. }
  5620. TEST(SSLClientServerTest, ClientCertPresent) {
  5621. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5622. }
  5623. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5624. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5625. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5626. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5627. }
  5628. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5629. void MemoryClientCertPresent(
  5630. const std::string &client_cert_file,
  5631. const std::string &client_private_key_file,
  5632. const std::string &client_encrypted_private_key_pass = std::string()) {
  5633. auto f = fopen(SERVER_CERT_FILE, "r+");
  5634. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5635. fclose(f);
  5636. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5637. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5638. fclose(f);
  5639. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5640. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5641. auto client_ca_cert_store = X509_STORE_new();
  5642. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5643. X509_free(client_cert);
  5644. fclose(f);
  5645. f = fopen(client_cert_file.c_str(), "r+");
  5646. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5647. fclose(f);
  5648. f = fopen(client_private_key_file.c_str(), "r+");
  5649. auto client_private_key = PEM_read_PrivateKey(
  5650. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5651. fclose(f);
  5652. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5653. ASSERT_TRUE(svr.is_valid());
  5654. svr.Get("/test", [&](const Request &req, Response &res) {
  5655. res.set_content("test", "text/plain");
  5656. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5657. ASSERT_TRUE(peer_cert != nullptr);
  5658. auto subject_name = X509_get_subject_name(peer_cert);
  5659. ASSERT_TRUE(subject_name != nullptr);
  5660. std::string common_name;
  5661. {
  5662. char name[BUFSIZ];
  5663. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5664. name, sizeof(name));
  5665. common_name.assign(name, static_cast<size_t>(name_len));
  5666. }
  5667. EXPECT_EQ("Common Name", common_name);
  5668. X509_free(peer_cert);
  5669. });
  5670. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5671. auto se = detail::scope_exit([&] {
  5672. svr.stop();
  5673. t.join();
  5674. ASSERT_FALSE(svr.is_running());
  5675. });
  5676. svr.wait_until_ready();
  5677. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5678. client_encrypted_private_key_pass);
  5679. cli.enable_server_certificate_verification(false);
  5680. cli.set_connection_timeout(30);
  5681. auto res = cli.Get("/test");
  5682. ASSERT_TRUE(res);
  5683. ASSERT_EQ(StatusCode::OK_200, res->status);
  5684. X509_free(server_cert);
  5685. EVP_PKEY_free(server_private_key);
  5686. X509_free(client_cert);
  5687. EVP_PKEY_free(client_private_key);
  5688. }
  5689. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5690. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5691. }
  5692. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5693. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5694. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5695. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5696. }
  5697. #endif
  5698. TEST(SSLClientServerTest, ClientCertMissing) {
  5699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5700. CLIENT_CA_CERT_DIR);
  5701. ASSERT_TRUE(svr.is_valid());
  5702. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5703. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5704. auto se = detail::scope_exit([&] {
  5705. svr.stop();
  5706. t.join();
  5707. ASSERT_FALSE(svr.is_running());
  5708. });
  5709. svr.wait_until_ready();
  5710. SSLClient cli(HOST, PORT);
  5711. auto res = cli.Get("/test");
  5712. cli.set_connection_timeout(30);
  5713. ASSERT_TRUE(!res);
  5714. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5715. }
  5716. TEST(SSLClientServerTest, TrustDirOptional) {
  5717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5718. ASSERT_TRUE(svr.is_valid());
  5719. svr.Get("/test", [&](const Request &, Response &res) {
  5720. res.set_content("test", "text/plain");
  5721. });
  5722. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5723. auto se = detail::scope_exit([&] {
  5724. svr.stop();
  5725. t.join();
  5726. ASSERT_FALSE(svr.is_running());
  5727. });
  5728. svr.wait_until_ready();
  5729. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5730. cli.enable_server_certificate_verification(false);
  5731. cli.set_connection_timeout(30);
  5732. auto res = cli.Get("/test");
  5733. ASSERT_TRUE(res);
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. }
  5736. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5737. class NoListenSSLServer : public SSLServer {
  5738. public:
  5739. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5740. const char *client_ca_cert_file_path,
  5741. const char *client_ca_cert_dir_path = nullptr)
  5742. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5743. client_ca_cert_dir_path),
  5744. stop_(false) {}
  5745. std::atomic_bool stop_;
  5746. private:
  5747. bool process_and_close_socket(socket_t /*sock*/) override {
  5748. // Don't create SSL context
  5749. while (!stop_.load()) {
  5750. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5751. }
  5752. return true;
  5753. }
  5754. };
  5755. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5756. CLIENT_CA_CERT_FILE);
  5757. ASSERT_TRUE(svr.is_valid());
  5758. svr.Get("/test", [&](const Request &, Response &res) {
  5759. res.set_content("test", "text/plain");
  5760. });
  5761. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5762. auto se = detail::scope_exit([&] {
  5763. svr.stop_ = true;
  5764. svr.stop();
  5765. t.join();
  5766. ASSERT_FALSE(svr.is_running());
  5767. });
  5768. svr.wait_until_ready();
  5769. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5770. cli.enable_server_certificate_verification(false);
  5771. cli.set_connection_timeout(1);
  5772. auto res = cli.Get("/test");
  5773. ASSERT_TRUE(!res);
  5774. EXPECT_EQ(Error::SSLConnection, res.error());
  5775. }
  5776. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5777. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5778. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5779. SSL_CTX_set_options(&ssl_ctx,
  5780. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5781. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5782. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5783. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5784. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5785. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5786. "ECDHE-DSS-AES128-SHA256:"
  5787. "ECDHE-RSA-AES256-SHA256:"
  5788. "ECDHE-DSS-AES256-SHA256:";
  5789. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5790. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5791. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5792. SSL_FILETYPE_PEM) != 1) {
  5793. return false;
  5794. }
  5795. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5796. CLIENT_CA_CERT_DIR);
  5797. SSL_CTX_set_verify(
  5798. &ssl_ctx,
  5799. SSL_VERIFY_PEER |
  5800. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5801. nullptr);
  5802. return true;
  5803. };
  5804. SSLServer svr(setup_ssl_ctx_callback);
  5805. ASSERT_TRUE(svr.is_valid());
  5806. svr.Get("/test", [&](const Request &req, Response &res) {
  5807. res.set_content("test", "text/plain");
  5808. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5809. ASSERT_TRUE(peer_cert != nullptr);
  5810. auto subject_name = X509_get_subject_name(peer_cert);
  5811. ASSERT_TRUE(subject_name != nullptr);
  5812. std::string common_name;
  5813. {
  5814. char name[BUFSIZ];
  5815. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5816. name, sizeof(name));
  5817. common_name.assign(name, static_cast<size_t>(name_len));
  5818. }
  5819. EXPECT_EQ("Common Name", common_name);
  5820. X509_free(peer_cert);
  5821. });
  5822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5823. auto se = detail::scope_exit([&] {
  5824. svr.stop();
  5825. t.join();
  5826. ASSERT_FALSE(svr.is_running());
  5827. });
  5828. svr.wait_until_ready();
  5829. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5830. cli.enable_server_certificate_verification(false);
  5831. cli.set_connection_timeout(30);
  5832. auto res = cli.Get("/test");
  5833. ASSERT_TRUE(res);
  5834. ASSERT_EQ(StatusCode::OK_200, res->status);
  5835. }
  5836. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5837. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5838. // prepare large data
  5839. std::random_device seed_gen;
  5840. std::mt19937 random(seed_gen());
  5841. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5842. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5843. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5844. // server
  5845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5846. ASSERT_TRUE(svr.is_valid());
  5847. svr.Post("/binary", [&](const Request &req, Response &res) {
  5848. EXPECT_EQ(large_size_byte, req.body.size());
  5849. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5850. res.set_content(req.body, "application/octet-stream");
  5851. });
  5852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5853. auto se = detail::scope_exit([&] {
  5854. svr.stop();
  5855. listen_thread.join();
  5856. ASSERT_FALSE(svr.is_running());
  5857. });
  5858. svr.wait_until_ready();
  5859. // client POST
  5860. SSLClient cli("localhost", PORT);
  5861. cli.enable_server_certificate_verification(false);
  5862. cli.set_read_timeout(std::chrono::seconds(100));
  5863. cli.set_write_timeout(std::chrono::seconds(100));
  5864. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5865. large_size_byte, "application/octet-stream");
  5866. // compare
  5867. EXPECT_EQ(StatusCode::OK_200, res->status);
  5868. EXPECT_EQ(large_size_byte, res->body.size());
  5869. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5870. }
  5871. #endif
  5872. #ifdef _WIN32
  5873. TEST(CleanupTest, WSACleanup) {
  5874. int ret = WSACleanup();
  5875. ASSERT_EQ(0, ret);
  5876. }
  5877. #endif
  5878. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5879. TEST(NoSSLSupport, SimpleInterface) {
  5880. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5881. }
  5882. #endif
  5883. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5884. TEST(InvalidScheme, SimpleInterface) {
  5885. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5886. }
  5887. #endif
  5888. TEST(NoScheme, SimpleInterface) {
  5889. Client cli("yahoo.com:80");
  5890. ASSERT_TRUE(cli.is_valid());
  5891. }
  5892. TEST(SendAPI, SimpleInterface_Online) {
  5893. Client cli("http://yahoo.com");
  5894. Request req;
  5895. req.method = "GET";
  5896. req.path = "/";
  5897. auto res = cli.send(req);
  5898. ASSERT_TRUE(res);
  5899. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5900. }
  5901. TEST(SendAPI, WithParamsInRequest) {
  5902. Server svr;
  5903. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  5904. EXPECT_TRUE(req.has_param("test"));
  5905. EXPECT_EQ("test_value", req.get_param_value("test"));
  5906. });
  5907. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  5908. auto se = detail::scope_exit([&] {
  5909. svr.stop();
  5910. t.join();
  5911. ASSERT_FALSE(svr.is_running());
  5912. });
  5913. svr.wait_until_ready();
  5914. Client cli(HOST, PORT);
  5915. {
  5916. Request req;
  5917. req.method = "GET";
  5918. req.path = "/";
  5919. req.params.emplace("test", "test_value");
  5920. auto res = cli.send(req);
  5921. ASSERT_TRUE(res);
  5922. }
  5923. {
  5924. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  5925. ASSERT_TRUE(res);
  5926. }
  5927. }
  5928. TEST(ClientImplMethods, GetSocketTest) {
  5929. httplib::Server svr;
  5930. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5931. res.status = StatusCode::OK_200;
  5932. });
  5933. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5934. auto se = detail::scope_exit([&] {
  5935. svr.stop();
  5936. thread.join();
  5937. ASSERT_FALSE(svr.is_running());
  5938. });
  5939. svr.wait_until_ready();
  5940. {
  5941. httplib::Client cli("http://127.0.0.1:3333");
  5942. cli.set_keep_alive(true);
  5943. // Use the behavior of cpp-httplib of opening the connection
  5944. // only when the first request happens. If that changes,
  5945. // this test would be obsolete.
  5946. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5947. // This also implicitly tests the server. But other tests would fail much
  5948. // earlier than this one to be considered.
  5949. auto res = cli.Get("/");
  5950. ASSERT_TRUE(res);
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5953. }
  5954. }
  5955. // Disabled due to out-of-memory problem on GitHub Actions
  5956. #ifdef _WIN64
  5957. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5958. // allocate content size larger than 2GB in memory
  5959. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5960. char *content = (char *)malloc(content_size);
  5961. ASSERT_TRUE(content);
  5962. Server svr;
  5963. svr.Get("/foo",
  5964. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5965. res.set_content(content, content_size, "application/octet-stream");
  5966. });
  5967. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5968. auto se = detail::scope_exit([&] {
  5969. svr.stop();
  5970. listen_thread.join();
  5971. if (content) free(content);
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.wait_until_ready();
  5975. Client cli(HOST, PORT);
  5976. auto res = cli.Get("/foo");
  5977. ASSERT_TRUE(res);
  5978. EXPECT_EQ(StatusCode::OK_200, res->status);
  5979. EXPECT_EQ(content_size, res->body.length());
  5980. }
  5981. #endif
  5982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5983. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5984. Client cli("http://yahoo.com");
  5985. auto res = cli.Get("/");
  5986. ASSERT_TRUE(res);
  5987. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5988. cli.set_follow_location(true);
  5989. res = cli.Get("/");
  5990. ASSERT_TRUE(res);
  5991. EXPECT_EQ(StatusCode::OK_200, res->status);
  5992. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5993. }
  5994. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5995. Client cli("https://yahoo.com");
  5996. auto res = cli.Get("/");
  5997. ASSERT_TRUE(res);
  5998. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5999. cli.set_follow_location(true);
  6000. res = cli.Get("/");
  6001. ASSERT_TRUE(res);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6004. }
  6005. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6006. Client cli("https://yahoo.com");
  6007. auto res = cli.Get("/");
  6008. ASSERT_TRUE(res);
  6009. ASSERT_FALSE(!res);
  6010. ASSERT_TRUE(res);
  6011. ASSERT_FALSE(res == nullptr);
  6012. ASSERT_TRUE(res != nullptr);
  6013. EXPECT_EQ(Error::Success, res.error());
  6014. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6015. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6016. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6017. cli.set_follow_location(true);
  6018. res = cli.Get("/");
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(Error::Success, res.error());
  6021. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6022. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6023. EXPECT_EQ(StatusCode::OK_200, res->status);
  6024. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6025. }
  6026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6027. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6028. Client cli("https://cdnjs.cloudflare.com");
  6029. auto res =
  6030. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. EXPECT_EQ(287630U, res->body.size());
  6034. EXPECT_EQ("application/javascript; charset=utf-8",
  6035. res->get_header_value("Content-Type"));
  6036. }
  6037. #endif
  6038. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6039. #undef REDIR_HOST // Silence compiler warning
  6040. #define REDIR_HOST "https://httpbingo.org"
  6041. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6042. Client cli(REDIR_HOST);
  6043. cli.set_follow_location(true);
  6044. auto res =
  6045. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6046. ASSERT_TRUE(res);
  6047. EXPECT_EQ(StatusCode::OK_200, res->status);
  6048. }
  6049. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6050. Client cli(REDIR_HOST);
  6051. cli.set_follow_location(true);
  6052. Params params;
  6053. params.emplace("url", "http://example.com");
  6054. params.emplace("status_code", "302");
  6055. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6056. ASSERT_TRUE(res);
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. }
  6059. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6060. Client cli(REDIR_HOST);
  6061. cli.set_follow_location(true);
  6062. Params params;
  6063. params.emplace("url", "http://example.com");
  6064. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(StatusCode::OK_200, res->status);
  6067. }
  6068. TEST(HttpToHttpsRedirectTest, CertFile) {
  6069. Server svr;
  6070. ASSERT_TRUE(svr.is_valid());
  6071. svr.Get("/index", [&](const Request &, Response &res) {
  6072. res.set_redirect("https://127.0.0.1:1235/index");
  6073. svr.stop();
  6074. });
  6075. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6076. ASSERT_TRUE(ssl_svr.is_valid());
  6077. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6078. res.set_content("test", "text/plain");
  6079. ssl_svr.stop();
  6080. });
  6081. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6082. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6083. auto se = detail::scope_exit([&] {
  6084. t2.join();
  6085. t.join();
  6086. ASSERT_FALSE(svr.is_running());
  6087. });
  6088. svr.wait_until_ready();
  6089. ssl_svr.wait_until_ready();
  6090. Client cli("127.0.0.1", PORT);
  6091. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6092. cli.enable_server_certificate_verification(true);
  6093. cli.set_follow_location(true);
  6094. cli.set_connection_timeout(30);
  6095. auto res = cli.Get("/index");
  6096. ASSERT_TRUE(res);
  6097. ASSERT_EQ(StatusCode::OK_200, res->status);
  6098. }
  6099. TEST(MultipartFormDataTest, LargeData) {
  6100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6101. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6102. const ContentReader &content_reader) {
  6103. if (req.is_multipart_form_data()) {
  6104. MultipartFormDataItems files;
  6105. content_reader(
  6106. [&](const MultipartFormData &file) {
  6107. files.push_back(file);
  6108. return true;
  6109. },
  6110. [&](const char *data, size_t data_length) {
  6111. files.back().content.append(data, data_length);
  6112. return true;
  6113. });
  6114. EXPECT_TRUE(std::string(files[0].name) == "document");
  6115. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6116. EXPECT_TRUE(files[0].filename == "2MB_data");
  6117. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6118. EXPECT_TRUE(files[1].name == "hello");
  6119. EXPECT_TRUE(files[1].content == "world");
  6120. EXPECT_TRUE(files[1].filename == "");
  6121. EXPECT_TRUE(files[1].content_type == "");
  6122. } else {
  6123. std::string body;
  6124. content_reader([&](const char *data, size_t data_length) {
  6125. body.append(data, data_length);
  6126. return true;
  6127. });
  6128. }
  6129. });
  6130. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6131. auto se = detail::scope_exit([&] {
  6132. svr.stop();
  6133. t.join();
  6134. ASSERT_FALSE(svr.is_running());
  6135. });
  6136. svr.wait_until_ready();
  6137. {
  6138. std::string data(1024 * 1024 * 2, '.');
  6139. std::stringstream buffer;
  6140. buffer << data;
  6141. Client cli("https://localhost:8080");
  6142. cli.enable_server_certificate_verification(false);
  6143. MultipartFormDataItems items{
  6144. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6145. {"hello", "world", "", ""},
  6146. };
  6147. auto res = cli.Post("/post", items);
  6148. ASSERT_TRUE(res);
  6149. ASSERT_EQ(StatusCode::OK_200, res->status);
  6150. }
  6151. }
  6152. TEST(MultipartFormDataTest, DataProviderItems) {
  6153. std::random_device seed_gen;
  6154. std::mt19937 random(seed_gen());
  6155. std::string rand1;
  6156. rand1.resize(1000);
  6157. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6158. std::string rand2;
  6159. rand2.resize(3000);
  6160. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6162. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6163. const ContentReader &content_reader) {
  6164. ASSERT_FALSE(req.is_multipart_form_data());
  6165. std::string body;
  6166. content_reader([&](const char *data, size_t data_length) {
  6167. body.append(data, data_length);
  6168. return true;
  6169. });
  6170. EXPECT_EQ(body, "");
  6171. });
  6172. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6173. const ContentReader &content_reader) {
  6174. ASSERT_TRUE(req.is_multipart_form_data());
  6175. MultipartFormDataItems files;
  6176. content_reader(
  6177. [&](const MultipartFormData &file) {
  6178. files.push_back(file);
  6179. return true;
  6180. },
  6181. [&](const char *data, size_t data_length) {
  6182. files.back().content.append(data, data_length);
  6183. return true;
  6184. });
  6185. ASSERT_TRUE(files.size() == 2);
  6186. EXPECT_EQ(std::string(files[0].name), "name1");
  6187. EXPECT_EQ(files[0].content, "Testing123");
  6188. EXPECT_EQ(files[0].filename, "filename1");
  6189. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6190. EXPECT_EQ(files[1].name, "name2");
  6191. EXPECT_EQ(files[1].content, "Testing456");
  6192. EXPECT_EQ(files[1].filename, "");
  6193. EXPECT_EQ(files[1].content_type, "");
  6194. });
  6195. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6196. const ContentReader &content_reader) {
  6197. ASSERT_TRUE(req.is_multipart_form_data());
  6198. MultipartFormDataItems files;
  6199. content_reader(
  6200. [&](const MultipartFormData &file) {
  6201. files.push_back(file);
  6202. return true;
  6203. },
  6204. [&](const char *data, size_t data_length) {
  6205. files.back().content.append(data, data_length);
  6206. return true;
  6207. });
  6208. ASSERT_TRUE(files.size() == 2);
  6209. EXPECT_EQ(files[0].name, "name3");
  6210. EXPECT_EQ(files[0].content, rand1);
  6211. EXPECT_EQ(files[0].filename, "filename3");
  6212. EXPECT_EQ(files[0].content_type, "");
  6213. EXPECT_EQ(files[1].name, "name4");
  6214. EXPECT_EQ(files[1].content, rand2);
  6215. EXPECT_EQ(files[1].filename, "filename4");
  6216. EXPECT_EQ(files[1].content_type, "");
  6217. });
  6218. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6219. const ContentReader &content_reader) {
  6220. ASSERT_TRUE(req.is_multipart_form_data());
  6221. MultipartFormDataItems files;
  6222. content_reader(
  6223. [&](const MultipartFormData &file) {
  6224. files.push_back(file);
  6225. return true;
  6226. },
  6227. [&](const char *data, size_t data_length) {
  6228. files.back().content.append(data, data_length);
  6229. return true;
  6230. });
  6231. ASSERT_TRUE(files.size() == 4);
  6232. EXPECT_EQ(std::string(files[0].name), "name1");
  6233. EXPECT_EQ(files[0].content, "Testing123");
  6234. EXPECT_EQ(files[0].filename, "filename1");
  6235. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6236. EXPECT_EQ(files[1].name, "name2");
  6237. EXPECT_EQ(files[1].content, "Testing456");
  6238. EXPECT_EQ(files[1].filename, "");
  6239. EXPECT_EQ(files[1].content_type, "");
  6240. EXPECT_EQ(files[2].name, "name3");
  6241. EXPECT_EQ(files[2].content, rand1);
  6242. EXPECT_EQ(files[2].filename, "filename3");
  6243. EXPECT_EQ(files[2].content_type, "");
  6244. EXPECT_EQ(files[3].name, "name4");
  6245. EXPECT_EQ(files[3].content, rand2);
  6246. EXPECT_EQ(files[3].filename, "filename4");
  6247. EXPECT_EQ(files[3].content_type, "");
  6248. });
  6249. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6250. auto se = detail::scope_exit([&] {
  6251. svr.stop();
  6252. t.join();
  6253. ASSERT_FALSE(svr.is_running());
  6254. });
  6255. svr.wait_until_ready();
  6256. {
  6257. Client cli("https://localhost:8080");
  6258. cli.enable_server_certificate_verification(false);
  6259. MultipartFormDataItems items{
  6260. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6261. {"name2", "Testing456", "", ""}, // not a file
  6262. };
  6263. {
  6264. auto res = cli.Post("/post-none", {}, {}, {});
  6265. ASSERT_TRUE(res);
  6266. ASSERT_EQ(StatusCode::OK_200, res->status);
  6267. }
  6268. MultipartFormDataProviderItems providers;
  6269. {
  6270. auto res =
  6271. cli.Post("/post-items", {}, items, providers); // empty providers
  6272. ASSERT_TRUE(res);
  6273. ASSERT_EQ(StatusCode::OK_200, res->status);
  6274. }
  6275. providers.push_back({"name3",
  6276. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6277. // test the offset is given correctly at each step
  6278. if (!offset)
  6279. sink.os.write(rand1.data(), 30);
  6280. else if (offset == 30)
  6281. sink.os.write(rand1.data() + 30, 300);
  6282. else if (offset == 330)
  6283. sink.os.write(rand1.data() + 330, 670);
  6284. else if (offset == rand1.size())
  6285. sink.done();
  6286. return true;
  6287. },
  6288. "filename3",
  6289. {}});
  6290. providers.push_back({"name4",
  6291. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6292. // test the offset is given correctly at each step
  6293. if (!offset)
  6294. sink.os.write(rand2.data(), 2000);
  6295. else if (offset == 2000)
  6296. sink.os.write(rand2.data() + 2000, 1);
  6297. else if (offset == 2001)
  6298. sink.os.write(rand2.data() + 2001, 999);
  6299. else if (offset == rand2.size())
  6300. sink.done();
  6301. return true;
  6302. },
  6303. "filename4",
  6304. {}});
  6305. {
  6306. auto res = cli.Post("/post-providers", {}, {}, providers);
  6307. ASSERT_TRUE(res);
  6308. ASSERT_EQ(StatusCode::OK_200, res->status);
  6309. }
  6310. {
  6311. auto res = cli.Post("/post-both", {}, items, providers);
  6312. ASSERT_TRUE(res);
  6313. ASSERT_EQ(StatusCode::OK_200, res->status);
  6314. }
  6315. }
  6316. }
  6317. TEST(MultipartFormDataTest, BadHeader) {
  6318. Server svr;
  6319. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6320. res.set_content("ok", "text/plain");
  6321. });
  6322. thread t = thread([&] { svr.listen(HOST, PORT); });
  6323. auto se = detail::scope_exit([&] {
  6324. svr.stop();
  6325. t.join();
  6326. ASSERT_FALSE(svr.is_running());
  6327. });
  6328. svr.wait_until_ready();
  6329. const std::string body =
  6330. "This is the preamble. It is to be ignored, though it\r\n"
  6331. "is a handy place for composition agents to include an\r\n"
  6332. "explanatory note to non-MIME conformant readers.\r\n"
  6333. "\r\n"
  6334. "\r\n"
  6335. "--simple boundary\r\n"
  6336. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6337. ": BAD...\r\n"
  6338. "\r\n"
  6339. "value1\r\n"
  6340. "--simple boundary\r\n"
  6341. "Content-Disposition: form-data; name=\"field2\"; "
  6342. "filename=\"example.txt\"\r\n"
  6343. "\r\n"
  6344. "value2\r\n"
  6345. "--simple boundary--\r\n"
  6346. "This is the epilogue. It is also to be ignored.\r\n";
  6347. std::string content_type =
  6348. R"(multipart/form-data; boundary="simple boundary")";
  6349. Client cli(HOST, PORT);
  6350. auto res = cli.Post("/post", body, content_type.c_str());
  6351. ASSERT_TRUE(res);
  6352. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6353. }
  6354. TEST(MultipartFormDataTest, WithPreamble) {
  6355. Server svr;
  6356. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6357. res.set_content("ok", "text/plain");
  6358. });
  6359. thread t = thread([&] { svr.listen(HOST, PORT); });
  6360. auto se = detail::scope_exit([&] {
  6361. svr.stop();
  6362. t.join();
  6363. ASSERT_FALSE(svr.is_running());
  6364. });
  6365. svr.wait_until_ready();
  6366. const std::string body =
  6367. "This is the preamble. It is to be ignored, though it\r\n"
  6368. "is a handy place for composition agents to include an\r\n"
  6369. "explanatory note to non-MIME conformant readers.\r\n"
  6370. "\r\n"
  6371. "\r\n"
  6372. "--simple boundary\r\n"
  6373. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6374. "\r\n"
  6375. "value1\r\n"
  6376. "--simple boundary\r\n"
  6377. "Content-Disposition: form-data; name=\"field2\"; "
  6378. "filename=\"example.txt\"\r\n"
  6379. "\r\n"
  6380. "value2\r\n"
  6381. "--simple boundary--\r\n"
  6382. "This is the epilogue. It is also to be ignored.\r\n";
  6383. std::string content_type =
  6384. R"(multipart/form-data; boundary="simple boundary")";
  6385. Client cli(HOST, PORT);
  6386. auto res = cli.Post("/post", body, content_type.c_str());
  6387. ASSERT_TRUE(res);
  6388. EXPECT_EQ(StatusCode::OK_200, res->status);
  6389. }
  6390. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6392. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6393. const ContentReader &content_reader) {
  6394. if (req.is_multipart_form_data()) {
  6395. MultipartFormDataItems files;
  6396. content_reader(
  6397. [&](const MultipartFormData &file) {
  6398. files.push_back(file);
  6399. return true;
  6400. },
  6401. [&](const char *data, size_t data_length) {
  6402. files.back().content.append(data, data_length);
  6403. return true;
  6404. });
  6405. EXPECT_TRUE(std::string(files[0].name) == "document");
  6406. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6407. EXPECT_TRUE(files[0].filename == "2MB_data");
  6408. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6409. EXPECT_TRUE(files[1].name == "hello");
  6410. EXPECT_TRUE(files[1].content == "world");
  6411. EXPECT_TRUE(files[1].filename == "");
  6412. EXPECT_TRUE(files[1].content_type == "");
  6413. } else {
  6414. std::string body;
  6415. content_reader([&](const char *data, size_t data_length) {
  6416. body.append(data, data_length);
  6417. return true;
  6418. });
  6419. }
  6420. });
  6421. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6422. auto se = detail::scope_exit([&] {
  6423. svr.stop();
  6424. t.join();
  6425. ASSERT_FALSE(svr.is_running());
  6426. });
  6427. svr.wait_until_ready();
  6428. {
  6429. std::string data(1024 * 1024 * 2, '.');
  6430. std::stringstream buffer;
  6431. buffer << data;
  6432. Client cli("https://localhost:8080");
  6433. cli.enable_server_certificate_verification(false);
  6434. MultipartFormDataItems items{
  6435. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6436. {"hello", "world", "", ""},
  6437. };
  6438. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6439. ASSERT_TRUE(res);
  6440. ASSERT_EQ(StatusCode::OK_200, res->status);
  6441. }
  6442. }
  6443. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6444. std::string data(1024 * 1024 * 2, '&');
  6445. std::stringstream buffer;
  6446. buffer << data;
  6447. Client cli("https://localhost:8080");
  6448. MultipartFormDataItems items{
  6449. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6450. {"hello", "world", "", ""},
  6451. };
  6452. for (const char &c : " \t\r\n") {
  6453. auto res =
  6454. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6455. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6456. ASSERT_FALSE(res);
  6457. }
  6458. }
  6459. TEST(MultipartFormDataTest, PutFormData) {
  6460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6461. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6462. const ContentReader &content_reader) {
  6463. if (req.is_multipart_form_data()) {
  6464. MultipartFormDataItems files;
  6465. content_reader(
  6466. [&](const MultipartFormData &file) {
  6467. files.push_back(file);
  6468. return true;
  6469. },
  6470. [&](const char *data, size_t data_length) {
  6471. files.back().content.append(data, data_length);
  6472. return true;
  6473. });
  6474. EXPECT_TRUE(std::string(files[0].name) == "document");
  6475. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6476. EXPECT_TRUE(files[0].filename == "2MB_data");
  6477. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6478. EXPECT_TRUE(files[1].name == "hello");
  6479. EXPECT_TRUE(files[1].content == "world");
  6480. EXPECT_TRUE(files[1].filename == "");
  6481. EXPECT_TRUE(files[1].content_type == "");
  6482. } else {
  6483. std::string body;
  6484. content_reader([&](const char *data, size_t data_length) {
  6485. body.append(data, data_length);
  6486. return true;
  6487. });
  6488. }
  6489. });
  6490. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6491. auto se = detail::scope_exit([&] {
  6492. svr.stop();
  6493. t.join();
  6494. ASSERT_FALSE(svr.is_running());
  6495. });
  6496. svr.wait_until_ready();
  6497. {
  6498. std::string data(1024 * 1024 * 2, '&');
  6499. std::stringstream buffer;
  6500. buffer << data;
  6501. Client cli("https://localhost:8080");
  6502. cli.enable_server_certificate_verification(false);
  6503. MultipartFormDataItems items{
  6504. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6505. {"hello", "world", "", ""},
  6506. };
  6507. auto res = cli.Put("/put", items);
  6508. ASSERT_TRUE(res);
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. }
  6511. }
  6512. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6514. svr.Put("/put_customboundary",
  6515. [&](const Request &req, const Response & /*res*/,
  6516. const ContentReader &content_reader) {
  6517. if (req.is_multipart_form_data()) {
  6518. MultipartFormDataItems files;
  6519. content_reader(
  6520. [&](const MultipartFormData &file) {
  6521. files.push_back(file);
  6522. return true;
  6523. },
  6524. [&](const char *data, size_t data_length) {
  6525. files.back().content.append(data, data_length);
  6526. return true;
  6527. });
  6528. EXPECT_TRUE(std::string(files[0].name) == "document");
  6529. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6530. EXPECT_TRUE(files[0].filename == "2MB_data");
  6531. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6532. EXPECT_TRUE(files[1].name == "hello");
  6533. EXPECT_TRUE(files[1].content == "world");
  6534. EXPECT_TRUE(files[1].filename == "");
  6535. EXPECT_TRUE(files[1].content_type == "");
  6536. } else {
  6537. std::string body;
  6538. content_reader([&](const char *data, size_t data_length) {
  6539. body.append(data, data_length);
  6540. return true;
  6541. });
  6542. }
  6543. });
  6544. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6545. auto se = detail::scope_exit([&] {
  6546. svr.stop();
  6547. t.join();
  6548. ASSERT_FALSE(svr.is_running());
  6549. });
  6550. svr.wait_until_ready();
  6551. {
  6552. std::string data(1024 * 1024 * 2, '&');
  6553. std::stringstream buffer;
  6554. buffer << data;
  6555. Client cli("https://localhost:8080");
  6556. cli.enable_server_certificate_verification(false);
  6557. MultipartFormDataItems items{
  6558. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6559. {"hello", "world", "", ""},
  6560. };
  6561. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6562. ASSERT_TRUE(res);
  6563. ASSERT_EQ(StatusCode::OK_200, res->status);
  6564. }
  6565. }
  6566. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6567. std::string data(1024 * 1024 * 2, '&');
  6568. std::stringstream buffer;
  6569. buffer << data;
  6570. Client cli("https://localhost:8080");
  6571. cli.enable_server_certificate_verification(false);
  6572. MultipartFormDataItems items{
  6573. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6574. {"hello", "world", "", ""},
  6575. };
  6576. for (const char &c : " \t\r\n") {
  6577. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6578. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6579. ASSERT_FALSE(res);
  6580. }
  6581. }
  6582. TEST(MultipartFormDataTest, AlternateFilename) {
  6583. auto handled = false;
  6584. Server svr;
  6585. svr.Post("/test", [&](const Request &req, Response &res) {
  6586. ASSERT_EQ(3u, req.files.size());
  6587. auto it = req.files.begin();
  6588. ASSERT_EQ("file1", it->second.name);
  6589. ASSERT_EQ("A.txt", it->second.filename);
  6590. ASSERT_EQ("text/plain", it->second.content_type);
  6591. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6592. ++it;
  6593. ASSERT_EQ("file2", it->second.name);
  6594. ASSERT_EQ("a.html", it->second.filename);
  6595. ASSERT_EQ("text/html", it->second.content_type);
  6596. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6597. it->second.content);
  6598. ++it;
  6599. ASSERT_EQ("text", it->second.name);
  6600. ASSERT_EQ("", it->second.filename);
  6601. ASSERT_EQ("", it->second.content_type);
  6602. ASSERT_EQ("text default", it->second.content);
  6603. res.set_content("ok", "text/plain");
  6604. handled = true;
  6605. });
  6606. thread t = thread([&] { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. t.join();
  6610. ASSERT_FALSE(svr.is_running());
  6611. ASSERT_TRUE(handled);
  6612. });
  6613. svr.wait_until_ready();
  6614. auto req = "POST /test HTTP/1.1\r\n"
  6615. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6616. "Content-Length: 399\r\n"
  6617. "\r\n"
  6618. "----------\r\n"
  6619. "Content-Disposition: form-data; name=\"text\"\r\n"
  6620. "\r\n"
  6621. "text default\r\n"
  6622. "----------\r\n"
  6623. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6624. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6625. "Content-Type: text/plain\r\n"
  6626. "\r\n"
  6627. "Content of a.txt.\r\n"
  6628. "\r\n"
  6629. "----------\r\n"
  6630. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6631. "\"a.html\"\r\n"
  6632. "Content-Type: text/html\r\n"
  6633. "\r\n"
  6634. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6635. "\r\n"
  6636. "------------\r\n";
  6637. ASSERT_TRUE(send_request(1, req));
  6638. }
  6639. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6640. auto handled = false;
  6641. Server svr;
  6642. svr.Post("/test", [&](const Request &req, Response &) {
  6643. ASSERT_EQ(2u, req.files.size());
  6644. auto it = req.files.begin();
  6645. ASSERT_EQ("text1", it->second.name);
  6646. ASSERT_EQ("text1", it->second.content);
  6647. ++it;
  6648. ASSERT_EQ("text2", it->second.name);
  6649. ASSERT_EQ("text2", it->second.content);
  6650. handled = true;
  6651. });
  6652. thread t = thread([&] { svr.listen(HOST, PORT); });
  6653. auto se = detail::scope_exit([&] {
  6654. svr.stop();
  6655. t.join();
  6656. ASSERT_FALSE(svr.is_running());
  6657. ASSERT_TRUE(handled);
  6658. });
  6659. svr.wait_until_ready();
  6660. auto req = "POST /test HTTP/1.1\r\n"
  6661. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6662. "Content-Length: 146\r\n"
  6663. "\r\n----------\r\n"
  6664. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6665. "\r\n"
  6666. "text1"
  6667. "\r\n----------\r\n"
  6668. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6669. "\r\n"
  6670. "text2"
  6671. "\r\n------------";
  6672. std::string response;
  6673. ASSERT_TRUE(send_request(1, req, &response));
  6674. ASSERT_EQ("200", response.substr(9, 3));
  6675. }
  6676. TEST(MultipartFormDataTest, ContentLength) {
  6677. auto handled = false;
  6678. Server svr;
  6679. svr.Post("/test", [&](const Request &req, Response &) {
  6680. ASSERT_EQ(2u, req.files.size());
  6681. auto it = req.files.begin();
  6682. ASSERT_EQ("text1", it->second.name);
  6683. ASSERT_EQ("text1", it->second.content);
  6684. ++it;
  6685. ASSERT_EQ("text2", it->second.name);
  6686. ASSERT_EQ("text2", it->second.content);
  6687. handled = true;
  6688. });
  6689. thread t = thread([&] { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. t.join();
  6693. ASSERT_FALSE(svr.is_running());
  6694. ASSERT_TRUE(handled);
  6695. });
  6696. svr.wait_until_ready();
  6697. auto req = "POST /test HTTP/1.1\r\n"
  6698. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6699. "Content-Length: 167\r\n"
  6700. "\r\n----------\r\n"
  6701. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6702. "Content-Length: 5\r\n"
  6703. "\r\n"
  6704. "text1"
  6705. "\r\n----------\r\n"
  6706. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6707. "\r\n"
  6708. "text2"
  6709. "\r\n------------\r\n";
  6710. std::string response;
  6711. ASSERT_TRUE(send_request(1, req, &response));
  6712. ASSERT_EQ("200", response.substr(9, 3));
  6713. }
  6714. #endif
  6715. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6716. static constexpr unsigned int number_of_tasks{1000000};
  6717. std::atomic_uint count{0};
  6718. std::unique_ptr<TaskQueue> task_queue{
  6719. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6720. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6721. auto queued = task_queue->enqueue(
  6722. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6723. EXPECT_TRUE(queued);
  6724. }
  6725. EXPECT_NO_THROW(task_queue->shutdown());
  6726. EXPECT_EQ(number_of_tasks, count.load());
  6727. }
  6728. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6729. static constexpr unsigned int number_of_tasks{1000000};
  6730. static constexpr unsigned int qlimit{2};
  6731. unsigned int queued_count{0};
  6732. std::atomic_uint count{0};
  6733. std::unique_ptr<TaskQueue> task_queue{
  6734. new ThreadPool{/*num_threads=*/1, qlimit}};
  6735. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6736. if (task_queue->enqueue(
  6737. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6738. queued_count++;
  6739. }
  6740. }
  6741. EXPECT_NO_THROW(task_queue->shutdown());
  6742. EXPECT_EQ(queued_count, count.load());
  6743. EXPECT_TRUE(queued_count <= number_of_tasks);
  6744. EXPECT_TRUE(queued_count >= qlimit);
  6745. }
  6746. TEST(TaskQueueTest, MaxQueuedRequests) {
  6747. static constexpr unsigned int qlimit{3};
  6748. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6749. std::condition_variable sem_cv;
  6750. std::mutex sem_mtx;
  6751. int credits = 0;
  6752. bool queued;
  6753. /* Fill up the queue with tasks that will block until we give them credits to
  6754. * complete. */
  6755. for (unsigned int n = 0; n <= qlimit;) {
  6756. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6757. std::unique_lock<std::mutex> lock(sem_mtx);
  6758. while (credits <= 0) {
  6759. sem_cv.wait(lock);
  6760. }
  6761. /* Consume the credit and signal the test code if they are all gone. */
  6762. if (--credits == 0) { sem_cv.notify_one(); }
  6763. });
  6764. if (n < qlimit) {
  6765. /* The first qlimit enqueues must succeed. */
  6766. EXPECT_TRUE(queued);
  6767. } else {
  6768. /* The last one will succeed only when the worker thread
  6769. * starts and dequeues the first blocking task. Although
  6770. * not necessary for the correctness of this test, we sleep for
  6771. * a short while to avoid busy waiting. */
  6772. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6773. }
  6774. if (queued) { n++; }
  6775. }
  6776. /* Further enqueues must fail since the queue is full. */
  6777. for (auto i = 0; i < 4; i++) {
  6778. queued = task_queue->enqueue([] {});
  6779. EXPECT_FALSE(queued);
  6780. }
  6781. /* Give the credits to allow the previous tasks to complete. */
  6782. {
  6783. std::unique_lock<std::mutex> lock(sem_mtx);
  6784. credits += qlimit + 1;
  6785. }
  6786. sem_cv.notify_all();
  6787. /* Wait for all the credits to be consumed. */
  6788. {
  6789. std::unique_lock<std::mutex> lock(sem_mtx);
  6790. while (credits > 0) {
  6791. sem_cv.wait(lock);
  6792. }
  6793. }
  6794. /* Check that we are able again to enqueue at least qlimit tasks. */
  6795. for (unsigned int i = 0; i < qlimit; i++) {
  6796. queued = task_queue->enqueue([] {});
  6797. EXPECT_TRUE(queued);
  6798. }
  6799. EXPECT_NO_THROW(task_queue->shutdown());
  6800. }
  6801. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6802. Server svr;
  6803. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6804. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6805. });
  6806. svr.Get("/hello", [](const Request &req, Response &res) {
  6807. res.set_content(req.get_param_value("key"), "text/plain");
  6808. });
  6809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6810. auto se = detail::scope_exit([&] {
  6811. svr.stop();
  6812. thread.join();
  6813. ASSERT_FALSE(svr.is_running());
  6814. });
  6815. svr.wait_until_ready();
  6816. {
  6817. Client cli(HOST, PORT);
  6818. cli.set_follow_location(true);
  6819. auto res = cli.Get("/");
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("val&key2=val2", res->body);
  6823. }
  6824. }
  6825. TEST(VulnerabilityTest, CRLFInjection) {
  6826. Server svr;
  6827. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6828. res.set_content("Hello 1", "text/plain");
  6829. });
  6830. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6831. res.set_content("Hello 2", "text/plain");
  6832. });
  6833. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6834. res.set_content("Hello 3", "text/plain");
  6835. });
  6836. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6837. res.set_content("Hello 4", "text/plain");
  6838. });
  6839. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6840. for (const auto &x : req.headers) {
  6841. auto key = x.first;
  6842. EXPECT_STRNE("evil", key.c_str());
  6843. }
  6844. });
  6845. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6846. auto se = detail::scope_exit([&] {
  6847. svr.stop();
  6848. thread.join();
  6849. ASSERT_FALSE(svr.is_running());
  6850. });
  6851. svr.wait_until_ready();
  6852. {
  6853. Client cli(HOST, PORT);
  6854. cli.Post("/test1", "A=B",
  6855. "application/x-www-form-urlencoded\r\nevil: hello1");
  6856. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6857. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6858. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6859. }
  6860. }
  6861. TEST(PathParamsTest, StaticMatch) {
  6862. const auto pattern = "/users/all";
  6863. detail::PathParamsMatcher matcher(pattern);
  6864. Request request;
  6865. request.path = "/users/all";
  6866. ASSERT_TRUE(matcher.match(request));
  6867. std::unordered_map<std::string, std::string> expected_params = {};
  6868. EXPECT_EQ(request.path_params, expected_params);
  6869. }
  6870. TEST(PathParamsTest, StaticMismatch) {
  6871. const auto pattern = "/users/all";
  6872. detail::PathParamsMatcher matcher(pattern);
  6873. Request request;
  6874. request.path = "/users/1";
  6875. ASSERT_FALSE(matcher.match(request));
  6876. }
  6877. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6878. const auto pattern = "/users/:id/subscriptions";
  6879. detail::PathParamsMatcher matcher(pattern);
  6880. Request request;
  6881. request.path = "/users/42/subscriptions";
  6882. ASSERT_TRUE(matcher.match(request));
  6883. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6884. EXPECT_EQ(request.path_params, expected_params);
  6885. }
  6886. TEST(PathParamsTest, SingleParamInTheEnd) {
  6887. const auto pattern = "/users/:id";
  6888. detail::PathParamsMatcher matcher(pattern);
  6889. Request request;
  6890. request.path = "/users/24";
  6891. ASSERT_TRUE(matcher.match(request));
  6892. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6893. EXPECT_EQ(request.path_params, expected_params);
  6894. }
  6895. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6896. const auto pattern = "/users/:id/";
  6897. detail::PathParamsMatcher matcher(pattern);
  6898. Request request;
  6899. request.path = "/users/42/";
  6900. ASSERT_TRUE(matcher.match(request));
  6901. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6902. EXPECT_EQ(request.path_params, expected_params);
  6903. }
  6904. TEST(PathParamsTest, EmptyParam) {
  6905. const auto pattern = "/users/:id/";
  6906. detail::PathParamsMatcher matcher(pattern);
  6907. Request request;
  6908. request.path = "/users//";
  6909. ASSERT_TRUE(matcher.match(request));
  6910. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6911. EXPECT_EQ(request.path_params, expected_params);
  6912. }
  6913. TEST(PathParamsTest, FragmentMismatch) {
  6914. const auto pattern = "/users/:id/";
  6915. detail::PathParamsMatcher matcher(pattern);
  6916. Request request;
  6917. request.path = "/admins/24/";
  6918. ASSERT_FALSE(matcher.match(request));
  6919. }
  6920. TEST(PathParamsTest, ExtraFragments) {
  6921. const auto pattern = "/users/:id";
  6922. detail::PathParamsMatcher matcher(pattern);
  6923. Request request;
  6924. request.path = "/users/42/subscriptions";
  6925. ASSERT_FALSE(matcher.match(request));
  6926. }
  6927. TEST(PathParamsTest, MissingTrailingParam) {
  6928. const auto pattern = "/users/:id";
  6929. detail::PathParamsMatcher matcher(pattern);
  6930. Request request;
  6931. request.path = "/users";
  6932. ASSERT_FALSE(matcher.match(request));
  6933. }
  6934. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6935. const auto pattern = "/users/:id/subscriptions";
  6936. detail::PathParamsMatcher matcher(pattern);
  6937. Request request;
  6938. request.path = "/users/subscriptions";
  6939. ASSERT_FALSE(matcher.match(request));
  6940. }
  6941. TEST(PathParamsTest, MultipleParams) {
  6942. const auto pattern = "/users/:userid/subscriptions/:subid";
  6943. detail::PathParamsMatcher matcher(pattern);
  6944. Request request;
  6945. request.path = "/users/42/subscriptions/2";
  6946. ASSERT_TRUE(matcher.match(request));
  6947. std::unordered_map<std::string, std::string> expected_params = {
  6948. {"userid", "42"}, {"subid", "2"}};
  6949. EXPECT_EQ(request.path_params, expected_params);
  6950. }
  6951. TEST(PathParamsTest, SequenceOfParams) {
  6952. const auto pattern = "/values/:x/:y/:z";
  6953. detail::PathParamsMatcher matcher(pattern);
  6954. Request request;
  6955. request.path = "/values/1/2/3";
  6956. ASSERT_TRUE(matcher.match(request));
  6957. std::unordered_map<std::string, std::string> expected_params = {
  6958. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6959. EXPECT_EQ(request.path_params, expected_params);
  6960. }
  6961. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6962. const auto pattern = "/prefix:suffix";
  6963. detail::PathParamsMatcher matcher(pattern);
  6964. Request request;
  6965. request.path = "/prefix:suffix";
  6966. ASSERT_TRUE(matcher.match(request));
  6967. const std::unordered_map<std::string, std::string> expected_params = {};
  6968. EXPECT_EQ(request.path_params, expected_params);
  6969. }
  6970. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6971. // If ipv6 regex working, regex match codepath is taken.
  6972. // else port will default to 80 in Client impl
  6973. int clientImplMagicPort = 80;
  6974. int port = 4321;
  6975. // above ports must be different to avoid false negative
  6976. EXPECT_NE(clientImplMagicPort, port);
  6977. std::string ipV6TestURL = "http://[ff06::c3]";
  6978. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6979. CLIENT_PRIVATE_KEY_FILE);
  6980. EXPECT_EQ(cli.port(), port);
  6981. }
  6982. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6983. auto file_path = "./www/dir/index.html";
  6984. auto dir_path = "./www/dir";
  6985. detail::FileStat stat_file(file_path);
  6986. EXPECT_TRUE(stat_file.is_file());
  6987. EXPECT_FALSE(stat_file.is_dir());
  6988. detail::FileStat stat_dir(dir_path);
  6989. EXPECT_FALSE(stat_dir.is_file());
  6990. EXPECT_TRUE(stat_dir.is_dir());
  6991. }
  6992. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6993. Server svr;
  6994. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6995. EXPECT_EQ(res.status, 400);
  6996. });
  6997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. thread.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. Client cli(HOST, PORT);
  7005. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  7006. }
  7007. TEST(InvalidHeaderCharsTest, is_field_name) {
  7008. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  7009. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  7010. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  7011. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  7012. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  7013. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  7014. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  7015. EXPECT_FALSE(detail::fields::is_field_name(""));
  7016. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  7017. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  7018. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  7019. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  7020. }
  7021. TEST(InvalidHeaderCharsTest, is_field_value) {
  7022. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  7023. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  7024. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  7025. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  7026. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  7027. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  7028. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  7029. EXPECT_TRUE(detail::fields::is_field_value(""));
  7030. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  7031. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  7032. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  7033. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  7034. EXPECT_TRUE(detail::fields::is_field_value("0"));
  7035. }
  7036. TEST(InvalidHeaderCharsTest, OnServer) {
  7037. Server svr;
  7038. svr.Get("/test_name", [&](const Request &req, Response &res) {
  7039. std::string header = "Not Set";
  7040. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7041. res.set_header(header, "value");
  7042. res.set_content("Page Content Page Content", "text/plain");
  7043. });
  7044. svr.Get("/test_value", [&](const Request &req, Response &res) {
  7045. std::string header = "Not Set";
  7046. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7047. res.set_header("X-Test", header);
  7048. res.set_content("Page Content Page Content", "text/plain");
  7049. });
  7050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. thread.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli(HOST, PORT);
  7058. {
  7059. auto res = cli.Get(
  7060. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7061. ASSERT_TRUE(res);
  7062. EXPECT_EQ("Page Content Page Content", res->body);
  7063. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7064. }
  7065. {
  7066. auto res = cli.Get(
  7067. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7068. ASSERT_TRUE(res);
  7069. EXPECT_EQ("Page Content Page Content", res->body);
  7070. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7071. }
  7072. }
  7073. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  7074. auto handled = false;
  7075. Server svr;
  7076. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  7077. thread t = thread([&] { svr.listen(HOST, PORT); });
  7078. auto se = detail::scope_exit([&] {
  7079. svr.stop();
  7080. t.join();
  7081. ASSERT_FALSE(svr.is_running());
  7082. ASSERT_FALSE(handled);
  7083. });
  7084. svr.wait_until_ready();
  7085. auto req = "POST /test HTTP/1.1\r\n"
  7086. "Content-Length: x\r\n"
  7087. "\r\n";
  7088. std::string response;
  7089. ASSERT_TRUE(send_request(1, req, &response));
  7090. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7091. response.substr(0, response.find("\r\n")));
  7092. }
  7093. #ifndef _WIN32
  7094. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7095. static constexpr char reject[] = "Unauthorized";
  7096. static constexpr char accept[] = "Upload accepted";
  7097. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7098. Server svr;
  7099. svr.set_expect_100_continue_handler(
  7100. [](const Request & /*req*/, Response &res) {
  7101. res.status = StatusCode::Unauthorized_401;
  7102. res.set_content(reject, "text/plain");
  7103. return res.status;
  7104. });
  7105. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7106. res.set_content(accept, "text/plain");
  7107. });
  7108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7109. auto se = detail::scope_exit([&] {
  7110. svr.stop();
  7111. thread.join();
  7112. ASSERT_FALSE(svr.is_running());
  7113. });
  7114. svr.wait_until_ready();
  7115. {
  7116. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7117. curl_easy_init(), &curl_easy_cleanup};
  7118. ASSERT_NE(curl, nullptr);
  7119. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7120. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7121. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7122. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7123. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7124. &curl_slist_free_all};
  7125. ASSERT_NE(list, nullptr);
  7126. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7127. struct read_data {
  7128. size_t read_size;
  7129. size_t total_size;
  7130. } data = {0, total_size};
  7131. using read_callback_t =
  7132. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7133. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7134. void *userdata) -> size_t {
  7135. read_data *data = (read_data *)userdata;
  7136. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7137. std::fill_n(ptr, size * nmemb, 'A');
  7138. data->read_size += size * nmemb;
  7139. return size * nmemb;
  7140. };
  7141. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7142. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7143. std::vector<char> buffer;
  7144. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7145. using write_callback_t =
  7146. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7147. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7148. void *userdata) -> size_t {
  7149. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7150. buffer->reserve(buffer->size() + size * nmemb + 1);
  7151. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7152. return size * nmemb;
  7153. };
  7154. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7155. {
  7156. const auto res = curl_easy_perform(curl.get());
  7157. ASSERT_EQ(res, CURLE_OK);
  7158. }
  7159. {
  7160. auto response_code = long{};
  7161. const auto res =
  7162. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7163. ASSERT_EQ(res, CURLE_OK);
  7164. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7165. }
  7166. {
  7167. auto dl = curl_off_t{};
  7168. const auto res =
  7169. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7170. ASSERT_EQ(res, CURLE_OK);
  7171. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7172. }
  7173. {
  7174. buffer.push_back('\0');
  7175. ASSERT_STRCASEEQ(buffer.data(), reject);
  7176. }
  7177. }
  7178. }
  7179. #endif
  7180. template <typename S, typename C>
  7181. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7182. svr.Get("/stream", [&](const Request &, Response &res) {
  7183. auto data = new std::string("01234567890123456789");
  7184. res.set_content_provider(
  7185. data->size(), "text/plain",
  7186. [&, data](size_t offset, size_t length, DataSink &sink) {
  7187. const size_t DATA_CHUNK_SIZE = 4;
  7188. const auto &d = *data;
  7189. std::this_thread::sleep_for(std::chrono::seconds(1));
  7190. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7191. return true;
  7192. },
  7193. [data](bool success) {
  7194. EXPECT_FALSE(success);
  7195. delete data;
  7196. });
  7197. });
  7198. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7199. auto i = new size_t(0);
  7200. res.set_content_provider(
  7201. "text/plain",
  7202. [i](size_t, DataSink &sink) {
  7203. if (*i < 5) {
  7204. std::this_thread::sleep_for(std::chrono::seconds(1));
  7205. sink.write("abcd", 4);
  7206. (*i)++;
  7207. } else {
  7208. sink.done();
  7209. }
  7210. return true;
  7211. },
  7212. [i](bool success) {
  7213. EXPECT_FALSE(success);
  7214. delete i;
  7215. });
  7216. });
  7217. svr.Get("/chunked", [&](const Request &, Response &res) {
  7218. auto i = new size_t(0);
  7219. res.set_chunked_content_provider(
  7220. "text/plain",
  7221. [i](size_t, DataSink &sink) {
  7222. if (*i < 5) {
  7223. std::this_thread::sleep_for(std::chrono::seconds(1));
  7224. sink.os << "abcd";
  7225. (*i)++;
  7226. } else {
  7227. sink.done();
  7228. }
  7229. return true;
  7230. },
  7231. [i](bool success) {
  7232. EXPECT_FALSE(success);
  7233. delete i;
  7234. });
  7235. });
  7236. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7237. auto se = detail::scope_exit([&] {
  7238. svr.stop();
  7239. listen_thread.join();
  7240. ASSERT_FALSE(svr.is_running());
  7241. });
  7242. svr.wait_until_ready();
  7243. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7244. {
  7245. auto start = std::chrono::steady_clock::now();
  7246. auto res = cli.Get("/stream");
  7247. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7248. std::chrono::steady_clock::now() - start)
  7249. .count();
  7250. ASSERT_FALSE(res);
  7251. EXPECT_EQ(Error::Read, res.error());
  7252. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7253. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7254. }
  7255. {
  7256. auto start = std::chrono::steady_clock::now();
  7257. auto res = cli.Get("/stream_without_length");
  7258. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7259. std::chrono::steady_clock::now() - start)
  7260. .count();
  7261. ASSERT_FALSE(res);
  7262. EXPECT_EQ(Error::Read, res.error());
  7263. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7264. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7265. }
  7266. {
  7267. auto start = std::chrono::steady_clock::now();
  7268. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  7269. EXPECT_EQ("abcd", string(data, data_length));
  7270. return true;
  7271. });
  7272. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7273. std::chrono::steady_clock::now() - start)
  7274. .count();
  7275. ASSERT_FALSE(res);
  7276. EXPECT_EQ(Error::Read, res.error());
  7277. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7278. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7279. }
  7280. }
  7281. TEST(MaxTimeoutTest, ContentStream) {
  7282. time_t timeout = 2000;
  7283. time_t threshold = 200;
  7284. Server svr;
  7285. Client cli("localhost", PORT);
  7286. max_timeout_test(svr, cli, timeout, threshold);
  7287. }
  7288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7289. TEST(MaxTimeoutTest, ContentStreamSSL) {
  7290. time_t timeout = 2000;
  7291. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  7292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7293. SSLClient cli("localhost", PORT);
  7294. cli.enable_server_certificate_verification(false);
  7295. max_timeout_test(svr, cli, timeout, threshold);
  7296. }
  7297. #endif
  7298. class EventDispatcher {
  7299. public:
  7300. EventDispatcher() {}
  7301. void wait_event(DataSink *sink) {
  7302. unique_lock<mutex> lk(m_);
  7303. int id = id_;
  7304. cv_.wait(lk, [&] { return cid_ == id; });
  7305. sink->write(message_.data(), message_.size());
  7306. }
  7307. void send_event(const string &message) {
  7308. lock_guard<mutex> lk(m_);
  7309. cid_ = id_++;
  7310. message_ = message;
  7311. cv_.notify_all();
  7312. }
  7313. private:
  7314. mutex m_;
  7315. condition_variable cv_;
  7316. atomic_int id_{0};
  7317. atomic_int cid_{-1};
  7318. string message_;
  7319. };
  7320. TEST(ClientInThreadTest, Issue2068) {
  7321. EventDispatcher ed;
  7322. Server svr;
  7323. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  7324. res.set_chunked_content_provider("text/event-stream",
  7325. [&](size_t /*offset*/, DataSink &sink) {
  7326. ed.wait_event(&sink);
  7327. return true;
  7328. });
  7329. });
  7330. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7331. svr.wait_until_ready();
  7332. thread event_thread([&] {
  7333. int id = 0;
  7334. while (svr.is_running()) {
  7335. this_thread::sleep_for(chrono::milliseconds(500));
  7336. std::stringstream ss;
  7337. ss << "data: " << id << "\n\n";
  7338. ed.send_event(ss.str());
  7339. id++;
  7340. }
  7341. });
  7342. auto se = detail::scope_exit([&] {
  7343. svr.stop();
  7344. listen_thread.join();
  7345. event_thread.join();
  7346. ASSERT_FALSE(svr.is_running());
  7347. });
  7348. {
  7349. auto client = detail::make_unique<Client>(HOST, PORT);
  7350. client->set_read_timeout(std::chrono::minutes(10));
  7351. std::atomic<bool> stop{false};
  7352. std::thread t([&] {
  7353. client->Get("/event1",
  7354. [&](const char *, size_t) -> bool { return !stop; });
  7355. });
  7356. std::this_thread::sleep_for(std::chrono::seconds(2));
  7357. stop = true;
  7358. client->stop();
  7359. client.reset();
  7360. t.join();
  7361. }
  7362. }