test.cc 263 KB

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