test.cc 309 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodeURLTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_url(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodeURLTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(TrimTests, TrimStringTests) {
  252. EXPECT_EQ("abc", detail::trim_copy("abc"));
  253. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  254. EXPECT_TRUE(detail::trim_copy("").empty());
  255. }
  256. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  257. // Simple case without quality values
  258. std::vector<std::string> result1;
  259. EXPECT_TRUE(detail::parse_accept_header(
  260. "text/html,application/json,text/plain", result1));
  261. EXPECT_EQ(result1.size(), 3U);
  262. EXPECT_EQ(result1[0], "text/html");
  263. EXPECT_EQ(result1[1], "application/json");
  264. EXPECT_EQ(result1[2], "text/plain");
  265. // With quality values
  266. std::vector<std::string> result2;
  267. EXPECT_TRUE(detail::parse_accept_header(
  268. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  269. EXPECT_EQ(result2.size(), 3U);
  270. EXPECT_EQ(result2[0], "application/json"); // highest q value
  271. EXPECT_EQ(result2[1], "text/html");
  272. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  273. }
  274. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  275. // Mixed with and without quality values
  276. std::vector<std::string> result;
  277. EXPECT_TRUE(detail::parse_accept_header(
  278. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  279. EXPECT_EQ(result.size(), 3U);
  280. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  281. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  282. EXPECT_EQ(result[2], "application/json"); // q=0.5
  283. }
  284. TEST(ParseAcceptHeaderTest, EdgeCases) {
  285. // Empty header
  286. std::vector<std::string> empty_result;
  287. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  288. EXPECT_TRUE(empty_result.empty());
  289. // Single type
  290. std::vector<std::string> single_result;
  291. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  292. EXPECT_EQ(single_result.size(), 1U);
  293. EXPECT_EQ(single_result[0], "application/json");
  294. // Wildcard types
  295. std::vector<std::string> wildcard_result;
  296. EXPECT_TRUE(detail::parse_accept_header(
  297. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  298. EXPECT_EQ(wildcard_result.size(), 3U);
  299. EXPECT_EQ(wildcard_result[0], "application/json");
  300. EXPECT_EQ(wildcard_result[1], "text/*");
  301. EXPECT_EQ(wildcard_result[2], "*/*");
  302. }
  303. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  304. // Common browser Accept header
  305. std::vector<std::string> browser_result;
  306. EXPECT_TRUE(
  307. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  308. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  309. browser_result));
  310. EXPECT_EQ(browser_result.size(), 6U);
  311. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  312. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  313. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  314. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  315. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  316. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  317. // API client header
  318. std::vector<std::string> api_result;
  319. EXPECT_TRUE(detail::parse_accept_header(
  320. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  321. api_result));
  322. EXPECT_EQ(api_result.size(), 3U);
  323. EXPECT_EQ(api_result[0], "application/json");
  324. EXPECT_EQ(api_result[1], "application/xml");
  325. EXPECT_EQ(api_result[2], "text/plain");
  326. }
  327. TEST(ParseAcceptHeaderTest, SpecialCases) {
  328. // Quality value with 3 decimal places
  329. std::vector<std::string> decimal_result;
  330. EXPECT_TRUE(detail::parse_accept_header(
  331. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  332. EXPECT_EQ(decimal_result.size(), 2U);
  333. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  334. EXPECT_EQ(decimal_result[1], "text/html");
  335. // Zero quality (should still be included but with lowest priority)
  336. std::vector<std::string> zero_q_result;
  337. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  338. zero_q_result));
  339. EXPECT_EQ(zero_q_result.size(), 2U);
  340. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  341. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  342. // No spaces around commas
  343. std::vector<std::string> no_space_result;
  344. EXPECT_TRUE(detail::parse_accept_header(
  345. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  346. no_space_result));
  347. EXPECT_EQ(no_space_result.size(), 3U);
  348. EXPECT_EQ(no_space_result[0], "text/html");
  349. EXPECT_EQ(no_space_result[1], "application/json");
  350. EXPECT_EQ(no_space_result[2], "text/plain");
  351. }
  352. TEST(ParseAcceptHeaderTest, InvalidCases) {
  353. std::vector<std::string> result;
  354. // Invalid quality value (> 1.0)
  355. EXPECT_FALSE(
  356. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  357. // Invalid quality value (< 0.0)
  358. EXPECT_FALSE(
  359. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  360. // Invalid quality value (not a number)
  361. EXPECT_FALSE(detail::parse_accept_header(
  362. "text/html;q=invalid,application/json", result));
  363. // Empty quality value
  364. EXPECT_FALSE(
  365. detail::parse_accept_header("text/html;q=,application/json", result));
  366. // Invalid media type format (no slash and not wildcard)
  367. EXPECT_FALSE(
  368. detail::parse_accept_header("invalidtype,application/json", result));
  369. // Empty media type
  370. result.clear();
  371. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  372. // Only commas
  373. result.clear();
  374. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  375. // Valid cases should still work
  376. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  377. EXPECT_EQ(result.size(), 1U);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1U);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1U);
  384. EXPECT_EQ(result[0], "text/*");
  385. }
  386. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  387. Server svr;
  388. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  389. EXPECT_EQ(req.accept_content_types.size(), 3U);
  390. EXPECT_EQ(req.accept_content_types[0], "application/json");
  391. EXPECT_EQ(req.accept_content_types[1], "text/html");
  392. EXPECT_EQ(req.accept_content_types[2], "*/*");
  393. res.set_content("ok", "text/plain");
  394. });
  395. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  396. EXPECT_TRUE(false);
  397. res.set_content("bad request", "text/plain");
  398. });
  399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  400. auto se = detail::scope_exit([&] {
  401. svr.stop();
  402. listen_thread.join();
  403. ASSERT_FALSE(svr.is_running());
  404. });
  405. svr.wait_until_ready();
  406. Client cli("localhost", PORT);
  407. {
  408. auto res =
  409. cli.Get("/accept_ok",
  410. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ(StatusCode::OK_200, res->status);
  413. }
  414. {
  415. auto res = cli.Get("/accept_bad_request",
  416. {{"Accept", "text/html;q=abc,application/json"}});
  417. ASSERT_TRUE(res);
  418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  419. }
  420. }
  421. TEST(DivideTest, DivideStringTests) {
  422. auto divide = [](const std::string &str, char d) {
  423. std::string lhs;
  424. std::string rhs;
  425. detail::divide(str, d,
  426. [&](const char *lhs_data, std::size_t lhs_size,
  427. const char *rhs_data, std::size_t rhs_size) {
  428. lhs.assign(lhs_data, lhs_size);
  429. rhs.assign(rhs_data, rhs_size);
  430. });
  431. return std::make_pair(std::move(lhs), std::move(rhs));
  432. };
  433. {
  434. const auto res = divide("", '=');
  435. EXPECT_EQ(res.first, "");
  436. EXPECT_EQ(res.second, "");
  437. }
  438. {
  439. const auto res = divide("=", '=');
  440. EXPECT_EQ(res.first, "");
  441. EXPECT_EQ(res.second, "");
  442. }
  443. {
  444. const auto res = divide(" ", '=');
  445. EXPECT_EQ(res.first, " ");
  446. EXPECT_EQ(res.second, "");
  447. }
  448. {
  449. const auto res = divide("a", '=');
  450. EXPECT_EQ(res.first, "a");
  451. EXPECT_EQ(res.second, "");
  452. }
  453. {
  454. const auto res = divide("a=", '=');
  455. EXPECT_EQ(res.first, "a");
  456. EXPECT_EQ(res.second, "");
  457. }
  458. {
  459. const auto res = divide("=b", '=');
  460. EXPECT_EQ(res.first, "");
  461. EXPECT_EQ(res.second, "b");
  462. }
  463. {
  464. const auto res = divide("a=b", '=');
  465. EXPECT_EQ(res.first, "a");
  466. EXPECT_EQ(res.second, "b");
  467. }
  468. {
  469. const auto res = divide("a=b=", '=');
  470. EXPECT_EQ(res.first, "a");
  471. EXPECT_EQ(res.second, "b=");
  472. }
  473. {
  474. const auto res = divide("a=b=c", '=');
  475. EXPECT_EQ(res.first, "a");
  476. EXPECT_EQ(res.second, "b=c");
  477. }
  478. }
  479. TEST(SplitTest, ParseQueryString) {
  480. string s = "key1=val1&key2=val2&key3=val3";
  481. Params dic;
  482. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  483. [&](const char *b, const char *e) {
  484. string key, val;
  485. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  486. if (key.empty()) {
  487. key.assign(b2, e2);
  488. } else {
  489. val.assign(b2, e2);
  490. }
  491. });
  492. dic.emplace(key, val);
  493. });
  494. EXPECT_EQ("val1", dic.find("key1")->second);
  495. EXPECT_EQ("val2", dic.find("key2")->second);
  496. EXPECT_EQ("val3", dic.find("key3")->second);
  497. }
  498. TEST(SplitTest, ParseInvalidQueryTests) {
  499. {
  500. string s = " ";
  501. Params dict;
  502. detail::parse_query_text(s, dict);
  503. EXPECT_TRUE(dict.empty());
  504. }
  505. {
  506. string s = " = =";
  507. Params dict;
  508. detail::parse_query_text(s, dict);
  509. EXPECT_TRUE(dict.empty());
  510. }
  511. }
  512. TEST(ParseQueryTest, ParseQueryString) {
  513. {
  514. std::string s = "key1=val1&key2=val2&key3=val3";
  515. Params dic;
  516. detail::parse_query_text(s, dic);
  517. EXPECT_EQ("val1", dic.find("key1")->second);
  518. EXPECT_EQ("val2", dic.find("key2")->second);
  519. EXPECT_EQ("val3", dic.find("key3")->second);
  520. }
  521. {
  522. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  523. Params dic;
  524. detail::parse_query_text(s, dic);
  525. EXPECT_EQ("", dic.find("key1")->second);
  526. EXPECT_EQ("val1", dic.find("key2")->second);
  527. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  528. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  529. }
  530. }
  531. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  532. Params dic;
  533. EXPECT_EQ(detail::params_to_query_str(dic), "");
  534. dic.emplace("key1", "val1");
  535. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  536. dic.emplace("key2", "val2");
  537. dic.emplace("key3", "val3");
  538. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  539. }
  540. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  541. string content_type = "multipart/form-data; boundary=something";
  542. string boundary;
  543. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  544. EXPECT_TRUE(ret);
  545. EXPECT_EQ(boundary, "something");
  546. }
  547. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  548. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  549. string boundary;
  550. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  551. EXPECT_TRUE(ret);
  552. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  553. }
  554. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  555. string content_type =
  556. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  557. string boundary;
  558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  559. EXPECT_TRUE(ret);
  560. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  561. }
  562. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  563. string content_type =
  564. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  565. string boundary;
  566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  567. EXPECT_TRUE(ret);
  568. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  569. }
  570. TEST(GetHeaderValueTest, DefaultValue) {
  571. Headers headers = {{"Dummy", "Dummy"}};
  572. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  573. EXPECT_STREQ("text/plain", val);
  574. }
  575. TEST(GetHeaderValueTest, DefaultValueInt) {
  576. Headers headers = {{"Dummy", "Dummy"}};
  577. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  578. EXPECT_EQ(100ull, val);
  579. }
  580. TEST(GetHeaderValueTest, RegularValue) {
  581. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  582. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  583. EXPECT_STREQ("text/html", val);
  584. }
  585. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  586. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  587. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  588. EXPECT_STREQ("text/html", val);
  589. }
  590. TEST(GetHeaderValueTest, SetContent) {
  591. Response res;
  592. res.set_content("html", "text/html");
  593. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  594. res.set_content("text", "text/plain");
  595. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  596. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  597. }
  598. TEST(GetHeaderValueTest, RegularValueInt) {
  599. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  600. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  601. EXPECT_EQ(100ull, val);
  602. }
  603. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  604. Headers headers = {{"Content-Length", "x"}};
  605. auto is_invalid_value = false;
  606. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  607. is_invalid_value);
  608. EXPECT_EQ(0ull, val);
  609. EXPECT_TRUE(is_invalid_value);
  610. }
  611. TEST(GetHeaderValueTest, Range) {
  612. {
  613. Headers headers = {make_range_header({{1, -1}})};
  614. auto val = detail::get_header_value(headers, "Range", 0, 0);
  615. EXPECT_STREQ("bytes=1-", val);
  616. }
  617. {
  618. Headers headers = {make_range_header({{-1, 1}})};
  619. auto val = detail::get_header_value(headers, "Range", 0, 0);
  620. EXPECT_STREQ("bytes=-1", val);
  621. }
  622. {
  623. Headers headers = {make_range_header({{1, 10}})};
  624. auto val = detail::get_header_value(headers, "Range", 0, 0);
  625. EXPECT_STREQ("bytes=1-10", val);
  626. }
  627. {
  628. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  629. auto val = detail::get_header_value(headers, "Range", 0, 0);
  630. EXPECT_STREQ("bytes=1-10, 100-", val);
  631. }
  632. {
  633. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  634. auto val = detail::get_header_value(headers, "Range", 0, 0);
  635. EXPECT_STREQ("bytes=1-10, 100-200", val);
  636. }
  637. {
  638. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  639. auto val = detail::get_header_value(headers, "Range", 0, 0);
  640. EXPECT_STREQ("bytes=0-0, -1", val);
  641. }
  642. }
  643. TEST(ParseHeaderValueTest, Range) {
  644. {
  645. Ranges ranges;
  646. auto ret = detail::parse_range_header("bytes=1-", ranges);
  647. EXPECT_TRUE(ret);
  648. EXPECT_EQ(1u, ranges.size());
  649. EXPECT_EQ(1u, ranges[0].first);
  650. EXPECT_EQ(-1, ranges[0].second);
  651. }
  652. {
  653. Ranges ranges;
  654. auto ret = detail::parse_range_header("bytes=-1", ranges);
  655. EXPECT_TRUE(ret);
  656. EXPECT_EQ(1u, ranges.size());
  657. EXPECT_EQ(-1, ranges[0].first);
  658. EXPECT_EQ(1u, ranges[0].second);
  659. }
  660. {
  661. Ranges ranges;
  662. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(1u, ranges.size());
  665. EXPECT_EQ(1u, ranges[0].first);
  666. EXPECT_EQ(10u, ranges[0].second);
  667. }
  668. {
  669. Ranges ranges;
  670. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  671. EXPECT_FALSE(ret);
  672. }
  673. {
  674. Ranges ranges;
  675. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  676. EXPECT_TRUE(ret);
  677. EXPECT_EQ(2u, ranges.size());
  678. EXPECT_EQ(1u, ranges[0].first);
  679. EXPECT_EQ(10u, ranges[0].second);
  680. EXPECT_EQ(100u, ranges[1].first);
  681. EXPECT_EQ(-1, ranges[1].second);
  682. }
  683. {
  684. Ranges ranges;
  685. auto ret =
  686. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  687. EXPECT_TRUE(ret);
  688. EXPECT_EQ(3u, ranges.size());
  689. EXPECT_EQ(1u, ranges[0].first);
  690. EXPECT_EQ(10u, ranges[0].second);
  691. EXPECT_EQ(100u, ranges[1].first);
  692. EXPECT_EQ(200u, ranges[1].second);
  693. EXPECT_EQ(300u, ranges[2].first);
  694. EXPECT_EQ(400u, ranges[2].second);
  695. }
  696. {
  697. Ranges ranges;
  698. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  699. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  700. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  701. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  702. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  703. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  704. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  705. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  706. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  707. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  708. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  709. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  710. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  711. EXPECT_TRUE(ranges.empty());
  712. }
  713. }
  714. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  715. Request req;
  716. req.set_header("Accept-Encoding", "gzip");
  717. Response res;
  718. res.set_header("Content-Type", "text/plain");
  719. auto ret = detail::encoding_type(req, res);
  720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  721. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  722. #else
  723. EXPECT_TRUE(ret == detail::EncodingType::None);
  724. #endif
  725. }
  726. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  727. Request req;
  728. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  729. Response res;
  730. res.set_header("Content-Type", "text/plain");
  731. auto ret = detail::encoding_type(req, res);
  732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  733. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  734. #elif CPPHTTPLIB_ZLIB_SUPPORT
  735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  736. #elif CPPHTTPLIB_ZSTD_SUPPORT
  737. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  738. #else
  739. EXPECT_TRUE(ret == detail::EncodingType::None);
  740. #endif
  741. }
  742. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  743. Request req;
  744. req.set_header("Accept-Encoding",
  745. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  746. Response res;
  747. res.set_header("Content-Type", "text/plain");
  748. auto ret = detail::encoding_type(req, res);
  749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  750. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  751. #elif CPPHTTPLIB_ZLIB_SUPPORT
  752. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  753. #elif CPPHTTPLIB_ZSTD_SUPPORT
  754. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  755. #else
  756. EXPECT_TRUE(ret == detail::EncodingType::None);
  757. #endif
  758. }
  759. TEST(BufferStreamTest, read) {
  760. detail::BufferStream strm1;
  761. Stream &strm = strm1;
  762. EXPECT_EQ(5, strm.write("hello"));
  763. char buf[512];
  764. EXPECT_EQ(2, strm.read(buf, 2));
  765. EXPECT_EQ('h', buf[0]);
  766. EXPECT_EQ('e', buf[1]);
  767. EXPECT_EQ(2, strm.read(buf, 2));
  768. EXPECT_EQ('l', buf[0]);
  769. EXPECT_EQ('l', buf[1]);
  770. EXPECT_EQ(1, strm.read(buf, 1));
  771. EXPECT_EQ('o', buf[0]);
  772. EXPECT_EQ(0, strm.read(buf, 1));
  773. }
  774. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. auto ip = hosted_at(host);
  777. EXPECT_EQ("23.96.13.243", ip);
  778. std::vector<std::string> addrs;
  779. hosted_at(host, addrs);
  780. EXPECT_EQ(1u, addrs.size());
  781. }
  782. #if 0 // It depends on each test environment...
  783. TEST(HostnameToIPConversionTest, YouTube_Online) {
  784. auto host = "www.youtube.com";
  785. std::vector<std::string> addrs;
  786. hosted_at(host, addrs);
  787. EXPECT_EQ(20u, addrs.size());
  788. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  789. EXPECT_TRUE(it != addrs.end());
  790. }
  791. #endif
  792. class ChunkedEncodingTest : public ::testing::Test {
  793. protected:
  794. ChunkedEncodingTest()
  795. : cli_(HOST, PORT)
  796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  797. ,
  798. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  799. #endif
  800. {
  801. cli_.set_connection_timeout(2);
  802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  803. cli_.enable_server_certificate_verification(false);
  804. #endif
  805. }
  806. virtual void SetUp() {
  807. read_file("./image.jpg", image_data_);
  808. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  809. res.set_content("Hello World!", "text/plain");
  810. });
  811. svr_.Get(
  812. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  813. res.set_chunked_content_provider(
  814. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  815. size_t remaining = image_data_.size() - offset;
  816. if (remaining == 0) {
  817. sink.done();
  818. } else {
  819. constexpr size_t CHUNK_SIZE = 1024;
  820. size_t send_size = std::min(CHUNK_SIZE, remaining);
  821. sink.write(&image_data_[offset], send_size);
  822. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  823. }
  824. return true;
  825. });
  826. });
  827. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  828. svr_.wait_until_ready();
  829. }
  830. virtual void TearDown() {
  831. svr_.stop();
  832. if (!request_threads_.empty()) {
  833. std::this_thread::sleep_for(std::chrono::seconds(1));
  834. for (auto &t : request_threads_) {
  835. t.join();
  836. }
  837. }
  838. t_.join();
  839. }
  840. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  841. SSLClient cli_;
  842. SSLServer svr_;
  843. #else
  844. Client cli_;
  845. Server svr_;
  846. #endif
  847. thread t_;
  848. std::vector<thread> request_threads_;
  849. std::string image_data_;
  850. };
  851. TEST_F(ChunkedEncodingTest, NormalGet) {
  852. auto res = cli_.Get("/chunked");
  853. ASSERT_TRUE(res);
  854. std::string out;
  855. read_file("./image.jpg", out);
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. EXPECT_EQ(out, res->body);
  858. }
  859. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  860. std::string body;
  861. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  862. body.append(data, data_length);
  863. return true;
  864. });
  865. ASSERT_TRUE(res);
  866. std::string out;
  867. read_file("./image.jpg", out);
  868. EXPECT_EQ(StatusCode::OK_200, res->status);
  869. EXPECT_EQ(out, body);
  870. }
  871. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  872. std::string body;
  873. auto res = cli_.Get(
  874. "/chunked",
  875. [&](const Response &response) {
  876. EXPECT_EQ(StatusCode::OK_200, response.status);
  877. return true;
  878. },
  879. [&](const char *data, size_t data_length) {
  880. body.append(data, data_length);
  881. return true;
  882. });
  883. ASSERT_TRUE(res);
  884. std::string out;
  885. read_file("./image.jpg", out);
  886. EXPECT_EQ(StatusCode::OK_200, res->status);
  887. EXPECT_EQ(out, body);
  888. }
  889. TEST(RangeTest, FromHTTPBin_Online) {
  890. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  891. auto host = "httpbin.org";
  892. auto path = std::string{"/range/32"};
  893. #else
  894. auto host = "nghttp2.org";
  895. auto path = std::string{"/httpbin/range/32"};
  896. #endif
  897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  898. auto port = 443;
  899. SSLClient cli(host, port);
  900. #else
  901. auto port = 80;
  902. Client cli(host, port);
  903. #endif
  904. cli.set_connection_timeout(5);
  905. {
  906. auto res = cli.Get(path);
  907. ASSERT_TRUE(res);
  908. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  909. EXPECT_EQ(StatusCode::OK_200, res->status);
  910. }
  911. {
  912. Headers headers = {make_range_header({{1, -1}})};
  913. auto res = cli.Get(path, headers);
  914. ASSERT_TRUE(res);
  915. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  917. }
  918. {
  919. Headers headers = {make_range_header({{1, 10}})};
  920. auto res = cli.Get(path, headers);
  921. ASSERT_TRUE(res);
  922. EXPECT_EQ("bcdefghijk", res->body);
  923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  924. }
  925. {
  926. Headers headers = {make_range_header({{0, 31}})};
  927. auto res = cli.Get(path, headers);
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  930. EXPECT_EQ(StatusCode::OK_200, res->status);
  931. }
  932. {
  933. Headers headers = {make_range_header({{0, -1}})};
  934. auto res = cli.Get(path, headers);
  935. ASSERT_TRUE(res);
  936. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  937. EXPECT_EQ(StatusCode::OK_200, res->status);
  938. }
  939. {
  940. Headers headers = {make_range_header({{0, 32}})};
  941. auto res = cli.Get(path, headers);
  942. ASSERT_TRUE(res);
  943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  944. }
  945. }
  946. TEST(ConnectionErrorTest, InvalidHost) {
  947. auto host = "-abcde.com";
  948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  949. auto port = 443;
  950. SSLClient cli(host, port);
  951. #else
  952. auto port = 80;
  953. Client cli(host, port);
  954. #endif
  955. cli.set_connection_timeout(std::chrono::seconds(2));
  956. auto res = cli.Get("/");
  957. ASSERT_TRUE(!res);
  958. EXPECT_EQ(Error::Connection, res.error());
  959. }
  960. TEST(ConnectionErrorTest, InvalidHost2) {
  961. auto host = "httpbin.org/";
  962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  963. SSLClient cli(host);
  964. #else
  965. Client cli(host);
  966. #endif
  967. cli.set_connection_timeout(std::chrono::seconds(2));
  968. auto res = cli.Get("/");
  969. ASSERT_TRUE(!res);
  970. EXPECT_EQ(Error::Connection, res.error());
  971. }
  972. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  973. auto host = "httpbin.org/";
  974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  975. SSLClient cli(host);
  976. #else
  977. Client cli(host);
  978. #endif
  979. cli.set_connection_timeout(std::chrono::seconds(2));
  980. auto res = cli.Get("/");
  981. ASSERT_TRUE(!res);
  982. stringstream s;
  983. s << "error code: " << res.error();
  984. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  985. }
  986. TEST(ConnectionErrorTest, InvalidPort) {
  987. auto host = "localhost";
  988. auto port = 44380;
  989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  990. SSLClient cli(host, port);
  991. #else
  992. Client cli(host, port);
  993. #endif
  994. cli.set_connection_timeout(std::chrono::seconds(2));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(!res);
  997. EXPECT_TRUE(Error::Connection == res.error() ||
  998. Error::ConnectionTimeout == res.error());
  999. }
  1000. TEST(ConnectionErrorTest, Timeout_Online) {
  1001. auto host = "google.com";
  1002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1003. auto port = 44380;
  1004. SSLClient cli(host, port);
  1005. #else
  1006. auto port = 8080;
  1007. Client cli(host, port);
  1008. #endif
  1009. cli.set_connection_timeout(std::chrono::seconds(2));
  1010. // only probe one address type so that the error reason
  1011. // correlates to the timed-out IPv4, not the unsupported
  1012. // IPv6 connection attempt
  1013. cli.set_address_family(AF_INET);
  1014. auto res = cli.Get("/");
  1015. ASSERT_TRUE(!res);
  1016. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1017. }
  1018. TEST(CancelTest, NoCancel_Online) {
  1019. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1020. auto host = "httpbin.org";
  1021. auto path = std::string{"/range/32"};
  1022. #else
  1023. auto host = "nghttp2.org";
  1024. auto path = std::string{"/httpbin/range/32"};
  1025. #endif
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. auto port = 443;
  1028. SSLClient cli(host, port);
  1029. #else
  1030. auto port = 80;
  1031. Client cli(host, port);
  1032. #endif
  1033. cli.set_connection_timeout(std::chrono::seconds(5));
  1034. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1035. ASSERT_TRUE(res);
  1036. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1037. EXPECT_EQ(StatusCode::OK_200, res->status);
  1038. }
  1039. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1040. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1041. auto host = "httpbin.org";
  1042. auto path = std::string{"/range/32"};
  1043. #else
  1044. auto host = "nghttp2.org";
  1045. auto path = std::string{"/httpbin/range/32"};
  1046. #endif
  1047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1048. auto port = 443;
  1049. SSLClient cli(host, port);
  1050. #else
  1051. auto port = 80;
  1052. Client cli(host, port);
  1053. #endif
  1054. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1055. cli.set_connection_timeout(std::chrono::seconds(5));
  1056. ASSERT_TRUE(!res);
  1057. EXPECT_EQ(Error::Canceled, res.error());
  1058. }
  1059. TEST(CancelTest, WithCancelLargePayload_Online) {
  1060. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1061. auto host = "httpbin.org";
  1062. auto path = std::string{"/range/65536"};
  1063. #else
  1064. auto host = "nghttp2.org";
  1065. auto path = std::string{"/httpbin/range/65536"};
  1066. #endif
  1067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1068. auto port = 443;
  1069. SSLClient cli(host, port);
  1070. #else
  1071. auto port = 80;
  1072. Client cli(host, port);
  1073. #endif
  1074. cli.set_connection_timeout(std::chrono::seconds(5));
  1075. uint32_t count = 0;
  1076. auto res =
  1077. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1078. ASSERT_TRUE(!res);
  1079. EXPECT_EQ(Error::Canceled, res.error());
  1080. }
  1081. TEST(CancelTest, NoCancelPost) {
  1082. Server svr;
  1083. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1084. res.set_content("Hello World!", "text/plain");
  1085. });
  1086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1087. auto se = detail::scope_exit([&] {
  1088. svr.stop();
  1089. thread.join();
  1090. ASSERT_FALSE(svr.is_running());
  1091. });
  1092. svr.wait_until_ready();
  1093. Client cli(HOST, PORT);
  1094. cli.set_connection_timeout(std::chrono::seconds(5));
  1095. auto res =
  1096. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1097. "application/json", [](uint64_t, uint64_t) { return true; });
  1098. ASSERT_TRUE(res);
  1099. EXPECT_EQ("Hello World!", res->body);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. }
  1102. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1103. Server svr;
  1104. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1108. auto se = detail::scope_exit([&] {
  1109. svr.stop();
  1110. thread.join();
  1111. ASSERT_FALSE(svr.is_running());
  1112. });
  1113. svr.wait_until_ready();
  1114. Client cli(HOST, PORT);
  1115. cli.set_connection_timeout(std::chrono::seconds(5));
  1116. auto res =
  1117. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1118. "application/json", [](uint64_t, uint64_t) { return false; });
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Canceled, res.error());
  1121. }
  1122. TEST(CancelTest, WithCancelLargePayloadPost) {
  1123. Server svr;
  1124. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1125. res.set_content(LARGE_DATA, "text/plain");
  1126. });
  1127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1128. auto se = detail::scope_exit([&] {
  1129. svr.stop();
  1130. thread.join();
  1131. ASSERT_FALSE(svr.is_running());
  1132. });
  1133. svr.wait_until_ready();
  1134. Client cli(HOST, PORT);
  1135. cli.set_connection_timeout(std::chrono::seconds(5));
  1136. auto res =
  1137. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1138. "application/json", [](uint64_t, uint64_t) { return false; });
  1139. ASSERT_TRUE(!res);
  1140. EXPECT_EQ(Error::Canceled, res.error());
  1141. }
  1142. TEST(CancelTest, NoCancelPut) {
  1143. Server svr;
  1144. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1145. res.set_content("Hello World!", "text/plain");
  1146. });
  1147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1148. auto se = detail::scope_exit([&] {
  1149. svr.stop();
  1150. thread.join();
  1151. ASSERT_FALSE(svr.is_running());
  1152. });
  1153. svr.wait_until_ready();
  1154. Client cli(HOST, PORT);
  1155. cli.set_connection_timeout(std::chrono::seconds(5));
  1156. auto res =
  1157. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1158. "application/json", [](uint64_t, uint64_t) { return true; });
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("Hello World!", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1164. Server svr;
  1165. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1166. res.set_content("Hello World!", "text/plain");
  1167. });
  1168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. thread.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. Client cli(HOST, PORT);
  1176. cli.set_connection_timeout(std::chrono::seconds(5));
  1177. auto res =
  1178. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1179. "application/json", [](uint64_t, uint64_t) { return false; });
  1180. ASSERT_TRUE(!res);
  1181. EXPECT_EQ(Error::Canceled, res.error());
  1182. }
  1183. TEST(CancelTest, WithCancelLargePayloadPut) {
  1184. Server svr;
  1185. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1186. res.set_content(LARGE_DATA, "text/plain");
  1187. });
  1188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1189. auto se = detail::scope_exit([&] {
  1190. svr.stop();
  1191. thread.join();
  1192. ASSERT_FALSE(svr.is_running());
  1193. });
  1194. svr.wait_until_ready();
  1195. Client cli(HOST, PORT);
  1196. cli.set_connection_timeout(std::chrono::seconds(5));
  1197. auto res =
  1198. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1199. "application/json", [](uint64_t, uint64_t) { return false; });
  1200. ASSERT_TRUE(!res);
  1201. EXPECT_EQ(Error::Canceled, res.error());
  1202. }
  1203. TEST(CancelTest, NoCancelPatch) {
  1204. Server svr;
  1205. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1206. res.set_content("Hello World!", "text/plain");
  1207. });
  1208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. thread.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. Client cli(HOST, PORT);
  1216. cli.set_connection_timeout(std::chrono::seconds(5));
  1217. auto res =
  1218. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1219. "application/json", [](uint64_t, uint64_t) { return true; });
  1220. ASSERT_TRUE(res);
  1221. EXPECT_EQ("Hello World!", res->body);
  1222. EXPECT_EQ(StatusCode::OK_200, res->status);
  1223. }
  1224. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1225. Server svr;
  1226. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1227. res.set_content("Hello World!", "text/plain");
  1228. });
  1229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1230. auto se = detail::scope_exit([&] {
  1231. svr.stop();
  1232. thread.join();
  1233. ASSERT_FALSE(svr.is_running());
  1234. });
  1235. svr.wait_until_ready();
  1236. Client cli(HOST, PORT);
  1237. cli.set_connection_timeout(std::chrono::seconds(5));
  1238. auto res =
  1239. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1240. "application/json", [](uint64_t, uint64_t) { return false; });
  1241. ASSERT_TRUE(!res);
  1242. EXPECT_EQ(Error::Canceled, res.error());
  1243. }
  1244. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1245. Server svr;
  1246. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1247. res.set_content(LARGE_DATA, "text/plain");
  1248. });
  1249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1250. auto se = detail::scope_exit([&] {
  1251. svr.stop();
  1252. thread.join();
  1253. ASSERT_FALSE(svr.is_running());
  1254. });
  1255. svr.wait_until_ready();
  1256. Client cli(HOST, PORT);
  1257. cli.set_connection_timeout(std::chrono::seconds(5));
  1258. auto res =
  1259. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1260. "application/json", [](uint64_t, uint64_t) { return false; });
  1261. ASSERT_TRUE(!res);
  1262. EXPECT_EQ(Error::Canceled, res.error());
  1263. }
  1264. TEST(CancelTest, NoCancelDelete) {
  1265. Server svr;
  1266. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return true; });
  1281. ASSERT_TRUE(res);
  1282. EXPECT_EQ("Hello World!", res->body);
  1283. EXPECT_EQ(StatusCode::OK_200, res->status);
  1284. }
  1285. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1286. Server svr;
  1287. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1288. res.set_content("Hello World!", "text/plain");
  1289. });
  1290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1291. auto se = detail::scope_exit([&] {
  1292. svr.stop();
  1293. thread.join();
  1294. ASSERT_FALSE(svr.is_running());
  1295. });
  1296. svr.wait_until_ready();
  1297. Client cli(HOST, PORT);
  1298. cli.set_connection_timeout(std::chrono::seconds(5));
  1299. auto res =
  1300. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1301. "application/json", [](uint64_t, uint64_t) { return false; });
  1302. ASSERT_TRUE(!res);
  1303. EXPECT_EQ(Error::Canceled, res.error());
  1304. }
  1305. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1306. Server svr;
  1307. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1308. res.set_content(LARGE_DATA, "text/plain");
  1309. });
  1310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1311. auto se = detail::scope_exit([&] {
  1312. svr.stop();
  1313. thread.join();
  1314. ASSERT_FALSE(svr.is_running());
  1315. });
  1316. svr.wait_until_ready();
  1317. Client cli(HOST, PORT);
  1318. cli.set_connection_timeout(std::chrono::seconds(5));
  1319. auto res =
  1320. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1321. "application/json", [](uint64_t, uint64_t) { return false; });
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_EQ(Error::Canceled, res.error());
  1324. }
  1325. static std::string remove_whitespace(const std::string &input) {
  1326. std::string output;
  1327. output.reserve(input.size());
  1328. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1329. [](unsigned char c) { return !std::isspace(c); });
  1330. return output;
  1331. }
  1332. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1333. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1334. auto host = "httpbin.org";
  1335. auto path = std::string{"/basic-auth/hello/world"};
  1336. #else
  1337. auto host = "nghttp2.org";
  1338. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1339. #endif
  1340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1341. auto port = 443;
  1342. SSLClient cli(host, port);
  1343. #else
  1344. auto port = 80;
  1345. Client cli(host, port);
  1346. #endif
  1347. {
  1348. auto res = cli.Get(path);
  1349. ASSERT_TRUE(res);
  1350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1351. }
  1352. {
  1353. auto res =
  1354. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1355. ASSERT_TRUE(res);
  1356. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1357. remove_whitespace(res->body));
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. {
  1361. cli.set_basic_auth("hello", "world");
  1362. auto res = cli.Get(path);
  1363. ASSERT_TRUE(res);
  1364. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1365. remove_whitespace(res->body));
  1366. EXPECT_EQ(StatusCode::OK_200, res->status);
  1367. }
  1368. {
  1369. cli.set_basic_auth("hello", "bad");
  1370. auto res = cli.Get(path);
  1371. ASSERT_TRUE(res);
  1372. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1373. }
  1374. {
  1375. cli.set_basic_auth("bad", "world");
  1376. auto res = cli.Get(path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. }
  1381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1382. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1383. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1384. auto host = "httpbin.org";
  1385. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1386. auto paths = std::vector<std::string>{
  1387. "/digest-auth/auth/hello/world/MD5",
  1388. "/digest-auth/auth/hello/world/SHA-256",
  1389. "/digest-auth/auth/hello/world/SHA-512",
  1390. "/digest-auth/auth-int/hello/world/MD5",
  1391. };
  1392. #else
  1393. auto host = "nghttp2.org";
  1394. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1395. auto paths = std::vector<std::string>{
  1396. "/httpbin/digest-auth/auth/hello/world/MD5",
  1397. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1398. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1399. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1400. };
  1401. #endif
  1402. auto port = 443;
  1403. SSLClient cli(host, port);
  1404. {
  1405. auto res = cli.Get(unauth_path);
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1408. }
  1409. {
  1410. cli.set_digest_auth("hello", "world");
  1411. for (const auto &path : paths) {
  1412. auto res = cli.Get(path.c_str());
  1413. ASSERT_TRUE(res);
  1414. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1415. remove_whitespace(res->body));
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. cli.set_digest_auth("hello", "bad");
  1419. for (const auto &path : paths) {
  1420. auto res = cli.Get(path.c_str());
  1421. ASSERT_TRUE(res);
  1422. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1423. }
  1424. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1425. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1426. // cli.set_digest_auth("bad", "world");
  1427. // for (const auto& path : paths) {
  1428. // auto res = cli.Get(path.c_str());
  1429. // ASSERT_TRUE(res);
  1430. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1431. // }
  1432. }
  1433. }
  1434. #endif
  1435. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1436. auto host = "google.com";
  1437. auto another_host = "example.com";
  1438. auto wrong_ip = "0.0.0.0";
  1439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1440. SSLClient cli(host);
  1441. #else
  1442. Client cli(host);
  1443. #endif
  1444. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1445. auto res = cli.Get("/");
  1446. ASSERT_TRUE(res);
  1447. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1448. }
  1449. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1450. auto host = "google.com";
  1451. auto wrong_ip = "0.0.0.0";
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. SSLClient cli(host);
  1454. #else
  1455. Client cli(host);
  1456. #endif
  1457. cli.set_hostname_addr_map({{host, wrong_ip}});
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::Connection, res.error());
  1461. }
  1462. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1463. auto host = "nghttp2.org";
  1464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1465. SSLClient cli(host);
  1466. #else
  1467. Client cli(host);
  1468. #endif
  1469. cli.set_follow_location(true);
  1470. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ(StatusCode::OK_200, res->status);
  1473. }
  1474. TEST(RedirectTest, Redirect_Online) {
  1475. auto host = "nghttp2.org";
  1476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1477. SSLClient cli(host);
  1478. #else
  1479. Client cli(host);
  1480. #endif
  1481. cli.set_follow_location(true);
  1482. auto res = cli.Get("/httpbin/redirect/3");
  1483. ASSERT_TRUE(res);
  1484. EXPECT_EQ(StatusCode::OK_200, res->status);
  1485. }
  1486. TEST(RelativeRedirectTest, Redirect_Online) {
  1487. auto host = "nghttp2.org";
  1488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1489. SSLClient cli(host);
  1490. #else
  1491. Client cli(host);
  1492. #endif
  1493. cli.set_follow_location(true);
  1494. auto res = cli.Get("/httpbin/relative-redirect/3");
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ(StatusCode::OK_200, res->status);
  1497. }
  1498. TEST(TooManyRedirectTest, Redirect_Online) {
  1499. auto host = "nghttp2.org";
  1500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1501. SSLClient cli(host);
  1502. #else
  1503. Client cli(host);
  1504. #endif
  1505. cli.set_follow_location(true);
  1506. auto res = cli.Get("/httpbin/redirect/21");
  1507. ASSERT_TRUE(!res);
  1508. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1509. }
  1510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1511. TEST(YahooRedirectTest, Redirect_Online) {
  1512. Client cli("yahoo.com");
  1513. auto res = cli.Get("/");
  1514. ASSERT_TRUE(res);
  1515. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1516. cli.set_follow_location(true);
  1517. res = cli.Get("/");
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ(StatusCode::OK_200, res->status);
  1520. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1521. }
  1522. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1523. #define REDIR_HOST "httpbingo.org"
  1524. #define REDIR_PATH "/redirect-to"
  1525. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1526. SSLClient cli(REDIR_HOST);
  1527. cli.set_follow_location(true);
  1528. auto res =
  1529. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ(StatusCode::OK_200, res->status);
  1532. }
  1533. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1534. SSLClient cli(REDIR_HOST);
  1535. cli.set_follow_location(true);
  1536. Params params;
  1537. params.emplace("url", "http://example.com");
  1538. params.emplace("status_code", "302");
  1539. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1540. ASSERT_TRUE(res);
  1541. EXPECT_EQ(StatusCode::OK_200, res->status);
  1542. }
  1543. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1544. SSLClient cli(REDIR_HOST);
  1545. cli.set_follow_location(true);
  1546. Params params;
  1547. params.emplace("url", "http://example.com");
  1548. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1549. ASSERT_TRUE(res);
  1550. EXPECT_EQ(StatusCode::OK_200, res->status);
  1551. }
  1552. TEST(UrlWithSpace, Redirect_Online) {
  1553. SSLClient cli("edge.forgecdn.net");
  1554. cli.set_follow_location(true);
  1555. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1556. ASSERT_TRUE(res);
  1557. EXPECT_EQ(StatusCode::OK_200, res->status);
  1558. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1559. }
  1560. #endif
  1561. #if !defined(_WIN32) && !defined(_WIN64)
  1562. TEST(ReceiveSignals, Signal) {
  1563. auto setupSignalHandlers = []() {
  1564. struct sigaction act;
  1565. sigemptyset(&act.sa_mask);
  1566. act.sa_flags = SA_SIGINFO;
  1567. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1568. switch (sig) {
  1569. case SIGINT:
  1570. default: break;
  1571. }
  1572. };
  1573. ::sigaction(SIGINT, &act, nullptr);
  1574. };
  1575. Server svr;
  1576. int port = 0;
  1577. auto thread = std::thread([&]() {
  1578. setupSignalHandlers();
  1579. port = svr.bind_to_any_port("localhost");
  1580. svr.listen_after_bind();
  1581. });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. ASSERT_TRUE(svr.is_running());
  1589. pthread_kill(thread.native_handle(), SIGINT);
  1590. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1591. ASSERT_TRUE(svr.is_running());
  1592. }
  1593. #endif
  1594. TEST(RedirectToDifferentPort, Redirect) {
  1595. Server svr1;
  1596. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1597. res.set_content("Hello World!", "text/plain");
  1598. });
  1599. int svr1_port = 0;
  1600. auto thread1 = std::thread([&]() {
  1601. svr1_port = svr1.bind_to_any_port("localhost");
  1602. svr1.listen_after_bind();
  1603. });
  1604. Server svr2;
  1605. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1606. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1607. });
  1608. int svr2_port = 0;
  1609. auto thread2 = std::thread([&]() {
  1610. svr2_port = svr2.bind_to_any_port("localhost");
  1611. svr2.listen_after_bind();
  1612. });
  1613. auto se = detail::scope_exit([&] {
  1614. svr2.stop();
  1615. thread2.join();
  1616. svr1.stop();
  1617. thread1.join();
  1618. ASSERT_FALSE(svr2.is_running());
  1619. ASSERT_FALSE(svr1.is_running());
  1620. });
  1621. svr1.wait_until_ready();
  1622. svr2.wait_until_ready();
  1623. Client cli("localhost", svr2_port);
  1624. cli.set_follow_location(true);
  1625. auto res = cli.Get("/2");
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::OK_200, res->status);
  1628. EXPECT_EQ("Hello World!", res->body);
  1629. }
  1630. TEST(RedirectFromPageWithContent, Redirect) {
  1631. Server svr;
  1632. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("___", "text/plain");
  1634. res.set_redirect("/2");
  1635. });
  1636. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1637. res.set_content("Hello World!", "text/plain");
  1638. });
  1639. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. th.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. {
  1647. Client cli("localhost", PORT);
  1648. cli.set_follow_location(true);
  1649. std::string body;
  1650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1651. body.append(data, data_length);
  1652. return true;
  1653. });
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::OK_200, res->status);
  1656. EXPECT_EQ("Hello World!", body);
  1657. }
  1658. {
  1659. Client cli("localhost", PORT);
  1660. std::string body;
  1661. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1662. body.append(data, data_length);
  1663. return true;
  1664. });
  1665. ASSERT_TRUE(res);
  1666. EXPECT_EQ(StatusCode::Found_302, res->status);
  1667. EXPECT_EQ("___", body);
  1668. }
  1669. }
  1670. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1671. Server svr;
  1672. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1673. res.set_content("___", "text/plain");
  1674. // res.set_redirect("/2");
  1675. res.set_redirect("http://[::1]:1234/2");
  1676. });
  1677. svr.Get("/2", [&](const Request &req, Response &res) {
  1678. auto host_header = req.headers.find("Host");
  1679. ASSERT_TRUE(host_header != req.headers.end());
  1680. EXPECT_EQ("[::1]:1234", host_header->second);
  1681. res.set_content("Hello World!", "text/plain");
  1682. });
  1683. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1684. auto se = detail::scope_exit([&] {
  1685. svr.stop();
  1686. th.join();
  1687. ASSERT_FALSE(svr.is_running());
  1688. });
  1689. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1690. // actually starts anything, so the condition !svr.is_running() will
  1691. // always remain true, and the loop never stops.
  1692. // This basically counts how many milliseconds have passed since the
  1693. // call to svr.listen(), and if after 5 seconds nothing started yet
  1694. // aborts the test.
  1695. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1696. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1697. ASSERT_LT(milliseconds, 5000U);
  1698. }
  1699. {
  1700. Client cli("http://[::1]:1234");
  1701. cli.set_follow_location(true);
  1702. std::string body;
  1703. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res);
  1708. EXPECT_EQ(StatusCode::OK_200, res->status);
  1709. EXPECT_EQ("Hello World!", body);
  1710. }
  1711. {
  1712. Client cli("http://[::1]:1234");
  1713. std::string body;
  1714. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1715. body.append(data, data_length);
  1716. return true;
  1717. });
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::Found_302, res->status);
  1720. EXPECT_EQ("___", body);
  1721. }
  1722. }
  1723. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1724. Server svr;
  1725. svr.Get("/foo", [](const Request &req, Response &res) {
  1726. auto a = req.params.find("a");
  1727. if (a != req.params.end()) {
  1728. res.set_content((*a).second, "text/plain");
  1729. res.status = StatusCode::OK_200;
  1730. } else {
  1731. res.status = StatusCode::BadRequest_400;
  1732. }
  1733. });
  1734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1735. auto se = detail::scope_exit([&] {
  1736. svr.stop();
  1737. thread.join();
  1738. ASSERT_FALSE(svr.is_running());
  1739. });
  1740. svr.wait_until_ready();
  1741. {
  1742. Client cli(HOST, PORT);
  1743. cli.set_url_encode(false);
  1744. auto res = cli.Get("/foo?a=explicitly+encoded");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. // This expects it back with a space, as the `+` won't have been
  1748. // url-encoded, and server-side the params get decoded turning `+`
  1749. // into spaces.
  1750. EXPECT_EQ("explicitly encoded", res->body);
  1751. }
  1752. }
  1753. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1754. Server svr;
  1755. svr.Get("/", [](const Request &req, Response &) {
  1756. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1757. });
  1758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1759. auto se = detail::scope_exit([&] {
  1760. svr.stop();
  1761. thread.join();
  1762. ASSERT_FALSE(svr.is_running());
  1763. });
  1764. svr.wait_until_ready();
  1765. {
  1766. Client cli(HOST, PORT);
  1767. cli.set_url_encode(false);
  1768. auto res = cli.Get("/?something=%0A");
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ(StatusCode::OK_200, res->status);
  1771. }
  1772. }
  1773. TEST(BindServerTest, DISABLED_BindDualStack) {
  1774. Server svr;
  1775. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content("Hello World!", "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. {
  1786. Client cli("127.0.0.1", PORT);
  1787. auto res = cli.Get("/1");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. {
  1793. Client cli("::1", PORT);
  1794. auto res = cli.Get("/1");
  1795. ASSERT_TRUE(res);
  1796. EXPECT_EQ(StatusCode::OK_200, res->status);
  1797. EXPECT_EQ("Hello World!", res->body);
  1798. }
  1799. }
  1800. TEST(BindServerTest, BindAndListenSeparately) {
  1801. Server svr;
  1802. int port = svr.bind_to_any_port("0.0.0.0");
  1803. ASSERT_TRUE(svr.is_valid());
  1804. ASSERT_TRUE(port > 0);
  1805. svr.stop();
  1806. }
  1807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1808. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1810. CLIENT_CA_CERT_DIR);
  1811. int port = svr.bind_to_any_port("0.0.0.0");
  1812. ASSERT_TRUE(svr.is_valid());
  1813. ASSERT_TRUE(port > 0);
  1814. svr.stop();
  1815. }
  1816. #endif
  1817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1818. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1819. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1820. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1821. int port = svr.bind_to_any_port("0.0.0.0");
  1822. ASSERT_TRUE(svr.is_valid());
  1823. ASSERT_TRUE(port > 0);
  1824. svr.stop();
  1825. }
  1826. #endif
  1827. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1828. X509 *readCertificate(const std::string &strFileName) {
  1829. std::ifstream inStream(strFileName);
  1830. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1831. std::istreambuf_iterator<char>());
  1832. if (strCertPEM.empty()) return (nullptr);
  1833. BIO *pbCert = BIO_new(BIO_s_mem());
  1834. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1835. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1836. BIO_free(pbCert);
  1837. return (pCert);
  1838. }
  1839. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1840. std::ifstream inStream(strFileName);
  1841. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1842. std::istreambuf_iterator<char>());
  1843. if (strPrivateKeyPEM.empty()) return (nullptr);
  1844. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1845. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1846. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1847. BIO_free(pbPrivKey);
  1848. return (pPrivateKey);
  1849. }
  1850. TEST(BindServerTest, UpdateCerts) {
  1851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1852. int port = svr.bind_to_any_port("0.0.0.0");
  1853. ASSERT_TRUE(svr.is_valid());
  1854. ASSERT_TRUE(port > 0);
  1855. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1856. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1857. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1858. ASSERT_TRUE(cert != nullptr);
  1859. ASSERT_TRUE(ca_cert != nullptr);
  1860. ASSERT_TRUE(key != nullptr);
  1861. X509_STORE *cert_store = X509_STORE_new();
  1862. X509_STORE_add_cert(cert_store, ca_cert);
  1863. svr.update_certs(cert, key, cert_store);
  1864. ASSERT_TRUE(svr.is_valid());
  1865. svr.stop();
  1866. X509_free(cert);
  1867. X509_free(ca_cert);
  1868. EVP_PKEY_free(key);
  1869. }
  1870. #endif
  1871. TEST(ErrorHandlerTest, ContentLength) {
  1872. Server svr;
  1873. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1874. res.status = StatusCode::OK_200;
  1875. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1876. "text/html"); // <= Content-Length still 13
  1877. });
  1878. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!\n", "text/plain");
  1880. res.status = 524;
  1881. });
  1882. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1883. auto se = detail::scope_exit([&] {
  1884. svr.stop();
  1885. thread.join();
  1886. ASSERT_FALSE(svr.is_running());
  1887. });
  1888. svr.wait_until_ready();
  1889. {
  1890. Client cli(HOST, PORT);
  1891. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1892. ASSERT_TRUE(res);
  1893. EXPECT_EQ(StatusCode::OK_200, res->status);
  1894. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1895. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1896. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1897. }
  1898. }
  1899. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1900. TEST(ExceptionTest, WithoutExceptionHandler) {
  1901. Server svr;
  1902. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1903. throw std::runtime_error("exception...");
  1904. });
  1905. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1906. throw std::runtime_error("exception\r\n...");
  1907. });
  1908. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1909. auto se = detail::scope_exit([&] {
  1910. svr.stop();
  1911. listen_thread.join();
  1912. ASSERT_FALSE(svr.is_running());
  1913. });
  1914. svr.wait_until_ready();
  1915. Client cli("localhost", PORT);
  1916. {
  1917. auto res = cli.Get("/exception");
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1920. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1921. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1922. }
  1923. {
  1924. auto res = cli.Get("/unknown");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1927. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1928. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1929. }
  1930. }
  1931. TEST(ExceptionTest, WithExceptionHandler) {
  1932. Server svr;
  1933. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1934. std::exception_ptr ep) {
  1935. EXPECT_FALSE(ep == nullptr);
  1936. try {
  1937. std::rethrow_exception(ep);
  1938. } catch (std::exception &e) {
  1939. EXPECT_EQ("abc", std::string(e.what()));
  1940. } catch (...) {}
  1941. res.status = StatusCode::InternalServerError_500;
  1942. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1943. "text/html"); // <= Content-Length still 13 at this point
  1944. });
  1945. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1946. res.set_content("Hello World!\n", "text/plain");
  1947. throw std::runtime_error("abc");
  1948. });
  1949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1950. auto se = detail::scope_exit([&] {
  1951. svr.stop();
  1952. thread.join();
  1953. ASSERT_FALSE(svr.is_running());
  1954. });
  1955. svr.wait_until_ready();
  1956. for (size_t i = 0; i < 10; i++) {
  1957. Client cli(HOST, PORT);
  1958. for (size_t j = 0; j < 100; j++) {
  1959. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1962. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1963. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1964. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1965. }
  1966. cli.set_keep_alive(true);
  1967. for (size_t j = 0; j < 100; j++) {
  1968. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1969. ASSERT_TRUE(res);
  1970. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1971. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1972. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1973. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1974. }
  1975. }
  1976. }
  1977. TEST(ExceptionTest, AndErrorHandler) {
  1978. Server svr;
  1979. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1980. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1981. });
  1982. svr.set_exception_handler(
  1983. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1984. EXPECT_FALSE(ep == nullptr);
  1985. try {
  1986. std::rethrow_exception(ep);
  1987. } catch (std::exception &e) {
  1988. res.set_content(e.what(), "text/html");
  1989. } catch (...) {}
  1990. res.status = StatusCode::InternalServerError_500;
  1991. });
  1992. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1993. throw std::runtime_error("EXCEPTION");
  1994. });
  1995. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1996. res.set_content("ERROR", "text/html");
  1997. res.status = StatusCode::InternalServerError_500;
  1998. });
  1999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2000. auto se = detail::scope_exit([&] {
  2001. svr.stop();
  2002. thread.join();
  2003. ASSERT_FALSE(svr.is_running());
  2004. });
  2005. svr.wait_until_ready();
  2006. Client cli(HOST, PORT);
  2007. {
  2008. auto res = cli.Get("/exception");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2011. EXPECT_EQ("EXCEPTION", res->body);
  2012. }
  2013. {
  2014. auto res = cli.Get("/error");
  2015. ASSERT_TRUE(res);
  2016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2017. EXPECT_EQ("ERROR", res->body);
  2018. }
  2019. {
  2020. auto res = cli.Get("/invalid");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2023. EXPECT_EQ("NOT_FOUND", res->body);
  2024. }
  2025. }
  2026. #endif
  2027. TEST(NoContentTest, ContentLength) {
  2028. Server svr;
  2029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2030. res.status = StatusCode::NoContent_204;
  2031. });
  2032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2033. auto se = detail::scope_exit([&] {
  2034. svr.stop();
  2035. thread.join();
  2036. ASSERT_FALSE(svr.is_running());
  2037. });
  2038. svr.wait_until_ready();
  2039. {
  2040. Client cli(HOST, PORT);
  2041. auto res = cli.Get("/hi");
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2044. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2045. }
  2046. }
  2047. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2050. ASSERT_TRUE(svr.is_valid());
  2051. #else
  2052. Server svr;
  2053. #endif
  2054. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2055. if (req.path == "/routing_handler") {
  2056. res.set_header("PRE_ROUTING", "on");
  2057. res.set_content("Routing Handler", "text/plain");
  2058. return httplib::Server::HandlerResponse::Handled;
  2059. }
  2060. return httplib::Server::HandlerResponse::Unhandled;
  2061. });
  2062. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2063. res.set_content("Error", "text/html");
  2064. });
  2065. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2066. if (req.path == "/routing_handler") {
  2067. res.set_header("POST_ROUTING", "on");
  2068. }
  2069. });
  2070. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2071. res.set_content("Hello World!\n", "text/plain");
  2072. });
  2073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2074. auto se = detail::scope_exit([&] {
  2075. svr.stop();
  2076. thread.join();
  2077. ASSERT_FALSE(svr.is_running());
  2078. });
  2079. svr.wait_until_ready();
  2080. {
  2081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2082. SSLClient cli(HOST, PORT);
  2083. cli.enable_server_certificate_verification(false);
  2084. #else
  2085. Client cli(HOST, PORT);
  2086. #endif
  2087. auto res = cli.Get("/routing_handler");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. EXPECT_EQ("Routing Handler", res->body);
  2091. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2092. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2093. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2094. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2095. }
  2096. {
  2097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2098. SSLClient cli(HOST, PORT);
  2099. cli.enable_server_certificate_verification(false);
  2100. #else
  2101. Client cli(HOST, PORT);
  2102. #endif
  2103. auto res = cli.Get("/hi");
  2104. ASSERT_TRUE(res);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. EXPECT_EQ("Hello World!\n", res->body);
  2107. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2108. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2109. }
  2110. {
  2111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2112. SSLClient cli(HOST, PORT);
  2113. cli.enable_server_certificate_verification(false);
  2114. #else
  2115. Client cli(HOST, PORT);
  2116. #endif
  2117. auto res = cli.Get("/aaa");
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2120. EXPECT_EQ("Error", res->body);
  2121. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2122. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2123. }
  2124. }
  2125. TEST(RequestHandlerTest, PreRequestHandler) {
  2126. auto route_path = "/user/:user";
  2127. Server svr;
  2128. svr.Get("/hi", [](const Request &, Response &res) {
  2129. res.set_content("hi", "text/plain");
  2130. });
  2131. svr.Get(route_path, [](const Request &req, Response &res) {
  2132. res.set_content(req.path_params.at("user"), "text/plain");
  2133. });
  2134. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2135. if (req.matched_route == route_path) {
  2136. auto user = req.path_params.at("user");
  2137. if (user != "john") {
  2138. res.status = StatusCode::Forbidden_403;
  2139. res.set_content("error", "text/html");
  2140. return Server::HandlerResponse::Handled;
  2141. }
  2142. }
  2143. return Server::HandlerResponse::Unhandled;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. Client cli(HOST, PORT);
  2153. {
  2154. auto res = cli.Get("/hi");
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::OK_200, res->status);
  2157. EXPECT_EQ("hi", res->body);
  2158. }
  2159. {
  2160. auto res = cli.Get("/user/john");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::OK_200, res->status);
  2163. EXPECT_EQ("john", res->body);
  2164. }
  2165. {
  2166. auto res = cli.Get("/user/invalid-user");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2169. EXPECT_EQ("error", res->body);
  2170. }
  2171. }
  2172. TEST(InvalidFormatTest, StatusCode) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.set_content("Hello World!\n", "text/plain");
  2176. res.status = 9999; // Status should be a three-digit code...
  2177. });
  2178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2179. auto se = detail::scope_exit([&] {
  2180. svr.stop();
  2181. thread.join();
  2182. ASSERT_FALSE(svr.is_running());
  2183. });
  2184. svr.wait_until_ready();
  2185. {
  2186. Client cli(HOST, PORT);
  2187. auto res = cli.Get("/hi");
  2188. ASSERT_FALSE(res);
  2189. }
  2190. }
  2191. TEST(URLFragmentTest, WithFragment) {
  2192. Server svr;
  2193. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2194. EXPECT_TRUE(req.target == "/hi");
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2206. EXPECT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::OK_200, res->status);
  2208. res = cli.Get("/hi%23key1=val1=key2=val2");
  2209. EXPECT_TRUE(res);
  2210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2211. }
  2212. }
  2213. TEST(HeaderWriter, SetHeaderWriter) {
  2214. Server svr;
  2215. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2216. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2217. return detail::write_headers(strm, hdrs);
  2218. });
  2219. svr.Get("/hi", [](const Request &req, Response &res) {
  2220. auto it = req.headers.find("CustomClientHeader");
  2221. EXPECT_TRUE(it != req.headers.end());
  2222. EXPECT_EQ(it->second, "CustomClientValue");
  2223. res.set_content("Hello World!\n", "text/plain");
  2224. });
  2225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2226. auto se = detail::scope_exit([&] {
  2227. svr.stop();
  2228. thread.join();
  2229. ASSERT_FALSE(svr.is_running());
  2230. });
  2231. svr.wait_until_ready();
  2232. {
  2233. Client cli(HOST, PORT);
  2234. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2235. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2236. return detail::write_headers(strm, hdrs);
  2237. });
  2238. auto res = cli.Get("/hi");
  2239. EXPECT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. auto it = res->headers.find("CustomServerHeader");
  2242. EXPECT_TRUE(it != res->headers.end());
  2243. EXPECT_EQ(it->second, "CustomServerValue");
  2244. }
  2245. }
  2246. class ServerTest : public ::testing::Test {
  2247. protected:
  2248. ServerTest()
  2249. : cli_(HOST, PORT)
  2250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2251. ,
  2252. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2253. #endif
  2254. {
  2255. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2256. cli_.enable_server_certificate_verification(false);
  2257. #endif
  2258. }
  2259. virtual void SetUp() {
  2260. svr_.set_mount_point("/", "./www");
  2261. svr_.set_mount_point("/mount", "./www2");
  2262. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2263. svr_.Get("/hi",
  2264. [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. })
  2267. .Get("/file_content",
  2268. [&](const Request & /*req*/, Response &res) {
  2269. res.set_file_content("./www/dir/test.html");
  2270. })
  2271. .Get("/file_content_with_content_type",
  2272. [&](const Request & /*req*/, Response &res) {
  2273. res.set_file_content("./www/file", "text/plain");
  2274. })
  2275. .Get("/invalid_file_content",
  2276. [&](const Request & /*req*/, Response &res) {
  2277. res.set_file_content("./www/dir/invalid_file_path");
  2278. })
  2279. .Get("/http_response_splitting",
  2280. [&](const Request & /*req*/, Response &res) {
  2281. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2282. EXPECT_EQ(0U, res.headers.size());
  2283. EXPECT_FALSE(res.has_header("a"));
  2284. res.set_header("a", "1\nSet-Cookie: a=1");
  2285. EXPECT_EQ(0U, res.headers.size());
  2286. EXPECT_FALSE(res.has_header("a"));
  2287. res.set_header("a", "1\rSet-Cookie: a=1");
  2288. EXPECT_EQ(0U, res.headers.size());
  2289. EXPECT_FALSE(res.has_header("a"));
  2290. res.set_header("a\r\nb", "0");
  2291. EXPECT_EQ(0U, res.headers.size());
  2292. EXPECT_FALSE(res.has_header("a"));
  2293. res.set_header("a\rb", "0");
  2294. EXPECT_EQ(0U, res.headers.size());
  2295. EXPECT_FALSE(res.has_header("a"));
  2296. res.set_header("a\nb", "0");
  2297. EXPECT_EQ(0U, res.headers.size());
  2298. EXPECT_FALSE(res.has_header("a"));
  2299. res.set_redirect("1\r\nSet-Cookie: a=1");
  2300. EXPECT_EQ(0U, res.headers.size());
  2301. EXPECT_FALSE(res.has_header("Location"));
  2302. })
  2303. .Get("/slow",
  2304. [&](const Request & /*req*/, Response &res) {
  2305. std::this_thread::sleep_for(std::chrono::seconds(2));
  2306. res.set_content("slow", "text/plain");
  2307. })
  2308. #if 0
  2309. .Post("/slowpost",
  2310. [&](const Request & /*req*/, Response &res) {
  2311. std::this_thread::sleep_for(std::chrono::seconds(2));
  2312. res.set_content("slow", "text/plain");
  2313. })
  2314. #endif
  2315. .Get("/remote_addr",
  2316. [&](const Request &req, Response &res) {
  2317. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2318. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2319. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2320. EXPECT_EQ(req.remote_port,
  2321. std::stoi(req.get_header_value("REMOTE_PORT")));
  2322. res.set_content(remote_addr.c_str(), "text/plain");
  2323. })
  2324. .Get("/local_addr",
  2325. [&](const Request &req, Response &res) {
  2326. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2327. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2328. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2329. auto local_port = req.get_header_value("LOCAL_PORT");
  2330. EXPECT_EQ(req.local_addr, local_addr);
  2331. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2332. res.set_content(local_addr.append(":").append(local_port),
  2333. "text/plain");
  2334. })
  2335. .Get("/endwith%",
  2336. [&](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!", "text/plain");
  2338. })
  2339. .Get("/a\\+\\+b",
  2340. [&](const Request &req, Response &res) {
  2341. ASSERT_TRUE(req.has_param("a +b"));
  2342. auto val = req.get_param_value("a +b");
  2343. res.set_content(val, "text/plain");
  2344. })
  2345. .Get("/", [&](const Request & /*req*/,
  2346. Response &res) { res.set_redirect("/hi"); })
  2347. .Post("/1",
  2348. [](const Request & /*req*/, Response &res) {
  2349. res.set_redirect("/2", StatusCode::SeeOther_303);
  2350. })
  2351. .Get("/2",
  2352. [](const Request & /*req*/, Response &res) {
  2353. res.set_content("redirected.", "text/plain");
  2354. res.status = StatusCode::OK_200;
  2355. })
  2356. .Post("/person",
  2357. [&](const Request &req, Response &res) {
  2358. if (req.has_param("name") && req.has_param("note")) {
  2359. persons_[req.get_param_value("name")] =
  2360. req.get_param_value("note");
  2361. } else {
  2362. res.status = StatusCode::BadRequest_400;
  2363. }
  2364. })
  2365. .Put("/person",
  2366. [&](const Request &req, Response &res) {
  2367. if (req.has_param("name") && req.has_param("note")) {
  2368. persons_[req.get_param_value("name")] =
  2369. req.get_param_value("note");
  2370. } else {
  2371. res.status = StatusCode::BadRequest_400;
  2372. }
  2373. })
  2374. .Get("/person/(.*)",
  2375. [&](const Request &req, Response &res) {
  2376. string name = req.matches[1];
  2377. if (persons_.find(name) != persons_.end()) {
  2378. auto note = persons_[name];
  2379. res.set_content(note, "text/plain");
  2380. } else {
  2381. res.status = StatusCode::NotFound_404;
  2382. }
  2383. })
  2384. .Delete("/person",
  2385. [&](const Request &req, Response &res) {
  2386. if (req.has_param("name")) {
  2387. string name = req.get_param_value("name");
  2388. if (persons_.find(name) != persons_.end()) {
  2389. persons_.erase(name);
  2390. res.set_content("DELETED", "text/plain");
  2391. } else {
  2392. res.status = StatusCode::NotFound_404;
  2393. }
  2394. } else {
  2395. res.status = StatusCode::BadRequest_400;
  2396. }
  2397. })
  2398. .Post("/x-www-form-urlencoded-json",
  2399. [&](const Request &req, Response &res) {
  2400. auto json = req.get_param_value("json");
  2401. ASSERT_EQ(JSON_DATA, json);
  2402. res.set_content(json, "appliation/json");
  2403. res.status = StatusCode::OK_200;
  2404. })
  2405. .Get("/streamed-chunked",
  2406. [&](const Request & /*req*/, Response &res) {
  2407. res.set_chunked_content_provider(
  2408. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2409. sink.os << "123";
  2410. sink.os << "456";
  2411. sink.os << "789";
  2412. sink.done();
  2413. return true;
  2414. });
  2415. })
  2416. .Get("/streamed-chunked2",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. auto i = new int(0);
  2419. res.set_chunked_content_provider(
  2420. "text/plain",
  2421. [i](size_t /*offset*/, DataSink &sink) {
  2422. switch (*i) {
  2423. case 0: sink.os << "123"; break;
  2424. case 1: sink.os << "456"; break;
  2425. case 2: sink.os << "789"; break;
  2426. case 3: sink.done(); break;
  2427. }
  2428. (*i)++;
  2429. return true;
  2430. },
  2431. [i](bool success) {
  2432. EXPECT_TRUE(success);
  2433. delete i;
  2434. });
  2435. })
  2436. .Get("/streamed-chunked-with-trailer",
  2437. [&](const Request & /*req*/, Response &res) {
  2438. auto i = new int(0);
  2439. res.set_header("Trailer", "Dummy1, Dummy2");
  2440. res.set_chunked_content_provider(
  2441. "text/plain",
  2442. [i](size_t /*offset*/, DataSink &sink) {
  2443. switch (*i) {
  2444. case 0: sink.os << "123"; break;
  2445. case 1: sink.os << "456"; break;
  2446. case 2: sink.os << "789"; break;
  2447. case 3: {
  2448. sink.done_with_trailer(
  2449. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2450. } break;
  2451. }
  2452. (*i)++;
  2453. return true;
  2454. },
  2455. [i](bool success) {
  2456. EXPECT_TRUE(success);
  2457. delete i;
  2458. });
  2459. })
  2460. .Get("/streamed",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. 6, "text/plain",
  2464. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2465. sink.os << (offset < 3 ? "a" : "b");
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/streamed-with-range",
  2470. [&](const Request &req, Response &res) {
  2471. auto data = new std::string("abcdefg");
  2472. res.set_content_provider(
  2473. data->size(), "text/plain",
  2474. [data](size_t offset, size_t length, DataSink &sink) {
  2475. size_t DATA_CHUNK_SIZE = 4;
  2476. const auto &d = *data;
  2477. auto out_len =
  2478. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2479. auto ret =
  2480. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2481. EXPECT_TRUE(ret);
  2482. return true;
  2483. },
  2484. [data, &req](bool success) {
  2485. EXPECT_EQ(success, !req.has_param("error"));
  2486. delete data;
  2487. });
  2488. })
  2489. .Get("/streamed-cancel",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_content_provider(
  2492. size_t(-1), "text/plain",
  2493. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2494. sink.os << "data_chunk";
  2495. return true;
  2496. });
  2497. })
  2498. .Get("/regex-with-delimiter",
  2499. [&](const Request &req, Response & /*res*/) {
  2500. ASSERT_TRUE(req.has_param("key"));
  2501. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2502. })
  2503. .Get("/with-range",
  2504. [&](const Request & /*req*/, Response &res) {
  2505. res.set_content("abcdefg", "text/plain");
  2506. })
  2507. .Get("/with-range-customized-response",
  2508. [&](const Request & /*req*/, Response &res) {
  2509. res.status = StatusCode::BadRequest_400;
  2510. res.set_content(JSON_DATA, "application/json");
  2511. })
  2512. .Post("/chunked",
  2513. [&](const Request &req, Response & /*res*/) {
  2514. EXPECT_EQ(req.body, "dechunked post body");
  2515. })
  2516. .Post("/large-chunked",
  2517. [&](const Request &req, Response & /*res*/) {
  2518. std::string expected(6 * 30 * 1024u, 'a');
  2519. EXPECT_EQ(req.body, expected);
  2520. })
  2521. .Post("/multipart",
  2522. [&](const Request &req, Response & /*res*/) {
  2523. EXPECT_EQ(6u, req.files.size());
  2524. ASSERT_TRUE(!req.has_file("???"));
  2525. ASSERT_TRUE(req.body.empty());
  2526. {
  2527. const auto &file = req.get_file_value("text1");
  2528. EXPECT_TRUE(file.filename.empty());
  2529. EXPECT_EQ("text default", file.content);
  2530. }
  2531. {
  2532. const auto &file = req.get_file_value("text2");
  2533. EXPECT_TRUE(file.filename.empty());
  2534. EXPECT_EQ("aωb", file.content);
  2535. }
  2536. {
  2537. const auto &file = req.get_file_value("file1");
  2538. EXPECT_EQ("hello.txt", file.filename);
  2539. EXPECT_EQ("text/plain", file.content_type);
  2540. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2541. }
  2542. {
  2543. const auto &file = req.get_file_value("file3");
  2544. EXPECT_TRUE(file.filename.empty());
  2545. EXPECT_EQ("application/octet-stream", file.content_type);
  2546. EXPECT_EQ(0u, file.content.size());
  2547. }
  2548. {
  2549. const auto &file = req.get_file_value("file4");
  2550. EXPECT_TRUE(file.filename.empty());
  2551. EXPECT_EQ(0u, file.content.size());
  2552. EXPECT_EQ("application/json tmp-string", file.content_type);
  2553. }
  2554. })
  2555. .Post("/multipart/multi_file_values",
  2556. [&](const Request &req, Response & /*res*/) {
  2557. EXPECT_EQ(5u, req.files.size());
  2558. ASSERT_TRUE(!req.has_file("???"));
  2559. ASSERT_TRUE(req.body.empty());
  2560. {
  2561. const auto &text_value = req.get_file_values("text");
  2562. EXPECT_EQ(1u, text_value.size());
  2563. auto &text = text_value[0];
  2564. EXPECT_TRUE(text.filename.empty());
  2565. EXPECT_EQ("default text", text.content);
  2566. }
  2567. {
  2568. const auto &text1_values = req.get_file_values("multi_text1");
  2569. EXPECT_EQ(2u, text1_values.size());
  2570. EXPECT_EQ("aaaaa", text1_values[0].content);
  2571. EXPECT_EQ("bbbbb", text1_values[1].content);
  2572. }
  2573. {
  2574. const auto &file1_values = req.get_file_values("multi_file1");
  2575. EXPECT_EQ(2u, file1_values.size());
  2576. auto file1 = file1_values[0];
  2577. EXPECT_EQ(file1.filename, "hello.txt");
  2578. EXPECT_EQ(file1.content_type, "text/plain");
  2579. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2580. auto file2 = file1_values[1];
  2581. EXPECT_EQ(file2.filename, "world.json");
  2582. EXPECT_EQ(file2.content_type, "application/json");
  2583. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2584. }
  2585. })
  2586. .Post("/empty",
  2587. [&](const Request &req, Response &res) {
  2588. EXPECT_EQ(req.body, "");
  2589. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2590. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2591. res.set_content("empty", "text/plain");
  2592. })
  2593. .Post("/empty-no-content-type",
  2594. [&](const Request &req, Response &res) {
  2595. EXPECT_EQ(req.body, "");
  2596. EXPECT_FALSE(req.has_header("Content-Type"));
  2597. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2598. res.set_content("empty-no-content-type", "text/plain");
  2599. })
  2600. .Post("/path-only",
  2601. [&](const Request &req, Response &res) {
  2602. EXPECT_EQ(req.body, "");
  2603. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2604. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2605. res.set_content("path-only", "text/plain");
  2606. })
  2607. .Post("/path-headers-only",
  2608. [&](const Request &req, Response &res) {
  2609. EXPECT_EQ(req.body, "");
  2610. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2611. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2612. EXPECT_EQ("world", req.get_header_value("hello"));
  2613. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2614. res.set_content("path-headers-only", "text/plain");
  2615. })
  2616. .Post("/post-large",
  2617. [&](const Request &req, Response &res) {
  2618. EXPECT_EQ(req.body, LARGE_DATA);
  2619. res.set_content(req.body, "text/plain");
  2620. })
  2621. .Put("/empty-no-content-type",
  2622. [&](const Request &req, Response &res) {
  2623. EXPECT_EQ(req.body, "");
  2624. EXPECT_FALSE(req.has_header("Content-Type"));
  2625. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2626. res.set_content("empty-no-content-type", "text/plain");
  2627. })
  2628. .Put("/put",
  2629. [&](const Request &req, Response &res) {
  2630. EXPECT_EQ(req.body, "PUT");
  2631. res.set_content(req.body, "text/plain");
  2632. })
  2633. .Put("/put-large",
  2634. [&](const Request &req, Response &res) {
  2635. EXPECT_EQ(req.body, LARGE_DATA);
  2636. res.set_content(req.body, "text/plain");
  2637. })
  2638. .Patch("/patch",
  2639. [&](const Request &req, Response &res) {
  2640. EXPECT_EQ(req.body, "PATCH");
  2641. res.set_content(req.body, "text/plain");
  2642. })
  2643. .Delete("/delete",
  2644. [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("DELETE", "text/plain");
  2646. })
  2647. .Delete("/delete-body",
  2648. [&](const Request &req, Response &res) {
  2649. EXPECT_EQ(req.body, "content");
  2650. res.set_content(req.body, "text/plain");
  2651. })
  2652. .Options(R"(\*)",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2655. })
  2656. .Get("/request-target",
  2657. [&](const Request &req, Response & /*res*/) {
  2658. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2659. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2660. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2661. })
  2662. .Get("/long-query-value",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2665. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2666. })
  2667. .Get("/too-long-query-value",
  2668. [&](const Request &req, Response & /*res*/) {
  2669. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2670. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2671. })
  2672. .Get("/array-param",
  2673. [&](const Request &req, Response & /*res*/) {
  2674. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2675. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2676. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2677. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2678. })
  2679. .Post("/validate-no-multiple-headers",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2682. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2683. })
  2684. .Post("/content_receiver",
  2685. [&](const Request &req, Response &res,
  2686. const ContentReader &content_reader) {
  2687. if (req.is_multipart_form_data()) {
  2688. MultipartFormDataItems files;
  2689. content_reader(
  2690. [&](const MultipartFormData &file) {
  2691. files.push_back(file);
  2692. return true;
  2693. },
  2694. [&](const char *data, size_t data_length) {
  2695. files.back().content.append(data, data_length);
  2696. return true;
  2697. });
  2698. EXPECT_EQ(5u, files.size());
  2699. {
  2700. const auto &file = get_file_value(files, "text1");
  2701. EXPECT_TRUE(file.filename.empty());
  2702. EXPECT_EQ("text default", file.content);
  2703. }
  2704. {
  2705. const auto &file = get_file_value(files, "text2");
  2706. EXPECT_TRUE(file.filename.empty());
  2707. EXPECT_EQ("aωb", file.content);
  2708. }
  2709. {
  2710. const auto &file = get_file_value(files, "file1");
  2711. EXPECT_EQ("hello.txt", file.filename);
  2712. EXPECT_EQ("text/plain", file.content_type);
  2713. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2714. }
  2715. {
  2716. const auto &file = get_file_value(files, "file3");
  2717. EXPECT_TRUE(file.filename.empty());
  2718. EXPECT_EQ("application/octet-stream", file.content_type);
  2719. EXPECT_EQ(0u, file.content.size());
  2720. }
  2721. } else {
  2722. std::string body;
  2723. content_reader([&](const char *data, size_t data_length) {
  2724. EXPECT_EQ(7U, data_length);
  2725. body.append(data, data_length);
  2726. return true;
  2727. });
  2728. EXPECT_EQ(body, "content");
  2729. res.set_content(body, "text/plain");
  2730. }
  2731. })
  2732. .Put("/content_receiver",
  2733. [&](const Request & /*req*/, Response &res,
  2734. const ContentReader &content_reader) {
  2735. std::string body;
  2736. content_reader([&](const char *data, size_t data_length) {
  2737. body.append(data, data_length);
  2738. return true;
  2739. });
  2740. EXPECT_EQ(body, "content");
  2741. res.set_content(body, "text/plain");
  2742. })
  2743. .Patch("/content_receiver",
  2744. [&](const Request & /*req*/, Response &res,
  2745. const ContentReader &content_reader) {
  2746. std::string body;
  2747. content_reader([&](const char *data, size_t data_length) {
  2748. body.append(data, data_length);
  2749. return true;
  2750. });
  2751. EXPECT_EQ(body, "content");
  2752. res.set_content(body, "text/plain");
  2753. })
  2754. .Post("/query-string-and-body",
  2755. [&](const Request &req, Response & /*res*/) {
  2756. ASSERT_TRUE(req.has_param("key"));
  2757. EXPECT_EQ(req.get_param_value("key"), "value");
  2758. EXPECT_EQ(req.body, "content");
  2759. })
  2760. .Get("/last-request",
  2761. [&](const Request &req, Response & /*res*/) {
  2762. EXPECT_EQ("close", req.get_header_value("Connection"));
  2763. })
  2764. .Get(R"(/redirect/(\d+))",
  2765. [&](const Request &req, Response &res) {
  2766. auto num = std::stoi(req.matches[1]) + 1;
  2767. std::string url = "/redirect/" + std::to_string(num);
  2768. res.set_redirect(url);
  2769. })
  2770. .Post("/binary",
  2771. [&](const Request &req, Response &res) {
  2772. EXPECT_EQ(4U, req.body.size());
  2773. EXPECT_EQ("application/octet-stream",
  2774. req.get_header_value("Content-Type"));
  2775. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2776. res.set_content(req.body, "application/octet-stream");
  2777. })
  2778. .Put("/binary",
  2779. [&](const Request &req, Response &res) {
  2780. EXPECT_EQ(4U, req.body.size());
  2781. EXPECT_EQ("application/octet-stream",
  2782. req.get_header_value("Content-Type"));
  2783. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2784. res.set_content(req.body, "application/octet-stream");
  2785. })
  2786. .Patch("/binary",
  2787. [&](const Request &req, Response &res) {
  2788. EXPECT_EQ(4U, req.body.size());
  2789. EXPECT_EQ("application/octet-stream",
  2790. req.get_header_value("Content-Type"));
  2791. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2792. res.set_content(req.body, "application/octet-stream");
  2793. })
  2794. .Delete("/binary",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(4U, req.body.size());
  2797. EXPECT_EQ("application/octet-stream",
  2798. req.get_header_value("Content-Type"));
  2799. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2800. res.set_content(req.body, "application/octet-stream");
  2801. })
  2802. .Get("/issue1772",
  2803. [&](const Request & /*req*/, Response &res) {
  2804. res.status = 401;
  2805. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2806. })
  2807. .Delete("/issue609",
  2808. [](const httplib::Request &, httplib::Response &res,
  2809. const httplib::ContentReader &) {
  2810. res.set_content("ok", "text/plain");
  2811. })
  2812. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2813. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2814. .Get("/compress",
  2815. [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(
  2817. "12345678901234567890123456789012345678901234567890123456789"
  2818. "01234567890123456789012345678901234567890",
  2819. "text/plain");
  2820. })
  2821. .Get("/nocompress",
  2822. [&](const Request & /*req*/, Response &res) {
  2823. res.set_content(
  2824. "12345678901234567890123456789012345678901234567890123456789"
  2825. "01234567890123456789012345678901234567890",
  2826. "application/octet-stream");
  2827. })
  2828. .Post("/compress-multipart",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(2u, req.files.size());
  2831. ASSERT_TRUE(!req.has_file("???"));
  2832. {
  2833. const auto &file = req.get_file_value("key1");
  2834. EXPECT_TRUE(file.filename.empty());
  2835. EXPECT_EQ("test", file.content);
  2836. }
  2837. {
  2838. const auto &file = req.get_file_value("key2");
  2839. EXPECT_TRUE(file.filename.empty());
  2840. EXPECT_EQ("--abcdefg123", file.content);
  2841. }
  2842. })
  2843. #endif
  2844. ;
  2845. persons_["john"] = "programmer";
  2846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2847. svr_.wait_until_ready();
  2848. }
  2849. virtual void TearDown() {
  2850. svr_.stop();
  2851. if (!request_threads_.empty()) {
  2852. std::this_thread::sleep_for(std::chrono::seconds(1));
  2853. for (auto &t : request_threads_) {
  2854. t.join();
  2855. }
  2856. }
  2857. t_.join();
  2858. }
  2859. map<string, string> persons_;
  2860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2861. SSLClient cli_;
  2862. SSLServer svr_;
  2863. #else
  2864. Client cli_;
  2865. Server svr_;
  2866. #endif
  2867. thread t_;
  2868. std::vector<thread> request_threads_;
  2869. };
  2870. TEST_F(ServerTest, GetMethod200) {
  2871. auto res = cli_.Get("/hi");
  2872. ASSERT_TRUE(res);
  2873. EXPECT_EQ("HTTP/1.1", res->version);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. EXPECT_EQ("OK", res->reason);
  2876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2877. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2878. EXPECT_EQ("Hello World!", res->body);
  2879. }
  2880. void performance_test(const char *host) {
  2881. auto port = 1234;
  2882. Server svr;
  2883. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2884. res.set_content("Benchmark Response", "text/plain");
  2885. });
  2886. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  2887. auto se = detail::scope_exit([&] {
  2888. svr.stop();
  2889. listen_thread.join();
  2890. ASSERT_FALSE(svr.is_running());
  2891. });
  2892. svr.wait_until_ready();
  2893. Client cli(host, port);
  2894. auto start = std::chrono::high_resolution_clock::now();
  2895. auto res = cli.Get("/benchmark");
  2896. ASSERT_TRUE(res);
  2897. EXPECT_EQ(StatusCode::OK_200, res->status);
  2898. auto end = std::chrono::high_resolution_clock::now();
  2899. auto elapsed =
  2900. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2901. .count();
  2902. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  2903. << "ms (Issue #1777)";
  2904. }
  2905. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  2906. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  2907. TEST_F(ServerTest, GetEmptyFile) {
  2908. auto res = cli_.Get("/empty_file");
  2909. ASSERT_TRUE(res);
  2910. EXPECT_EQ(StatusCode::OK_200, res->status);
  2911. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2912. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2913. EXPECT_EQ("", res->body);
  2914. }
  2915. TEST_F(ServerTest, GetFileContent) {
  2916. auto res = cli_.Get("/file_content");
  2917. ASSERT_TRUE(res);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2920. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2921. EXPECT_EQ("test.html", res->body);
  2922. }
  2923. TEST_F(ServerTest, GetFileContentWithRange) {
  2924. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2925. ASSERT_TRUE(res);
  2926. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2927. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2928. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2929. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2930. EXPECT_EQ("est", res->body);
  2931. }
  2932. TEST_F(ServerTest, GetFileContentWithContentType) {
  2933. auto res = cli_.Get("/file_content_with_content_type");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2937. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2938. EXPECT_EQ("file\n", res->body);
  2939. }
  2940. TEST_F(ServerTest, GetInvalidFileContent) {
  2941. auto res = cli_.Get("/invalid_file_content");
  2942. ASSERT_TRUE(res);
  2943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2944. }
  2945. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2946. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2947. ASSERT_TRUE(res);
  2948. EXPECT_EQ("HTTP/1.1", res->version);
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2951. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2952. EXPECT_EQ("Hello World!", res->body);
  2953. }
  2954. TEST_F(ServerTest, GetMethod302) {
  2955. auto res = cli_.Get("/");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::Found_302, res->status);
  2958. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2959. }
  2960. TEST_F(ServerTest, GetMethod302Redirect) {
  2961. cli_.set_follow_location(true);
  2962. auto res = cli_.Get("/");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::OK_200, res->status);
  2965. EXPECT_EQ("Hello World!", res->body);
  2966. EXPECT_EQ("/hi", res->location);
  2967. }
  2968. TEST_F(ServerTest, GetMethod404) {
  2969. auto res = cli_.Get("/invalid");
  2970. ASSERT_TRUE(res);
  2971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2972. }
  2973. TEST_F(ServerTest, HeadMethod200) {
  2974. auto res = cli_.Head("/hi");
  2975. ASSERT_TRUE(res);
  2976. EXPECT_EQ(StatusCode::OK_200, res->status);
  2977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2978. EXPECT_TRUE(res->body.empty());
  2979. }
  2980. TEST_F(ServerTest, HeadMethod200Static) {
  2981. auto res = cli_.Head("/mount/dir/index.html");
  2982. ASSERT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2986. EXPECT_TRUE(res->body.empty());
  2987. }
  2988. TEST_F(ServerTest, HeadMethod404) {
  2989. auto res = cli_.Head("/invalid");
  2990. ASSERT_TRUE(res);
  2991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2992. EXPECT_TRUE(res->body.empty());
  2993. }
  2994. TEST_F(ServerTest, GetMethodPersonJohn) {
  2995. auto res = cli_.Get("/person/john");
  2996. ASSERT_TRUE(res);
  2997. EXPECT_EQ(StatusCode::OK_200, res->status);
  2998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2999. EXPECT_EQ("programmer", res->body);
  3000. }
  3001. TEST_F(ServerTest, PostMethod1) {
  3002. auto res = cli_.Get("/person/john1");
  3003. ASSERT_TRUE(res);
  3004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3005. res = cli_.Post("/person", "name=john1&note=coder",
  3006. "application/x-www-form-urlencoded");
  3007. ASSERT_TRUE(res);
  3008. ASSERT_EQ(StatusCode::OK_200, res->status);
  3009. res = cli_.Get("/person/john1");
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(StatusCode::OK_200, res->status);
  3012. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3013. ASSERT_EQ("coder", res->body);
  3014. }
  3015. TEST_F(ServerTest, PostMethod2) {
  3016. auto res = cli_.Get("/person/john2");
  3017. ASSERT_TRUE(res);
  3018. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3019. Params params;
  3020. params.emplace("name", "john2");
  3021. params.emplace("note", "coder");
  3022. res = cli_.Post("/person", params);
  3023. ASSERT_TRUE(res);
  3024. ASSERT_EQ(StatusCode::OK_200, res->status);
  3025. res = cli_.Get("/person/john2");
  3026. ASSERT_TRUE(res);
  3027. ASSERT_EQ(StatusCode::OK_200, res->status);
  3028. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3029. ASSERT_EQ("coder", res->body);
  3030. }
  3031. TEST_F(ServerTest, PutMethod3) {
  3032. auto res = cli_.Get("/person/john3");
  3033. ASSERT_TRUE(res);
  3034. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3035. Params params;
  3036. params.emplace("name", "john3");
  3037. params.emplace("note", "coder");
  3038. res = cli_.Put("/person", params);
  3039. ASSERT_TRUE(res);
  3040. ASSERT_EQ(StatusCode::OK_200, res->status);
  3041. res = cli_.Get("/person/john3");
  3042. ASSERT_TRUE(res);
  3043. ASSERT_EQ(StatusCode::OK_200, res->status);
  3044. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3045. ASSERT_EQ("coder", res->body);
  3046. }
  3047. TEST_F(ServerTest, DeleteMethod1) {
  3048. auto res = cli_.Get("/person/john4");
  3049. ASSERT_TRUE(res);
  3050. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3051. Params params;
  3052. params.emplace("name", "john4");
  3053. params.emplace("note", "coder");
  3054. res = cli_.Post("/person", params);
  3055. ASSERT_TRUE(res);
  3056. ASSERT_EQ(StatusCode::OK_200, res->status);
  3057. res = cli_.Get("/person/john4");
  3058. ASSERT_TRUE(res);
  3059. ASSERT_EQ(StatusCode::OK_200, res->status);
  3060. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3061. ASSERT_EQ("coder", res->body);
  3062. Params delete_params;
  3063. delete_params.emplace("name", "john4");
  3064. res = cli_.Delete("/person", delete_params);
  3065. ASSERT_TRUE(res);
  3066. ASSERT_EQ(StatusCode::OK_200, res->status);
  3067. ASSERT_EQ("DELETED", res->body);
  3068. res = cli_.Get("/person/john4");
  3069. ASSERT_TRUE(res);
  3070. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3071. }
  3072. TEST_F(ServerTest, DeleteMethod2) {
  3073. auto res = cli_.Get("/person/john5");
  3074. ASSERT_TRUE(res);
  3075. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3076. Params params;
  3077. params.emplace("name", "john5");
  3078. params.emplace("note", "developer");
  3079. res = cli_.Post("/person", params);
  3080. ASSERT_TRUE(res);
  3081. ASSERT_EQ(StatusCode::OK_200, res->status);
  3082. res = cli_.Get("/person/john5");
  3083. ASSERT_TRUE(res);
  3084. ASSERT_EQ(StatusCode::OK_200, res->status);
  3085. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3086. ASSERT_EQ("developer", res->body);
  3087. Params delete_params;
  3088. delete_params.emplace("name", "john5");
  3089. Headers headers;
  3090. headers.emplace("Custom-Header", "test-value");
  3091. res = cli_.Delete("/person", headers, delete_params);
  3092. ASSERT_TRUE(res);
  3093. ASSERT_EQ(StatusCode::OK_200, res->status);
  3094. ASSERT_EQ("DELETED", res->body);
  3095. res = cli_.Get("/person/john5");
  3096. ASSERT_TRUE(res);
  3097. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3098. }
  3099. TEST_F(ServerTest, DeleteMethod3) {
  3100. auto res = cli_.Get("/person/john6");
  3101. ASSERT_TRUE(res);
  3102. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3103. Params params;
  3104. params.emplace("name", "john6");
  3105. params.emplace("note", "tester");
  3106. res = cli_.Post("/person", params);
  3107. ASSERT_TRUE(res);
  3108. ASSERT_EQ(StatusCode::OK_200, res->status);
  3109. res = cli_.Get("/person/john6");
  3110. ASSERT_TRUE(res);
  3111. ASSERT_EQ(StatusCode::OK_200, res->status);
  3112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3113. ASSERT_EQ("tester", res->body);
  3114. Params delete_params;
  3115. delete_params.emplace("name", "john6");
  3116. Headers headers;
  3117. headers.emplace("Custom-Header", "test-value");
  3118. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3119. ASSERT_TRUE(res);
  3120. ASSERT_EQ(StatusCode::OK_200, res->status);
  3121. ASSERT_EQ("DELETED", res->body);
  3122. res = cli_.Get("/person/john6");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3125. }
  3126. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3127. Params params;
  3128. params.emplace("json", JSON_DATA);
  3129. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(StatusCode::OK_200, res->status);
  3132. ASSERT_EQ(JSON_DATA, res->body);
  3133. }
  3134. TEST_F(ServerTest, PostEmptyContent) {
  3135. auto res = cli_.Post("/empty", "", "text/plain");
  3136. ASSERT_TRUE(res);
  3137. ASSERT_EQ(StatusCode::OK_200, res->status);
  3138. ASSERT_EQ("empty", res->body);
  3139. }
  3140. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3141. auto res = cli_.Post("/empty-no-content-type");
  3142. ASSERT_TRUE(res);
  3143. ASSERT_EQ(StatusCode::OK_200, res->status);
  3144. ASSERT_EQ("empty-no-content-type", res->body);
  3145. }
  3146. TEST_F(ServerTest, PostPathOnly) {
  3147. auto res = cli_.Post("/path-only");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("path-only", res->body);
  3151. }
  3152. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3153. auto res = cli_.Post("/path-headers-only",
  3154. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::OK_200, res->status);
  3157. ASSERT_EQ("path-headers-only", res->body);
  3158. }
  3159. TEST_F(ServerTest, PostLarge) {
  3160. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3161. ASSERT_TRUE(res);
  3162. ASSERT_EQ(StatusCode::OK_200, res->status);
  3163. EXPECT_EQ(LARGE_DATA, res->body);
  3164. }
  3165. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3166. auto res = cli_.Put("/empty-no-content-type");
  3167. ASSERT_TRUE(res);
  3168. ASSERT_EQ(StatusCode::OK_200, res->status);
  3169. ASSERT_EQ("empty-no-content-type", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetMethodDir) {
  3172. auto res = cli_.Get("/dir/");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3176. auto body = R"(<html>
  3177. <head>
  3178. </head>
  3179. <body>
  3180. <a href="/dir/test.html">Test</a>
  3181. <a href="/hi">hi</a>
  3182. </body>
  3183. </html>
  3184. )";
  3185. EXPECT_EQ(body, res->body);
  3186. }
  3187. TEST_F(ServerTest, GetMethodDirTest) {
  3188. auto res = cli_.Get("/dir/test.html");
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3192. EXPECT_EQ("test.html", res->body);
  3193. }
  3194. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3195. auto res = cli_.Get("/dir/../dir/test.html");
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3199. EXPECT_EQ("test.html", res->body);
  3200. }
  3201. TEST_F(ServerTest, GetMethodInvalidPath) {
  3202. auto res = cli_.Get("/dir/../test.html");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3205. }
  3206. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3207. auto res = cli_.Get("/../www/dir/test.html");
  3208. ASSERT_TRUE(res);
  3209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3210. }
  3211. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3212. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3215. }
  3216. TEST_F(ServerTest, GetMethodDirMountTest) {
  3217. auto res = cli_.Get("/mount/dir/test.html");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("test.html", res->body);
  3222. }
  3223. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3224. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3228. EXPECT_EQ("test.html", res->body);
  3229. }
  3230. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3231. auto res = cli_.Get("/mount/dir/../test.html");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3234. }
  3235. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3236. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3239. }
  3240. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3241. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3246. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3249. }
  3250. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3251. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, PostMethod303) {
  3256. auto res = cli_.Post("/1", "body", "text/plain");
  3257. ASSERT_TRUE(res);
  3258. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3259. EXPECT_EQ("/2", res->get_header_value("Location"));
  3260. }
  3261. TEST_F(ServerTest, PostMethod303Redirect) {
  3262. cli_.set_follow_location(true);
  3263. auto res = cli_.Post("/1", "body", "text/plain");
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("redirected.", res->body);
  3267. EXPECT_EQ("/2", res->location);
  3268. }
  3269. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3270. auto res = cli_.Get("/dir/test.abcde");
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3274. EXPECT_EQ("abcde", res->body);
  3275. }
  3276. TEST_F(ServerTest, StaticFileRange) {
  3277. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3280. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3281. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3282. EXPECT_EQ(true, res->has_header("Content-Range"));
  3283. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3284. EXPECT_EQ(std::string("cd"), res->body);
  3285. }
  3286. TEST_F(ServerTest, StaticFileRanges) {
  3287. auto res =
  3288. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3291. EXPECT_TRUE(
  3292. res->get_header_value("Content-Type")
  3293. .find(
  3294. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3295. 0);
  3296. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3297. }
  3298. TEST_F(ServerTest, StaticFileRangeHead) {
  3299. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3302. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ(true, res->has_header("Content-Range"));
  3305. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3306. }
  3307. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3308. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3312. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3313. EXPECT_EQ(true, res->has_header("Content-Range"));
  3314. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3315. res->get_header_value("Content-Range"));
  3316. EXPECT_EQ("LAST\n", res->body);
  3317. }
  3318. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3319. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3324. EXPECT_EQ(true, res->has_header("Content-Range"));
  3325. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3326. }
  3327. TEST_F(ServerTest, StaticFileBigFile) {
  3328. auto res = cli_.Get("/dir/1MB.txt");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3333. }
  3334. TEST_F(ServerTest, InvalidBaseDirMount) {
  3335. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3336. }
  3337. TEST_F(ServerTest, Binary) {
  3338. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3339. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3340. "application/octet-stream");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ(4U, res->body.size());
  3344. res = cli_.Put("/binary", binary.data(), binary.size(),
  3345. "application/octet-stream");
  3346. ASSERT_TRUE(res);
  3347. ASSERT_EQ(StatusCode::OK_200, res->status);
  3348. ASSERT_EQ(4U, res->body.size());
  3349. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3350. "application/octet-stream");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ(4U, res->body.size());
  3354. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3355. "application/octet-stream");
  3356. ASSERT_TRUE(res);
  3357. ASSERT_EQ(StatusCode::OK_200, res->status);
  3358. ASSERT_EQ(4U, res->body.size());
  3359. }
  3360. TEST_F(ServerTest, BinaryString) {
  3361. auto binary = std::string("\x00\x01\x02\x03", 4);
  3362. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3363. ASSERT_TRUE(res);
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. ASSERT_EQ(4U, res->body.size());
  3366. res = cli_.Put("/binary", binary, "application/octet-stream");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ(4U, res->body.size());
  3370. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::OK_200, res->status);
  3373. ASSERT_EQ(4U, res->body.size());
  3374. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3375. ASSERT_TRUE(res);
  3376. ASSERT_EQ(StatusCode::OK_200, res->status);
  3377. ASSERT_EQ(4U, res->body.size());
  3378. }
  3379. TEST_F(ServerTest, EmptyRequest) {
  3380. auto res = cli_.Get("");
  3381. ASSERT_TRUE(!res);
  3382. EXPECT_EQ(Error::Connection, res.error());
  3383. }
  3384. TEST_F(ServerTest, LongRequest) {
  3385. std::string request;
  3386. for (size_t i = 0; i < 545; i++) {
  3387. request += "/TooLongRequest";
  3388. }
  3389. request += "OK";
  3390. auto res = cli_.Get(request.c_str());
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, TooLongRequest) {
  3395. std::string request;
  3396. for (size_t i = 0; i < 546; i++) {
  3397. request += "/TooLongRequest";
  3398. }
  3399. request += "_NG";
  3400. auto res = cli_.Get(request.c_str());
  3401. ASSERT_TRUE(res);
  3402. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3403. }
  3404. TEST_F(ServerTest, AlmostTooLongRequest) {
  3405. // test for #2046 - URI length check shouldn't include other content on req
  3406. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3407. // leading /, space, HTTP/1.1)
  3408. std::string request =
  3409. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3410. auto res = cli_.Get(request.c_str());
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3413. }
  3414. TEST_F(ServerTest, LongHeader) {
  3415. Request req;
  3416. req.method = "GET";
  3417. req.path = "/hi";
  3418. std::string host_and_port;
  3419. host_and_port += HOST;
  3420. host_and_port += ":";
  3421. host_and_port += std::to_string(PORT);
  3422. req.headers.emplace("Host", host_and_port.c_str());
  3423. req.headers.emplace("Accept", "*/*");
  3424. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3425. req.headers.emplace(
  3426. "Header-Name",
  3427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3455. "@@@@@@@@@@@@@@@@");
  3456. auto res = std::make_shared<Response>();
  3457. auto error = Error::Success;
  3458. auto ret = cli_.send(req, *res, error);
  3459. ASSERT_TRUE(ret);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. }
  3462. TEST_F(ServerTest, LongQueryValue) {
  3463. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3466. }
  3467. TEST_F(ServerTest, TooLongQueryValue) {
  3468. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3469. ASSERT_FALSE(res);
  3470. EXPECT_EQ(Error::Read, res.error());
  3471. }
  3472. TEST_F(ServerTest, TooLongHeader) {
  3473. Request req;
  3474. req.method = "GET";
  3475. req.path = "/hi";
  3476. std::string host_and_port;
  3477. host_and_port += HOST;
  3478. host_and_port += ":";
  3479. host_and_port += std::to_string(PORT);
  3480. req.headers.emplace("Host", host_and_port.c_str());
  3481. req.headers.emplace("Accept", "*/*");
  3482. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3483. req.headers.emplace(
  3484. "Header-Name",
  3485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3513. "@@@@@@@@@@@@@@@@@");
  3514. auto res = std::make_shared<Response>();
  3515. auto error = Error::Success;
  3516. auto ret = cli_.send(req, *res, error);
  3517. ASSERT_TRUE(ret);
  3518. EXPECT_EQ(StatusCode::OK_200, res->status);
  3519. }
  3520. TEST_F(ServerTest, HeaderCountAtLimit) {
  3521. // Test with headers just under the 100 limit
  3522. httplib::Headers headers;
  3523. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3524. // This should keep us just under the 100 header limit
  3525. for (int i = 0; i < 95; i++) {
  3526. std::string name = "X-Test-Header-" + std::to_string(i);
  3527. std::string value = "value" + std::to_string(i);
  3528. headers.emplace(name, value);
  3529. }
  3530. // This should work fine as we're under the limit
  3531. auto res = cli_.Get("/hi", headers);
  3532. EXPECT_TRUE(res);
  3533. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3534. }
  3535. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3536. // Test with many headers to exceed the 100 limit
  3537. httplib::Headers headers;
  3538. // Add 150 headers to definitely exceed the 100 limit
  3539. for (int i = 0; i < 150; i++) {
  3540. std::string name = "X-Test-Header-" + std::to_string(i);
  3541. std::string value = "value" + std::to_string(i);
  3542. headers.emplace(name, value);
  3543. }
  3544. // This should fail due to exceeding header count limit
  3545. auto res = cli_.Get("/hi", headers);
  3546. // The request should either fail or return 400 Bad Request
  3547. if (res) {
  3548. // If we get a response, it should be 400 Bad Request
  3549. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3550. } else {
  3551. // Or the request should fail entirely
  3552. EXPECT_FALSE(res);
  3553. }
  3554. }
  3555. TEST_F(ServerTest, PercentEncoding) {
  3556. auto res = cli_.Get("/e%6edwith%");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. TEST_F(ServerTest, PercentEncodingUnicode) {
  3561. auto res = cli_.Get("/e%u006edwith%");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. }
  3565. TEST_F(ServerTest, InvalidPercentEncoding) {
  3566. auto res = cli_.Get("/%endwith%");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3569. }
  3570. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3571. auto res = cli_.Get("/%uendwith%");
  3572. ASSERT_TRUE(res);
  3573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3574. }
  3575. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3576. auto res = cli_.Get("/hello?aaa=bbb%");
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3579. }
  3580. TEST_F(ServerTest, PlusSignEncoding) {
  3581. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ("a +b", res->body);
  3585. }
  3586. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3587. // This test simulates a potential DoS attack using many headers
  3588. // to verify our security fix prevents memory exhaustion
  3589. httplib::Headers attack_headers;
  3590. // Attempt to add many headers like an attacker would (200 headers to far
  3591. // exceed limit)
  3592. for (int i = 0; i < 200; i++) {
  3593. std::string name = "X-Attack-Header-" + std::to_string(i);
  3594. std::string value = "attack_payload_" + std::to_string(i);
  3595. attack_headers.emplace(name, value);
  3596. }
  3597. // Try to POST with excessive headers
  3598. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3599. // Should either fail or return 400 Bad Request due to security limit
  3600. if (res) {
  3601. // If we get a response, it should be 400 Bad Request
  3602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3603. } else {
  3604. // Request failed, which is the expected behavior for DoS protection
  3605. EXPECT_FALSE(res);
  3606. }
  3607. }
  3608. TEST_F(ServerTest, MultipartFormData) {
  3609. MultipartFormDataItemsForClientInput items = {
  3610. {"text1", "text default", "", ""},
  3611. {"text2", "aωb", "", ""},
  3612. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3613. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3614. {"file3", "", "", "application/octet-stream"},
  3615. {"file4", "", "", " application/json tmp-string "}};
  3616. auto res = cli_.Post("/multipart", items);
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. }
  3620. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3621. MultipartFormDataItemsForClientInput items = {
  3622. {"text", "default text", "", ""},
  3623. {"multi_text1", "aaaaa", "", ""},
  3624. {"multi_text1", "bbbbb", "", ""},
  3625. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3626. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3627. "application/json"},
  3628. };
  3629. auto res = cli_.Post("/multipart/multi_file_values", items);
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. }
  3633. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3634. auto res = cli_.Get("/hi");
  3635. ASSERT_TRUE(res);
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3638. EXPECT_EQ("Hello World!", res->body);
  3639. }
  3640. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3641. Request req;
  3642. req.method = "POST";
  3643. req.path = "/chunked";
  3644. std::string host_and_port;
  3645. host_and_port += HOST;
  3646. host_and_port += ":";
  3647. host_and_port += std::to_string(PORT);
  3648. req.headers.emplace("Host", host_and_port.c_str());
  3649. req.headers.emplace("Accept", "*/*");
  3650. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3651. req.headers.emplace("Content-Type", "text/plain");
  3652. req.headers.emplace("Content-Length", "0");
  3653. req.headers.emplace(
  3654. "Transfer-Encoding",
  3655. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3656. // Client does not chunk, so make a chunked body manually.
  3657. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3658. auto res = std::make_shared<Response>();
  3659. auto error = Error::Success;
  3660. auto ret = cli_.send(req, *res, error);
  3661. ASSERT_TRUE(ret);
  3662. EXPECT_EQ(StatusCode::OK_200, res->status);
  3663. }
  3664. TEST_F(ServerTest, GetStreamed2) {
  3665. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3668. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3669. EXPECT_EQ(true, res->has_header("Content-Range"));
  3670. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3671. EXPECT_EQ(std::string("ab"), res->body);
  3672. }
  3673. TEST_F(ServerTest, GetStreamed) {
  3674. auto res = cli_.Get("/streamed");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::OK_200, res->status);
  3677. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3678. EXPECT_EQ(std::string("aaabbb"), res->body);
  3679. }
  3680. TEST_F(ServerTest, GetStreamedWithRange1) {
  3681. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3684. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3685. EXPECT_EQ(true, res->has_header("Content-Range"));
  3686. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3687. EXPECT_EQ(std::string("def"), res->body);
  3688. }
  3689. TEST_F(ServerTest, GetStreamedWithRange2) {
  3690. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3693. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3694. EXPECT_EQ(true, res->has_header("Content-Range"));
  3695. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3696. EXPECT_EQ(std::string("bcdefg"), res->body);
  3697. }
  3698. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3699. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3702. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3703. EXPECT_EQ(true, res->has_header("Content-Range"));
  3704. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3705. EXPECT_EQ(std::string("efg"), res->body);
  3706. }
  3707. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3708. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3711. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3712. EXPECT_EQ(false, res->has_header("Content-Range"));
  3713. EXPECT_EQ(0U, res->body.size());
  3714. }
  3715. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3716. auto res = cli_.Get("/streamed-with-range",
  3717. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3718. "92233720368547758079223372036854775807"}});
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3721. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3722. EXPECT_EQ(false, res->has_header("Content-Range"));
  3723. EXPECT_EQ(0U, res->body.size());
  3724. }
  3725. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3726. auto res = cli_.Get(
  3727. "/with-range",
  3728. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3729. {"Accept-Encoding", ""}});
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3733. EXPECT_EQ(true, res->has_header("Content-Range"));
  3734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3735. EXPECT_EQ(std::string("abcdefg"), res->body);
  3736. }
  3737. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3738. auto res = cli_.Get("/with-range", {
  3739. {"Range", "bytes=0-"},
  3740. {"Accept-Encoding", ""},
  3741. });
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3744. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ(true, res->has_header("Content-Range"));
  3746. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3747. EXPECT_EQ(std::string("abcdefg"), res->body);
  3748. }
  3749. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3750. auto res =
  3751. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3754. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3755. EXPECT_EQ(false, res->has_header("Content-Range"));
  3756. EXPECT_EQ(267U, res->body.size());
  3757. // Check that both range contents are present
  3758. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3759. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3760. // Check that Content-Range headers are present for both ranges
  3761. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3762. std::string::npos);
  3763. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3764. std::string::npos);
  3765. }
  3766. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3767. Ranges ranges;
  3768. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3769. ranges.emplace_back(0, -1);
  3770. }
  3771. auto res =
  3772. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3775. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(false, res->has_header("Content-Range"));
  3777. EXPECT_EQ(0U, res->body.size());
  3778. }
  3779. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3780. auto res =
  3781. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3784. EXPECT_EQ(5U, res->body.size());
  3785. // Check that overlapping ranges are coalesced into a single range
  3786. EXPECT_EQ("bcdef", res->body);
  3787. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3788. // Should be single range, not multipart
  3789. EXPECT_TRUE(res->has_header("Content-Range"));
  3790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3791. }
  3792. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3793. auto res =
  3794. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3797. EXPECT_EQ(268U, res->body.size());
  3798. // Check that both range contents are present
  3799. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3800. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3801. // Check that Content-Range headers are present for both ranges
  3802. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3803. std::string::npos);
  3804. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3805. std::string::npos);
  3806. }
  3807. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3808. auto res =
  3809. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3812. EXPECT_EQ(269U, res->body.size());
  3813. // Check that both duplicate range contents are present
  3814. size_t first_abc = res->body.find("abc\r\n");
  3815. EXPECT_TRUE(first_abc != std::string::npos);
  3816. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3817. EXPECT_TRUE(second_abc != std::string::npos);
  3818. // Check that Content-Range headers are present for both ranges
  3819. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3820. EXPECT_TRUE(first_range != std::string::npos);
  3821. size_t second_range =
  3822. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3823. EXPECT_TRUE(second_range != std::string::npos);
  3824. }
  3825. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3826. auto res = cli_.Get("/streamed-with-range?error",
  3827. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3830. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3831. EXPECT_EQ(false, res->has_header("Content-Range"));
  3832. EXPECT_EQ(0U, res->body.size());
  3833. }
  3834. TEST_F(ServerTest, GetStreamedEndless) {
  3835. uint64_t offset = 0;
  3836. auto res = cli_.Get("/streamed-cancel",
  3837. [&](const char * /*data*/, uint64_t data_length) {
  3838. if (offset < 100) {
  3839. offset += data_length;
  3840. return true;
  3841. }
  3842. return false;
  3843. });
  3844. ASSERT_TRUE(!res);
  3845. EXPECT_EQ(Error::Canceled, res.error());
  3846. }
  3847. TEST_F(ServerTest, ClientStop) {
  3848. std::atomic_size_t count{4};
  3849. std::vector<std::thread> threads;
  3850. for (auto i = count.load(); i != 0; --i) {
  3851. threads.emplace_back([&]() {
  3852. auto res = cli_.Get("/streamed-cancel",
  3853. [&](const char *, uint64_t) { return true; });
  3854. --count;
  3855. ASSERT_TRUE(!res);
  3856. EXPECT_TRUE(res.error() == Error::Canceled ||
  3857. res.error() == Error::Read || res.error() == Error::Write);
  3858. });
  3859. }
  3860. std::this_thread::sleep_for(std::chrono::seconds(2));
  3861. while (count != 0) {
  3862. cli_.stop();
  3863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3864. }
  3865. for (auto &t : threads) {
  3866. t.join();
  3867. }
  3868. }
  3869. TEST_F(ServerTest, GetWithRange1) {
  3870. auto res = cli_.Get("/with-range", {
  3871. make_range_header({{3, 5}}),
  3872. {"Accept-Encoding", ""},
  3873. });
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3876. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(true, res->has_header("Content-Range"));
  3878. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3879. EXPECT_EQ(std::string("def"), res->body);
  3880. }
  3881. TEST_F(ServerTest, GetWithRange2) {
  3882. auto res = cli_.Get("/with-range", {
  3883. make_range_header({{1, -1}}),
  3884. {"Accept-Encoding", ""},
  3885. });
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3888. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(true, res->has_header("Content-Range"));
  3890. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3891. EXPECT_EQ(std::string("bcdefg"), res->body);
  3892. }
  3893. TEST_F(ServerTest, GetWithRange3) {
  3894. auto res = cli_.Get("/with-range", {
  3895. make_range_header({{0, 0}}),
  3896. {"Accept-Encoding", ""},
  3897. });
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3900. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3901. EXPECT_EQ(true, res->has_header("Content-Range"));
  3902. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3903. EXPECT_EQ(std::string("a"), res->body);
  3904. }
  3905. TEST_F(ServerTest, GetWithRange4) {
  3906. auto res = cli_.Get("/with-range", {
  3907. make_range_header({{-1, 2}}),
  3908. {"Accept-Encoding", ""},
  3909. });
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3912. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3913. EXPECT_EQ(true, res->has_header("Content-Range"));
  3914. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3915. EXPECT_EQ(std::string("fg"), res->body);
  3916. }
  3917. TEST_F(ServerTest, GetWithRange5) {
  3918. auto res = cli_.Get("/with-range", {
  3919. make_range_header({{0, 5}}),
  3920. {"Accept-Encoding", ""},
  3921. });
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3924. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3925. EXPECT_EQ(true, res->has_header("Content-Range"));
  3926. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3927. EXPECT_EQ(std::string("abcdef"), res->body);
  3928. }
  3929. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3930. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3933. }
  3934. TEST_F(ServerTest, GetWithRangeMultipart) {
  3935. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3938. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3939. EXPECT_EQ(false, res->has_header("Content-Range"));
  3940. EXPECT_EQ(267U, res->body.size());
  3941. }
  3942. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3943. auto res =
  3944. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3947. }
  3948. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3949. auto res = cli_.Get("/with-range-customized-response",
  3950. {{make_range_header({{1, 2}})}});
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3953. EXPECT_EQ(true, res->has_header("Content-Length"));
  3954. EXPECT_EQ(false, res->has_header("Content-Range"));
  3955. EXPECT_EQ(JSON_DATA, res->body);
  3956. }
  3957. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3958. auto res = cli_.Get("/with-range-customized-response",
  3959. {{make_range_header({{1, 2}, {4, 5}})}});
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3962. EXPECT_EQ(true, res->has_header("Content-Length"));
  3963. EXPECT_EQ(false, res->has_header("Content-Range"));
  3964. EXPECT_EQ(JSON_DATA, res->body);
  3965. }
  3966. TEST_F(ServerTest, Issue1772) {
  3967. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3968. ASSERT_TRUE(res);
  3969. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3970. }
  3971. TEST_F(ServerTest, Issue609) {
  3972. auto res = cli_.Delete("/issue609");
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::OK_200, res->status);
  3975. EXPECT_EQ(std::string("ok"), res->body);
  3976. }
  3977. TEST_F(ServerTest, GetStreamedChunked) {
  3978. auto res = cli_.Get("/streamed-chunked");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ(std::string("123456789"), res->body);
  3982. }
  3983. TEST_F(ServerTest, GetStreamedChunked2) {
  3984. auto res = cli_.Get("/streamed-chunked2");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ(std::string("123456789"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3990. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::OK_200, res->status);
  3993. EXPECT_EQ(std::string("123456789"), res->body);
  3994. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3995. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3996. }
  3997. TEST_F(ServerTest, LargeChunkedPost) {
  3998. Request req;
  3999. req.method = "POST";
  4000. req.path = "/large-chunked";
  4001. std::string host_and_port;
  4002. host_and_port += HOST;
  4003. host_and_port += ":";
  4004. host_and_port += std::to_string(PORT);
  4005. req.headers.emplace("Host", host_and_port.c_str());
  4006. req.headers.emplace("Accept", "*/*");
  4007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4008. req.headers.emplace("Content-Type", "text/plain");
  4009. req.headers.emplace("Content-Length", "0");
  4010. req.headers.emplace("Transfer-Encoding", "chunked");
  4011. std::string long_string(30 * 1024u, 'a');
  4012. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4013. // Attempt to make a large enough post to exceed OS buffers, to test that
  4014. // the server handles short reads if the full chunk data isn't available.
  4015. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4016. auto res = std::make_shared<Response>();
  4017. auto error = Error::Success;
  4018. auto ret = cli_.send(req, *res, error);
  4019. ASSERT_TRUE(ret);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. }
  4022. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4023. auto res = cli_.Get("/remote_addr");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4027. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4028. }
  4029. TEST_F(ServerTest, GetMethodLocalAddr) {
  4030. auto res = cli_.Get("/local_addr");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::OK_200, res->status);
  4033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4034. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4035. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4036. }
  4037. TEST_F(ServerTest, HTTPResponseSplitting) {
  4038. auto res = cli_.Get("/http_response_splitting");
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. TEST_F(ServerTest, SlowRequest) {
  4043. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4044. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4046. }
  4047. #if 0
  4048. TEST_F(ServerTest, SlowPost) {
  4049. char buffer[64 * 1024];
  4050. memset(buffer, 0x42, sizeof(buffer));
  4051. auto res = cli_.Post(
  4052. "/slowpost", 64 * 1024 * 1024,
  4053. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4054. auto ret = sink.write(buffer, sizeof(buffer));
  4055. EXPECT_TRUE(ret);
  4056. return true;
  4057. },
  4058. "text/plain");
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::OK_200, res->status);
  4061. }
  4062. TEST_F(ServerTest, SlowPostFail) {
  4063. char buffer[64 * 1024];
  4064. memset(buffer, 0x42, sizeof(buffer));
  4065. cli_.set_write_timeout(std::chrono::seconds(0));
  4066. auto res = cli_.Post(
  4067. "/slowpost", 64 * 1024 * 1024,
  4068. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4069. sink.write(buffer, sizeof(buffer));
  4070. return true;
  4071. },
  4072. "text/plain");
  4073. ASSERT_TRUE(!res);
  4074. EXPECT_EQ(Error::Write, res.error());
  4075. }
  4076. #endif
  4077. TEST_F(ServerTest, Put) {
  4078. auto res = cli_.Put("/put", "PUT", "text/plain");
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. EXPECT_EQ("PUT", res->body);
  4082. }
  4083. TEST_F(ServerTest, PutWithContentProvider) {
  4084. auto res = cli_.Put(
  4085. "/put", 3,
  4086. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4087. sink.os << "PUT";
  4088. return true;
  4089. },
  4090. "text/plain");
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("PUT", res->body);
  4094. }
  4095. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4096. auto res = cli_.Post(
  4097. "/post", 42,
  4098. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4099. return false;
  4100. },
  4101. "text/plain");
  4102. ASSERT_TRUE(!res);
  4103. EXPECT_EQ(Error::Canceled, res.error());
  4104. }
  4105. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4106. auto res = cli_.Put(
  4107. "/put",
  4108. [](size_t /*offset*/, DataSink &sink) {
  4109. sink.os << "PUT";
  4110. sink.done();
  4111. return true;
  4112. },
  4113. "text/plain");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. EXPECT_EQ("PUT", res->body);
  4117. }
  4118. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4119. auto res = cli_.Post(
  4120. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4121. "text/plain");
  4122. ASSERT_TRUE(!res);
  4123. EXPECT_EQ(Error::Canceled, res.error());
  4124. }
  4125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4126. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4127. cli_.set_compress(true);
  4128. auto res = cli_.Put(
  4129. "/put", 3,
  4130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4131. sink.os << "PUT";
  4132. return true;
  4133. },
  4134. "text/plain");
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::OK_200, res->status);
  4137. EXPECT_EQ("PUT", res->body);
  4138. }
  4139. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4140. cli_.set_compress(true);
  4141. auto res = cli_.Post(
  4142. "/post", 42,
  4143. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4144. return false;
  4145. },
  4146. "text/plain");
  4147. ASSERT_TRUE(!res);
  4148. EXPECT_EQ(Error::Canceled, res.error());
  4149. }
  4150. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4151. cli_.set_compress(true);
  4152. auto res = cli_.Put(
  4153. "/put",
  4154. [](size_t /*offset*/, DataSink &sink) {
  4155. sink.os << "PUT";
  4156. sink.done();
  4157. return true;
  4158. },
  4159. "text/plain");
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. EXPECT_EQ("PUT", res->body);
  4163. }
  4164. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4165. cli_.set_compress(true);
  4166. auto res = cli_.Post(
  4167. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4168. "text/plain");
  4169. ASSERT_TRUE(!res);
  4170. EXPECT_EQ(Error::Canceled, res.error());
  4171. }
  4172. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4173. cli_.set_compress(true);
  4174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. EXPECT_EQ(LARGE_DATA, res->body);
  4178. }
  4179. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4181. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4182. Client cli(s.c_str());
  4183. cli.enable_server_certificate_verification(false);
  4184. #else
  4185. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4186. Client cli(s.c_str());
  4187. #endif
  4188. cli.set_compress(true);
  4189. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ(LARGE_DATA, res->body);
  4193. // The compressed size should be less than a 10th of the original. May vary
  4194. // depending on the zlib library.
  4195. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4196. static_cast<uint64_t>(10 * 1024 * 1024));
  4197. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4198. }
  4199. TEST_F(ServerTest, PutContentWithDeflate) {
  4200. cli_.set_compress(false);
  4201. Headers headers;
  4202. headers.emplace("Content-Encoding", "deflate");
  4203. // PUT in deflate format:
  4204. auto res = cli_.Put("/put", headers,
  4205. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::OK_200, res->status);
  4208. EXPECT_EQ("PUT", res->body);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4211. Headers headers;
  4212. headers.emplace("Accept-Encoding", "gzip, deflate");
  4213. auto res = cli_.Get("/streamed-chunked", headers);
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::OK_200, res->status);
  4216. EXPECT_EQ(std::string("123456789"), res->body);
  4217. }
  4218. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4219. Headers headers;
  4220. headers.emplace("Accept-Encoding", "gzip, deflate");
  4221. auto res = cli_.Get("/streamed-chunked2", headers);
  4222. ASSERT_TRUE(res);
  4223. EXPECT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(std::string("123456789"), res->body);
  4225. }
  4226. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4227. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST(GzipDecompressor, ChunkedDecompression) {
  4232. std::string data;
  4233. for (size_t i = 0; i < 32 * 1024; ++i) {
  4234. data.push_back(static_cast<char>('a' + i % 26));
  4235. }
  4236. std::string compressed_data;
  4237. {
  4238. httplib::detail::gzip_compressor compressor;
  4239. bool result = compressor.compress(
  4240. data.data(), data.size(),
  4241. /*last=*/true,
  4242. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4243. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4244. compressed_data_size);
  4245. return true;
  4246. });
  4247. ASSERT_TRUE(result);
  4248. }
  4249. std::string decompressed_data;
  4250. {
  4251. httplib::detail::gzip_decompressor decompressor;
  4252. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4253. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4254. size_t chunk_size = 130;
  4255. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4256. chunk_begin += chunk_size) {
  4257. size_t current_chunk_size =
  4258. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4259. bool result = decompressor.decompress(
  4260. compressed_data.data() + chunk_begin, current_chunk_size,
  4261. [&](const char *decompressed_data_chunk,
  4262. size_t decompressed_data_chunk_size) {
  4263. decompressed_data.insert(decompressed_data.size(),
  4264. decompressed_data_chunk,
  4265. decompressed_data_chunk_size);
  4266. return true;
  4267. });
  4268. ASSERT_TRUE(result);
  4269. }
  4270. }
  4271. ASSERT_EQ(data, decompressed_data);
  4272. }
  4273. TEST(GzipDecompressor, DeflateDecompression) {
  4274. std::string original_text = "Raw deflate without gzip";
  4275. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4276. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4277. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4278. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4279. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4280. std::string decompressed_data;
  4281. {
  4282. httplib::detail::gzip_decompressor decompressor;
  4283. bool result = decompressor.decompress(
  4284. compressed_data.data(), compressed_data.size(),
  4285. [&](const char *decompressed_data_chunk,
  4286. size_t decompressed_data_chunk_size) {
  4287. decompressed_data.insert(decompressed_data.size(),
  4288. decompressed_data_chunk,
  4289. decompressed_data_chunk_size);
  4290. return true;
  4291. });
  4292. ASSERT_TRUE(result);
  4293. }
  4294. ASSERT_EQ(original_text, decompressed_data);
  4295. }
  4296. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4297. std::string original_text = "Raw deflate without gzip";
  4298. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4299. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4300. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4301. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4302. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4303. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4304. std::string decompressed_data;
  4305. {
  4306. httplib::detail::gzip_decompressor decompressor;
  4307. bool result = decompressor.decompress(
  4308. compressed_data.data(), compressed_data.size(),
  4309. [&](const char *decompressed_data_chunk,
  4310. size_t decompressed_data_chunk_size) {
  4311. decompressed_data.insert(decompressed_data.size(),
  4312. decompressed_data_chunk,
  4313. decompressed_data_chunk_size);
  4314. return true;
  4315. });
  4316. ASSERT_TRUE(result);
  4317. }
  4318. ASSERT_EQ(original_text, decompressed_data);
  4319. }
  4320. #ifdef _WIN32
  4321. TEST(GzipDecompressor, LargeRandomData) {
  4322. // prepare large random data that is difficult to be compressed and is
  4323. // expected to have large size even when compressed
  4324. std::random_device seed_gen;
  4325. std::mt19937 random(seed_gen());
  4326. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4327. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4328. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4329. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4330. // compress data over 4GiB
  4331. std::string compressed_data;
  4332. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4333. httplib::detail::gzip_compressor compressor;
  4334. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4335. data.size() * sizeof(std::uint32_t), true,
  4336. [&](const char *data, size_t size) {
  4337. compressed_data.insert(
  4338. compressed_data.size(), data, size);
  4339. return true;
  4340. });
  4341. ASSERT_TRUE(result);
  4342. // FIXME: compressed data size is expected to be greater than 4GiB,
  4343. // but there is no guarantee
  4344. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4345. // decompress data over 4GiB
  4346. std::string decompressed_data;
  4347. decompressed_data.reserve(data_size);
  4348. httplib::detail::gzip_decompressor decompressor;
  4349. result = decompressor.decompress(
  4350. compressed_data.data(), compressed_data.size(),
  4351. [&](const char *data, size_t size) {
  4352. decompressed_data.insert(decompressed_data.size(), data, size);
  4353. return true;
  4354. });
  4355. ASSERT_TRUE(result);
  4356. // compare
  4357. ASSERT_EQ(data_size, decompressed_data.size());
  4358. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4359. 0);
  4360. }
  4361. #endif
  4362. #endif
  4363. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4364. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4365. Headers headers;
  4366. headers.emplace("Accept-Encoding", "br");
  4367. auto res = cli_.Get("/streamed-chunked", headers);
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ(std::string("123456789"), res->body);
  4371. }
  4372. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4373. Headers headers;
  4374. headers.emplace("Accept-Encoding", "br");
  4375. auto res = cli_.Get("/streamed-chunked2", headers);
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ(std::string("123456789"), res->body);
  4379. }
  4380. #endif
  4381. TEST_F(ServerTest, Patch) {
  4382. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. EXPECT_EQ("PATCH", res->body);
  4386. }
  4387. TEST_F(ServerTest, Delete) {
  4388. auto res = cli_.Delete("/delete");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ("DELETE", res->body);
  4392. }
  4393. TEST_F(ServerTest, DeleteContentReceiver) {
  4394. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("content", res->body);
  4398. }
  4399. TEST_F(ServerTest, Options) {
  4400. auto res = cli_.Options("*");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4404. EXPECT_TRUE(res->body.empty());
  4405. }
  4406. TEST_F(ServerTest, URL) {
  4407. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. }
  4411. TEST_F(ServerTest, ArrayParam) {
  4412. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4413. ASSERT_TRUE(res);
  4414. EXPECT_EQ(StatusCode::OK_200, res->status);
  4415. }
  4416. TEST_F(ServerTest, NoMultipleHeaders) {
  4417. Headers headers = {{"Content-Length", "5"}};
  4418. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4419. "text/plain");
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::OK_200, res->status);
  4422. }
  4423. TEST_F(ServerTest, PostContentReceiver) {
  4424. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4425. ASSERT_TRUE(res);
  4426. ASSERT_EQ(StatusCode::OK_200, res->status);
  4427. ASSERT_EQ("content", res->body);
  4428. }
  4429. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4430. MultipartFormDataItemsForClientInput items = {
  4431. {"text1", "text default", "", ""},
  4432. {"text2", "aωb", "", ""},
  4433. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4434. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4435. {"file3", "", "", "application/octet-stream"},
  4436. };
  4437. auto res = cli_.Post("/content_receiver", items);
  4438. ASSERT_TRUE(res);
  4439. EXPECT_EQ(StatusCode::OK_200, res->status);
  4440. }
  4441. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4442. MultipartFormDataItemsForClientInput items = {
  4443. {"text1", "text default", "", ""},
  4444. {"text2", "aωb", "", ""},
  4445. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4446. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4447. {"file3", "", "", "application/octet-stream"},
  4448. };
  4449. auto boundary = std::string("+++++");
  4450. std::string body;
  4451. for (const auto &item : items) {
  4452. body += "--" + boundary + "\r\n";
  4453. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4454. if (!item.filename.empty()) {
  4455. body += "; filename=\"" + item.filename + "\"";
  4456. }
  4457. body += "\r\n";
  4458. if (!item.content_type.empty()) {
  4459. body += "Content-Type: " + item.content_type + "\r\n";
  4460. }
  4461. body += "\r\n";
  4462. body += item.content + "\r\n";
  4463. }
  4464. body += "--" + boundary + "--\r\n";
  4465. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4466. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. }
  4470. TEST_F(ServerTest, PostContentReceiverGzip) {
  4471. cli_.set_compress(true);
  4472. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4473. ASSERT_TRUE(res);
  4474. ASSERT_EQ(StatusCode::OK_200, res->status);
  4475. ASSERT_EQ("content", res->body);
  4476. }
  4477. TEST_F(ServerTest, PutContentReceiver) {
  4478. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4479. ASSERT_TRUE(res);
  4480. ASSERT_EQ(StatusCode::OK_200, res->status);
  4481. ASSERT_EQ("content", res->body);
  4482. }
  4483. TEST_F(ServerTest, PatchContentReceiver) {
  4484. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4485. ASSERT_TRUE(res);
  4486. ASSERT_EQ(StatusCode::OK_200, res->status);
  4487. ASSERT_EQ("content", res->body);
  4488. }
  4489. template <typename ClientType>
  4490. void TestWithHeadersAndContentReceiver(
  4491. ClientType &cli,
  4492. std::function<Result(ClientType &, const std::string &, const Headers &,
  4493. const std::string &, const std::string &,
  4494. ContentReceiver, DownloadProgress)>
  4495. request_func) {
  4496. Headers headers;
  4497. headers.emplace("X-Custom-Header", "test-value");
  4498. std::string received_body;
  4499. auto res = request_func(
  4500. cli, "/content_receiver", headers, "content", "application/json",
  4501. [&](const char *data, size_t data_length) {
  4502. received_body.append(data, data_length);
  4503. return true;
  4504. },
  4505. nullptr);
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("content", received_body);
  4509. }
  4510. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4512. using ClientT = SSLClient;
  4513. #else
  4514. using ClientT = Client;
  4515. #endif
  4516. TestWithHeadersAndContentReceiver<ClientT>(
  4517. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4518. const std::string &body, const std::string &content_type,
  4519. ContentReceiver receiver, DownloadProgress progress) {
  4520. return cli.Post(path, headers, body, content_type, receiver, progress);
  4521. });
  4522. }
  4523. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4524. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4525. using ClientT = SSLClient;
  4526. #else
  4527. using ClientT = Client;
  4528. #endif
  4529. TestWithHeadersAndContentReceiver<ClientT>(
  4530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4531. const std::string &body, const std::string &content_type,
  4532. ContentReceiver receiver, DownloadProgress progress) {
  4533. return cli.Put(path, headers, body, content_type, receiver, progress);
  4534. });
  4535. }
  4536. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4538. using ClientT = SSLClient;
  4539. #else
  4540. using ClientT = Client;
  4541. #endif
  4542. TestWithHeadersAndContentReceiver<ClientT>(
  4543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4544. const std::string &body, const std::string &content_type,
  4545. ContentReceiver receiver, DownloadProgress progress) {
  4546. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4547. });
  4548. }
  4549. template <typename ClientType>
  4550. void TestWithHeadersAndContentReceiverWithProgress(
  4551. ClientType &cli,
  4552. std::function<Result(ClientType &, const std::string &, const Headers &,
  4553. const std::string &, const std::string &,
  4554. ContentReceiver, DownloadProgress)>
  4555. request_func) {
  4556. Headers headers;
  4557. headers.emplace("X-Test-Header", "progress-test");
  4558. std::string received_body;
  4559. auto progress_called = false;
  4560. auto res = request_func(
  4561. cli, "/content_receiver", headers, "content", "text/plain",
  4562. [&](const char *data, size_t data_length) {
  4563. received_body.append(data, data_length);
  4564. return true;
  4565. },
  4566. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4567. progress_called = true;
  4568. return true;
  4569. });
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. EXPECT_EQ("content", received_body);
  4573. EXPECT_TRUE(progress_called);
  4574. }
  4575. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4577. using ClientT = SSLClient;
  4578. #else
  4579. using ClientT = Client;
  4580. #endif
  4581. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4582. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4583. const std::string &body, const std::string &content_type,
  4584. ContentReceiver receiver, DownloadProgress progress) {
  4585. return cli.Post(path, headers, body, content_type, receiver, progress);
  4586. });
  4587. }
  4588. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4590. using ClientT = SSLClient;
  4591. #else
  4592. using ClientT = Client;
  4593. #endif
  4594. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4595. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4596. const std::string &body, const std::string &content_type,
  4597. ContentReceiver receiver, DownloadProgress progress) {
  4598. return cli.Put(path, headers, body, content_type, receiver, progress);
  4599. });
  4600. }
  4601. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4602. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4603. using ClientT = SSLClient;
  4604. #else
  4605. using ClientT = Client;
  4606. #endif
  4607. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4608. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4609. const std::string &body, const std::string &content_type,
  4610. ContentReceiver receiver, DownloadProgress progress) {
  4611. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4612. });
  4613. }
  4614. template <typename ClientType>
  4615. void TestWithHeadersAndContentReceiverError(
  4616. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4617. const Headers &, const std::string &,
  4618. const std::string &, ContentReceiver)>
  4619. request_func) {
  4620. Headers headers;
  4621. headers.emplace("X-Error-Test", "true");
  4622. std::string received_body;
  4623. auto receiver_failed = false;
  4624. auto res =
  4625. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4626. [&](const char *data, size_t data_length) {
  4627. received_body.append(data, data_length);
  4628. receiver_failed = true;
  4629. return false;
  4630. });
  4631. ASSERT_FALSE(res);
  4632. EXPECT_TRUE(receiver_failed);
  4633. }
  4634. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4636. using ClientT = SSLClient;
  4637. #else
  4638. using ClientT = Client;
  4639. #endif
  4640. TestWithHeadersAndContentReceiverError<ClientT>(
  4641. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4642. const std::string &body, const std::string &content_type,
  4643. ContentReceiver receiver) {
  4644. return cli.Post(path, headers, body, content_type, receiver);
  4645. });
  4646. }
  4647. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4648. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4649. using ClientT = SSLClient;
  4650. #else
  4651. using ClientT = Client;
  4652. #endif
  4653. TestWithHeadersAndContentReceiverError<ClientT>(
  4654. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4655. const std::string &body, const std::string &content_type,
  4656. ContentReceiver receiver) {
  4657. return cli.Put(path, headers, body, content_type, receiver);
  4658. });
  4659. }
  4660. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4662. using ClientT = SSLClient;
  4663. #else
  4664. using ClientT = Client;
  4665. #endif
  4666. TestWithHeadersAndContentReceiverError<ClientT>(
  4667. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4668. const std::string &body, const std::string &content_type,
  4669. ContentReceiver receiver) {
  4670. return cli.Patch(path, headers, body, content_type, receiver);
  4671. });
  4672. }
  4673. TEST_F(ServerTest, PostQueryStringAndBody) {
  4674. auto res =
  4675. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4676. ASSERT_TRUE(res);
  4677. ASSERT_EQ(StatusCode::OK_200, res->status);
  4678. }
  4679. TEST_F(ServerTest, HTTP2Magic) {
  4680. Request req;
  4681. req.method = "PRI";
  4682. req.path = "*";
  4683. req.body = "SM";
  4684. auto res = std::make_shared<Response>();
  4685. auto error = Error::Success;
  4686. auto ret = cli_.send(req, *res, error);
  4687. ASSERT_TRUE(ret);
  4688. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4689. }
  4690. TEST_F(ServerTest, KeepAlive) {
  4691. auto res = cli_.Get("/hi");
  4692. ASSERT_TRUE(res);
  4693. EXPECT_EQ(StatusCode::OK_200, res->status);
  4694. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4695. EXPECT_EQ("Hello World!", res->body);
  4696. res = cli_.Get("/hi");
  4697. ASSERT_TRUE(res);
  4698. EXPECT_EQ(StatusCode::OK_200, res->status);
  4699. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4700. EXPECT_EQ("Hello World!", res->body);
  4701. res = cli_.Get("/hi");
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4705. EXPECT_EQ("Hello World!", res->body);
  4706. res = cli_.Get("/not-exist");
  4707. ASSERT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4709. res = cli_.Post("/empty", "", "text/plain");
  4710. ASSERT_TRUE(res);
  4711. EXPECT_EQ(StatusCode::OK_200, res->status);
  4712. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4713. EXPECT_EQ("empty", res->body);
  4714. EXPECT_EQ("close", res->get_header_value("Connection"));
  4715. res = cli_.Post(
  4716. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4717. "text/plain");
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4721. EXPECT_EQ("empty", res->body);
  4722. cli_.set_keep_alive(false);
  4723. res = cli_.Get("/last-request");
  4724. ASSERT_TRUE(res);
  4725. EXPECT_EQ(StatusCode::OK_200, res->status);
  4726. EXPECT_EQ("close", res->get_header_value("Connection"));
  4727. }
  4728. TEST_F(ServerTest, TooManyRedirect) {
  4729. cli_.set_follow_location(true);
  4730. auto res = cli_.Get("/redirect/0");
  4731. ASSERT_TRUE(!res);
  4732. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4733. }
  4734. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4735. TEST_F(ServerTest, Gzip) {
  4736. Headers headers;
  4737. headers.emplace("Accept-Encoding", "gzip, deflate");
  4738. auto res = cli_.Get("/compress", headers);
  4739. ASSERT_TRUE(res);
  4740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4742. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4743. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4744. "7890123456789012345678901234567890",
  4745. res->body);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. }
  4748. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4749. Headers headers;
  4750. headers.emplace("Accept-Encoding", "");
  4751. auto res = cli_.Get("/compress", headers);
  4752. ASSERT_TRUE(res);
  4753. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4755. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4756. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4757. "7890123456789012345678901234567890",
  4758. res->body);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. }
  4761. TEST_F(ServerTest, GzipWithContentReceiver) {
  4762. Headers headers;
  4763. headers.emplace("Accept-Encoding", "gzip, deflate");
  4764. std::string body;
  4765. auto res = cli_.Get("/compress", headers,
  4766. [&](const char *data, uint64_t data_length) {
  4767. EXPECT_EQ(100U, data_length);
  4768. body.append(data, data_length);
  4769. return true;
  4770. });
  4771. ASSERT_TRUE(res);
  4772. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4773. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4774. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4775. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4776. "7890123456789012345678901234567890",
  4777. body);
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. }
  4780. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4781. Headers headers;
  4782. headers.emplace("Accept-Encoding", "gzip, deflate");
  4783. cli_.set_decompress(false);
  4784. auto res = cli_.Get("/compress", headers);
  4785. ASSERT_TRUE(res);
  4786. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4788. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4789. EXPECT_EQ(33U, res->body.size());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. }
  4792. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4793. Headers headers;
  4794. headers.emplace("Accept-Encoding", "");
  4795. std::string body;
  4796. auto res = cli_.Get("/compress", headers,
  4797. [&](const char *data, uint64_t data_length) {
  4798. EXPECT_EQ(100U, data_length);
  4799. body.append(data, data_length);
  4800. return true;
  4801. });
  4802. ASSERT_TRUE(res);
  4803. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4804. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4805. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4806. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4807. "7890123456789012345678901234567890",
  4808. body);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, NoGzip) {
  4812. Headers headers;
  4813. headers.emplace("Accept-Encoding", "gzip, deflate");
  4814. auto res = cli_.Get("/nocompress", headers);
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4817. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4818. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4819. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4820. "7890123456789012345678901234567890",
  4821. res->body);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4825. Headers headers;
  4826. headers.emplace("Accept-Encoding", "gzip, deflate");
  4827. std::string body;
  4828. auto res = cli_.Get("/nocompress", headers,
  4829. [&](const char *data, uint64_t data_length) {
  4830. EXPECT_EQ(100U, data_length);
  4831. body.append(data, data_length);
  4832. return true;
  4833. });
  4834. ASSERT_TRUE(res);
  4835. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4836. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4837. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4839. "7890123456789012345678901234567890",
  4840. body);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. }
  4843. TEST_F(ServerTest, MultipartFormDataGzip) {
  4844. MultipartFormDataItemsForClientInput items = {
  4845. {"key1", "test", "", ""},
  4846. {"key2", "--abcdefg123", "", ""},
  4847. };
  4848. cli_.set_compress(true);
  4849. auto res = cli_.Post("/compress-multipart", items);
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::OK_200, res->status);
  4852. }
  4853. #endif
  4854. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4855. TEST_F(ServerTest, Brotli) {
  4856. Headers headers;
  4857. headers.emplace("Accept-Encoding", "br");
  4858. auto res = cli_.Get("/compress", headers);
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4862. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4863. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4864. "7890123456789012345678901234567890",
  4865. res->body);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. }
  4868. #endif
  4869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4870. TEST_F(ServerTest, Zstd) {
  4871. Headers headers;
  4872. headers.emplace("Accept-Encoding", "zstd");
  4873. auto res = cli_.Get("/compress", headers);
  4874. ASSERT_TRUE(res);
  4875. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4877. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4879. "7890123456789012345678901234567890",
  4880. res->body);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4884. Headers headers;
  4885. headers.emplace("Accept-Encoding", "");
  4886. auto res = cli_.Get("/compress", headers);
  4887. ASSERT_TRUE(res);
  4888. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4889. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4890. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4891. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4892. "7890123456789012345678901234567890",
  4893. res->body);
  4894. EXPECT_EQ(StatusCode::OK_200, res->status);
  4895. }
  4896. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4897. Headers headers;
  4898. headers.emplace("Accept-Encoding", "zstd");
  4899. std::string body;
  4900. auto res = cli_.Get("/compress", headers,
  4901. [&](const char *data, uint64_t data_length) {
  4902. EXPECT_EQ(100U, data_length);
  4903. body.append(data, data_length);
  4904. return true;
  4905. });
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4911. "7890123456789012345678901234567890",
  4912. body);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. }
  4915. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4916. Headers headers;
  4917. headers.emplace("Accept-Encoding", "zstd");
  4918. cli_.set_decompress(false);
  4919. auto res = cli_.Get("/compress", headers);
  4920. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4921. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4922. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4923. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4927. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4928. EXPECT_EQ(StatusCode::OK_200, res->status);
  4929. ASSERT_EQ(26U, res->body.size());
  4930. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4931. 0);
  4932. }
  4933. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4934. Headers headers;
  4935. headers.emplace("Accept-Encoding", "");
  4936. std::string body;
  4937. auto res = cli_.Get("/compress", headers,
  4938. [&](const char *data, uint64_t data_length) {
  4939. EXPECT_EQ(100U, data_length);
  4940. body.append(data, data_length);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(res);
  4944. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4948. "7890123456789012345678901234567890",
  4949. body);
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. }
  4952. TEST_F(ServerTest, NoZstd) {
  4953. Headers headers;
  4954. headers.emplace("Accept-Encoding", "zstd");
  4955. auto res = cli_.Get("/nocompress", headers);
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4958. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4959. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4960. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4961. "7890123456789012345678901234567890",
  4962. res->body);
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. }
  4965. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4966. Headers headers;
  4967. headers.emplace("Accept-Encoding", "zstd");
  4968. std::string body;
  4969. auto res = cli_.Get("/nocompress", headers,
  4970. [&](const char *data, uint64_t data_length) {
  4971. EXPECT_EQ(100U, data_length);
  4972. body.append(data, data_length);
  4973. return true;
  4974. });
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4977. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4978. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4979. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4980. "7890123456789012345678901234567890",
  4981. body);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. }
  4984. // TODO: How to enable zstd ??
  4985. TEST_F(ServerTest, MultipartFormDataZstd) {
  4986. MultipartFormDataItemsForClientInput items = {
  4987. {"key1", "test", "", ""},
  4988. {"key2", "--abcdefg123", "", ""},
  4989. };
  4990. Headers headers;
  4991. headers.emplace("Accept-Encoding", "zstd");
  4992. cli_.set_compress(true);
  4993. auto res = cli_.Post("/compress-multipart", headers, items);
  4994. ASSERT_TRUE(res);
  4995. EXPECT_EQ(StatusCode::OK_200, res->status);
  4996. }
  4997. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4998. Headers headers;
  4999. headers.emplace("Accept-Encoding", "zstd");
  5000. cli_.set_compress(true);
  5001. auto res = cli_.Put(
  5002. "/put", headers, 3,
  5003. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5004. sink.os << "PUT";
  5005. return true;
  5006. },
  5007. "text/plain");
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. EXPECT_EQ("PUT", res->body);
  5011. }
  5012. // Pre-compression logging tests
  5013. TEST_F(ServerTest, PreCompressionLogging) {
  5014. // Test data for compression (matches the actual /compress endpoint content)
  5015. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5016. // Variables to capture logging data
  5017. std::string pre_compression_body;
  5018. std::string pre_compression_content_type;
  5019. std::string pre_compression_content_encoding;
  5020. std::string post_compression_body;
  5021. std::string post_compression_content_type;
  5022. std::string post_compression_content_encoding;
  5023. // Set up pre-compression logger
  5024. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5025. pre_compression_body = res.body;
  5026. pre_compression_content_type = res.get_header_value("Content-Type");
  5027. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5028. });
  5029. // Set up post-compression logger
  5030. svr_.set_logger([&](const Request &req, const Response &res) {
  5031. post_compression_body = res.body;
  5032. post_compression_content_type = res.get_header_value("Content-Type");
  5033. post_compression_content_encoding = res.get_header_value("Content-Encoding");
  5034. });
  5035. // Test with gzip compression
  5036. Headers headers;
  5037. headers.emplace("Accept-Encoding", "gzip");
  5038. auto res = cli_.Get("/compress", headers);
  5039. // Verify response was compressed
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5043. // Verify pre-compression logger captured uncompressed content
  5044. EXPECT_EQ(test_content, pre_compression_body);
  5045. EXPECT_EQ("text/plain", pre_compression_content_type);
  5046. EXPECT_TRUE(pre_compression_content_encoding.empty()); // No encoding header before compression
  5047. // Verify post-compression logger captured compressed content
  5048. EXPECT_NE(test_content, post_compression_body); // Should be different after compression
  5049. EXPECT_EQ("text/plain", post_compression_content_type);
  5050. EXPECT_EQ("gzip", post_compression_content_encoding);
  5051. // Verify compressed content is smaller
  5052. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5053. }
  5054. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5055. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5056. std::string pre_compression_body;
  5057. std::string post_compression_body;
  5058. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5059. pre_compression_body = res.body;
  5060. });
  5061. svr_.set_logger([&](const Request &req, const Response &res) {
  5062. post_compression_body = res.body;
  5063. });
  5064. Headers headers;
  5065. headers.emplace("Accept-Encoding", "br");
  5066. auto res = cli_.Get("/compress", headers);
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5070. // Verify pre-compression content is uncompressed
  5071. EXPECT_EQ(test_content, pre_compression_body);
  5072. // Verify post-compression content is compressed
  5073. EXPECT_NE(test_content, post_compression_body);
  5074. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5075. }
  5076. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5077. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5078. std::string pre_compression_body;
  5079. std::string post_compression_body;
  5080. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5081. pre_compression_body = res.body;
  5082. });
  5083. svr_.set_logger([&](const Request &req, const Response &res) {
  5084. post_compression_body = res.body;
  5085. });
  5086. // Request without compression (use /nocompress endpoint)
  5087. Headers headers;
  5088. auto res = cli_.Get("/nocompress", headers);
  5089. ASSERT_TRUE(res);
  5090. EXPECT_EQ(StatusCode::OK_200, res->status);
  5091. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5092. // Pre-compression logger should not be called when no compression is applied
  5093. EXPECT_TRUE(pre_compression_body.empty()); // Pre-compression logger not called
  5094. EXPECT_EQ(test_content, post_compression_body); // Post-compression logger captures final content
  5095. }
  5096. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5097. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5098. std::string pre_compression_body;
  5099. bool pre_logger_called = false;
  5100. // Set only pre-compression logger
  5101. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5102. pre_compression_body = res.body;
  5103. pre_logger_called = true;
  5104. });
  5105. Headers headers;
  5106. headers.emplace("Accept-Encoding", "gzip");
  5107. auto res = cli_.Get("/compress", headers);
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5111. // Verify pre-compression logger was called
  5112. EXPECT_TRUE(pre_logger_called);
  5113. EXPECT_EQ(test_content, pre_compression_body);
  5114. }
  5115. TEST(ZstdDecompressor, ChunkedDecompression) {
  5116. std::string data;
  5117. for (size_t i = 0; i < 32 * 1024; ++i) {
  5118. data.push_back(static_cast<char>('a' + i % 26));
  5119. }
  5120. std::string compressed_data;
  5121. {
  5122. httplib::detail::zstd_compressor compressor;
  5123. bool result = compressor.compress(
  5124. data.data(), data.size(),
  5125. /*last=*/true,
  5126. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5127. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5128. compressed_data_size);
  5129. return true;
  5130. });
  5131. ASSERT_TRUE(result);
  5132. }
  5133. std::string decompressed_data;
  5134. {
  5135. httplib::detail::zstd_decompressor decompressor;
  5136. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5137. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5138. size_t chunk_size = 130;
  5139. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5140. chunk_begin += chunk_size) {
  5141. size_t current_chunk_size =
  5142. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5143. bool result = decompressor.decompress(
  5144. compressed_data.data() + chunk_begin, current_chunk_size,
  5145. [&](const char *decompressed_data_chunk,
  5146. size_t decompressed_data_chunk_size) {
  5147. decompressed_data.insert(decompressed_data.size(),
  5148. decompressed_data_chunk,
  5149. decompressed_data_chunk_size);
  5150. return true;
  5151. });
  5152. ASSERT_TRUE(result);
  5153. }
  5154. }
  5155. ASSERT_EQ(data, decompressed_data);
  5156. }
  5157. TEST(ZstdDecompressor, Decompress) {
  5158. std::string original_text = "Compressed with ZSTD";
  5159. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5160. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5161. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5162. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5163. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5164. std::string decompressed_data;
  5165. {
  5166. httplib::detail::zstd_decompressor decompressor;
  5167. bool result = decompressor.decompress(
  5168. compressed_data.data(), compressed_data.size(),
  5169. [&](const char *decompressed_data_chunk,
  5170. size_t decompressed_data_chunk_size) {
  5171. decompressed_data.insert(decompressed_data.size(),
  5172. decompressed_data_chunk,
  5173. decompressed_data_chunk_size);
  5174. return true;
  5175. });
  5176. ASSERT_TRUE(result);
  5177. }
  5178. ASSERT_EQ(original_text, decompressed_data);
  5179. }
  5180. #endif
  5181. // Sends a raw request to a server listening at HOST:PORT.
  5182. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5183. std::string *resp = nullptr) {
  5184. auto error = Error::Success;
  5185. auto client_sock = detail::create_client_socket(
  5186. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5187. /*connection_timeout_sec=*/5, 0,
  5188. /*read_timeout_sec=*/5, 0,
  5189. /*write_timeout_sec=*/5, 0, std::string(), error);
  5190. if (client_sock == INVALID_SOCKET) { return false; }
  5191. auto ret = detail::process_client_socket(
  5192. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5193. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5194. if (req.size() !=
  5195. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5196. return false;
  5197. }
  5198. char buf[512];
  5199. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5200. while (line_reader.getline()) {
  5201. if (resp) { *resp += line_reader.ptr(); }
  5202. }
  5203. return true;
  5204. });
  5205. detail::close_socket(client_sock);
  5206. return ret;
  5207. }
  5208. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5209. Server svr;
  5210. std::string header_value;
  5211. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5212. header_value = req.get_header_value("foo");
  5213. res.set_content("ok", "text/plain");
  5214. });
  5215. thread t = thread([&] { svr.listen(HOST, PORT); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. t.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5223. // like characters are not treated the same - use vertical tab and escape.
  5224. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5225. "foo: \t \v bar \x1B\t \r\n"
  5226. "Connection: close\r\n"
  5227. "\r\n";
  5228. std::string res;
  5229. ASSERT_TRUE(send_request(5, req, &res));
  5230. EXPECT_EQ(header_value, "");
  5231. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5232. }
  5233. // Sends a raw request and verifies that there isn't a crash or exception.
  5234. static void test_raw_request(const std::string &req,
  5235. std::string *out = nullptr) {
  5236. Server svr;
  5237. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5238. res.set_content("ok", "text/plain");
  5239. });
  5240. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5241. res.set_content("ok", "text/plain");
  5242. });
  5243. svr.Get("/header_field_value_check",
  5244. [&](const Request & /*req*/, Response &res) {
  5245. res.set_content("ok", "text/plain");
  5246. });
  5247. // Server read timeout must be longer than the client read timeout for the
  5248. // bug to reproduce, probably to force the server to process a request
  5249. // without a trailing blank line.
  5250. const time_t client_read_timeout_sec = 1;
  5251. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5252. bool listen_thread_ok = false;
  5253. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5254. auto se = detail::scope_exit([&] {
  5255. svr.stop();
  5256. t.join();
  5257. ASSERT_FALSE(svr.is_running());
  5258. EXPECT_TRUE(listen_thread_ok);
  5259. });
  5260. svr.wait_until_ready();
  5261. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5262. }
  5263. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5264. // A certain header line causes an exception if the header property is parsed
  5265. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5266. test_raw_request(
  5267. "GET /hi HTTP/1.1\r\n"
  5268. " : "
  5269. " "
  5270. " ");
  5271. }
  5272. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5273. // A certain header line causes an exception if the header property *name* is
  5274. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5275. // greedy matcher and requires backtracking when there are a lot of ":"
  5276. // characters.
  5277. // This occurs with libc++ but not libstdc++.
  5278. test_raw_request(
  5279. "GET /hi HTTP/1.1\r\n"
  5280. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5281. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5282. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5283. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5284. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5285. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5286. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5287. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5288. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5289. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5290. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5291. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5292. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5293. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5294. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5295. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5296. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5297. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5298. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5299. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5300. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5301. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5302. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5303. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5304. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5305. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5306. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5307. "&&&%%%");
  5308. }
  5309. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5310. // Make sure this doesn't crash the server.
  5311. // In a previous version of the header line regex, the "\r" rendered the line
  5312. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5313. // a new position where the leading white space ended and the field value
  5314. // began.
  5315. // The crash occurs with libc++ but not libstdc++.
  5316. test_raw_request("GET /hi HTTP/1.1\r\n"
  5317. "a:" +
  5318. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5319. "\r\n"
  5320. "\r\n");
  5321. }
  5322. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5323. std::string out;
  5324. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5325. "Content-Type: text/plain\r\n"
  5326. "Transfer-Encoding: chunked\r\n"
  5327. "\r\n"
  5328. "nothex\r\n",
  5329. &out);
  5330. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5331. }
  5332. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5333. std::string out;
  5334. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5335. "Content-Type: text/plain\r\n"
  5336. "Transfer-Encoding: chunked\r\n"
  5337. "\r\n"
  5338. "3\r\n"
  5339. "xyz\r\n"
  5340. "NaN\r\n",
  5341. &out);
  5342. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5343. }
  5344. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5345. std::string out;
  5346. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5347. "Content-Type: text/plain\r\n"
  5348. "Transfer-Encoding: chunked\r\n"
  5349. "\r\n"
  5350. // Length is too large for 64 bits.
  5351. "1ffffffffffffffff\r\n"
  5352. "xyz\r\n",
  5353. &out);
  5354. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5355. }
  5356. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5357. test_raw_request("GET /hi HTTP/1.1\r\n"
  5358. "Content-Type: text/plain\r\n\r");
  5359. }
  5360. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5361. std::string out;
  5362. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5363. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5364. }
  5365. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5366. std::string out;
  5367. std::string request(
  5368. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5369. test_raw_request(request, &out);
  5370. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5371. }
  5372. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5373. std::string out;
  5374. std::string request(
  5375. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5376. test_raw_request(request, &out);
  5377. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5378. }
  5379. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5380. std::string out;
  5381. std::string request(
  5382. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5383. test_raw_request(request, &out);
  5384. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5385. }
  5386. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5387. std::string out;
  5388. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5389. "Test: \r\n\r\n",
  5390. &out);
  5391. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5392. }
  5393. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5394. Server svr;
  5395. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5396. res.set_header("Cache-Control", "no-cache");
  5397. res.set_chunked_content_provider(
  5398. "text/event-stream", [](size_t offset, DataSink &sink) {
  5399. std::string s = "data:";
  5400. s += std::to_string(offset);
  5401. s += "\n\n";
  5402. auto ret = sink.write(s.data(), s.size());
  5403. EXPECT_TRUE(ret);
  5404. std::this_thread::sleep_for(std::chrono::seconds(1));
  5405. return true;
  5406. });
  5407. });
  5408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5409. svr.wait_until_ready();
  5410. Client client(HOST, PORT);
  5411. const Headers headers = {{"Accept", "text/event-stream"}};
  5412. auto get_thread = std::thread([&client, &headers]() {
  5413. auto res = client.Get(
  5414. "/events", headers,
  5415. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5416. });
  5417. auto se = detail::scope_exit([&] {
  5418. svr.stop();
  5419. get_thread.join();
  5420. listen_thread.join();
  5421. ASSERT_FALSE(svr.is_running());
  5422. });
  5423. // Give GET time to get a few messages.
  5424. std::this_thread::sleep_for(std::chrono::seconds(2));
  5425. }
  5426. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5427. httplib::Server svr;
  5428. svr.Post("/hi",
  5429. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5430. res.status = StatusCode::OK_200;
  5431. });
  5432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5433. svr.wait_until_ready();
  5434. Client cli(HOST, PORT);
  5435. auto res = cli.Post("/hi", "data", "text/plain");
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. svr.stop();
  5439. thread.join();
  5440. ASSERT_FALSE(svr.is_running());
  5441. res = cli.Post("/hi", "data", "text/plain");
  5442. ASSERT_FALSE(res);
  5443. }
  5444. TEST(ServerStopTest, ListenFailure) {
  5445. Server svr;
  5446. auto t = thread([&]() {
  5447. auto ret = svr.listen("????", PORT);
  5448. EXPECT_FALSE(ret);
  5449. });
  5450. svr.wait_until_ready();
  5451. svr.stop();
  5452. t.join();
  5453. }
  5454. TEST(ServerStopTest, Decommision) {
  5455. Server svr;
  5456. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5457. for (int i = 0; i < 4; i++) {
  5458. auto is_even = !(i % 2);
  5459. std::thread t{[&] {
  5460. try {
  5461. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5462. if (is_even) {
  5463. throw std::runtime_error("Some thing that happens to go wrong.");
  5464. }
  5465. svr.listen(HOST, PORT);
  5466. } catch (...) { svr.decommission(); }
  5467. }};
  5468. svr.wait_until_ready();
  5469. // Server is up
  5470. {
  5471. Client cli(HOST, PORT);
  5472. auto res = cli.Get("/hi");
  5473. if (is_even) {
  5474. EXPECT_FALSE(res);
  5475. } else {
  5476. EXPECT_TRUE(res);
  5477. EXPECT_EQ("hi...", res->body);
  5478. }
  5479. }
  5480. svr.stop();
  5481. t.join();
  5482. // Server is down...
  5483. {
  5484. Client cli(HOST, PORT);
  5485. auto res = cli.Get("/hi");
  5486. EXPECT_FALSE(res);
  5487. }
  5488. }
  5489. }
  5490. // Helper function for string body upload progress tests
  5491. template <typename SetupHandler, typename ClientCall>
  5492. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5493. ClientCall &&client_call,
  5494. const string &body) {
  5495. Server svr;
  5496. setup_handler(svr);
  5497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5498. auto se = detail::scope_exit([&] {
  5499. svr.stop();
  5500. t.join();
  5501. });
  5502. svr.wait_until_ready();
  5503. Client cli(HOST, PORT);
  5504. vector<uint64_t> progress_values;
  5505. bool progress_called = false;
  5506. auto res =
  5507. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5508. progress_values.push_back(current);
  5509. progress_called = true;
  5510. return true;
  5511. });
  5512. ASSERT_TRUE(res);
  5513. EXPECT_EQ(200, res->status);
  5514. EXPECT_TRUE(progress_called);
  5515. }
  5516. TEST(UploadProgressTest, PostStringBodyBasic) {
  5517. TestStringBodyUploadProgress(
  5518. [](Server &svr) {
  5519. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5520. res.set_content("received", "text/plain");
  5521. });
  5522. },
  5523. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5524. return cli.Post("/test", body, "text/plain", progress_callback);
  5525. },
  5526. "test data for upload progress");
  5527. }
  5528. TEST(UploadProgressTest, PutStringBodyBasic) {
  5529. TestStringBodyUploadProgress(
  5530. [](Server &svr) {
  5531. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5532. res.set_content("put received", "text/plain");
  5533. });
  5534. },
  5535. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5536. return cli.Put("/test", body, "text/plain", progress_callback);
  5537. },
  5538. "put test data for upload progress");
  5539. }
  5540. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5541. TestStringBodyUploadProgress(
  5542. [](Server &svr) {
  5543. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5544. res.set_content("patch received", "text/plain");
  5545. });
  5546. },
  5547. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5548. return cli.Patch("/test", body, "text/plain", progress_callback);
  5549. },
  5550. "patch test data for upload progress");
  5551. }
  5552. // Helper function for content provider upload progress tests
  5553. template <typename SetupHandler, typename ClientCall>
  5554. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5555. ClientCall &&client_call) {
  5556. Server svr;
  5557. setup_handler(svr);
  5558. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5559. auto se = detail::scope_exit([&] {
  5560. svr.stop();
  5561. t.join();
  5562. });
  5563. svr.wait_until_ready();
  5564. Client cli(HOST, PORT);
  5565. vector<uint64_t> progress_values;
  5566. auto res =
  5567. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5568. progress_values.push_back(current);
  5569. return true;
  5570. });
  5571. ASSERT_TRUE(res);
  5572. EXPECT_EQ(200, res->status);
  5573. EXPECT_FALSE(progress_values.empty());
  5574. }
  5575. TEST(UploadProgressTest, PostContentProviderProgress) {
  5576. TestContentProviderUploadProgress(
  5577. [](Server &svr) {
  5578. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5579. res.set_content("provider received", "text/plain");
  5580. });
  5581. },
  5582. [](Client &cli, UploadProgress progress_callback) {
  5583. return cli.Post(
  5584. "/test", 10,
  5585. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5586. sink.os << "test data";
  5587. return true;
  5588. },
  5589. "text/plain", progress_callback);
  5590. });
  5591. }
  5592. // Helper function for multipart upload progress tests
  5593. template <typename SetupHandler, typename ClientCall>
  5594. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5595. ClientCall &&client_call,
  5596. const string &endpoint) {
  5597. Server svr;
  5598. setup_handler(svr);
  5599. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5600. auto se = detail::scope_exit([&] {
  5601. svr.stop();
  5602. t.join();
  5603. });
  5604. svr.wait_until_ready();
  5605. Client cli(HOST, PORT);
  5606. vector<uint64_t> progress_values;
  5607. MultipartFormDataItemsForClientInput items = {
  5608. {"field1", "value1", "", ""},
  5609. {"field2", "longer value for progress tracking test", "", ""},
  5610. {"file1", "file content data for upload progress", "test.txt",
  5611. "text/plain"}};
  5612. auto res = client_call(cli, endpoint, items,
  5613. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5614. progress_values.push_back(current);
  5615. return true;
  5616. });
  5617. ASSERT_TRUE(res);
  5618. EXPECT_EQ(200, res->status);
  5619. EXPECT_FALSE(progress_values.empty());
  5620. }
  5621. TEST(UploadProgressTest, PostMultipartProgress) {
  5622. TestMultipartUploadProgress(
  5623. [](Server &svr) {
  5624. svr.Post("/multipart", [](const Request &req, Response &res) {
  5625. EXPECT_FALSE(req.files.empty());
  5626. res.set_content("multipart received", "text/plain");
  5627. });
  5628. },
  5629. [](Client &cli, const string &endpoint,
  5630. const MultipartFormDataItemsForClientInput &items,
  5631. UploadProgress progress_callback) {
  5632. return cli.Post(endpoint, items, progress_callback);
  5633. },
  5634. "/multipart");
  5635. }
  5636. // Helper function for basic download progress tests
  5637. template <typename SetupHandler, typename ClientCall>
  5638. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5639. ClientCall &&client_call, const string &endpoint,
  5640. size_t expected_content_size) {
  5641. Server svr;
  5642. setup_handler(svr);
  5643. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5644. auto se = detail::scope_exit([&] {
  5645. svr.stop();
  5646. t.join();
  5647. });
  5648. svr.wait_until_ready();
  5649. Client cli(HOST, PORT);
  5650. vector<uint64_t> progress_values;
  5651. auto res = client_call(cli, endpoint,
  5652. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5653. progress_values.push_back(current);
  5654. return true;
  5655. });
  5656. ASSERT_TRUE(res);
  5657. EXPECT_EQ(200, res->status);
  5658. EXPECT_FALSE(progress_values.empty());
  5659. EXPECT_EQ(expected_content_size, res->body.size());
  5660. }
  5661. TEST(DownloadProgressTest, GetBasic) {
  5662. TestBasicDownloadProgress(
  5663. [](Server &svr) {
  5664. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5665. string content(1000, 'D');
  5666. res.set_content(content, "text/plain");
  5667. });
  5668. },
  5669. [](Client &cli, const string &endpoint,
  5670. DownloadProgress progress_callback) {
  5671. return cli.Get(endpoint, progress_callback);
  5672. },
  5673. "/download", 1000u);
  5674. }
  5675. // Helper function for content receiver download progress tests
  5676. template <typename SetupHandler, typename ClientCall>
  5677. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5678. ClientCall &&client_call,
  5679. const string &endpoint,
  5680. size_t expected_content_size) {
  5681. Server svr;
  5682. setup_handler(svr);
  5683. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5684. auto se = detail::scope_exit([&] {
  5685. svr.stop();
  5686. t.join();
  5687. });
  5688. svr.wait_until_ready();
  5689. Client cli(HOST, PORT);
  5690. vector<uint64_t> progress_values;
  5691. string received_body;
  5692. auto res = client_call(
  5693. cli, endpoint,
  5694. [&](const char *data, size_t data_length) -> bool {
  5695. received_body.append(data, data_length);
  5696. return true;
  5697. },
  5698. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5699. progress_values.push_back(current);
  5700. return true;
  5701. });
  5702. ASSERT_TRUE(res);
  5703. EXPECT_EQ(200, res->status);
  5704. EXPECT_FALSE(progress_values.empty());
  5705. EXPECT_EQ(expected_content_size, received_body.size());
  5706. EXPECT_TRUE(res->body.empty());
  5707. }
  5708. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5709. TestContentReceiverDownloadProgress(
  5710. [](Server &svr) {
  5711. svr.Get("/download-receiver",
  5712. [](const Request & /*req*/, Response &res) {
  5713. string content(2000, 'R');
  5714. res.set_content(content, "text/plain");
  5715. });
  5716. },
  5717. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5718. DownloadProgress progress_callback) {
  5719. return cli.Get(endpoint, content_receiver, progress_callback);
  5720. },
  5721. "/download-receiver", 2000u);
  5722. }
  5723. TEST(StreamingTest, NoContentLengthStreaming) {
  5724. Server svr;
  5725. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5726. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5727. if (offset < 6) {
  5728. sink.os << (offset < 3 ? "a" : "b");
  5729. } else {
  5730. sink.done();
  5731. }
  5732. return true;
  5733. });
  5734. });
  5735. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5736. auto listen_se = detail::scope_exit([&] {
  5737. svr.stop();
  5738. listen_thread.join();
  5739. ASSERT_FALSE(svr.is_running());
  5740. });
  5741. svr.wait_until_ready();
  5742. Client client(HOST, PORT);
  5743. auto get_thread = std::thread([&client]() {
  5744. std::string s;
  5745. auto res =
  5746. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5747. s += std::string(data, len);
  5748. return true;
  5749. });
  5750. ASSERT_TRUE(res);
  5751. EXPECT_EQ(StatusCode::OK_200, res->status);
  5752. EXPECT_EQ("aaabbb", s);
  5753. });
  5754. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5755. // Give GET time to get a few messages.
  5756. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5757. }
  5758. TEST(MountTest, Unmount) {
  5759. Server svr;
  5760. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5761. auto se = detail::scope_exit([&] {
  5762. svr.stop();
  5763. listen_thread.join();
  5764. ASSERT_FALSE(svr.is_running());
  5765. });
  5766. svr.wait_until_ready();
  5767. Client cli("localhost", PORT);
  5768. svr.set_mount_point("/mount2", "./www2");
  5769. auto res = cli.Get("/");
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5772. res = cli.Get("/mount2/dir/test.html");
  5773. ASSERT_TRUE(res);
  5774. EXPECT_EQ(StatusCode::OK_200, res->status);
  5775. svr.set_mount_point("/", "./www");
  5776. res = cli.Get("/dir/");
  5777. ASSERT_TRUE(res);
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. svr.remove_mount_point("/");
  5780. res = cli.Get("/dir/");
  5781. ASSERT_TRUE(res);
  5782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5783. svr.remove_mount_point("/mount2");
  5784. res = cli.Get("/mount2/dir/test.html");
  5785. ASSERT_TRUE(res);
  5786. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5787. }
  5788. TEST(MountTest, Redicect) {
  5789. Server svr;
  5790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5791. auto se = detail::scope_exit([&] {
  5792. svr.stop();
  5793. listen_thread.join();
  5794. ASSERT_FALSE(svr.is_running());
  5795. });
  5796. svr.set_mount_point("/", "./www");
  5797. svr.wait_until_ready();
  5798. Client cli("localhost", PORT);
  5799. auto res = cli.Get("/dir/");
  5800. ASSERT_TRUE(res);
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. res = cli.Get("/dir");
  5803. ASSERT_TRUE(res);
  5804. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5805. res = cli.Get("/file");
  5806. ASSERT_TRUE(res);
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. res = cli.Get("/file/");
  5809. ASSERT_TRUE(res);
  5810. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5811. cli.set_follow_location(true);
  5812. res = cli.Get("/dir");
  5813. ASSERT_TRUE(res);
  5814. EXPECT_EQ(StatusCode::OK_200, res->status);
  5815. }
  5816. TEST(MountTest, MultibytesPathName) {
  5817. Server svr;
  5818. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5819. auto se = detail::scope_exit([&] {
  5820. svr.stop();
  5821. listen_thread.join();
  5822. ASSERT_FALSE(svr.is_running());
  5823. });
  5824. svr.set_mount_point("/", "./www");
  5825. svr.wait_until_ready();
  5826. Client cli("localhost", PORT);
  5827. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5828. ASSERT_TRUE(res);
  5829. EXPECT_EQ(StatusCode::OK_200, res->status);
  5830. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5831. }
  5832. TEST(KeepAliveTest, ReadTimeout) {
  5833. Server svr;
  5834. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5835. std::this_thread::sleep_for(std::chrono::seconds(2));
  5836. res.set_content("a", "text/plain");
  5837. });
  5838. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5839. res.set_content("b", "text/plain");
  5840. });
  5841. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5842. auto se = detail::scope_exit([&] {
  5843. svr.stop();
  5844. listen_thread.join();
  5845. ASSERT_FALSE(svr.is_running());
  5846. });
  5847. svr.wait_until_ready();
  5848. Client cli("localhost", PORT);
  5849. cli.set_keep_alive(true);
  5850. cli.set_read_timeout(std::chrono::seconds(1));
  5851. auto resa = cli.Get("/a");
  5852. ASSERT_FALSE(resa);
  5853. EXPECT_EQ(Error::Read, resa.error());
  5854. auto resb = cli.Get("/b");
  5855. ASSERT_TRUE(resb);
  5856. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5857. EXPECT_EQ("b", resb->body);
  5858. }
  5859. TEST(KeepAliveTest, MaxCount) {
  5860. size_t keep_alive_max_count = 3;
  5861. Server svr;
  5862. svr.set_keep_alive_max_count(keep_alive_max_count);
  5863. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5864. res.set_content("Hello World!", "text/plain");
  5865. });
  5866. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5867. auto se = detail::scope_exit([&] {
  5868. svr.stop();
  5869. listen_thread.join();
  5870. ASSERT_FALSE(svr.is_running());
  5871. });
  5872. svr.wait_until_ready();
  5873. Client cli(HOST, PORT);
  5874. cli.set_keep_alive(true);
  5875. for (size_t i = 0; i < 5; i++) {
  5876. auto result = cli.Get("/hi");
  5877. ASSERT_TRUE(result);
  5878. EXPECT_EQ(StatusCode::OK_200, result->status);
  5879. if (i == keep_alive_max_count - 1) {
  5880. EXPECT_EQ("close", result->get_header_value("Connection"));
  5881. } else {
  5882. EXPECT_FALSE(result->has_header("Connection"));
  5883. }
  5884. }
  5885. }
  5886. TEST(KeepAliveTest, Issue1041) {
  5887. Server svr;
  5888. svr.set_keep_alive_timeout(3);
  5889. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5890. res.set_content("Hello World!", "text/plain");
  5891. });
  5892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5893. auto se = detail::scope_exit([&] {
  5894. svr.stop();
  5895. listen_thread.join();
  5896. ASSERT_FALSE(svr.is_running());
  5897. });
  5898. svr.wait_until_ready();
  5899. Client cli(HOST, PORT);
  5900. cli.set_keep_alive(true);
  5901. auto result = cli.Get("/hi");
  5902. ASSERT_TRUE(result);
  5903. EXPECT_EQ(StatusCode::OK_200, result->status);
  5904. std::this_thread::sleep_for(std::chrono::seconds(5));
  5905. result = cli.Get("/hi");
  5906. ASSERT_TRUE(result);
  5907. EXPECT_EQ(StatusCode::OK_200, result->status);
  5908. }
  5909. TEST(KeepAliveTest, Issue1959) {
  5910. Server svr;
  5911. svr.set_keep_alive_timeout(5);
  5912. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5913. res.set_content("a", "text/plain");
  5914. });
  5915. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5916. auto se = detail::scope_exit([&] {
  5917. if (!svr.is_running()) return;
  5918. svr.stop();
  5919. listen_thread.join();
  5920. ASSERT_FALSE(svr.is_running());
  5921. });
  5922. svr.wait_until_ready();
  5923. Client cli("localhost", PORT);
  5924. cli.set_keep_alive(true);
  5925. using namespace std::chrono;
  5926. auto start = steady_clock::now();
  5927. cli.Get("/a");
  5928. svr.stop();
  5929. listen_thread.join();
  5930. auto end = steady_clock::now();
  5931. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5932. EXPECT_LT(elapsed, 5000);
  5933. }
  5934. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5935. TEST(KeepAliveTest, SSLClientReconnection) {
  5936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5937. ASSERT_TRUE(svr.is_valid());
  5938. svr.set_keep_alive_timeout(1);
  5939. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5940. res.set_content("Hello World!", "text/plain");
  5941. });
  5942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5943. auto se = detail::scope_exit([&] {
  5944. svr.stop();
  5945. listen_thread.join();
  5946. ASSERT_FALSE(svr.is_running());
  5947. });
  5948. svr.wait_until_ready();
  5949. SSLClient cli(HOST, PORT);
  5950. cli.enable_server_certificate_verification(false);
  5951. cli.set_keep_alive(true);
  5952. auto result = cli.Get("/hi");
  5953. ASSERT_TRUE(result);
  5954. EXPECT_EQ(StatusCode::OK_200, result->status);
  5955. result = cli.Get("/hi");
  5956. ASSERT_TRUE(result);
  5957. EXPECT_EQ(StatusCode::OK_200, result->status);
  5958. std::this_thread::sleep_for(std::chrono::seconds(2));
  5959. // Recoonect
  5960. result = cli.Get("/hi");
  5961. ASSERT_TRUE(result);
  5962. EXPECT_EQ(StatusCode::OK_200, result->status);
  5963. result = cli.Get("/hi");
  5964. ASSERT_TRUE(result);
  5965. EXPECT_EQ(StatusCode::OK_200, result->status);
  5966. }
  5967. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5969. ASSERT_TRUE(svr.is_valid());
  5970. svr.set_keep_alive_timeout(1);
  5971. std::string content = "reconnect";
  5972. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5973. res.set_content("Hello World!", "text/plain");
  5974. });
  5975. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5976. auto se = detail::scope_exit([&] {
  5977. svr.stop();
  5978. listen_thread.join();
  5979. ASSERT_FALSE(svr.is_running());
  5980. });
  5981. svr.wait_until_ready();
  5982. SSLClient cli(HOST, PORT);
  5983. cli.enable_server_certificate_verification(false);
  5984. cli.set_keep_alive(true);
  5985. auto result = cli.Post(
  5986. "/hi", content.size(),
  5987. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5988. sink.write(content.c_str(), content.size());
  5989. return true;
  5990. },
  5991. "text/plain");
  5992. ASSERT_TRUE(result);
  5993. EXPECT_EQ(200, result->status);
  5994. std::this_thread::sleep_for(std::chrono::seconds(2));
  5995. // Recoonect
  5996. result = cli.Post(
  5997. "/hi", content.size(),
  5998. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5999. sink.write(content.c_str(), content.size());
  6000. return true;
  6001. },
  6002. "text/plain");
  6003. ASSERT_TRUE(result);
  6004. EXPECT_EQ(200, result->status);
  6005. result = cli.Post(
  6006. "/hi", content.size(),
  6007. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6008. sink.write(content.c_str(), content.size());
  6009. return true;
  6010. },
  6011. "text/plain");
  6012. ASSERT_TRUE(result);
  6013. EXPECT_EQ(200, result->status);
  6014. }
  6015. #endif
  6016. TEST(ClientProblemDetectionTest, ContentProvider) {
  6017. Server svr;
  6018. size_t content_length = 1024 * 1024;
  6019. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6020. res.set_content_provider(
  6021. content_length, "text/plain",
  6022. [&](size_t offset, size_t length, DataSink &sink) {
  6023. auto out_len = std::min(length, static_cast<size_t>(1024));
  6024. std::string out(out_len, '@');
  6025. sink.write(out.data(), out_len);
  6026. return offset < 4096;
  6027. },
  6028. [](bool success) { ASSERT_FALSE(success); });
  6029. });
  6030. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6031. res.set_content_provider(
  6032. 0, "text/plain",
  6033. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6034. EXPECT_TRUE(false);
  6035. return true;
  6036. },
  6037. [](bool success) { ASSERT_FALSE(success); });
  6038. });
  6039. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6040. auto se = detail::scope_exit([&] {
  6041. svr.stop();
  6042. listen_thread.join();
  6043. ASSERT_FALSE(svr.is_running());
  6044. });
  6045. svr.wait_until_ready();
  6046. Client cli("localhost", PORT);
  6047. {
  6048. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6049. size_t /*data_length*/) { return false; });
  6050. ASSERT_FALSE(res);
  6051. }
  6052. {
  6053. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6054. size_t /*data_length*/) { return false; });
  6055. ASSERT_TRUE(res);
  6056. }
  6057. }
  6058. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6059. Server svr;
  6060. svr.set_error_handler([](Request const &, Response &res) -> void {
  6061. res.set_chunked_content_provider(
  6062. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6063. sink.os << "hello";
  6064. sink.os << "world";
  6065. sink.done();
  6066. return true;
  6067. });
  6068. });
  6069. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6070. auto se = detail::scope_exit([&] {
  6071. svr.stop();
  6072. listen_thread.join();
  6073. ASSERT_FALSE(svr.is_running());
  6074. });
  6075. svr.wait_until_ready();
  6076. Client cli("localhost", PORT);
  6077. auto res = cli.Get("/");
  6078. ASSERT_TRUE(res);
  6079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6080. EXPECT_EQ("helloworld", res->body);
  6081. }
  6082. TEST(LongPollingTest, ClientCloseDetection) {
  6083. Server svr;
  6084. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6085. res.set_chunked_content_provider(
  6086. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6087. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6088. sink.os << "hello";
  6089. auto count = 10;
  6090. while (count > 0 && sink.is_writable()) {
  6091. this_thread::sleep_for(chrono::milliseconds(10));
  6092. count--;
  6093. }
  6094. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6095. return true;
  6096. });
  6097. });
  6098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6099. auto se = detail::scope_exit([&] {
  6100. svr.stop();
  6101. listen_thread.join();
  6102. ASSERT_FALSE(svr.is_running());
  6103. });
  6104. svr.wait_until_ready();
  6105. Client cli("localhost", PORT);
  6106. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6107. EXPECT_EQ("hello", string(data, data_length));
  6108. return false; // close the socket immediately.
  6109. });
  6110. ASSERT_FALSE(res);
  6111. }
  6112. TEST(GetWithParametersTest, GetWithParameters) {
  6113. Server svr;
  6114. svr.Get("/", [&](const Request &req, Response &) {
  6115. EXPECT_EQ("world", req.get_param_value("hello"));
  6116. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6117. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6118. });
  6119. svr.Get("/params", [&](const Request &req, Response &) {
  6120. EXPECT_EQ("world", req.get_param_value("hello"));
  6121. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6122. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6123. });
  6124. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6125. EXPECT_EQ("resource-id", req.matches[1]);
  6126. EXPECT_EQ("foo", req.get_param_value("param1"));
  6127. EXPECT_EQ("bar", req.get_param_value("param2"));
  6128. });
  6129. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6130. EXPECT_EQ("user-id", req.path_params.at("id"));
  6131. EXPECT_EQ("foo", req.get_param_value("param1"));
  6132. EXPECT_EQ("bar", req.get_param_value("param2"));
  6133. });
  6134. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6135. auto se = detail::scope_exit([&] {
  6136. svr.stop();
  6137. listen_thread.join();
  6138. ASSERT_FALSE(svr.is_running());
  6139. });
  6140. svr.wait_until_ready();
  6141. {
  6142. Client cli(HOST, PORT);
  6143. Params params;
  6144. params.emplace("hello", "world");
  6145. params.emplace("hello2", "world2");
  6146. params.emplace("hello3", "world3");
  6147. auto res = cli.Get("/", params, Headers{});
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. }
  6151. {
  6152. Client cli(HOST, PORT);
  6153. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6154. ASSERT_TRUE(res);
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. }
  6157. {
  6158. Client cli(HOST, PORT);
  6159. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6160. ASSERT_TRUE(res);
  6161. EXPECT_EQ(StatusCode::OK_200, res->status);
  6162. }
  6163. {
  6164. Client cli(HOST, PORT);
  6165. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6166. ASSERT_TRUE(res);
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. }
  6169. }
  6170. TEST(GetWithParametersTest, GetWithParameters2) {
  6171. Server svr;
  6172. svr.Get("/", [&](const Request &req, Response &res) {
  6173. auto text = req.get_param_value("hello");
  6174. res.set_content(text, "text/plain");
  6175. });
  6176. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6177. auto se = detail::scope_exit([&] {
  6178. svr.stop();
  6179. listen_thread.join();
  6180. ASSERT_FALSE(svr.is_running());
  6181. });
  6182. svr.wait_until_ready();
  6183. Client cli("localhost", PORT);
  6184. Params params;
  6185. params.emplace("hello", "world");
  6186. std::string body;
  6187. auto res = cli.Get("/", params, Headers{},
  6188. [&](const char *data, size_t data_length) {
  6189. body.append(data, data_length);
  6190. return true;
  6191. });
  6192. ASSERT_TRUE(res);
  6193. EXPECT_EQ(StatusCode::OK_200, res->status);
  6194. EXPECT_EQ("world", body);
  6195. }
  6196. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6197. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6198. auto host = "httpbin.org";
  6199. auto path = std::string{"/range/32"};
  6200. #else
  6201. auto host = "nghttp2.org";
  6202. auto path = std::string{"/httpbin/range/32"};
  6203. #endif
  6204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6205. SSLClient cli(host);
  6206. #else
  6207. Client cli(host);
  6208. #endif
  6209. cli.set_default_headers({make_range_header({{1, 10}})});
  6210. cli.set_connection_timeout(5);
  6211. {
  6212. auto res = cli.Get(path);
  6213. ASSERT_TRUE(res);
  6214. EXPECT_EQ("bcdefghijk", res->body);
  6215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6216. }
  6217. {
  6218. auto res = cli.Get(path);
  6219. ASSERT_TRUE(res);
  6220. EXPECT_EQ("bcdefghijk", res->body);
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. }
  6223. }
  6224. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6225. Server svr;
  6226. svr.set_default_headers({{"Hello", "World"}});
  6227. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6228. res.set_content("ok", "text/plain");
  6229. });
  6230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6231. auto se = detail::scope_exit([&] {
  6232. svr.stop();
  6233. listen_thread.join();
  6234. ASSERT_FALSE(svr.is_running());
  6235. });
  6236. svr.wait_until_ready();
  6237. Client cli("localhost", PORT);
  6238. auto res = cli.Get("/");
  6239. ASSERT_TRUE(res);
  6240. EXPECT_EQ(StatusCode::OK_200, res->status);
  6241. EXPECT_EQ("ok", res->body);
  6242. EXPECT_EQ("World", res->get_header_value("Hello"));
  6243. }
  6244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6245. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6247. ASSERT_TRUE(svr.is_valid());
  6248. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6249. std::this_thread::sleep_for(std::chrono::seconds(2));
  6250. res.set_content("a", "text/plain");
  6251. });
  6252. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6253. res.set_content("b", "text/plain");
  6254. });
  6255. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6256. auto se = detail::scope_exit([&] {
  6257. svr.stop();
  6258. listen_thread.join();
  6259. ASSERT_FALSE(svr.is_running());
  6260. });
  6261. svr.wait_until_ready();
  6262. SSLClient cli("localhost", PORT);
  6263. cli.enable_server_certificate_verification(false);
  6264. cli.set_keep_alive(true);
  6265. cli.set_read_timeout(std::chrono::seconds(1));
  6266. auto resa = cli.Get("/a");
  6267. ASSERT_TRUE(!resa);
  6268. EXPECT_EQ(Error::Read, resa.error());
  6269. auto resb = cli.Get("/b");
  6270. ASSERT_TRUE(resb);
  6271. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6272. EXPECT_EQ("b", resb->body);
  6273. }
  6274. #endif
  6275. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6276. protected:
  6277. ServerTestWithAI_PASSIVE()
  6278. : cli_(HOST, PORT)
  6279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6280. ,
  6281. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6282. #endif
  6283. {
  6284. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6285. cli_.enable_server_certificate_verification(false);
  6286. #endif
  6287. }
  6288. virtual void SetUp() {
  6289. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6290. res.set_content("Hello World!", "text/plain");
  6291. });
  6292. t_ = thread(
  6293. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6294. svr_.wait_until_ready();
  6295. }
  6296. virtual void TearDown() {
  6297. svr_.stop();
  6298. t_.join();
  6299. }
  6300. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6301. SSLClient cli_;
  6302. SSLServer svr_;
  6303. #else
  6304. Client cli_;
  6305. Server svr_;
  6306. #endif
  6307. thread t_;
  6308. };
  6309. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6310. auto res = cli_.Get("/hi");
  6311. ASSERT_TRUE(res);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6314. EXPECT_EQ("Hello World!", res->body);
  6315. }
  6316. class ServerUpDownTest : public ::testing::Test {
  6317. protected:
  6318. ServerUpDownTest() : cli_(HOST, PORT) {}
  6319. virtual void SetUp() {
  6320. t_ = thread([&]() {
  6321. svr_.bind_to_any_port(HOST);
  6322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6323. ASSERT_TRUE(svr_.listen_after_bind());
  6324. });
  6325. svr_.wait_until_ready();
  6326. }
  6327. virtual void TearDown() {
  6328. svr_.stop();
  6329. t_.join();
  6330. }
  6331. Client cli_;
  6332. Server svr_;
  6333. thread t_;
  6334. };
  6335. TEST_F(ServerUpDownTest, QuickStartStop) {
  6336. // Should not crash, especially when run with
  6337. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6338. }
  6339. class PayloadMaxLengthTest : public ::testing::Test {
  6340. protected:
  6341. PayloadMaxLengthTest()
  6342. : cli_(HOST, PORT)
  6343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6344. ,
  6345. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6346. #endif
  6347. {
  6348. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6349. cli_.enable_server_certificate_verification(false);
  6350. #endif
  6351. }
  6352. virtual void SetUp() {
  6353. svr_.set_payload_max_length(8);
  6354. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6355. res.set_content("test", "text/plain");
  6356. });
  6357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6358. svr_.wait_until_ready();
  6359. }
  6360. virtual void TearDown() {
  6361. svr_.stop();
  6362. t_.join();
  6363. }
  6364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6365. SSLClient cli_;
  6366. SSLServer svr_;
  6367. #else
  6368. Client cli_;
  6369. Server svr_;
  6370. #endif
  6371. thread t_;
  6372. };
  6373. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6374. auto res = cli_.Post("/test", "123456789", "text/plain");
  6375. ASSERT_TRUE(res);
  6376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6377. res = cli_.Post("/test", "12345678", "text/plain");
  6378. ASSERT_TRUE(res);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. TEST(HostAndPortPropertiesTest, NoSSL) {
  6382. httplib::Client cli("www.google.com", 1234);
  6383. ASSERT_EQ("www.google.com", cli.host());
  6384. ASSERT_EQ(1234, cli.port());
  6385. }
  6386. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6387. httplib::Client cli("www.google.com:1234");
  6388. ASSERT_EQ("www.google.com", cli.host());
  6389. ASSERT_EQ(1234, cli.port());
  6390. }
  6391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6392. TEST(HostAndPortPropertiesTest, SSL) {
  6393. httplib::SSLClient cli("www.google.com");
  6394. ASSERT_EQ("www.google.com", cli.host());
  6395. ASSERT_EQ(443, cli.port());
  6396. }
  6397. #endif
  6398. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6399. TEST(SSLClientTest, UpdateCAStore) {
  6400. httplib::SSLClient httplib_client("www.google.com");
  6401. auto ca_store_1 = X509_STORE_new();
  6402. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6403. nullptr);
  6404. httplib_client.set_ca_cert_store(ca_store_1);
  6405. auto ca_store_2 = X509_STORE_new();
  6406. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6407. nullptr);
  6408. httplib_client.set_ca_cert_store(ca_store_2);
  6409. }
  6410. TEST(SSLClientTest, ServerNameIndication_Online) {
  6411. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6412. auto host = "httpbin.org";
  6413. auto path = std::string{"/get"};
  6414. #else
  6415. auto host = "nghttp2.org";
  6416. auto path = std::string{"/httpbin/get"};
  6417. #endif
  6418. SSLClient cli(host, 443);
  6419. auto res = cli.Get(path);
  6420. ASSERT_TRUE(res);
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. }
  6423. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6424. // Use a site that will cause SSL verification failure due to self-signed cert
  6425. SSLClient cli("self-signed.badssl.com", 443);
  6426. cli.enable_server_certificate_verification(true);
  6427. auto res = cli.Get("/");
  6428. ASSERT_TRUE(!res);
  6429. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6430. // For SSL server verification errors, ssl_error should be 0, only
  6431. // ssl_openssl_error should be set
  6432. EXPECT_EQ(0, res.ssl_error());
  6433. // Verify OpenSSL error is captured for SSLServerVerification
  6434. // This occurs when SSL_get_verify_result() returns a verification failure
  6435. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6436. res.ssl_openssl_error());
  6437. }
  6438. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6439. // Use a site where hostname doesn't match the certificate
  6440. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6441. SSLClient cli("wrong.host.badssl.com", 443);
  6442. cli.enable_server_certificate_verification(true);
  6443. cli.enable_server_hostname_verification(true);
  6444. auto res = cli.Get("/");
  6445. ASSERT_TRUE(!res);
  6446. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6447. // For SSL hostname verification errors, ssl_error should be 0, only
  6448. // ssl_openssl_error should be set
  6449. EXPECT_EQ(0, res.ssl_error());
  6450. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6451. // This occurs when verify_host() fails due to hostname mismatch
  6452. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6453. res.ssl_openssl_error());
  6454. }
  6455. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6456. Client cli("https://google.com");
  6457. auto res = cli.Get("/");
  6458. ASSERT_TRUE(res);
  6459. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6460. }
  6461. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6462. SSLClient cli("google.com");
  6463. cli.set_ca_cert_path(CA_CERT_FILE);
  6464. auto res = cli.Get("/");
  6465. ASSERT_TRUE(res);
  6466. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6467. }
  6468. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6469. SSLClient cli("google.com");
  6470. cli.enable_server_certificate_verification(true);
  6471. cli.set_ca_cert_path("hello");
  6472. auto res = cli.Get("/");
  6473. ASSERT_TRUE(!res);
  6474. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6475. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6476. // should be set
  6477. EXPECT_EQ(0, res.ssl_error());
  6478. // Verify OpenSSL error is captured for SSLLoadingCerts
  6479. // This error occurs when SSL_CTX_load_verify_locations() fails
  6480. // > openssl errstr 0x80000002
  6481. // error:80000002:system library::No such file or directory
  6482. // > openssl errstr 0xA000126
  6483. // error:0A000126:SSL routines::unexpected eof while reading
  6484. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6485. res.ssl_openssl_error() == 0xA000126);
  6486. }
  6487. TEST(SSLClientTest, ServerCertificateVerification4) {
  6488. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6489. ASSERT_TRUE(svr.is_valid());
  6490. svr.Get("/test", [&](const Request &, Response &res) {
  6491. res.set_content("test", "text/plain");
  6492. svr.stop();
  6493. ASSERT_TRUE(true);
  6494. });
  6495. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6496. auto se = detail::scope_exit([&] {
  6497. t.join();
  6498. ASSERT_FALSE(svr.is_running());
  6499. });
  6500. svr.wait_until_ready();
  6501. SSLClient cli("127.0.0.1", PORT);
  6502. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6503. cli.enable_server_certificate_verification(true);
  6504. cli.set_connection_timeout(30);
  6505. auto res = cli.Get("/test");
  6506. ASSERT_TRUE(res);
  6507. ASSERT_EQ(StatusCode::OK_200, res->status);
  6508. }
  6509. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6510. std::string cert;
  6511. read_file(CA_CERT_FILE, cert);
  6512. SSLClient cli("google.com");
  6513. cli.load_ca_cert_store(cert.data(), cert.size());
  6514. const auto res = cli.Get("/");
  6515. ASSERT_TRUE(res);
  6516. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6517. }
  6518. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6519. // clang-format off
  6520. static constexpr char cert[] =
  6521. "GlobalSign Root CA\n"
  6522. "==================\n"
  6523. "-----BEGIN CERTIFICATE-----\n"
  6524. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6525. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6526. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6527. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6528. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6529. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6530. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6531. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6532. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6533. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6534. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6535. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6536. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6537. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6538. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6539. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6540. "-----END CERTIFICATE-----\n";
  6541. // clang-format on
  6542. SSLClient cli("google.com");
  6543. cli.load_ca_cert_store(cert, sizeof(cert));
  6544. const auto res = cli.Get("/");
  6545. ASSERT_TRUE(res);
  6546. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6547. }
  6548. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6549. SSLClient cli("www.youtube.com");
  6550. cli.set_ca_cert_path(CA_CERT_FILE);
  6551. cli.enable_server_certificate_verification(true);
  6552. cli.set_follow_location(true);
  6553. auto res = cli.Get("/");
  6554. ASSERT_TRUE(res);
  6555. ASSERT_EQ(StatusCode::OK_200, res->status);
  6556. }
  6557. TEST(SSLClientTest, Issue2004_Online) {
  6558. Client client("https://google.com");
  6559. client.set_follow_location(true);
  6560. auto res = client.Get("/");
  6561. ASSERT_TRUE(res);
  6562. ASSERT_EQ(StatusCode::OK_200, res->status);
  6563. auto body = res->body;
  6564. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6565. }
  6566. #if 0
  6567. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6568. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6569. ASSERT_TRUE(cli != nullptr);
  6570. cli->set_address_family(AF_INET6);
  6571. cli->set_interface("en0");
  6572. auto res = cli->Get("/get");
  6573. ASSERT_TRUE(res);
  6574. ASSERT_EQ(StatusCode::OK_200, res->status);
  6575. }
  6576. #endif
  6577. void ClientCertPresent(
  6578. const std::string &client_cert_file,
  6579. const std::string &client_private_key_file,
  6580. const std::string &client_encrypted_private_key_pass = std::string()) {
  6581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6582. CLIENT_CA_CERT_DIR);
  6583. ASSERT_TRUE(svr.is_valid());
  6584. svr.Get("/test", [&](const Request &req, Response &res) {
  6585. res.set_content("test", "text/plain");
  6586. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6587. ASSERT_TRUE(peer_cert != nullptr);
  6588. auto subject_name = X509_get_subject_name(peer_cert);
  6589. ASSERT_TRUE(subject_name != nullptr);
  6590. std::string common_name;
  6591. {
  6592. char name[BUFSIZ];
  6593. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6594. name, sizeof(name));
  6595. common_name.assign(name, static_cast<size_t>(name_len));
  6596. }
  6597. EXPECT_EQ("Common Name", common_name);
  6598. X509_free(peer_cert);
  6599. });
  6600. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6601. auto se = detail::scope_exit([&] {
  6602. svr.stop();
  6603. t.join();
  6604. ASSERT_FALSE(svr.is_running());
  6605. });
  6606. svr.wait_until_ready();
  6607. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6608. client_encrypted_private_key_pass);
  6609. cli.enable_server_certificate_verification(false);
  6610. cli.set_connection_timeout(30);
  6611. auto res = cli.Get("/test");
  6612. ASSERT_TRUE(res);
  6613. ASSERT_EQ(StatusCode::OK_200, res->status);
  6614. }
  6615. TEST(SSLClientServerTest, ClientCertPresent) {
  6616. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6617. }
  6618. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6619. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6620. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6621. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6622. }
  6623. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6624. void MemoryClientCertPresent(
  6625. const std::string &client_cert_file,
  6626. const std::string &client_private_key_file,
  6627. const std::string &client_encrypted_private_key_pass = std::string()) {
  6628. auto f = fopen(SERVER_CERT_FILE, "r+");
  6629. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6630. fclose(f);
  6631. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6632. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6633. fclose(f);
  6634. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6635. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6636. auto client_ca_cert_store = X509_STORE_new();
  6637. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6638. X509_free(client_cert);
  6639. fclose(f);
  6640. f = fopen(client_cert_file.c_str(), "r+");
  6641. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6642. fclose(f);
  6643. f = fopen(client_private_key_file.c_str(), "r+");
  6644. auto client_private_key = PEM_read_PrivateKey(
  6645. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6646. fclose(f);
  6647. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6648. ASSERT_TRUE(svr.is_valid());
  6649. svr.Get("/test", [&](const Request &req, Response &res) {
  6650. res.set_content("test", "text/plain");
  6651. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6652. ASSERT_TRUE(peer_cert != nullptr);
  6653. auto subject_name = X509_get_subject_name(peer_cert);
  6654. ASSERT_TRUE(subject_name != nullptr);
  6655. std::string common_name;
  6656. {
  6657. char name[BUFSIZ];
  6658. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6659. name, sizeof(name));
  6660. common_name.assign(name, static_cast<size_t>(name_len));
  6661. }
  6662. EXPECT_EQ("Common Name", common_name);
  6663. X509_free(peer_cert);
  6664. });
  6665. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6666. auto se = detail::scope_exit([&] {
  6667. svr.stop();
  6668. t.join();
  6669. ASSERT_FALSE(svr.is_running());
  6670. });
  6671. svr.wait_until_ready();
  6672. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6673. client_encrypted_private_key_pass);
  6674. cli.enable_server_certificate_verification(false);
  6675. cli.set_connection_timeout(30);
  6676. auto res = cli.Get("/test");
  6677. ASSERT_TRUE(res);
  6678. ASSERT_EQ(StatusCode::OK_200, res->status);
  6679. X509_free(server_cert);
  6680. EVP_PKEY_free(server_private_key);
  6681. X509_free(client_cert);
  6682. EVP_PKEY_free(client_private_key);
  6683. }
  6684. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6685. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6686. }
  6687. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6688. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6689. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6690. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6691. }
  6692. #endif
  6693. TEST(SSLClientServerTest, ClientCertMissing) {
  6694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6695. CLIENT_CA_CERT_DIR);
  6696. ASSERT_TRUE(svr.is_valid());
  6697. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6699. auto se = detail::scope_exit([&] {
  6700. svr.stop();
  6701. t.join();
  6702. ASSERT_FALSE(svr.is_running());
  6703. });
  6704. svr.wait_until_ready();
  6705. SSLClient cli(HOST, PORT);
  6706. cli.set_connection_timeout(30);
  6707. auto res = cli.Get("/test");
  6708. ASSERT_TRUE(!res);
  6709. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6710. // For SSL server verification errors, ssl_error should be 0, only
  6711. // ssl_openssl_error should be set
  6712. EXPECT_EQ(0, res.ssl_error());
  6713. // Verify OpenSSL error is captured for SSLServerVerification
  6714. // Note: This test may have different error codes depending on the exact
  6715. // verification failure
  6716. EXPECT_NE(0UL, res.ssl_openssl_error());
  6717. }
  6718. TEST(SSLClientServerTest, TrustDirOptional) {
  6719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6720. ASSERT_TRUE(svr.is_valid());
  6721. svr.Get("/test", [&](const Request &, Response &res) {
  6722. res.set_content("test", "text/plain");
  6723. });
  6724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6725. auto se = detail::scope_exit([&] {
  6726. svr.stop();
  6727. t.join();
  6728. ASSERT_FALSE(svr.is_running());
  6729. });
  6730. svr.wait_until_ready();
  6731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6732. cli.enable_server_certificate_verification(false);
  6733. cli.set_connection_timeout(30);
  6734. auto res = cli.Get("/test");
  6735. ASSERT_TRUE(res);
  6736. ASSERT_EQ(StatusCode::OK_200, res->status);
  6737. }
  6738. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6739. class NoListenSSLServer : public SSLServer {
  6740. public:
  6741. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6742. const char *client_ca_cert_file_path,
  6743. const char *client_ca_cert_dir_path = nullptr)
  6744. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6745. client_ca_cert_dir_path),
  6746. stop_(false) {}
  6747. std::atomic_bool stop_;
  6748. private:
  6749. bool process_and_close_socket(socket_t /*sock*/) override {
  6750. // Don't create SSL context
  6751. while (!stop_.load()) {
  6752. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6753. }
  6754. return true;
  6755. }
  6756. };
  6757. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6758. CLIENT_CA_CERT_FILE);
  6759. ASSERT_TRUE(svr.is_valid());
  6760. svr.Get("/test", [&](const Request &, Response &res) {
  6761. res.set_content("test", "text/plain");
  6762. });
  6763. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6764. auto se = detail::scope_exit([&] {
  6765. svr.stop_ = true;
  6766. svr.stop();
  6767. t.join();
  6768. ASSERT_FALSE(svr.is_running());
  6769. });
  6770. svr.wait_until_ready();
  6771. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6772. cli.enable_server_certificate_verification(false);
  6773. cli.set_connection_timeout(1);
  6774. auto res = cli.Get("/test");
  6775. ASSERT_TRUE(!res);
  6776. EXPECT_EQ(Error::SSLConnection, res.error());
  6777. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  6778. }
  6779. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6780. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6781. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6782. SSL_CTX_set_options(&ssl_ctx,
  6783. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6784. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6785. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6786. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6787. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6788. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6789. "ECDHE-DSS-AES128-SHA256:"
  6790. "ECDHE-RSA-AES256-SHA256:"
  6791. "ECDHE-DSS-AES256-SHA256:";
  6792. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6793. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6794. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6795. SSL_FILETYPE_PEM) != 1) {
  6796. return false;
  6797. }
  6798. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6799. CLIENT_CA_CERT_DIR);
  6800. SSL_CTX_set_verify(
  6801. &ssl_ctx,
  6802. SSL_VERIFY_PEER |
  6803. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6804. nullptr);
  6805. return true;
  6806. };
  6807. SSLServer svr(setup_ssl_ctx_callback);
  6808. ASSERT_TRUE(svr.is_valid());
  6809. svr.Get("/test", [&](const Request &req, Response &res) {
  6810. res.set_content("test", "text/plain");
  6811. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6812. ASSERT_TRUE(peer_cert != nullptr);
  6813. auto subject_name = X509_get_subject_name(peer_cert);
  6814. ASSERT_TRUE(subject_name != nullptr);
  6815. std::string common_name;
  6816. {
  6817. char name[BUFSIZ];
  6818. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6819. name, sizeof(name));
  6820. common_name.assign(name, static_cast<size_t>(name_len));
  6821. }
  6822. EXPECT_EQ("Common Name", common_name);
  6823. X509_free(peer_cert);
  6824. });
  6825. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6826. auto se = detail::scope_exit([&] {
  6827. svr.stop();
  6828. t.join();
  6829. ASSERT_FALSE(svr.is_running());
  6830. });
  6831. svr.wait_until_ready();
  6832. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6833. cli.enable_server_certificate_verification(false);
  6834. cli.set_connection_timeout(30);
  6835. auto res = cli.Get("/test");
  6836. ASSERT_TRUE(res);
  6837. ASSERT_EQ(StatusCode::OK_200, res->status);
  6838. }
  6839. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6840. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6841. // prepare large data
  6842. std::random_device seed_gen;
  6843. std::mt19937 random(seed_gen());
  6844. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6845. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6846. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6847. // server
  6848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6849. ASSERT_TRUE(svr.is_valid());
  6850. svr.Post("/binary", [&](const Request &req, Response &res) {
  6851. EXPECT_EQ(large_size_byte, req.body.size());
  6852. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6853. res.set_content(req.body, "application/octet-stream");
  6854. });
  6855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6856. auto se = detail::scope_exit([&] {
  6857. svr.stop();
  6858. listen_thread.join();
  6859. ASSERT_FALSE(svr.is_running());
  6860. });
  6861. svr.wait_until_ready();
  6862. // client POST
  6863. SSLClient cli("localhost", PORT);
  6864. cli.enable_server_certificate_verification(false);
  6865. cli.set_read_timeout(std::chrono::seconds(100));
  6866. cli.set_write_timeout(std::chrono::seconds(100));
  6867. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6868. large_size_byte, "application/octet-stream");
  6869. // compare
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. EXPECT_EQ(large_size_byte, res->body.size());
  6872. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6873. }
  6874. #endif
  6875. #ifdef _WIN32
  6876. TEST(CleanupTest, WSACleanup) {
  6877. int ret = WSACleanup();
  6878. ASSERT_EQ(0, ret);
  6879. }
  6880. #endif
  6881. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6882. TEST(NoSSLSupport, SimpleInterface) {
  6883. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6884. }
  6885. #endif
  6886. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6887. TEST(InvalidScheme, SimpleInterface) {
  6888. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6889. }
  6890. #endif
  6891. TEST(NoScheme, SimpleInterface) {
  6892. Client cli("yahoo.com:80");
  6893. ASSERT_TRUE(cli.is_valid());
  6894. }
  6895. TEST(SendAPI, SimpleInterface_Online) {
  6896. Client cli("http://yahoo.com");
  6897. Request req;
  6898. req.method = "GET";
  6899. req.path = "/";
  6900. auto res = cli.send(req);
  6901. ASSERT_TRUE(res);
  6902. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6903. }
  6904. TEST(SendAPI, WithParamsInRequest) {
  6905. Server svr;
  6906. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6907. EXPECT_TRUE(req.has_param("test"));
  6908. EXPECT_EQ("test_value", req.get_param_value("test"));
  6909. });
  6910. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6911. auto se = detail::scope_exit([&] {
  6912. svr.stop();
  6913. t.join();
  6914. ASSERT_FALSE(svr.is_running());
  6915. });
  6916. svr.wait_until_ready();
  6917. Client cli(HOST, PORT);
  6918. {
  6919. Request req;
  6920. req.method = "GET";
  6921. req.path = "/";
  6922. req.params.emplace("test", "test_value");
  6923. auto res = cli.send(req);
  6924. ASSERT_TRUE(res);
  6925. }
  6926. {
  6927. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6928. ASSERT_TRUE(res);
  6929. }
  6930. }
  6931. TEST(ClientImplMethods, GetSocketTest) {
  6932. httplib::Server svr;
  6933. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6934. res.status = StatusCode::OK_200;
  6935. });
  6936. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6937. auto se = detail::scope_exit([&] {
  6938. svr.stop();
  6939. thread.join();
  6940. ASSERT_FALSE(svr.is_running());
  6941. });
  6942. svr.wait_until_ready();
  6943. {
  6944. httplib::Client cli("http://127.0.0.1:3333");
  6945. cli.set_keep_alive(true);
  6946. // Use the behavior of cpp-httplib of opening the connection
  6947. // only when the first request happens. If that changes,
  6948. // this test would be obsolete.
  6949. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6950. // This also implicitly tests the server. But other tests would fail much
  6951. // earlier than this one to be considered.
  6952. auto res = cli.Get("/");
  6953. ASSERT_TRUE(res);
  6954. EXPECT_EQ(StatusCode::OK_200, res->status);
  6955. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6956. }
  6957. }
  6958. // Disabled due to out-of-memory problem on GitHub Actions
  6959. #ifdef _WIN64
  6960. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6961. // allocate content size larger than 2GB in memory
  6962. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6963. char *content = (char *)malloc(content_size);
  6964. ASSERT_TRUE(content);
  6965. Server svr;
  6966. svr.Get("/foo",
  6967. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6968. res.set_content(content, content_size, "application/octet-stream");
  6969. });
  6970. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6971. auto se = detail::scope_exit([&] {
  6972. svr.stop();
  6973. listen_thread.join();
  6974. if (content) free(content);
  6975. ASSERT_FALSE(svr.is_running());
  6976. });
  6977. svr.wait_until_ready();
  6978. Client cli(HOST, PORT);
  6979. auto res = cli.Get("/foo");
  6980. ASSERT_TRUE(res);
  6981. EXPECT_EQ(StatusCode::OK_200, res->status);
  6982. EXPECT_EQ(content_size, res->body.length());
  6983. }
  6984. #endif
  6985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6986. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6987. Client cli("http://yahoo.com");
  6988. auto res = cli.Get("/");
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6991. cli.set_follow_location(true);
  6992. res = cli.Get("/");
  6993. ASSERT_TRUE(res);
  6994. EXPECT_EQ(StatusCode::OK_200, res->status);
  6995. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6996. }
  6997. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6998. Client cli("https://yahoo.com");
  6999. auto res = cli.Get("/");
  7000. ASSERT_TRUE(res);
  7001. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7002. cli.set_follow_location(true);
  7003. res = cli.Get("/");
  7004. ASSERT_TRUE(res);
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7007. }
  7008. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7009. Client cli("https://yahoo.com");
  7010. auto res = cli.Get("/");
  7011. ASSERT_TRUE(res);
  7012. ASSERT_FALSE(!res);
  7013. ASSERT_TRUE(res);
  7014. ASSERT_FALSE(res == nullptr);
  7015. ASSERT_TRUE(res != nullptr);
  7016. EXPECT_EQ(Error::Success, res.error());
  7017. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7018. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7019. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7020. cli.set_follow_location(true);
  7021. res = cli.Get("/");
  7022. ASSERT_TRUE(res);
  7023. EXPECT_EQ(Error::Success, res.error());
  7024. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7025. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7028. }
  7029. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7030. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7031. Client cli("https://cdnjs.cloudflare.com");
  7032. auto res =
  7033. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7034. ASSERT_TRUE(res);
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. EXPECT_EQ(287630U, res->body.size());
  7037. EXPECT_EQ("application/javascript; charset=utf-8",
  7038. res->get_header_value("Content-Type"));
  7039. }
  7040. #endif
  7041. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7042. #undef REDIR_HOST // Silence compiler warning
  7043. #define REDIR_HOST "https://httpbingo.org"
  7044. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7045. Client cli(REDIR_HOST);
  7046. cli.set_follow_location(true);
  7047. auto res =
  7048. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. }
  7052. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7053. Client cli(REDIR_HOST);
  7054. cli.set_follow_location(true);
  7055. Params params;
  7056. params.emplace("url", "http://example.com");
  7057. params.emplace("status_code", "302");
  7058. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7059. ASSERT_TRUE(res);
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7063. Client cli(REDIR_HOST);
  7064. cli.set_follow_location(true);
  7065. Params params;
  7066. params.emplace("url", "http://example.com");
  7067. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7068. ASSERT_TRUE(res);
  7069. EXPECT_EQ(StatusCode::OK_200, res->status);
  7070. }
  7071. TEST(HttpToHttpsRedirectTest, CertFile) {
  7072. Server svr;
  7073. ASSERT_TRUE(svr.is_valid());
  7074. svr.Get("/index", [&](const Request &, Response &res) {
  7075. res.set_redirect("https://127.0.0.1:1235/index");
  7076. svr.stop();
  7077. });
  7078. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7079. ASSERT_TRUE(ssl_svr.is_valid());
  7080. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7081. res.set_content("test", "text/plain");
  7082. ssl_svr.stop();
  7083. });
  7084. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7085. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7086. auto se = detail::scope_exit([&] {
  7087. t2.join();
  7088. t.join();
  7089. ASSERT_FALSE(svr.is_running());
  7090. });
  7091. svr.wait_until_ready();
  7092. ssl_svr.wait_until_ready();
  7093. Client cli("127.0.0.1", PORT);
  7094. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7095. cli.enable_server_certificate_verification(true);
  7096. cli.set_follow_location(true);
  7097. cli.set_connection_timeout(30);
  7098. auto res = cli.Get("/index");
  7099. ASSERT_TRUE(res);
  7100. ASSERT_EQ(StatusCode::OK_200, res->status);
  7101. }
  7102. TEST(MultipartFormDataTest, LargeData) {
  7103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7104. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7105. const ContentReader &content_reader) {
  7106. if (req.is_multipart_form_data()) {
  7107. MultipartFormDataItems files;
  7108. content_reader(
  7109. [&](const MultipartFormData &file) {
  7110. files.push_back(file);
  7111. return true;
  7112. },
  7113. [&](const char *data, size_t data_length) {
  7114. files.back().content.append(data, data_length);
  7115. return true;
  7116. });
  7117. EXPECT_TRUE(std::string(files[0].name) == "document");
  7118. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7119. EXPECT_TRUE(files[0].filename == "2MB_data");
  7120. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7121. EXPECT_TRUE(files[1].name == "hello");
  7122. EXPECT_TRUE(files[1].content == "world");
  7123. EXPECT_TRUE(files[1].filename == "");
  7124. EXPECT_TRUE(files[1].content_type == "");
  7125. } else {
  7126. std::string body;
  7127. content_reader([&](const char *data, size_t data_length) {
  7128. body.append(data, data_length);
  7129. return true;
  7130. });
  7131. }
  7132. });
  7133. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. t.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. {
  7141. std::string data(1024 * 1024 * 2, '.');
  7142. std::stringstream buffer;
  7143. buffer << data;
  7144. Client cli("https://localhost:8080");
  7145. cli.enable_server_certificate_verification(false);
  7146. MultipartFormDataItemsForClientInput items{
  7147. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7148. {"hello", "world", "", ""},
  7149. };
  7150. auto res = cli.Post("/post", items);
  7151. ASSERT_TRUE(res);
  7152. ASSERT_EQ(StatusCode::OK_200, res->status);
  7153. }
  7154. }
  7155. TEST(MultipartFormDataTest, DataProviderItems) {
  7156. std::random_device seed_gen;
  7157. std::mt19937 random(seed_gen());
  7158. std::string rand1;
  7159. rand1.resize(1000);
  7160. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7161. std::string rand2;
  7162. rand2.resize(3000);
  7163. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7165. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7166. const ContentReader &content_reader) {
  7167. ASSERT_FALSE(req.is_multipart_form_data());
  7168. std::string body;
  7169. content_reader([&](const char *data, size_t data_length) {
  7170. body.append(data, data_length);
  7171. return true;
  7172. });
  7173. EXPECT_EQ(body, "");
  7174. });
  7175. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7176. const ContentReader &content_reader) {
  7177. ASSERT_TRUE(req.is_multipart_form_data());
  7178. MultipartFormDataItems files;
  7179. content_reader(
  7180. [&](const MultipartFormData &file) {
  7181. files.push_back(file);
  7182. return true;
  7183. },
  7184. [&](const char *data, size_t data_length) {
  7185. files.back().content.append(data, data_length);
  7186. return true;
  7187. });
  7188. ASSERT_TRUE(files.size() == 2);
  7189. EXPECT_EQ(std::string(files[0].name), "name1");
  7190. EXPECT_EQ(files[0].content, "Testing123");
  7191. EXPECT_EQ(files[0].filename, "filename1");
  7192. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7193. EXPECT_EQ(files[1].name, "name2");
  7194. EXPECT_EQ(files[1].content, "Testing456");
  7195. EXPECT_EQ(files[1].filename, "");
  7196. EXPECT_EQ(files[1].content_type, "");
  7197. });
  7198. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7199. const ContentReader &content_reader) {
  7200. ASSERT_TRUE(req.is_multipart_form_data());
  7201. MultipartFormDataItems files;
  7202. content_reader(
  7203. [&](const MultipartFormData &file) {
  7204. files.push_back(file);
  7205. return true;
  7206. },
  7207. [&](const char *data, size_t data_length) {
  7208. files.back().content.append(data, data_length);
  7209. return true;
  7210. });
  7211. ASSERT_TRUE(files.size() == 2);
  7212. EXPECT_EQ(files[0].name, "name3");
  7213. EXPECT_EQ(files[0].content, rand1);
  7214. EXPECT_EQ(files[0].filename, "filename3");
  7215. EXPECT_EQ(files[0].content_type, "");
  7216. EXPECT_EQ(files[1].name, "name4");
  7217. EXPECT_EQ(files[1].content, rand2);
  7218. EXPECT_EQ(files[1].filename, "filename4");
  7219. EXPECT_EQ(files[1].content_type, "");
  7220. });
  7221. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7222. const ContentReader &content_reader) {
  7223. ASSERT_TRUE(req.is_multipart_form_data());
  7224. MultipartFormDataItems files;
  7225. content_reader(
  7226. [&](const MultipartFormData &file) {
  7227. files.push_back(file);
  7228. return true;
  7229. },
  7230. [&](const char *data, size_t data_length) {
  7231. files.back().content.append(data, data_length);
  7232. return true;
  7233. });
  7234. ASSERT_TRUE(files.size() == 4);
  7235. EXPECT_EQ(std::string(files[0].name), "name1");
  7236. EXPECT_EQ(files[0].content, "Testing123");
  7237. EXPECT_EQ(files[0].filename, "filename1");
  7238. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7239. EXPECT_EQ(files[1].name, "name2");
  7240. EXPECT_EQ(files[1].content, "Testing456");
  7241. EXPECT_EQ(files[1].filename, "");
  7242. EXPECT_EQ(files[1].content_type, "");
  7243. EXPECT_EQ(files[2].name, "name3");
  7244. EXPECT_EQ(files[2].content, rand1);
  7245. EXPECT_EQ(files[2].filename, "filename3");
  7246. EXPECT_EQ(files[2].content_type, "");
  7247. EXPECT_EQ(files[3].name, "name4");
  7248. EXPECT_EQ(files[3].content, rand2);
  7249. EXPECT_EQ(files[3].filename, "filename4");
  7250. EXPECT_EQ(files[3].content_type, "");
  7251. });
  7252. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7253. auto se = detail::scope_exit([&] {
  7254. svr.stop();
  7255. t.join();
  7256. ASSERT_FALSE(svr.is_running());
  7257. });
  7258. svr.wait_until_ready();
  7259. {
  7260. Client cli("https://localhost:8080");
  7261. cli.enable_server_certificate_verification(false);
  7262. MultipartFormDataItemsForClientInput items{
  7263. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7264. {"name2", "Testing456", "", ""}, // not a file
  7265. };
  7266. {
  7267. auto res = cli.Post("/post-none", {}, {}, {});
  7268. ASSERT_TRUE(res);
  7269. ASSERT_EQ(StatusCode::OK_200, res->status);
  7270. }
  7271. MultipartFormDataProviderItems providers;
  7272. {
  7273. auto res =
  7274. cli.Post("/post-items", {}, items, providers); // empty providers
  7275. ASSERT_TRUE(res);
  7276. ASSERT_EQ(StatusCode::OK_200, res->status);
  7277. }
  7278. providers.push_back({"name3",
  7279. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7280. // test the offset is given correctly at each step
  7281. if (!offset)
  7282. sink.os.write(rand1.data(), 30);
  7283. else if (offset == 30)
  7284. sink.os.write(rand1.data() + 30, 300);
  7285. else if (offset == 330)
  7286. sink.os.write(rand1.data() + 330, 670);
  7287. else if (offset == rand1.size())
  7288. sink.done();
  7289. return true;
  7290. },
  7291. "filename3",
  7292. {}});
  7293. providers.push_back({"name4",
  7294. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7295. // test the offset is given correctly at each step
  7296. if (!offset)
  7297. sink.os.write(rand2.data(), 2000);
  7298. else if (offset == 2000)
  7299. sink.os.write(rand2.data() + 2000, 1);
  7300. else if (offset == 2001)
  7301. sink.os.write(rand2.data() + 2001, 999);
  7302. else if (offset == rand2.size())
  7303. sink.done();
  7304. return true;
  7305. },
  7306. "filename4",
  7307. {}});
  7308. {
  7309. auto res = cli.Post("/post-providers", {}, {}, providers);
  7310. ASSERT_TRUE(res);
  7311. ASSERT_EQ(StatusCode::OK_200, res->status);
  7312. }
  7313. {
  7314. auto res = cli.Post("/post-both", {}, items, providers);
  7315. ASSERT_TRUE(res);
  7316. ASSERT_EQ(StatusCode::OK_200, res->status);
  7317. }
  7318. }
  7319. }
  7320. TEST(MultipartFormDataTest, BadHeader) {
  7321. Server svr;
  7322. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7323. res.set_content("ok", "text/plain");
  7324. });
  7325. thread t = thread([&] { svr.listen(HOST, PORT); });
  7326. auto se = detail::scope_exit([&] {
  7327. svr.stop();
  7328. t.join();
  7329. ASSERT_FALSE(svr.is_running());
  7330. });
  7331. svr.wait_until_ready();
  7332. const std::string body =
  7333. "This is the preamble. It is to be ignored, though it\r\n"
  7334. "is a handy place for composition agents to include an\r\n"
  7335. "explanatory note to non-MIME conformant readers.\r\n"
  7336. "\r\n"
  7337. "\r\n"
  7338. "--simple boundary\r\n"
  7339. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7340. ": BAD...\r\n"
  7341. "\r\n"
  7342. "value1\r\n"
  7343. "--simple boundary\r\n"
  7344. "Content-Disposition: form-data; name=\"field2\"; "
  7345. "filename=\"example.txt\"\r\n"
  7346. "\r\n"
  7347. "value2\r\n"
  7348. "--simple boundary--\r\n"
  7349. "This is the epilogue. It is also to be ignored.\r\n";
  7350. std::string content_type =
  7351. R"(multipart/form-data; boundary="simple boundary")";
  7352. Client cli(HOST, PORT);
  7353. auto res = cli.Post("/post", body, content_type.c_str());
  7354. ASSERT_TRUE(res);
  7355. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7356. }
  7357. TEST(MultipartFormDataTest, WithPreamble) {
  7358. Server svr;
  7359. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7360. res.set_content("ok", "text/plain");
  7361. });
  7362. thread t = thread([&] { svr.listen(HOST, PORT); });
  7363. auto se = detail::scope_exit([&] {
  7364. svr.stop();
  7365. t.join();
  7366. ASSERT_FALSE(svr.is_running());
  7367. });
  7368. svr.wait_until_ready();
  7369. const std::string body =
  7370. "This is the preamble. It is to be ignored, though it\r\n"
  7371. "is a handy place for composition agents to include an\r\n"
  7372. "explanatory note to non-MIME conformant readers.\r\n"
  7373. "\r\n"
  7374. "\r\n"
  7375. "--simple boundary\r\n"
  7376. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7377. "\r\n"
  7378. "value1\r\n"
  7379. "--simple boundary\r\n"
  7380. "Content-Disposition: form-data; name=\"field2\"; "
  7381. "filename=\"example.txt\"\r\n"
  7382. "\r\n"
  7383. "value2\r\n"
  7384. "--simple boundary--\r\n"
  7385. "This is the epilogue. It is also to be ignored.\r\n";
  7386. std::string content_type =
  7387. R"(multipart/form-data; boundary="simple boundary")";
  7388. Client cli(HOST, PORT);
  7389. auto res = cli.Post("/post", body, content_type.c_str());
  7390. ASSERT_TRUE(res);
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. }
  7393. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7395. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7396. const ContentReader &content_reader) {
  7397. if (req.is_multipart_form_data()) {
  7398. MultipartFormDataItems files;
  7399. content_reader(
  7400. [&](const MultipartFormData &file) {
  7401. files.push_back(file);
  7402. return true;
  7403. },
  7404. [&](const char *data, size_t data_length) {
  7405. files.back().content.append(data, data_length);
  7406. return true;
  7407. });
  7408. EXPECT_TRUE(std::string(files[0].name) == "document");
  7409. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7410. EXPECT_TRUE(files[0].filename == "2MB_data");
  7411. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7412. EXPECT_TRUE(files[1].name == "hello");
  7413. EXPECT_TRUE(files[1].content == "world");
  7414. EXPECT_TRUE(files[1].filename == "");
  7415. EXPECT_TRUE(files[1].content_type == "");
  7416. } else {
  7417. std::string body;
  7418. content_reader([&](const char *data, size_t data_length) {
  7419. body.append(data, data_length);
  7420. return true;
  7421. });
  7422. }
  7423. });
  7424. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7425. auto se = detail::scope_exit([&] {
  7426. svr.stop();
  7427. t.join();
  7428. ASSERT_FALSE(svr.is_running());
  7429. });
  7430. svr.wait_until_ready();
  7431. {
  7432. std::string data(1024 * 1024 * 2, '.');
  7433. std::stringstream buffer;
  7434. buffer << data;
  7435. Client cli("https://localhost:8080");
  7436. cli.enable_server_certificate_verification(false);
  7437. MultipartFormDataItemsForClientInput items{
  7438. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7439. {"hello", "world", "", ""},
  7440. };
  7441. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7442. ASSERT_TRUE(res);
  7443. ASSERT_EQ(StatusCode::OK_200, res->status);
  7444. }
  7445. }
  7446. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7447. std::string data(1024 * 1024 * 2, '&');
  7448. std::stringstream buffer;
  7449. buffer << data;
  7450. Client cli("https://localhost:8080");
  7451. MultipartFormDataItemsForClientInput items{
  7452. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7453. {"hello", "world", "", ""},
  7454. };
  7455. for (const char &c : " \t\r\n") {
  7456. auto res =
  7457. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7458. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7459. ASSERT_FALSE(res);
  7460. }
  7461. }
  7462. TEST(MultipartFormDataTest, PutFormData) {
  7463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7464. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7465. const ContentReader &content_reader) {
  7466. if (req.is_multipart_form_data()) {
  7467. MultipartFormDataItems files;
  7468. content_reader(
  7469. [&](const MultipartFormData &file) {
  7470. files.push_back(file);
  7471. return true;
  7472. },
  7473. [&](const char *data, size_t data_length) {
  7474. files.back().content.append(data, data_length);
  7475. return true;
  7476. });
  7477. EXPECT_TRUE(std::string(files[0].name) == "document");
  7478. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7479. EXPECT_TRUE(files[0].filename == "2MB_data");
  7480. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7481. EXPECT_TRUE(files[1].name == "hello");
  7482. EXPECT_TRUE(files[1].content == "world");
  7483. EXPECT_TRUE(files[1].filename == "");
  7484. EXPECT_TRUE(files[1].content_type == "");
  7485. } else {
  7486. std::string body;
  7487. content_reader([&](const char *data, size_t data_length) {
  7488. body.append(data, data_length);
  7489. return true;
  7490. });
  7491. }
  7492. });
  7493. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7494. auto se = detail::scope_exit([&] {
  7495. svr.stop();
  7496. t.join();
  7497. ASSERT_FALSE(svr.is_running());
  7498. });
  7499. svr.wait_until_ready();
  7500. {
  7501. std::string data(1024 * 1024 * 2, '&');
  7502. std::stringstream buffer;
  7503. buffer << data;
  7504. Client cli("https://localhost:8080");
  7505. cli.enable_server_certificate_verification(false);
  7506. MultipartFormDataItemsForClientInput items{
  7507. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7508. {"hello", "world", "", ""},
  7509. };
  7510. auto res = cli.Put("/put", items);
  7511. ASSERT_TRUE(res);
  7512. ASSERT_EQ(StatusCode::OK_200, res->status);
  7513. }
  7514. }
  7515. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7517. svr.Put("/put_customboundary",
  7518. [&](const Request &req, const Response & /*res*/,
  7519. const ContentReader &content_reader) {
  7520. if (req.is_multipart_form_data()) {
  7521. MultipartFormDataItems files;
  7522. content_reader(
  7523. [&](const MultipartFormData &file) {
  7524. files.push_back(file);
  7525. return true;
  7526. },
  7527. [&](const char *data, size_t data_length) {
  7528. files.back().content.append(data, data_length);
  7529. return true;
  7530. });
  7531. EXPECT_TRUE(std::string(files[0].name) == "document");
  7532. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7533. EXPECT_TRUE(files[0].filename == "2MB_data");
  7534. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7535. EXPECT_TRUE(files[1].name == "hello");
  7536. EXPECT_TRUE(files[1].content == "world");
  7537. EXPECT_TRUE(files[1].filename == "");
  7538. EXPECT_TRUE(files[1].content_type == "");
  7539. } else {
  7540. std::string body;
  7541. content_reader([&](const char *data, size_t data_length) {
  7542. body.append(data, data_length);
  7543. return true;
  7544. });
  7545. }
  7546. });
  7547. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7548. auto se = detail::scope_exit([&] {
  7549. svr.stop();
  7550. t.join();
  7551. ASSERT_FALSE(svr.is_running());
  7552. });
  7553. svr.wait_until_ready();
  7554. {
  7555. std::string data(1024 * 1024 * 2, '&');
  7556. std::stringstream buffer;
  7557. buffer << data;
  7558. Client cli("https://localhost:8080");
  7559. cli.enable_server_certificate_verification(false);
  7560. MultipartFormDataItemsForClientInput items{
  7561. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7562. {"hello", "world", "", ""},
  7563. };
  7564. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7565. ASSERT_TRUE(res);
  7566. ASSERT_EQ(StatusCode::OK_200, res->status);
  7567. }
  7568. }
  7569. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7570. std::string data(1024 * 1024 * 2, '&');
  7571. std::stringstream buffer;
  7572. buffer << data;
  7573. Client cli("https://localhost:8080");
  7574. cli.enable_server_certificate_verification(false);
  7575. MultipartFormDataItemsForClientInput items{
  7576. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7577. {"hello", "world", "", ""},
  7578. };
  7579. for (const char &c : " \t\r\n") {
  7580. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7581. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7582. ASSERT_FALSE(res);
  7583. }
  7584. }
  7585. TEST(MultipartFormDataTest, AlternateFilename) {
  7586. auto handled = false;
  7587. Server svr;
  7588. svr.Post("/test", [&](const Request &req, Response &res) {
  7589. ASSERT_EQ(3u, req.files.size());
  7590. auto it = req.files.begin();
  7591. ASSERT_EQ("file1", it->second.name);
  7592. ASSERT_EQ("A.txt", it->second.filename);
  7593. ASSERT_EQ("text/plain", it->second.content_type);
  7594. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7595. ++it;
  7596. ASSERT_EQ("file2", it->second.name);
  7597. ASSERT_EQ("a.html", it->second.filename);
  7598. ASSERT_EQ("text/html", it->second.content_type);
  7599. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7600. it->second.content);
  7601. ++it;
  7602. ASSERT_EQ("text", it->second.name);
  7603. ASSERT_EQ("", it->second.filename);
  7604. ASSERT_EQ("", it->second.content_type);
  7605. ASSERT_EQ("text default", it->second.content);
  7606. res.set_content("ok", "text/plain");
  7607. handled = true;
  7608. });
  7609. thread t = thread([&] { svr.listen(HOST, PORT); });
  7610. auto se = detail::scope_exit([&] {
  7611. svr.stop();
  7612. t.join();
  7613. ASSERT_FALSE(svr.is_running());
  7614. ASSERT_TRUE(handled);
  7615. });
  7616. svr.wait_until_ready();
  7617. auto req = "POST /test HTTP/1.1\r\n"
  7618. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7619. "Content-Length: 399\r\n"
  7620. "\r\n"
  7621. "----------\r\n"
  7622. "Content-Disposition: form-data; name=\"text\"\r\n"
  7623. "\r\n"
  7624. "text default\r\n"
  7625. "----------\r\n"
  7626. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7627. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7628. "Content-Type: text/plain\r\n"
  7629. "\r\n"
  7630. "Content of a.txt.\r\n"
  7631. "\r\n"
  7632. "----------\r\n"
  7633. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7634. "\"a.html\"\r\n"
  7635. "Content-Type: text/html\r\n"
  7636. "\r\n"
  7637. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7638. "\r\n"
  7639. "------------\r\n";
  7640. ASSERT_TRUE(send_request(1, req));
  7641. }
  7642. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7643. auto handled = false;
  7644. Server svr;
  7645. svr.Post("/test", [&](const Request &req, Response &) {
  7646. ASSERT_EQ(2u, req.files.size());
  7647. auto it = req.files.begin();
  7648. ASSERT_EQ("text1", it->second.name);
  7649. ASSERT_EQ("text1", it->second.content);
  7650. ++it;
  7651. ASSERT_EQ("text2", it->second.name);
  7652. ASSERT_EQ("text2", it->second.content);
  7653. handled = true;
  7654. });
  7655. thread t = thread([&] { svr.listen(HOST, PORT); });
  7656. auto se = detail::scope_exit([&] {
  7657. svr.stop();
  7658. t.join();
  7659. ASSERT_FALSE(svr.is_running());
  7660. ASSERT_TRUE(handled);
  7661. });
  7662. svr.wait_until_ready();
  7663. auto req = "POST /test HTTP/1.1\r\n"
  7664. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7665. "Content-Length: 146\r\n"
  7666. "\r\n----------\r\n"
  7667. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7668. "\r\n"
  7669. "text1"
  7670. "\r\n----------\r\n"
  7671. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7672. "\r\n"
  7673. "text2"
  7674. "\r\n------------";
  7675. std::string response;
  7676. ASSERT_TRUE(send_request(1, req, &response));
  7677. ASSERT_EQ("200", response.substr(9, 3));
  7678. }
  7679. TEST(MultipartFormDataTest, ContentLength) {
  7680. auto handled = false;
  7681. Server svr;
  7682. svr.Post("/test", [&](const Request &req, Response &) {
  7683. ASSERT_EQ(2u, req.files.size());
  7684. auto it = req.files.begin();
  7685. ASSERT_EQ("text1", it->second.name);
  7686. ASSERT_EQ("text1", it->second.content);
  7687. ++it;
  7688. ASSERT_EQ("text2", it->second.name);
  7689. ASSERT_EQ("text2", it->second.content);
  7690. handled = true;
  7691. });
  7692. thread t = thread([&] { svr.listen(HOST, PORT); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. t.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. ASSERT_TRUE(handled);
  7698. });
  7699. svr.wait_until_ready();
  7700. auto req = "POST /test HTTP/1.1\r\n"
  7701. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7702. "Content-Length: 167\r\n"
  7703. "\r\n----------\r\n"
  7704. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7705. "Content-Length: 5\r\n"
  7706. "\r\n"
  7707. "text1"
  7708. "\r\n----------\r\n"
  7709. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7710. "\r\n"
  7711. "text2"
  7712. "\r\n------------\r\n";
  7713. std::string response;
  7714. ASSERT_TRUE(send_request(1, req, &response));
  7715. ASSERT_EQ("200", response.substr(9, 3));
  7716. }
  7717. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7718. auto handled = false;
  7719. Server svr;
  7720. svr.Post("/test", [&](const Request &req, Response &) {
  7721. ASSERT_EQ(2u, req.files.size());
  7722. auto it = req.files.begin();
  7723. ASSERT_EQ("text1", it->second.name);
  7724. ASSERT_EQ("text1", it->second.content);
  7725. ASSERT_EQ(1U, it->second.headers.count("Content-Length"));
  7726. auto content_length = it->second.headers.find("CONTENT-length");
  7727. ASSERT_EQ("5", content_length->second);
  7728. ASSERT_EQ(3U, it->second.headers.size());
  7729. ++it;
  7730. ASSERT_EQ("text2", it->second.name);
  7731. ASSERT_EQ("text2", it->second.content);
  7732. auto &headers = it->second.headers;
  7733. ASSERT_EQ(3U, headers.size());
  7734. auto custom_header = headers.find("x-whatever");
  7735. ASSERT_TRUE(custom_header != headers.end());
  7736. ASSERT_NE("customvalue", custom_header->second);
  7737. ASSERT_EQ("CustomValue", custom_header->second);
  7738. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7739. handled = true;
  7740. });
  7741. thread t = thread([&] { svr.listen(HOST, PORT); });
  7742. auto se = detail::scope_exit([&] {
  7743. svr.stop();
  7744. t.join();
  7745. ASSERT_FALSE(svr.is_running());
  7746. ASSERT_TRUE(handled);
  7747. });
  7748. svr.wait_until_ready();
  7749. auto req = "POST /test HTTP/1.1\r\n"
  7750. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7751. "Content-Length: 232\r\n"
  7752. "\r\n----------\r\n"
  7753. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7754. "Content-Length: 5\r\n"
  7755. "X-Test: 1\r\n"
  7756. "\r\n"
  7757. "text1"
  7758. "\r\n----------\r\n"
  7759. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7760. "Content-Type: text/plain\r\n"
  7761. "X-Whatever: CustomValue\r\n"
  7762. "\r\n"
  7763. "text2"
  7764. "\r\n------------\r\n"
  7765. "That should be disregarded. Not even read";
  7766. std::string response;
  7767. ASSERT_TRUE(send_request(1, req, &response));
  7768. ASSERT_EQ("200", response.substr(9, 3));
  7769. }
  7770. #endif
  7771. TEST(MultipartFormDataTest, LargeHeader) {
  7772. auto handled = false;
  7773. Server svr;
  7774. svr.Post("/test", [&](const Request &req, Response &) {
  7775. ASSERT_EQ(1u, req.files.size());
  7776. auto it = req.files.begin();
  7777. ASSERT_EQ("name1", it->second.name);
  7778. ASSERT_EQ("text1", it->second.content);
  7779. handled = true;
  7780. });
  7781. thread t = thread([&] { svr.listen(HOST, PORT); });
  7782. auto se = detail::scope_exit([&] {
  7783. svr.stop();
  7784. t.join();
  7785. ASSERT_FALSE(svr.is_running());
  7786. ASSERT_TRUE(handled);
  7787. });
  7788. svr.wait_until_ready();
  7789. auto boundary = std::string("cpp-httplib-multipart-data");
  7790. std::string content = "--" + boundary +
  7791. "\r\n"
  7792. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7793. "\r\n"
  7794. "text1\r\n"
  7795. "--" +
  7796. boundary + "--\r\n";
  7797. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7798. "Content-Type: multipart/form-data;boundary=" +
  7799. boundary +
  7800. "\r\n"
  7801. "Content-Length: " +
  7802. std::to_string(content.size()) +
  7803. "\r\n"
  7804. "Dummy-Header: ";
  7805. std::string header_suffix = "\r\n"
  7806. "\r\n";
  7807. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7808. size_t header_dummy_size =
  7809. read_buff_size -
  7810. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7811. auto header_dummy = std::string(header_dummy_size, '@');
  7812. auto req = header_prefix + header_dummy + header_suffix + content;
  7813. std::string response;
  7814. ASSERT_TRUE(send_request(1, req, &response));
  7815. ASSERT_EQ("200", response.substr(9, 3));
  7816. }
  7817. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7818. static constexpr unsigned int number_of_tasks{1000000};
  7819. std::atomic_uint count{0};
  7820. std::unique_ptr<TaskQueue> task_queue{
  7821. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7822. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7823. auto queued = task_queue->enqueue(
  7824. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7825. EXPECT_TRUE(queued);
  7826. }
  7827. EXPECT_NO_THROW(task_queue->shutdown());
  7828. EXPECT_EQ(number_of_tasks, count.load());
  7829. }
  7830. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7831. static constexpr unsigned int number_of_tasks{1000000};
  7832. static constexpr unsigned int qlimit{2};
  7833. unsigned int queued_count{0};
  7834. std::atomic_uint count{0};
  7835. std::unique_ptr<TaskQueue> task_queue{
  7836. new ThreadPool{/*num_threads=*/1, qlimit}};
  7837. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7838. if (task_queue->enqueue(
  7839. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7840. queued_count++;
  7841. }
  7842. }
  7843. EXPECT_NO_THROW(task_queue->shutdown());
  7844. EXPECT_EQ(queued_count, count.load());
  7845. EXPECT_TRUE(queued_count <= number_of_tasks);
  7846. EXPECT_TRUE(queued_count >= qlimit);
  7847. }
  7848. TEST(TaskQueueTest, MaxQueuedRequests) {
  7849. static constexpr unsigned int qlimit{3};
  7850. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7851. std::condition_variable sem_cv;
  7852. std::mutex sem_mtx;
  7853. int credits = 0;
  7854. bool queued;
  7855. /* Fill up the queue with tasks that will block until we give them credits to
  7856. * complete. */
  7857. for (unsigned int n = 0; n <= qlimit;) {
  7858. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7859. std::unique_lock<std::mutex> lock(sem_mtx);
  7860. while (credits <= 0) {
  7861. sem_cv.wait(lock);
  7862. }
  7863. /* Consume the credit and signal the test code if they are all gone. */
  7864. if (--credits == 0) { sem_cv.notify_one(); }
  7865. });
  7866. if (n < qlimit) {
  7867. /* The first qlimit enqueues must succeed. */
  7868. EXPECT_TRUE(queued);
  7869. } else {
  7870. /* The last one will succeed only when the worker thread
  7871. * starts and dequeues the first blocking task. Although
  7872. * not necessary for the correctness of this test, we sleep for
  7873. * a short while to avoid busy waiting. */
  7874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7875. }
  7876. if (queued) { n++; }
  7877. }
  7878. /* Further enqueues must fail since the queue is full. */
  7879. for (auto i = 0; i < 4; i++) {
  7880. queued = task_queue->enqueue([] {});
  7881. EXPECT_FALSE(queued);
  7882. }
  7883. /* Give the credits to allow the previous tasks to complete. */
  7884. {
  7885. std::unique_lock<std::mutex> lock(sem_mtx);
  7886. credits += qlimit + 1;
  7887. }
  7888. sem_cv.notify_all();
  7889. /* Wait for all the credits to be consumed. */
  7890. {
  7891. std::unique_lock<std::mutex> lock(sem_mtx);
  7892. while (credits > 0) {
  7893. sem_cv.wait(lock);
  7894. }
  7895. }
  7896. /* Check that we are able again to enqueue at least qlimit tasks. */
  7897. for (unsigned int i = 0; i < qlimit; i++) {
  7898. queued = task_queue->enqueue([] {});
  7899. EXPECT_TRUE(queued);
  7900. }
  7901. EXPECT_NO_THROW(task_queue->shutdown());
  7902. }
  7903. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7904. Server svr;
  7905. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7906. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7907. });
  7908. svr.Get("/hello", [](const Request &req, Response &res) {
  7909. res.set_content(req.get_param_value("key"), "text/plain");
  7910. });
  7911. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7912. auto se = detail::scope_exit([&] {
  7913. svr.stop();
  7914. thread.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. {
  7919. Client cli(HOST, PORT);
  7920. cli.set_follow_location(true);
  7921. auto res = cli.Get("/");
  7922. ASSERT_TRUE(res);
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_EQ("val&key2=val2", res->body);
  7925. }
  7926. }
  7927. TEST(VulnerabilityTest, CRLFInjection) {
  7928. Server svr;
  7929. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7930. res.set_content("Hello 1", "text/plain");
  7931. });
  7932. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7933. res.set_content("Hello 2", "text/plain");
  7934. });
  7935. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7936. res.set_content("Hello 3", "text/plain");
  7937. });
  7938. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7939. res.set_content("Hello 4", "text/plain");
  7940. });
  7941. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7942. for (const auto &x : req.headers) {
  7943. auto key = x.first;
  7944. EXPECT_STRNE("evil", key.c_str());
  7945. }
  7946. });
  7947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7948. auto se = detail::scope_exit([&] {
  7949. svr.stop();
  7950. thread.join();
  7951. ASSERT_FALSE(svr.is_running());
  7952. });
  7953. svr.wait_until_ready();
  7954. {
  7955. Client cli(HOST, PORT);
  7956. cli.Post("/test1", "A=B",
  7957. "application/x-www-form-urlencoded\r\nevil: hello1");
  7958. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7959. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7960. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7961. }
  7962. }
  7963. TEST(PathParamsTest, StaticMatch) {
  7964. const auto pattern = "/users/all";
  7965. detail::PathParamsMatcher matcher(pattern);
  7966. Request request;
  7967. request.path = "/users/all";
  7968. ASSERT_TRUE(matcher.match(request));
  7969. std::unordered_map<std::string, std::string> expected_params = {};
  7970. EXPECT_EQ(request.path_params, expected_params);
  7971. }
  7972. TEST(PathParamsTest, StaticMismatch) {
  7973. const auto pattern = "/users/all";
  7974. detail::PathParamsMatcher matcher(pattern);
  7975. Request request;
  7976. request.path = "/users/1";
  7977. ASSERT_FALSE(matcher.match(request));
  7978. }
  7979. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7980. const auto pattern = "/users/:id/subscriptions";
  7981. detail::PathParamsMatcher matcher(pattern);
  7982. Request request;
  7983. request.path = "/users/42/subscriptions";
  7984. ASSERT_TRUE(matcher.match(request));
  7985. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7986. EXPECT_EQ(request.path_params, expected_params);
  7987. }
  7988. TEST(PathParamsTest, SingleParamInTheEnd) {
  7989. const auto pattern = "/users/:id";
  7990. detail::PathParamsMatcher matcher(pattern);
  7991. Request request;
  7992. request.path = "/users/24";
  7993. ASSERT_TRUE(matcher.match(request));
  7994. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7995. EXPECT_EQ(request.path_params, expected_params);
  7996. }
  7997. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7998. const auto pattern = "/users/:id/";
  7999. detail::PathParamsMatcher matcher(pattern);
  8000. Request request;
  8001. request.path = "/users/42/";
  8002. ASSERT_TRUE(matcher.match(request));
  8003. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8004. EXPECT_EQ(request.path_params, expected_params);
  8005. }
  8006. TEST(PathParamsTest, EmptyParam) {
  8007. const auto pattern = "/users/:id/";
  8008. detail::PathParamsMatcher matcher(pattern);
  8009. Request request;
  8010. request.path = "/users//";
  8011. ASSERT_TRUE(matcher.match(request));
  8012. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8013. EXPECT_EQ(request.path_params, expected_params);
  8014. }
  8015. TEST(PathParamsTest, FragmentMismatch) {
  8016. const auto pattern = "/users/:id/";
  8017. detail::PathParamsMatcher matcher(pattern);
  8018. Request request;
  8019. request.path = "/admins/24/";
  8020. ASSERT_FALSE(matcher.match(request));
  8021. }
  8022. TEST(PathParamsTest, ExtraFragments) {
  8023. const auto pattern = "/users/:id";
  8024. detail::PathParamsMatcher matcher(pattern);
  8025. Request request;
  8026. request.path = "/users/42/subscriptions";
  8027. ASSERT_FALSE(matcher.match(request));
  8028. }
  8029. TEST(PathParamsTest, MissingTrailingParam) {
  8030. const auto pattern = "/users/:id";
  8031. detail::PathParamsMatcher matcher(pattern);
  8032. Request request;
  8033. request.path = "/users";
  8034. ASSERT_FALSE(matcher.match(request));
  8035. }
  8036. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8037. const auto pattern = "/users/:id/subscriptions";
  8038. detail::PathParamsMatcher matcher(pattern);
  8039. Request request;
  8040. request.path = "/users/subscriptions";
  8041. ASSERT_FALSE(matcher.match(request));
  8042. }
  8043. TEST(PathParamsTest, MultipleParams) {
  8044. const auto pattern = "/users/:userid/subscriptions/:subid";
  8045. detail::PathParamsMatcher matcher(pattern);
  8046. Request request;
  8047. request.path = "/users/42/subscriptions/2";
  8048. ASSERT_TRUE(matcher.match(request));
  8049. std::unordered_map<std::string, std::string> expected_params = {
  8050. {"userid", "42"}, {"subid", "2"}};
  8051. EXPECT_EQ(request.path_params, expected_params);
  8052. }
  8053. TEST(PathParamsTest, SequenceOfParams) {
  8054. const auto pattern = "/values/:x/:y/:z";
  8055. detail::PathParamsMatcher matcher(pattern);
  8056. Request request;
  8057. request.path = "/values/1/2/3";
  8058. ASSERT_TRUE(matcher.match(request));
  8059. std::unordered_map<std::string, std::string> expected_params = {
  8060. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8061. EXPECT_EQ(request.path_params, expected_params);
  8062. }
  8063. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8064. const auto pattern = "/prefix:suffix";
  8065. detail::PathParamsMatcher matcher(pattern);
  8066. Request request;
  8067. request.path = "/prefix:suffix";
  8068. ASSERT_TRUE(matcher.match(request));
  8069. const std::unordered_map<std::string, std::string> expected_params = {};
  8070. EXPECT_EQ(request.path_params, expected_params);
  8071. }
  8072. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8073. // If ipv6 regex working, regex match codepath is taken.
  8074. // else port will default to 80 in Client impl
  8075. int clientImplMagicPort = 80;
  8076. int port = 4321;
  8077. // above ports must be different to avoid false negative
  8078. EXPECT_NE(clientImplMagicPort, port);
  8079. std::string ipV6TestURL = "http://[ff06::c3]";
  8080. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8081. CLIENT_PRIVATE_KEY_FILE);
  8082. EXPECT_EQ(cli.port(), port);
  8083. }
  8084. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8085. auto file_path = "./www/dir/index.html";
  8086. auto dir_path = "./www/dir";
  8087. detail::FileStat stat_file(file_path);
  8088. EXPECT_TRUE(stat_file.is_file());
  8089. EXPECT_FALSE(stat_file.is_dir());
  8090. detail::FileStat stat_dir(dir_path);
  8091. EXPECT_FALSE(stat_dir.is_file());
  8092. EXPECT_TRUE(stat_dir.is_dir());
  8093. }
  8094. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8095. Server svr;
  8096. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8097. EXPECT_EQ(res.status, 400);
  8098. });
  8099. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8100. auto se = detail::scope_exit([&] {
  8101. svr.stop();
  8102. thread.join();
  8103. ASSERT_FALSE(svr.is_running());
  8104. });
  8105. svr.wait_until_ready();
  8106. Client cli(HOST, PORT);
  8107. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8108. }
  8109. TEST(InvalidHeaderCharsTest, is_field_name) {
  8110. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8111. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8112. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8113. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8114. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8115. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8116. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8117. EXPECT_FALSE(detail::fields::is_field_name(""));
  8118. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8119. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8120. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8121. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8122. }
  8123. TEST(InvalidHeaderCharsTest, is_field_value) {
  8124. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8125. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8126. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8127. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8128. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8129. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8130. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8131. EXPECT_TRUE(detail::fields::is_field_value(""));
  8132. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8133. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8134. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8135. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8136. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8137. }
  8138. TEST(InvalidHeaderCharsTest, OnServer) {
  8139. Server svr;
  8140. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8141. std::string header = "Not Set";
  8142. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8143. res.set_header(header, "value");
  8144. res.set_content("Page Content Page Content", "text/plain");
  8145. });
  8146. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8147. std::string header = "Not Set";
  8148. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8149. res.set_header("X-Test", header);
  8150. res.set_content("Page Content Page Content", "text/plain");
  8151. });
  8152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8153. auto se = detail::scope_exit([&] {
  8154. svr.stop();
  8155. thread.join();
  8156. ASSERT_FALSE(svr.is_running());
  8157. });
  8158. svr.wait_until_ready();
  8159. Client cli(HOST, PORT);
  8160. {
  8161. auto res = cli.Get(
  8162. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8163. ASSERT_TRUE(res);
  8164. EXPECT_EQ("Page Content Page Content", res->body);
  8165. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8166. }
  8167. {
  8168. auto res = cli.Get(
  8169. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8170. ASSERT_TRUE(res);
  8171. EXPECT_EQ("Page Content Page Content", res->body);
  8172. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8173. }
  8174. }
  8175. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8176. auto handled = false;
  8177. Server svr;
  8178. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8179. thread t = thread([&] { svr.listen(HOST, PORT); });
  8180. auto se = detail::scope_exit([&] {
  8181. svr.stop();
  8182. t.join();
  8183. ASSERT_FALSE(svr.is_running());
  8184. ASSERT_FALSE(handled);
  8185. });
  8186. svr.wait_until_ready();
  8187. auto req = "POST /test HTTP/1.1\r\n"
  8188. "Content-Length: x\r\n"
  8189. "\r\n";
  8190. std::string response;
  8191. ASSERT_TRUE(send_request(1, req, &response));
  8192. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8193. response.substr(0, response.find("\r\n")));
  8194. }
  8195. #ifndef _WIN32
  8196. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8197. static constexpr char reject[] = "Unauthorized";
  8198. static constexpr char accept[] = "Upload accepted";
  8199. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8200. Server svr;
  8201. svr.set_expect_100_continue_handler(
  8202. [](const Request & /*req*/, Response &res) {
  8203. res.status = StatusCode::Unauthorized_401;
  8204. res.set_content(reject, "text/plain");
  8205. return res.status;
  8206. });
  8207. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8208. res.set_content(accept, "text/plain");
  8209. });
  8210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8211. auto se = detail::scope_exit([&] {
  8212. svr.stop();
  8213. thread.join();
  8214. ASSERT_FALSE(svr.is_running());
  8215. });
  8216. svr.wait_until_ready();
  8217. {
  8218. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8219. curl_easy_init(), &curl_easy_cleanup};
  8220. ASSERT_NE(curl, nullptr);
  8221. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8222. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8223. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8224. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8225. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8226. &curl_slist_free_all};
  8227. ASSERT_NE(list, nullptr);
  8228. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8229. struct read_data {
  8230. size_t read_size;
  8231. size_t total_size;
  8232. } data = {0, total_size};
  8233. using read_callback_t =
  8234. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8235. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8236. void *userdata) -> size_t {
  8237. read_data *data = (read_data *)userdata;
  8238. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8239. std::fill_n(ptr, size * nmemb, 'A');
  8240. data->read_size += size * nmemb;
  8241. return size * nmemb;
  8242. };
  8243. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8244. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8245. std::vector<char> buffer;
  8246. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8247. using write_callback_t =
  8248. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8249. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8250. void *userdata) -> size_t {
  8251. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8252. buffer->reserve(buffer->size() + size * nmemb + 1);
  8253. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8254. return size * nmemb;
  8255. };
  8256. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8257. {
  8258. const auto res = curl_easy_perform(curl.get());
  8259. ASSERT_EQ(res, CURLE_OK);
  8260. }
  8261. {
  8262. auto response_code = long{};
  8263. const auto res =
  8264. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8265. ASSERT_EQ(res, CURLE_OK);
  8266. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8267. }
  8268. {
  8269. auto dl = curl_off_t{};
  8270. const auto res =
  8271. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8272. ASSERT_EQ(res, CURLE_OK);
  8273. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8274. }
  8275. {
  8276. buffer.push_back('\0');
  8277. ASSERT_STRCASEEQ(buffer.data(), reject);
  8278. }
  8279. }
  8280. }
  8281. #endif
  8282. template <typename S, typename C>
  8283. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8284. svr.Get("/stream", [&](const Request &, Response &res) {
  8285. auto data = new std::string("01234567890123456789");
  8286. res.set_content_provider(
  8287. data->size(), "text/plain",
  8288. [&, data](size_t offset, size_t length, DataSink &sink) {
  8289. const size_t DATA_CHUNK_SIZE = 4;
  8290. const auto &d = *data;
  8291. std::this_thread::sleep_for(std::chrono::seconds(1));
  8292. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8293. return true;
  8294. },
  8295. [data](bool success) {
  8296. EXPECT_FALSE(success);
  8297. delete data;
  8298. });
  8299. });
  8300. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8301. auto i = new size_t(0);
  8302. res.set_content_provider(
  8303. "text/plain",
  8304. [i](size_t, DataSink &sink) {
  8305. if (*i < 5) {
  8306. std::this_thread::sleep_for(std::chrono::seconds(1));
  8307. sink.write("abcd", 4);
  8308. (*i)++;
  8309. } else {
  8310. sink.done();
  8311. }
  8312. return true;
  8313. },
  8314. [i](bool success) {
  8315. EXPECT_FALSE(success);
  8316. delete i;
  8317. });
  8318. });
  8319. svr.Get("/chunked", [&](const Request &, Response &res) {
  8320. auto i = new size_t(0);
  8321. res.set_chunked_content_provider(
  8322. "text/plain",
  8323. [i](size_t, DataSink &sink) {
  8324. if (*i < 5) {
  8325. std::this_thread::sleep_for(std::chrono::seconds(1));
  8326. sink.os << "abcd";
  8327. (*i)++;
  8328. } else {
  8329. sink.done();
  8330. }
  8331. return true;
  8332. },
  8333. [i](bool success) {
  8334. EXPECT_FALSE(success);
  8335. delete i;
  8336. });
  8337. });
  8338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8339. auto se = detail::scope_exit([&] {
  8340. svr.stop();
  8341. listen_thread.join();
  8342. ASSERT_FALSE(svr.is_running());
  8343. });
  8344. svr.wait_until_ready();
  8345. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8346. {
  8347. auto start = std::chrono::steady_clock::now();
  8348. auto res = cli.Get("/stream");
  8349. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8350. std::chrono::steady_clock::now() - start)
  8351. .count();
  8352. ASSERT_FALSE(res);
  8353. EXPECT_EQ(Error::Read, res.error());
  8354. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8355. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8356. }
  8357. {
  8358. auto start = std::chrono::steady_clock::now();
  8359. auto res = cli.Get("/stream_without_length");
  8360. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8361. std::chrono::steady_clock::now() - start)
  8362. .count();
  8363. ASSERT_FALSE(res);
  8364. EXPECT_EQ(Error::Read, res.error());
  8365. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8366. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8367. }
  8368. {
  8369. auto start = std::chrono::steady_clock::now();
  8370. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8371. EXPECT_EQ("abcd", string(data, data_length));
  8372. return true;
  8373. });
  8374. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8375. std::chrono::steady_clock::now() - start)
  8376. .count();
  8377. ASSERT_FALSE(res);
  8378. EXPECT_EQ(Error::Read, res.error());
  8379. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8380. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8381. }
  8382. }
  8383. TEST(MaxTimeoutTest, ContentStream) {
  8384. time_t timeout = 2000;
  8385. time_t threshold = 200;
  8386. Server svr;
  8387. Client cli("localhost", PORT);
  8388. max_timeout_test(svr, cli, timeout, threshold);
  8389. }
  8390. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8391. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8392. time_t timeout = 2000;
  8393. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8395. SSLClient cli("localhost", PORT);
  8396. cli.enable_server_certificate_verification(false);
  8397. max_timeout_test(svr, cli, timeout, threshold);
  8398. }
  8399. #endif
  8400. class EventDispatcher {
  8401. public:
  8402. EventDispatcher() {}
  8403. void wait_event(DataSink *sink) {
  8404. unique_lock<mutex> lk(m_);
  8405. int id = id_;
  8406. cv_.wait(lk, [&] { return cid_ == id; });
  8407. sink->write(message_.data(), message_.size());
  8408. }
  8409. void send_event(const string &message) {
  8410. lock_guard<mutex> lk(m_);
  8411. cid_ = id_++;
  8412. message_ = message;
  8413. cv_.notify_all();
  8414. }
  8415. private:
  8416. mutex m_;
  8417. condition_variable cv_;
  8418. atomic_int id_{0};
  8419. atomic_int cid_{-1};
  8420. string message_;
  8421. };
  8422. TEST(ClientInThreadTest, Issue2068) {
  8423. EventDispatcher ed;
  8424. Server svr;
  8425. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8426. res.set_chunked_content_provider("text/event-stream",
  8427. [&](size_t /*offset*/, DataSink &sink) {
  8428. ed.wait_event(&sink);
  8429. return true;
  8430. });
  8431. });
  8432. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8433. svr.wait_until_ready();
  8434. thread event_thread([&] {
  8435. int id = 0;
  8436. while (svr.is_running()) {
  8437. this_thread::sleep_for(chrono::milliseconds(500));
  8438. std::stringstream ss;
  8439. ss << "data: " << id << "\n\n";
  8440. ed.send_event(ss.str());
  8441. id++;
  8442. }
  8443. });
  8444. auto se = detail::scope_exit([&] {
  8445. svr.stop();
  8446. listen_thread.join();
  8447. event_thread.join();
  8448. ASSERT_FALSE(svr.is_running());
  8449. });
  8450. {
  8451. auto client = detail::make_unique<Client>(HOST, PORT);
  8452. client->set_read_timeout(std::chrono::minutes(10));
  8453. std::atomic<bool> stop{false};
  8454. std::thread t([&] {
  8455. client->Get("/event1",
  8456. [&](const char *, size_t) -> bool { return !stop; });
  8457. });
  8458. std::this_thread::sleep_for(std::chrono::seconds(2));
  8459. stop = true;
  8460. client->stop();
  8461. client.reset();
  8462. t.join();
  8463. }
  8464. }