1
0

test.cc 271 KB

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