test.cc 212 KB

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