test.cc 330 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(ConnectionErrorTest, InvalidHost) {
  1092. auto host = "-abcde.com";
  1093. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1094. auto port = 443;
  1095. SSLClient cli(host, port);
  1096. #else
  1097. auto port = 80;
  1098. Client cli(host, port);
  1099. #endif
  1100. cli.set_connection_timeout(std::chrono::seconds(2));
  1101. auto res = cli.Get("/");
  1102. ASSERT_TRUE(!res);
  1103. EXPECT_EQ(Error::Connection, res.error());
  1104. }
  1105. TEST(ConnectionErrorTest, InvalidHost2) {
  1106. auto host = "httpbin.org/";
  1107. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1108. SSLClient cli(host);
  1109. #else
  1110. Client cli(host);
  1111. #endif
  1112. cli.set_connection_timeout(std::chrono::seconds(2));
  1113. auto res = cli.Get("/");
  1114. ASSERT_TRUE(!res);
  1115. EXPECT_EQ(Error::Connection, res.error());
  1116. }
  1117. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1118. auto host = "httpbin.org/";
  1119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1120. SSLClient cli(host);
  1121. #else
  1122. Client cli(host);
  1123. #endif
  1124. cli.set_connection_timeout(std::chrono::seconds(2));
  1125. auto res = cli.Get("/");
  1126. ASSERT_TRUE(!res);
  1127. stringstream s;
  1128. s << "error code: " << res.error();
  1129. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1130. }
  1131. TEST(ConnectionErrorTest, InvalidPort) {
  1132. auto host = "localhost";
  1133. auto port = 44380;
  1134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1135. SSLClient cli(host, port);
  1136. #else
  1137. Client cli(host, port);
  1138. #endif
  1139. cli.set_connection_timeout(std::chrono::seconds(2));
  1140. auto res = cli.Get("/");
  1141. ASSERT_TRUE(!res);
  1142. EXPECT_TRUE(Error::Connection == res.error() ||
  1143. Error::ConnectionTimeout == res.error());
  1144. }
  1145. TEST(ConnectionErrorTest, Timeout_Online) {
  1146. auto host = "google.com";
  1147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1148. auto port = 44380;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 8080;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(std::chrono::seconds(2));
  1155. // only probe one address type so that the error reason
  1156. // correlates to the timed-out IPv4, not the unsupported
  1157. // IPv6 connection attempt
  1158. cli.set_address_family(AF_INET);
  1159. auto res = cli.Get("/");
  1160. ASSERT_TRUE(!res);
  1161. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1162. }
  1163. TEST(CancelTest, NoCancel_Online) {
  1164. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1165. auto host = "httpbin.org";
  1166. auto path = std::string{"/range/32"};
  1167. #else
  1168. auto host = "nghttp2.org";
  1169. auto path = std::string{"/httpbin/range/32"};
  1170. #endif
  1171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1172. auto port = 443;
  1173. SSLClient cli(host, port);
  1174. #else
  1175. auto port = 80;
  1176. Client cli(host, port);
  1177. #endif
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. }
  1184. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1185. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1186. auto host = "httpbin.org";
  1187. auto path = std::string{"/range/32"};
  1188. #else
  1189. auto host = "nghttp2.org";
  1190. auto path = std::string{"/httpbin/range/32"};
  1191. #endif
  1192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1193. auto port = 443;
  1194. SSLClient cli(host, port);
  1195. #else
  1196. auto port = 80;
  1197. Client cli(host, port);
  1198. #endif
  1199. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1200. cli.set_connection_timeout(std::chrono::seconds(5));
  1201. ASSERT_TRUE(!res);
  1202. EXPECT_EQ(Error::Canceled, res.error());
  1203. }
  1204. TEST(CancelTest, WithCancelLargePayload_Online) {
  1205. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1206. auto host = "httpbin.org";
  1207. auto path = std::string{"/range/65536"};
  1208. #else
  1209. auto host = "nghttp2.org";
  1210. auto path = std::string{"/httpbin/range/65536"};
  1211. #endif
  1212. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(5));
  1220. uint32_t count = 0;
  1221. auto res =
  1222. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1223. ASSERT_TRUE(!res);
  1224. EXPECT_EQ(Error::Canceled, res.error());
  1225. }
  1226. TEST(CancelTest, NoCancelPost) {
  1227. Server svr;
  1228. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1229. res.set_content("Hello World!", "text/plain");
  1230. });
  1231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1232. auto se = detail::scope_exit([&] {
  1233. svr.stop();
  1234. thread.join();
  1235. ASSERT_FALSE(svr.is_running());
  1236. });
  1237. svr.wait_until_ready();
  1238. Client cli(HOST, PORT);
  1239. cli.set_connection_timeout(std::chrono::seconds(5));
  1240. auto res =
  1241. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1242. "application/json", [](uint64_t, uint64_t) { return true; });
  1243. ASSERT_TRUE(res);
  1244. EXPECT_EQ("Hello World!", res->body);
  1245. EXPECT_EQ(StatusCode::OK_200, res->status);
  1246. }
  1247. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1248. Server svr;
  1249. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1250. res.set_content("Hello World!", "text/plain");
  1251. });
  1252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1253. auto se = detail::scope_exit([&] {
  1254. svr.stop();
  1255. thread.join();
  1256. ASSERT_FALSE(svr.is_running());
  1257. });
  1258. svr.wait_until_ready();
  1259. Client cli(HOST, PORT);
  1260. cli.set_connection_timeout(std::chrono::seconds(5));
  1261. auto res =
  1262. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1263. "application/json", [](uint64_t, uint64_t) { return false; });
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::Canceled, res.error());
  1266. }
  1267. TEST(CancelTest, WithCancelLargePayloadPost) {
  1268. Server svr;
  1269. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1270. res.set_content(LARGE_DATA, "text/plain");
  1271. });
  1272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1273. auto se = detail::scope_exit([&] {
  1274. svr.stop();
  1275. thread.join();
  1276. ASSERT_FALSE(svr.is_running());
  1277. });
  1278. svr.wait_until_ready();
  1279. Client cli(HOST, PORT);
  1280. cli.set_connection_timeout(std::chrono::seconds(5));
  1281. auto res =
  1282. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1283. "application/json", [](uint64_t, uint64_t) { return false; });
  1284. ASSERT_TRUE(!res);
  1285. EXPECT_EQ(Error::Canceled, res.error());
  1286. }
  1287. TEST(CancelTest, NoCancelPut) {
  1288. Server svr;
  1289. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1290. res.set_content("Hello World!", "text/plain");
  1291. });
  1292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1293. auto se = detail::scope_exit([&] {
  1294. svr.stop();
  1295. thread.join();
  1296. ASSERT_FALSE(svr.is_running());
  1297. });
  1298. svr.wait_until_ready();
  1299. Client cli(HOST, PORT);
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res =
  1302. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1303. "application/json", [](uint64_t, uint64_t) { return true; });
  1304. ASSERT_TRUE(res);
  1305. EXPECT_EQ("Hello World!", res->body);
  1306. EXPECT_EQ(StatusCode::OK_200, res->status);
  1307. }
  1308. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1309. Server svr;
  1310. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1311. res.set_content("Hello World!", "text/plain");
  1312. });
  1313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1314. auto se = detail::scope_exit([&] {
  1315. svr.stop();
  1316. thread.join();
  1317. ASSERT_FALSE(svr.is_running());
  1318. });
  1319. svr.wait_until_ready();
  1320. Client cli(HOST, PORT);
  1321. cli.set_connection_timeout(std::chrono::seconds(5));
  1322. auto res =
  1323. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1324. "application/json", [](uint64_t, uint64_t) { return false; });
  1325. ASSERT_TRUE(!res);
  1326. EXPECT_EQ(Error::Canceled, res.error());
  1327. }
  1328. TEST(CancelTest, WithCancelLargePayloadPut) {
  1329. Server svr;
  1330. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1331. res.set_content(LARGE_DATA, "text/plain");
  1332. });
  1333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1334. auto se = detail::scope_exit([&] {
  1335. svr.stop();
  1336. thread.join();
  1337. ASSERT_FALSE(svr.is_running());
  1338. });
  1339. svr.wait_until_ready();
  1340. Client cli(HOST, PORT);
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. auto res =
  1343. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1344. "application/json", [](uint64_t, uint64_t) { return false; });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPatch) {
  1349. Server svr;
  1350. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1370. Server svr;
  1371. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1390. Server svr;
  1391. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1392. res.set_content(LARGE_DATA, "text/plain");
  1393. });
  1394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1395. auto se = detail::scope_exit([&] {
  1396. svr.stop();
  1397. thread.join();
  1398. ASSERT_FALSE(svr.is_running());
  1399. });
  1400. svr.wait_until_ready();
  1401. Client cli(HOST, PORT);
  1402. cli.set_connection_timeout(std::chrono::seconds(5));
  1403. auto res =
  1404. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1405. "application/json", [](uint64_t, uint64_t) { return false; });
  1406. ASSERT_TRUE(!res);
  1407. EXPECT_EQ(Error::Canceled, res.error());
  1408. }
  1409. TEST(CancelTest, NoCancelDelete) {
  1410. Server svr;
  1411. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1412. res.set_content("Hello World!", "text/plain");
  1413. });
  1414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1415. auto se = detail::scope_exit([&] {
  1416. svr.stop();
  1417. thread.join();
  1418. ASSERT_FALSE(svr.is_running());
  1419. });
  1420. svr.wait_until_ready();
  1421. Client cli(HOST, PORT);
  1422. cli.set_connection_timeout(std::chrono::seconds(5));
  1423. auto res =
  1424. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1425. "application/json", [](uint64_t, uint64_t) { return true; });
  1426. ASSERT_TRUE(res);
  1427. EXPECT_EQ("Hello World!", res->body);
  1428. EXPECT_EQ(StatusCode::OK_200, res->status);
  1429. }
  1430. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1431. Server svr;
  1432. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1433. res.set_content("Hello World!", "text/plain");
  1434. });
  1435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1436. auto se = detail::scope_exit([&] {
  1437. svr.stop();
  1438. thread.join();
  1439. ASSERT_FALSE(svr.is_running());
  1440. });
  1441. svr.wait_until_ready();
  1442. Client cli(HOST, PORT);
  1443. cli.set_connection_timeout(std::chrono::seconds(5));
  1444. auto res =
  1445. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1446. "application/json", [](uint64_t, uint64_t) { return false; });
  1447. ASSERT_TRUE(!res);
  1448. EXPECT_EQ(Error::Canceled, res.error());
  1449. }
  1450. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1451. Server svr;
  1452. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_connection_timeout(std::chrono::seconds(5));
  1464. auto res =
  1465. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1466. "application/json", [](uint64_t, uint64_t) { return false; });
  1467. ASSERT_TRUE(!res);
  1468. EXPECT_EQ(Error::Canceled, res.error());
  1469. }
  1470. static std::string remove_whitespace(const std::string &input) {
  1471. std::string output;
  1472. output.reserve(input.size());
  1473. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1474. [](unsigned char c) { return !std::isspace(c); });
  1475. return output;
  1476. }
  1477. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1478. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1479. auto host = "httpbin.org";
  1480. auto path = std::string{"/basic-auth/hello/world"};
  1481. #else
  1482. auto host = "nghttp2.org";
  1483. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1484. #endif
  1485. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1486. auto port = 443;
  1487. SSLClient cli(host, port);
  1488. #else
  1489. auto port = 80;
  1490. Client cli(host, port);
  1491. #endif
  1492. {
  1493. auto res = cli.Get(path);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1496. }
  1497. {
  1498. auto res =
  1499. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1502. remove_whitespace(res->body));
  1503. EXPECT_EQ(StatusCode::OK_200, res->status);
  1504. }
  1505. {
  1506. cli.set_basic_auth("hello", "world");
  1507. auto res = cli.Get(path);
  1508. ASSERT_TRUE(res);
  1509. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1510. remove_whitespace(res->body));
  1511. EXPECT_EQ(StatusCode::OK_200, res->status);
  1512. }
  1513. {
  1514. cli.set_basic_auth("hello", "bad");
  1515. auto res = cli.Get(path);
  1516. ASSERT_TRUE(res);
  1517. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1518. }
  1519. {
  1520. cli.set_basic_auth("bad", "world");
  1521. auto res = cli.Get(path);
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1524. }
  1525. }
  1526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1527. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1528. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1529. auto host = "httpbin.org";
  1530. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1531. auto paths = std::vector<std::string>{
  1532. "/digest-auth/auth/hello/world/MD5",
  1533. "/digest-auth/auth/hello/world/SHA-256",
  1534. "/digest-auth/auth/hello/world/SHA-512",
  1535. "/digest-auth/auth-int/hello/world/MD5",
  1536. };
  1537. #else
  1538. auto host = "nghttp2.org";
  1539. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1540. auto paths = std::vector<std::string>{
  1541. "/httpbin/digest-auth/auth/hello/world/MD5",
  1542. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1543. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1544. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1545. };
  1546. #endif
  1547. auto port = 443;
  1548. SSLClient cli(host, port);
  1549. {
  1550. auto res = cli.Get(unauth_path);
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1553. }
  1554. {
  1555. cli.set_digest_auth("hello", "world");
  1556. for (const auto &path : paths) {
  1557. auto res = cli.Get(path.c_str());
  1558. ASSERT_TRUE(res);
  1559. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1560. remove_whitespace(res->body));
  1561. EXPECT_EQ(StatusCode::OK_200, res->status);
  1562. }
  1563. cli.set_digest_auth("hello", "bad");
  1564. for (const auto &path : paths) {
  1565. auto res = cli.Get(path.c_str());
  1566. ASSERT_TRUE(res);
  1567. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1568. }
  1569. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1570. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1571. // cli.set_digest_auth("bad", "world");
  1572. // for (const auto& path : paths) {
  1573. // auto res = cli.Get(path.c_str());
  1574. // ASSERT_TRUE(res);
  1575. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1576. // }
  1577. }
  1578. }
  1579. #endif
  1580. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1581. auto host = "google.com";
  1582. auto another_host = "example.com";
  1583. auto wrong_ip = "0.0.0.0";
  1584. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1585. SSLClient cli(host);
  1586. #else
  1587. Client cli(host);
  1588. #endif
  1589. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1590. auto res = cli.Get("/");
  1591. ASSERT_TRUE(res);
  1592. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1593. }
  1594. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1595. auto host = "google.com";
  1596. auto wrong_ip = "0.0.0.0";
  1597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1598. SSLClient cli(host);
  1599. #else
  1600. Client cli(host);
  1601. #endif
  1602. cli.set_hostname_addr_map({{host, wrong_ip}});
  1603. auto res = cli.Get("/");
  1604. ASSERT_TRUE(!res);
  1605. EXPECT_EQ(Error::Connection, res.error());
  1606. }
  1607. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1608. auto host = "nghttp2.org";
  1609. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1610. SSLClient cli(host);
  1611. #else
  1612. Client cli(host);
  1613. #endif
  1614. cli.set_follow_location(true);
  1615. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1616. ASSERT_TRUE(res);
  1617. EXPECT_EQ(StatusCode::OK_200, res->status);
  1618. }
  1619. TEST(RedirectTest, Redirect_Online) {
  1620. auto host = "nghttp2.org";
  1621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1622. SSLClient cli(host);
  1623. #else
  1624. Client cli(host);
  1625. #endif
  1626. cli.set_follow_location(true);
  1627. auto res = cli.Get("/httpbin/redirect/3");
  1628. ASSERT_TRUE(res);
  1629. EXPECT_EQ(StatusCode::OK_200, res->status);
  1630. }
  1631. TEST(RelativeRedirectTest, Redirect_Online) {
  1632. auto host = "nghttp2.org";
  1633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1634. SSLClient cli(host);
  1635. #else
  1636. Client cli(host);
  1637. #endif
  1638. cli.set_follow_location(true);
  1639. auto res = cli.Get("/httpbin/relative-redirect/3");
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. TEST(TooManyRedirectTest, Redirect_Online) {
  1644. auto host = "nghttp2.org";
  1645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1646. SSLClient cli(host);
  1647. #else
  1648. Client cli(host);
  1649. #endif
  1650. cli.set_follow_location(true);
  1651. auto res = cli.Get("/httpbin/redirect/21");
  1652. ASSERT_TRUE(!res);
  1653. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1654. }
  1655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1656. TEST(YahooRedirectTest, Redirect_Online) {
  1657. Client cli("yahoo.com");
  1658. auto res = cli.Get("/");
  1659. ASSERT_TRUE(res);
  1660. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1661. cli.set_follow_location(true);
  1662. res = cli.Get("/");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1666. }
  1667. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1668. #define REDIR_HOST "httpbingo.org"
  1669. #define REDIR_PATH "/redirect-to"
  1670. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1671. SSLClient cli(REDIR_HOST);
  1672. cli.set_follow_location(true);
  1673. auto res =
  1674. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1675. ASSERT_TRUE(res);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1679. SSLClient cli(REDIR_HOST);
  1680. cli.set_follow_location(true);
  1681. Params params;
  1682. params.emplace("url", "http://example.com");
  1683. params.emplace("status_code", "302");
  1684. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1689. SSLClient cli(REDIR_HOST);
  1690. cli.set_follow_location(true);
  1691. Params params;
  1692. params.emplace("url", "http://example.com");
  1693. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1694. ASSERT_TRUE(res);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. TEST(UrlWithSpace, Redirect_Online) {
  1698. SSLClient cli("edge.forgecdn.net");
  1699. cli.set_follow_location(true);
  1700. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1704. }
  1705. #endif
  1706. #if !defined(_WIN32) && !defined(_WIN64)
  1707. TEST(ReceiveSignals, Signal) {
  1708. auto setupSignalHandlers = []() {
  1709. struct sigaction act;
  1710. sigemptyset(&act.sa_mask);
  1711. act.sa_flags = SA_SIGINFO;
  1712. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1713. switch (sig) {
  1714. case SIGINT:
  1715. default: break;
  1716. }
  1717. };
  1718. ::sigaction(SIGINT, &act, nullptr);
  1719. };
  1720. Server svr;
  1721. int port = 0;
  1722. auto thread = std::thread([&]() {
  1723. setupSignalHandlers();
  1724. port = svr.bind_to_any_port("localhost");
  1725. svr.listen_after_bind();
  1726. });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. ASSERT_TRUE(svr.is_running());
  1734. pthread_kill(thread.native_handle(), SIGINT);
  1735. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1736. ASSERT_TRUE(svr.is_running());
  1737. }
  1738. #endif
  1739. TEST(RedirectToDifferentPort, Redirect) {
  1740. Server svr1;
  1741. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1742. res.set_content("Hello World!", "text/plain");
  1743. });
  1744. int svr1_port = 0;
  1745. auto thread1 = std::thread([&]() {
  1746. svr1_port = svr1.bind_to_any_port("localhost");
  1747. svr1.listen_after_bind();
  1748. });
  1749. Server svr2;
  1750. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1751. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1752. });
  1753. int svr2_port = 0;
  1754. auto thread2 = std::thread([&]() {
  1755. svr2_port = svr2.bind_to_any_port("localhost");
  1756. svr2.listen_after_bind();
  1757. });
  1758. auto se = detail::scope_exit([&] {
  1759. svr2.stop();
  1760. thread2.join();
  1761. svr1.stop();
  1762. thread1.join();
  1763. ASSERT_FALSE(svr2.is_running());
  1764. ASSERT_FALSE(svr1.is_running());
  1765. });
  1766. svr1.wait_until_ready();
  1767. svr2.wait_until_ready();
  1768. Client cli("localhost", svr2_port);
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/2");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. EXPECT_EQ("Hello World!", res->body);
  1774. }
  1775. TEST(RedirectFromPageWithContent, Redirect) {
  1776. Server svr;
  1777. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1778. res.set_content("___", "text/plain");
  1779. res.set_redirect("/2");
  1780. });
  1781. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1782. res.set_content("Hello World!", "text/plain");
  1783. });
  1784. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1785. auto se = detail::scope_exit([&] {
  1786. svr.stop();
  1787. th.join();
  1788. ASSERT_FALSE(svr.is_running());
  1789. });
  1790. svr.wait_until_ready();
  1791. {
  1792. Client cli("localhost", PORT);
  1793. cli.set_follow_location(true);
  1794. std::string body;
  1795. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1796. body.append(data, data_length);
  1797. return true;
  1798. });
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. EXPECT_EQ("Hello World!", body);
  1802. }
  1803. {
  1804. Client cli("localhost", PORT);
  1805. std::string body;
  1806. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1807. body.append(data, data_length);
  1808. return true;
  1809. });
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::Found_302, res->status);
  1812. EXPECT_EQ("___", body);
  1813. }
  1814. }
  1815. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1816. Server svr;
  1817. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1818. res.set_content("___", "text/plain");
  1819. // res.set_redirect("/2");
  1820. res.set_redirect("http://[::1]:1234/2");
  1821. });
  1822. svr.Get("/2", [&](const Request &req, Response &res) {
  1823. auto host_header = req.headers.find("Host");
  1824. ASSERT_TRUE(host_header != req.headers.end());
  1825. EXPECT_EQ("[::1]:1234", host_header->second);
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. th.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1835. // actually starts anything, so the condition !svr.is_running() will
  1836. // always remain true, and the loop never stops.
  1837. // This basically counts how many milliseconds have passed since the
  1838. // call to svr.listen(), and if after 5 seconds nothing started yet
  1839. // aborts the test.
  1840. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1841. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1842. ASSERT_LT(milliseconds, 5000U);
  1843. }
  1844. {
  1845. Client cli("http://[::1]:1234");
  1846. cli.set_follow_location(true);
  1847. std::string body;
  1848. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1849. body.append(data, data_length);
  1850. return true;
  1851. });
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. EXPECT_EQ("Hello World!", body);
  1855. }
  1856. {
  1857. Client cli("http://[::1]:1234");
  1858. std::string body;
  1859. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1860. body.append(data, data_length);
  1861. return true;
  1862. });
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::Found_302, res->status);
  1865. EXPECT_EQ("___", body);
  1866. }
  1867. }
  1868. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1869. Server svr;
  1870. svr.Get("/foo", [](const Request &req, Response &res) {
  1871. auto a = req.params.find("a");
  1872. if (a != req.params.end()) {
  1873. res.set_content((*a).second, "text/plain");
  1874. res.status = StatusCode::OK_200;
  1875. } else {
  1876. res.status = StatusCode::BadRequest_400;
  1877. }
  1878. });
  1879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. {
  1887. Client cli(HOST, PORT);
  1888. cli.set_path_encode(false);
  1889. auto res = cli.Get("/foo?a=explicitly+encoded");
  1890. ASSERT_TRUE(res);
  1891. EXPECT_EQ(StatusCode::OK_200, res->status);
  1892. // This expects it back with a space, as the `+` won't have been
  1893. // url-encoded, and server-side the params get decoded turning `+`
  1894. // into spaces.
  1895. EXPECT_EQ("explicitly encoded", res->body);
  1896. }
  1897. }
  1898. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1899. Server svr;
  1900. svr.Get("/", [](const Request &req, Response &) {
  1901. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1902. });
  1903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. {
  1911. Client cli(HOST, PORT);
  1912. cli.set_path_encode(false);
  1913. auto res = cli.Get("/?something=%0A");
  1914. ASSERT_TRUE(res);
  1915. EXPECT_EQ(StatusCode::OK_200, res->status);
  1916. }
  1917. }
  1918. TEST(BindServerTest, DISABLED_BindDualStack) {
  1919. Server svr;
  1920. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1921. res.set_content("Hello World!", "text/plain");
  1922. });
  1923. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1924. auto se = detail::scope_exit([&] {
  1925. svr.stop();
  1926. thread.join();
  1927. ASSERT_FALSE(svr.is_running());
  1928. });
  1929. svr.wait_until_ready();
  1930. {
  1931. Client cli("127.0.0.1", PORT);
  1932. auto res = cli.Get("/1");
  1933. ASSERT_TRUE(res);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ("Hello World!", res->body);
  1936. }
  1937. {
  1938. Client cli("::1", PORT);
  1939. auto res = cli.Get("/1");
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::OK_200, res->status);
  1942. EXPECT_EQ("Hello World!", res->body);
  1943. }
  1944. }
  1945. TEST(BindServerTest, BindAndListenSeparately) {
  1946. Server svr;
  1947. int port = svr.bind_to_any_port("0.0.0.0");
  1948. ASSERT_TRUE(svr.is_valid());
  1949. ASSERT_TRUE(port > 0);
  1950. svr.stop();
  1951. }
  1952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1953. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1955. CLIENT_CA_CERT_DIR);
  1956. int port = svr.bind_to_any_port("0.0.0.0");
  1957. ASSERT_TRUE(svr.is_valid());
  1958. ASSERT_TRUE(port > 0);
  1959. svr.stop();
  1960. }
  1961. #endif
  1962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1963. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1964. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1965. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1966. int port = svr.bind_to_any_port("0.0.0.0");
  1967. ASSERT_TRUE(svr.is_valid());
  1968. ASSERT_TRUE(port > 0);
  1969. svr.stop();
  1970. }
  1971. #endif
  1972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1973. X509 *readCertificate(const std::string &strFileName) {
  1974. std::ifstream inStream(strFileName);
  1975. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1976. std::istreambuf_iterator<char>());
  1977. if (strCertPEM.empty()) return (nullptr);
  1978. BIO *pbCert = BIO_new(BIO_s_mem());
  1979. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1980. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1981. BIO_free(pbCert);
  1982. return (pCert);
  1983. }
  1984. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1985. std::ifstream inStream(strFileName);
  1986. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1987. std::istreambuf_iterator<char>());
  1988. if (strPrivateKeyPEM.empty()) return (nullptr);
  1989. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1990. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1991. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1992. BIO_free(pbPrivKey);
  1993. return (pPrivateKey);
  1994. }
  1995. TEST(BindServerTest, UpdateCerts) {
  1996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1997. int port = svr.bind_to_any_port("0.0.0.0");
  1998. ASSERT_TRUE(svr.is_valid());
  1999. ASSERT_TRUE(port > 0);
  2000. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2001. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2002. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2003. ASSERT_TRUE(cert != nullptr);
  2004. ASSERT_TRUE(ca_cert != nullptr);
  2005. ASSERT_TRUE(key != nullptr);
  2006. X509_STORE *cert_store = X509_STORE_new();
  2007. X509_STORE_add_cert(cert_store, ca_cert);
  2008. svr.update_certs(cert, key, cert_store);
  2009. ASSERT_TRUE(svr.is_valid());
  2010. svr.stop();
  2011. X509_free(cert);
  2012. X509_free(ca_cert);
  2013. EVP_PKEY_free(key);
  2014. }
  2015. #endif
  2016. TEST(ErrorHandlerTest, ContentLength) {
  2017. Server svr;
  2018. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2019. res.status = StatusCode::OK_200;
  2020. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2021. "text/html"); // <= Content-Length still 13
  2022. });
  2023. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2024. res.set_content("Hello World!\n", "text/plain");
  2025. res.status = 524;
  2026. });
  2027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2028. auto se = detail::scope_exit([&] {
  2029. svr.stop();
  2030. thread.join();
  2031. ASSERT_FALSE(svr.is_running());
  2032. });
  2033. svr.wait_until_ready();
  2034. {
  2035. Client cli(HOST, PORT);
  2036. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2042. }
  2043. }
  2044. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2045. TEST(ExceptionTest, WithoutExceptionHandler) {
  2046. Server svr;
  2047. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2048. throw std::runtime_error("exception...");
  2049. });
  2050. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2051. throw std::runtime_error("exception\r\n...");
  2052. });
  2053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2054. auto se = detail::scope_exit([&] {
  2055. svr.stop();
  2056. listen_thread.join();
  2057. ASSERT_FALSE(svr.is_running());
  2058. });
  2059. svr.wait_until_ready();
  2060. Client cli("localhost", PORT);
  2061. {
  2062. auto res = cli.Get("/exception");
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2065. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2066. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2067. }
  2068. {
  2069. auto res = cli.Get("/unknown");
  2070. ASSERT_TRUE(res);
  2071. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2072. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2073. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2074. }
  2075. }
  2076. TEST(ExceptionTest, WithExceptionHandler) {
  2077. Server svr;
  2078. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2079. std::exception_ptr ep) {
  2080. EXPECT_FALSE(ep == nullptr);
  2081. try {
  2082. std::rethrow_exception(ep);
  2083. } catch (std::exception &e) {
  2084. EXPECT_EQ("abc", std::string(e.what()));
  2085. } catch (...) {}
  2086. res.status = StatusCode::InternalServerError_500;
  2087. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2088. "text/html"); // <= Content-Length still 13 at this point
  2089. });
  2090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2091. res.set_content("Hello World!\n", "text/plain");
  2092. throw std::runtime_error("abc");
  2093. });
  2094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2095. auto se = detail::scope_exit([&] {
  2096. svr.stop();
  2097. thread.join();
  2098. ASSERT_FALSE(svr.is_running());
  2099. });
  2100. svr.wait_until_ready();
  2101. for (size_t i = 0; i < 10; i++) {
  2102. Client cli(HOST, PORT);
  2103. for (size_t j = 0; j < 100; j++) {
  2104. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2108. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2109. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2110. }
  2111. cli.set_keep_alive(true);
  2112. for (size_t j = 0; j < 100; j++) {
  2113. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2118. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2119. }
  2120. }
  2121. }
  2122. TEST(ExceptionTest, AndErrorHandler) {
  2123. Server svr;
  2124. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2125. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2126. });
  2127. svr.set_exception_handler(
  2128. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2129. EXPECT_FALSE(ep == nullptr);
  2130. try {
  2131. std::rethrow_exception(ep);
  2132. } catch (std::exception &e) {
  2133. res.set_content(e.what(), "text/html");
  2134. } catch (...) {}
  2135. res.status = StatusCode::InternalServerError_500;
  2136. });
  2137. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2138. throw std::runtime_error("EXCEPTION");
  2139. });
  2140. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2141. res.set_content("ERROR", "text/html");
  2142. res.status = StatusCode::InternalServerError_500;
  2143. });
  2144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2145. auto se = detail::scope_exit([&] {
  2146. svr.stop();
  2147. thread.join();
  2148. ASSERT_FALSE(svr.is_running());
  2149. });
  2150. svr.wait_until_ready();
  2151. Client cli(HOST, PORT);
  2152. {
  2153. auto res = cli.Get("/exception");
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2156. EXPECT_EQ("EXCEPTION", res->body);
  2157. }
  2158. {
  2159. auto res = cli.Get("/error");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. EXPECT_EQ("ERROR", res->body);
  2163. }
  2164. {
  2165. auto res = cli.Get("/invalid");
  2166. ASSERT_TRUE(res);
  2167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2168. EXPECT_EQ("NOT_FOUND", res->body);
  2169. }
  2170. }
  2171. #endif
  2172. TEST(NoContentTest, ContentLength) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.status = StatusCode::NoContent_204;
  2176. });
  2177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. thread.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. svr.wait_until_ready();
  2184. {
  2185. Client cli(HOST, PORT);
  2186. auto res = cli.Get("/hi");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2189. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2190. }
  2191. }
  2192. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2195. ASSERT_TRUE(svr.is_valid());
  2196. #else
  2197. Server svr;
  2198. #endif
  2199. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2200. if (req.path == "/routing_handler") {
  2201. res.set_header("PRE_ROUTING", "on");
  2202. res.set_content("Routing Handler", "text/plain");
  2203. return httplib::Server::HandlerResponse::Handled;
  2204. }
  2205. return httplib::Server::HandlerResponse::Unhandled;
  2206. });
  2207. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2208. res.set_content("Error", "text/html");
  2209. });
  2210. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2211. if (req.path == "/routing_handler") {
  2212. res.set_header("POST_ROUTING", "on");
  2213. }
  2214. });
  2215. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2216. res.set_content("Hello World!\n", "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. SSLClient cli(HOST, PORT);
  2228. cli.enable_server_certificate_verification(false);
  2229. #else
  2230. Client cli(HOST, PORT);
  2231. #endif
  2232. auto res = cli.Get("/routing_handler");
  2233. ASSERT_TRUE(res);
  2234. EXPECT_EQ(StatusCode::OK_200, res->status);
  2235. EXPECT_EQ("Routing Handler", res->body);
  2236. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2237. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2238. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2239. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2240. }
  2241. {
  2242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2243. SSLClient cli(HOST, PORT);
  2244. cli.enable_server_certificate_verification(false);
  2245. #else
  2246. Client cli(HOST, PORT);
  2247. #endif
  2248. auto res = cli.Get("/hi");
  2249. ASSERT_TRUE(res);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ("Hello World!\n", res->body);
  2252. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2253. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2254. }
  2255. {
  2256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2257. SSLClient cli(HOST, PORT);
  2258. cli.enable_server_certificate_verification(false);
  2259. #else
  2260. Client cli(HOST, PORT);
  2261. #endif
  2262. auto res = cli.Get("/aaa");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("Error", res->body);
  2266. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2267. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2268. }
  2269. }
  2270. TEST(RequestHandlerTest, PreRequestHandler) {
  2271. auto route_path = "/user/:user";
  2272. Server svr;
  2273. svr.Get("/hi", [](const Request &, Response &res) {
  2274. res.set_content("hi", "text/plain");
  2275. });
  2276. svr.Get(route_path, [](const Request &req, Response &res) {
  2277. res.set_content(req.path_params.at("user"), "text/plain");
  2278. });
  2279. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2280. if (req.matched_route == route_path) {
  2281. auto user = req.path_params.at("user");
  2282. if (user != "john") {
  2283. res.status = StatusCode::Forbidden_403;
  2284. res.set_content("error", "text/html");
  2285. return Server::HandlerResponse::Handled;
  2286. }
  2287. }
  2288. return Server::HandlerResponse::Unhandled;
  2289. });
  2290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2291. auto se = detail::scope_exit([&] {
  2292. svr.stop();
  2293. thread.join();
  2294. ASSERT_FALSE(svr.is_running());
  2295. });
  2296. svr.wait_until_ready();
  2297. Client cli(HOST, PORT);
  2298. {
  2299. auto res = cli.Get("/hi");
  2300. ASSERT_TRUE(res);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. EXPECT_EQ("hi", res->body);
  2303. }
  2304. {
  2305. auto res = cli.Get("/user/john");
  2306. ASSERT_TRUE(res);
  2307. EXPECT_EQ(StatusCode::OK_200, res->status);
  2308. EXPECT_EQ("john", res->body);
  2309. }
  2310. {
  2311. auto res = cli.Get("/user/invalid-user");
  2312. ASSERT_TRUE(res);
  2313. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2314. EXPECT_EQ("error", res->body);
  2315. }
  2316. }
  2317. TEST(InvalidFormatTest, StatusCode) {
  2318. Server svr;
  2319. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2320. res.set_content("Hello World!\n", "text/plain");
  2321. res.status = 9999; // Status should be a three-digit code...
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. Client cli(HOST, PORT);
  2332. auto res = cli.Get("/hi");
  2333. ASSERT_FALSE(res);
  2334. }
  2335. }
  2336. TEST(URLFragmentTest, WithFragment) {
  2337. Server svr;
  2338. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2339. EXPECT_TRUE(req.target == "/hi");
  2340. });
  2341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2342. auto se = detail::scope_exit([&] {
  2343. svr.stop();
  2344. thread.join();
  2345. ASSERT_FALSE(svr.is_running());
  2346. });
  2347. svr.wait_until_ready();
  2348. {
  2349. Client cli(HOST, PORT);
  2350. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2351. EXPECT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. res = cli.Get("/hi%23key1=val1=key2=val2");
  2354. EXPECT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2356. }
  2357. }
  2358. TEST(HeaderWriter, SetHeaderWriter) {
  2359. Server svr;
  2360. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2361. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2362. return detail::write_headers(strm, hdrs);
  2363. });
  2364. svr.Get("/hi", [](const Request &req, Response &res) {
  2365. auto it = req.headers.find("CustomClientHeader");
  2366. EXPECT_TRUE(it != req.headers.end());
  2367. EXPECT_EQ(it->second, "CustomClientValue");
  2368. res.set_content("Hello World!\n", "text/plain");
  2369. });
  2370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2371. auto se = detail::scope_exit([&] {
  2372. svr.stop();
  2373. thread.join();
  2374. ASSERT_FALSE(svr.is_running());
  2375. });
  2376. svr.wait_until_ready();
  2377. {
  2378. Client cli(HOST, PORT);
  2379. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2380. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2381. return detail::write_headers(strm, hdrs);
  2382. });
  2383. auto res = cli.Get("/hi");
  2384. EXPECT_TRUE(res);
  2385. EXPECT_EQ(StatusCode::OK_200, res->status);
  2386. auto it = res->headers.find("CustomServerHeader");
  2387. EXPECT_TRUE(it != res->headers.end());
  2388. EXPECT_EQ(it->second, "CustomServerValue");
  2389. }
  2390. }
  2391. class ServerTest : public ::testing::Test {
  2392. protected:
  2393. ServerTest()
  2394. : cli_(HOST, PORT)
  2395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2396. ,
  2397. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2398. #endif
  2399. {
  2400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2401. cli_.enable_server_certificate_verification(false);
  2402. #endif
  2403. }
  2404. virtual void SetUp() {
  2405. svr_.set_mount_point("/", "./www");
  2406. svr_.set_mount_point("/mount", "./www2");
  2407. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2408. svr_.Get("/hi",
  2409. [&](const Request & /*req*/, Response &res) {
  2410. res.set_content("Hello World!", "text/plain");
  2411. })
  2412. .Get("/file_content",
  2413. [&](const Request & /*req*/, Response &res) {
  2414. res.set_file_content("./www/dir/test.html");
  2415. })
  2416. .Get("/file_content_with_content_type",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. res.set_file_content("./www/file", "text/plain");
  2419. })
  2420. .Get("/invalid_file_content",
  2421. [&](const Request & /*req*/, Response &res) {
  2422. res.set_file_content("./www/dir/invalid_file_path");
  2423. })
  2424. .Get("/http_response_splitting",
  2425. [&](const Request & /*req*/, Response &res) {
  2426. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2427. EXPECT_EQ(0U, res.headers.size());
  2428. EXPECT_FALSE(res.has_header("a"));
  2429. res.set_header("a", "1\nSet-Cookie: a=1");
  2430. EXPECT_EQ(0U, res.headers.size());
  2431. EXPECT_FALSE(res.has_header("a"));
  2432. res.set_header("a", "1\rSet-Cookie: a=1");
  2433. EXPECT_EQ(0U, res.headers.size());
  2434. EXPECT_FALSE(res.has_header("a"));
  2435. res.set_header("a\r\nb", "0");
  2436. EXPECT_EQ(0U, res.headers.size());
  2437. EXPECT_FALSE(res.has_header("a"));
  2438. res.set_header("a\rb", "0");
  2439. EXPECT_EQ(0U, res.headers.size());
  2440. EXPECT_FALSE(res.has_header("a"));
  2441. res.set_header("a\nb", "0");
  2442. EXPECT_EQ(0U, res.headers.size());
  2443. EXPECT_FALSE(res.has_header("a"));
  2444. res.set_redirect("1\r\nSet-Cookie: a=1");
  2445. EXPECT_EQ(0U, res.headers.size());
  2446. EXPECT_FALSE(res.has_header("Location"));
  2447. })
  2448. .Get("/slow",
  2449. [&](const Request & /*req*/, Response &res) {
  2450. std::this_thread::sleep_for(std::chrono::seconds(2));
  2451. res.set_content("slow", "text/plain");
  2452. })
  2453. #if 0
  2454. .Post("/slowpost",
  2455. [&](const Request & /*req*/, Response &res) {
  2456. std::this_thread::sleep_for(std::chrono::seconds(2));
  2457. res.set_content("slow", "text/plain");
  2458. })
  2459. #endif
  2460. .Get("/remote_addr",
  2461. [&](const Request &req, Response &res) {
  2462. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2463. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2464. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2465. EXPECT_EQ(req.remote_port,
  2466. std::stoi(req.get_header_value("REMOTE_PORT")));
  2467. res.set_content(remote_addr.c_str(), "text/plain");
  2468. })
  2469. .Get("/local_addr",
  2470. [&](const Request &req, Response &res) {
  2471. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2472. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2473. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2474. auto local_port = req.get_header_value("LOCAL_PORT");
  2475. EXPECT_EQ(req.local_addr, local_addr);
  2476. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2477. res.set_content(local_addr.append(":").append(local_port),
  2478. "text/plain");
  2479. })
  2480. .Get("/endwith%",
  2481. [&](const Request & /*req*/, Response &res) {
  2482. res.set_content("Hello World!", "text/plain");
  2483. })
  2484. .Get("/a\\+\\+b",
  2485. [&](const Request &req, Response &res) {
  2486. ASSERT_TRUE(req.has_param("a +b"));
  2487. auto val = req.get_param_value("a +b");
  2488. res.set_content(val, "text/plain");
  2489. })
  2490. .Get("/", [&](const Request & /*req*/,
  2491. Response &res) { res.set_redirect("/hi"); })
  2492. .Post("/1",
  2493. [](const Request & /*req*/, Response &res) {
  2494. res.set_redirect("/2", StatusCode::SeeOther_303);
  2495. })
  2496. .Get("/2",
  2497. [](const Request & /*req*/, Response &res) {
  2498. res.set_content("redirected.", "text/plain");
  2499. res.status = StatusCode::OK_200;
  2500. })
  2501. .Post("/person",
  2502. [&](const Request &req, Response &res) {
  2503. if (req.has_param("name") && req.has_param("note")) {
  2504. persons_[req.get_param_value("name")] =
  2505. req.get_param_value("note");
  2506. } else {
  2507. res.status = StatusCode::BadRequest_400;
  2508. }
  2509. })
  2510. .Put("/person",
  2511. [&](const Request &req, Response &res) {
  2512. if (req.has_param("name") && req.has_param("note")) {
  2513. persons_[req.get_param_value("name")] =
  2514. req.get_param_value("note");
  2515. } else {
  2516. res.status = StatusCode::BadRequest_400;
  2517. }
  2518. })
  2519. .Get("/person/(.*)",
  2520. [&](const Request &req, Response &res) {
  2521. string name = req.matches[1];
  2522. if (persons_.find(name) != persons_.end()) {
  2523. auto note = persons_[name];
  2524. res.set_content(note, "text/plain");
  2525. } else {
  2526. res.status = StatusCode::NotFound_404;
  2527. }
  2528. })
  2529. .Delete("/person",
  2530. [&](const Request &req, Response &res) {
  2531. if (req.has_param("name")) {
  2532. string name = req.get_param_value("name");
  2533. if (persons_.find(name) != persons_.end()) {
  2534. persons_.erase(name);
  2535. res.set_content("DELETED", "text/plain");
  2536. } else {
  2537. res.status = StatusCode::NotFound_404;
  2538. }
  2539. } else {
  2540. res.status = StatusCode::BadRequest_400;
  2541. }
  2542. })
  2543. .Post("/x-www-form-urlencoded-json",
  2544. [&](const Request &req, Response &res) {
  2545. auto json = req.get_param_value("json");
  2546. ASSERT_EQ(JSON_DATA, json);
  2547. res.set_content(json, "appliation/json");
  2548. res.status = StatusCode::OK_200;
  2549. })
  2550. .Get("/streamed-chunked",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_chunked_content_provider(
  2553. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2554. sink.os << "123";
  2555. sink.os << "456";
  2556. sink.os << "789";
  2557. sink.done();
  2558. return true;
  2559. });
  2560. })
  2561. .Get("/streamed-chunked2",
  2562. [&](const Request & /*req*/, Response &res) {
  2563. auto i = new int(0);
  2564. res.set_chunked_content_provider(
  2565. "text/plain",
  2566. [i](size_t /*offset*/, DataSink &sink) {
  2567. switch (*i) {
  2568. case 0: sink.os << "123"; break;
  2569. case 1: sink.os << "456"; break;
  2570. case 2: sink.os << "789"; break;
  2571. case 3: sink.done(); break;
  2572. }
  2573. (*i)++;
  2574. return true;
  2575. },
  2576. [i](bool success) {
  2577. EXPECT_TRUE(success);
  2578. delete i;
  2579. });
  2580. })
  2581. .Get("/streamed-chunked-with-trailer",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. auto i = new int(0);
  2584. res.set_header("Trailer", "Dummy1, Dummy2");
  2585. res.set_chunked_content_provider(
  2586. "text/plain",
  2587. [i](size_t /*offset*/, DataSink &sink) {
  2588. switch (*i) {
  2589. case 0: sink.os << "123"; break;
  2590. case 1: sink.os << "456"; break;
  2591. case 2: sink.os << "789"; break;
  2592. case 3: {
  2593. sink.done_with_trailer(
  2594. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2595. } break;
  2596. }
  2597. (*i)++;
  2598. return true;
  2599. },
  2600. [i](bool success) {
  2601. EXPECT_TRUE(success);
  2602. delete i;
  2603. });
  2604. })
  2605. .Get("/streamed",
  2606. [&](const Request & /*req*/, Response &res) {
  2607. res.set_content_provider(
  2608. 6, "text/plain",
  2609. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2610. sink.os << (offset < 3 ? "a" : "b");
  2611. return true;
  2612. });
  2613. })
  2614. .Get("/streamed-with-range",
  2615. [&](const Request &req, Response &res) {
  2616. auto data = new std::string("abcdefg");
  2617. res.set_content_provider(
  2618. data->size(), "text/plain",
  2619. [data](size_t offset, size_t length, DataSink &sink) {
  2620. size_t DATA_CHUNK_SIZE = 4;
  2621. const auto &d = *data;
  2622. auto out_len =
  2623. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2624. auto ret =
  2625. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2626. EXPECT_TRUE(ret);
  2627. return true;
  2628. },
  2629. [data, &req](bool success) {
  2630. EXPECT_EQ(success, !req.has_param("error"));
  2631. delete data;
  2632. });
  2633. })
  2634. .Get("/streamed-cancel",
  2635. [&](const Request & /*req*/, Response &res) {
  2636. res.set_content_provider(
  2637. size_t(-1), "text/plain",
  2638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2639. sink.os << "data_chunk";
  2640. return true;
  2641. });
  2642. })
  2643. .Get("/regex-with-delimiter",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. ASSERT_TRUE(req.has_param("key"));
  2646. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2647. })
  2648. .Get("/with-range",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_content("abcdefg", "text/plain");
  2651. })
  2652. .Get("/test-start-time",
  2653. [&](const Request &req, Response & /*res*/) {
  2654. EXPECT_NE(req.start_time_,
  2655. std::chrono::steady_clock::time_point::min());
  2656. })
  2657. .Get("/with-range-customized-response",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. res.status = StatusCode::BadRequest_400;
  2660. res.set_content(JSON_DATA, "application/json");
  2661. })
  2662. .Post("/chunked",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. EXPECT_EQ(req.body, "dechunked post body");
  2665. })
  2666. .Post("/large-chunked",
  2667. [&](const Request &req, Response & /*res*/) {
  2668. std::string expected(6 * 30 * 1024u, 'a');
  2669. EXPECT_EQ(req.body, expected);
  2670. })
  2671. .Post("/multipart",
  2672. [&](const Request &req, Response & /*res*/) {
  2673. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2674. req.form.get_field_count("text2") +
  2675. req.form.get_field_count("file3") +
  2676. req.form.get_field_count("file4"));
  2677. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2678. req.form.get_file_count("file2"));
  2679. ASSERT_TRUE(!req.form.has_file("???"));
  2680. ASSERT_TRUE(!req.form.has_field("???"));
  2681. ASSERT_TRUE(req.body.empty());
  2682. {
  2683. const auto &text = req.form.get_field("text1");
  2684. EXPECT_EQ("text default", text);
  2685. }
  2686. {
  2687. const auto &text = req.form.get_field("text2");
  2688. EXPECT_EQ("aωb", text);
  2689. }
  2690. {
  2691. const auto &file = req.form.get_file("file1");
  2692. EXPECT_EQ("hello.txt", file.filename);
  2693. EXPECT_EQ("text/plain", file.content_type);
  2694. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2695. }
  2696. {
  2697. const auto &file = req.form.get_file("file2");
  2698. EXPECT_EQ("world.json", file.filename);
  2699. EXPECT_EQ("application/json", file.content_type);
  2700. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2701. }
  2702. {
  2703. const auto &text = req.form.get_field("file3");
  2704. EXPECT_EQ(0u, text.size());
  2705. }
  2706. {
  2707. const auto &text = req.form.get_field("file4");
  2708. EXPECT_EQ(0u, text.size());
  2709. }
  2710. })
  2711. .Post("/multipart/multi_file_values",
  2712. [&](const Request &req, Response & /*res*/) {
  2713. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2714. req.form.get_field_count("multi_text1"));
  2715. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2716. ASSERT_TRUE(!req.form.has_file("???"));
  2717. ASSERT_TRUE(!req.form.has_field("???"));
  2718. ASSERT_TRUE(req.body.empty());
  2719. {
  2720. const auto &text = req.form.get_field("text");
  2721. EXPECT_EQ("default text", text);
  2722. }
  2723. {
  2724. const auto &text1_values = req.form.get_fields("multi_text1");
  2725. EXPECT_EQ(2u, text1_values.size());
  2726. EXPECT_EQ("aaaaa", text1_values[0]);
  2727. EXPECT_EQ("bbbbb", text1_values[1]);
  2728. }
  2729. {
  2730. const auto &file1_values = req.form.get_files("multi_file1");
  2731. EXPECT_EQ(2u, file1_values.size());
  2732. auto file1 = file1_values[0];
  2733. EXPECT_EQ(file1.filename, "hello.txt");
  2734. EXPECT_EQ(file1.content_type, "text/plain");
  2735. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2736. auto file2 = file1_values[1];
  2737. EXPECT_EQ(file2.filename, "world.json");
  2738. EXPECT_EQ(file2.content_type, "application/json");
  2739. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2740. }
  2741. })
  2742. .Post("/empty",
  2743. [&](const Request &req, Response &res) {
  2744. EXPECT_EQ(req.body, "");
  2745. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2746. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2747. res.set_content("empty", "text/plain");
  2748. })
  2749. .Post("/empty-no-content-type",
  2750. [&](const Request &req, Response &res) {
  2751. EXPECT_EQ(req.body, "");
  2752. EXPECT_FALSE(req.has_header("Content-Type"));
  2753. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2754. res.set_content("empty-no-content-type", "text/plain");
  2755. })
  2756. .Post("/path-only",
  2757. [&](const Request &req, Response &res) {
  2758. EXPECT_EQ(req.body, "");
  2759. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2760. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2761. res.set_content("path-only", "text/plain");
  2762. })
  2763. .Post("/path-headers-only",
  2764. [&](const Request &req, Response &res) {
  2765. EXPECT_EQ(req.body, "");
  2766. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2767. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2768. EXPECT_EQ("world", req.get_header_value("hello"));
  2769. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2770. res.set_content("path-headers-only", "text/plain");
  2771. })
  2772. .Post("/post-large",
  2773. [&](const Request &req, Response &res) {
  2774. EXPECT_EQ(req.body, LARGE_DATA);
  2775. res.set_content(req.body, "text/plain");
  2776. })
  2777. .Put("/empty-no-content-type",
  2778. [&](const Request &req, Response &res) {
  2779. EXPECT_EQ(req.body, "");
  2780. EXPECT_FALSE(req.has_header("Content-Type"));
  2781. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2782. res.set_content("empty-no-content-type", "text/plain");
  2783. })
  2784. .Put("/put",
  2785. [&](const Request &req, Response &res) {
  2786. EXPECT_EQ(req.body, "PUT");
  2787. res.set_content(req.body, "text/plain");
  2788. })
  2789. .Put("/put-large",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, LARGE_DATA);
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Patch("/patch",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(req.body, "PATCH");
  2797. res.set_content(req.body, "text/plain");
  2798. })
  2799. .Delete("/delete",
  2800. [&](const Request & /*req*/, Response &res) {
  2801. res.set_content("DELETE", "text/plain");
  2802. })
  2803. .Delete("/delete-body",
  2804. [&](const Request &req, Response &res) {
  2805. EXPECT_EQ(req.body, "content");
  2806. res.set_content(req.body, "text/plain");
  2807. })
  2808. .Options(R"(\*)",
  2809. [&](const Request & /*req*/, Response &res) {
  2810. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2811. })
  2812. .Get("/request-target",
  2813. [&](const Request &req, Response & /*res*/) {
  2814. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2815. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2816. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2817. })
  2818. .Get("/long-query-value",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2821. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2822. })
  2823. .Get("/too-long-query-value",
  2824. [&](const Request &req, Response & /*res*/) {
  2825. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2826. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2827. })
  2828. .Get("/array-param",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2831. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2832. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2833. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2834. })
  2835. .Post("/validate-no-multiple-headers",
  2836. [&](const Request &req, Response & /*res*/) {
  2837. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2838. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2839. })
  2840. .Post("/content_receiver",
  2841. [&](const Request &req, Response &res,
  2842. const ContentReader &content_reader) {
  2843. if (req.is_multipart_form_data()) {
  2844. std::vector<FormData> items;
  2845. content_reader(
  2846. [&](const FormData &file) {
  2847. items.push_back(file);
  2848. return true;
  2849. },
  2850. [&](const char *data, size_t data_length) {
  2851. items.back().content.append(data, data_length);
  2852. return true;
  2853. });
  2854. EXPECT_EQ(5u, items.size());
  2855. {
  2856. const auto &file = get_file_value(items, "text1");
  2857. EXPECT_TRUE(file.filename.empty());
  2858. EXPECT_EQ("text default", file.content);
  2859. }
  2860. {
  2861. const auto &file = get_file_value(items, "text2");
  2862. EXPECT_TRUE(file.filename.empty());
  2863. EXPECT_EQ("aωb", file.content);
  2864. }
  2865. {
  2866. const auto &file = get_file_value(items, "file1");
  2867. EXPECT_EQ("hello.txt", file.filename);
  2868. EXPECT_EQ("text/plain", file.content_type);
  2869. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2870. }
  2871. {
  2872. const auto &file = get_file_value(items, "file2");
  2873. EXPECT_EQ("world.json", file.filename);
  2874. EXPECT_EQ("application/json", file.content_type);
  2875. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2876. }
  2877. {
  2878. const auto &file = get_file_value(items, "file3");
  2879. EXPECT_TRUE(file.filename.empty());
  2880. EXPECT_EQ("application/octet-stream", file.content_type);
  2881. EXPECT_EQ(0u, file.content.size());
  2882. }
  2883. } else {
  2884. std::string body;
  2885. content_reader([&](const char *data, size_t data_length) {
  2886. EXPECT_EQ(7U, data_length);
  2887. body.append(data, data_length);
  2888. return true;
  2889. });
  2890. EXPECT_EQ(body, "content");
  2891. res.set_content(body, "text/plain");
  2892. }
  2893. })
  2894. .Put("/content_receiver",
  2895. [&](const Request & /*req*/, Response &res,
  2896. const ContentReader &content_reader) {
  2897. std::string body;
  2898. content_reader([&](const char *data, size_t data_length) {
  2899. body.append(data, data_length);
  2900. return true;
  2901. });
  2902. EXPECT_EQ(body, "content");
  2903. res.set_content(body, "text/plain");
  2904. })
  2905. .Patch("/content_receiver",
  2906. [&](const Request & /*req*/, Response &res,
  2907. const ContentReader &content_reader) {
  2908. std::string body;
  2909. content_reader([&](const char *data, size_t data_length) {
  2910. body.append(data, data_length);
  2911. return true;
  2912. });
  2913. EXPECT_EQ(body, "content");
  2914. res.set_content(body, "text/plain");
  2915. })
  2916. .Post("/query-string-and-body",
  2917. [&](const Request &req, Response & /*res*/) {
  2918. ASSERT_TRUE(req.has_param("key"));
  2919. EXPECT_EQ(req.get_param_value("key"), "value");
  2920. EXPECT_EQ(req.body, "content");
  2921. })
  2922. .Get("/last-request",
  2923. [&](const Request &req, Response & /*res*/) {
  2924. EXPECT_EQ("close", req.get_header_value("Connection"));
  2925. })
  2926. .Get(R"(/redirect/(\d+))",
  2927. [&](const Request &req, Response &res) {
  2928. auto num = std::stoi(req.matches[1]) + 1;
  2929. std::string url = "/redirect/" + std::to_string(num);
  2930. res.set_redirect(url);
  2931. })
  2932. .Post("/binary",
  2933. [&](const Request &req, Response &res) {
  2934. EXPECT_EQ(4U, req.body.size());
  2935. EXPECT_EQ("application/octet-stream",
  2936. req.get_header_value("Content-Type"));
  2937. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2938. res.set_content(req.body, "application/octet-stream");
  2939. })
  2940. .Put("/binary",
  2941. [&](const Request &req, Response &res) {
  2942. EXPECT_EQ(4U, req.body.size());
  2943. EXPECT_EQ("application/octet-stream",
  2944. req.get_header_value("Content-Type"));
  2945. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2946. res.set_content(req.body, "application/octet-stream");
  2947. })
  2948. .Patch("/binary",
  2949. [&](const Request &req, Response &res) {
  2950. EXPECT_EQ(4U, req.body.size());
  2951. EXPECT_EQ("application/octet-stream",
  2952. req.get_header_value("Content-Type"));
  2953. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2954. res.set_content(req.body, "application/octet-stream");
  2955. })
  2956. .Delete("/binary",
  2957. [&](const Request &req, Response &res) {
  2958. EXPECT_EQ(4U, req.body.size());
  2959. EXPECT_EQ("application/octet-stream",
  2960. req.get_header_value("Content-Type"));
  2961. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2962. res.set_content(req.body, "application/octet-stream");
  2963. })
  2964. .Get("/issue1772",
  2965. [&](const Request & /*req*/, Response &res) {
  2966. res.status = 401;
  2967. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2968. })
  2969. .Delete("/issue609",
  2970. [](const httplib::Request &, httplib::Response &res,
  2971. const httplib::ContentReader &) {
  2972. res.set_content("ok", "text/plain");
  2973. })
  2974. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2975. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2976. .Get("/compress",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content(
  2979. "12345678901234567890123456789012345678901234567890123456789"
  2980. "01234567890123456789012345678901234567890",
  2981. "text/plain");
  2982. })
  2983. .Get("/nocompress",
  2984. [&](const Request & /*req*/, Response &res) {
  2985. res.set_content(
  2986. "12345678901234567890123456789012345678901234567890123456789"
  2987. "01234567890123456789012345678901234567890",
  2988. "application/octet-stream");
  2989. })
  2990. .Post("/compress-multipart",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. EXPECT_EQ(2u, req.form.fields.size());
  2993. ASSERT_TRUE(!req.form.has_field("???"));
  2994. {
  2995. const auto &text = req.form.get_field("key1");
  2996. EXPECT_EQ("test", text);
  2997. }
  2998. {
  2999. const auto &text = req.form.get_field("key2");
  3000. EXPECT_EQ("--abcdefg123", text);
  3001. }
  3002. })
  3003. #endif
  3004. ;
  3005. persons_["john"] = "programmer";
  3006. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3007. svr_.wait_until_ready();
  3008. }
  3009. virtual void TearDown() {
  3010. svr_.stop();
  3011. if (!request_threads_.empty()) {
  3012. std::this_thread::sleep_for(std::chrono::seconds(1));
  3013. for (auto &t : request_threads_) {
  3014. t.join();
  3015. }
  3016. }
  3017. t_.join();
  3018. }
  3019. map<string, string> persons_;
  3020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3021. SSLClient cli_;
  3022. SSLServer svr_;
  3023. #else
  3024. Client cli_;
  3025. Server svr_;
  3026. #endif
  3027. thread t_;
  3028. std::vector<thread> request_threads_;
  3029. };
  3030. TEST_F(ServerTest, GetMethod200) {
  3031. auto res = cli_.Get("/hi");
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ("HTTP/1.1", res->version);
  3034. EXPECT_EQ(StatusCode::OK_200, res->status);
  3035. EXPECT_EQ("OK", res->reason);
  3036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3037. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3038. EXPECT_EQ("Hello World!", res->body);
  3039. }
  3040. void performance_test(const char *host) {
  3041. auto port = 1234;
  3042. Server svr;
  3043. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3044. res.set_content("Benchmark Response", "text/plain");
  3045. });
  3046. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3047. auto se = detail::scope_exit([&] {
  3048. svr.stop();
  3049. listen_thread.join();
  3050. ASSERT_FALSE(svr.is_running());
  3051. });
  3052. svr.wait_until_ready();
  3053. Client cli(host, port);
  3054. auto start = std::chrono::high_resolution_clock::now();
  3055. auto res = cli.Get("/benchmark");
  3056. ASSERT_TRUE(res);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. auto end = std::chrono::high_resolution_clock::now();
  3059. auto elapsed =
  3060. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3061. .count();
  3062. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3063. << "ms (Issue #1777)";
  3064. }
  3065. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3066. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3067. TEST_F(ServerTest, GetEmptyFile) {
  3068. auto res = cli_.Get("/empty_file");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3072. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3073. EXPECT_EQ("", res->body);
  3074. }
  3075. TEST_F(ServerTest, GetFileContent) {
  3076. auto res = cli_.Get("/file_content");
  3077. ASSERT_TRUE(res);
  3078. EXPECT_EQ(StatusCode::OK_200, res->status);
  3079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3080. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3081. EXPECT_EQ("test.html", res->body);
  3082. }
  3083. TEST_F(ServerTest, GetFileContentWithRange) {
  3084. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3087. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3088. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3089. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3090. EXPECT_EQ("est", res->body);
  3091. }
  3092. TEST_F(ServerTest, GetFileContentWithContentType) {
  3093. auto res = cli_.Get("/file_content_with_content_type");
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3097. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3098. EXPECT_EQ("file\n", res->body);
  3099. }
  3100. TEST_F(ServerTest, GetInvalidFileContent) {
  3101. auto res = cli_.Get("/invalid_file_content");
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3104. }
  3105. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3106. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3107. ASSERT_TRUE(res);
  3108. EXPECT_EQ("HTTP/1.1", res->version);
  3109. EXPECT_EQ(StatusCode::OK_200, res->status);
  3110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3111. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3112. EXPECT_EQ("Hello World!", res->body);
  3113. }
  3114. TEST_F(ServerTest, GetMethod302) {
  3115. auto res = cli_.Get("/");
  3116. ASSERT_TRUE(res);
  3117. EXPECT_EQ(StatusCode::Found_302, res->status);
  3118. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3119. }
  3120. TEST_F(ServerTest, GetMethod302Redirect) {
  3121. cli_.set_follow_location(true);
  3122. auto res = cli_.Get("/");
  3123. ASSERT_TRUE(res);
  3124. EXPECT_EQ(StatusCode::OK_200, res->status);
  3125. EXPECT_EQ("Hello World!", res->body);
  3126. EXPECT_EQ("/hi", res->location);
  3127. }
  3128. TEST_F(ServerTest, GetMethod404) {
  3129. auto res = cli_.Get("/invalid");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3132. }
  3133. TEST_F(ServerTest, HeadMethod200) {
  3134. auto res = cli_.Head("/hi");
  3135. ASSERT_TRUE(res);
  3136. EXPECT_EQ(StatusCode::OK_200, res->status);
  3137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3138. EXPECT_TRUE(res->body.empty());
  3139. }
  3140. TEST_F(ServerTest, HeadMethod200Static) {
  3141. auto res = cli_.Head("/mount/dir/index.html");
  3142. ASSERT_TRUE(res);
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3145. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3146. EXPECT_TRUE(res->body.empty());
  3147. }
  3148. TEST_F(ServerTest, HeadMethod404) {
  3149. auto res = cli_.Head("/invalid");
  3150. ASSERT_TRUE(res);
  3151. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3152. EXPECT_TRUE(res->body.empty());
  3153. }
  3154. TEST_F(ServerTest, GetMethodPersonJohn) {
  3155. auto res = cli_.Get("/person/john");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(StatusCode::OK_200, res->status);
  3158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("programmer", res->body);
  3160. }
  3161. TEST_F(ServerTest, PostMethod1) {
  3162. auto res = cli_.Get("/person/john1");
  3163. ASSERT_TRUE(res);
  3164. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3165. res = cli_.Post("/person", "name=john1&note=coder",
  3166. "application/x-www-form-urlencoded");
  3167. ASSERT_TRUE(res);
  3168. ASSERT_EQ(StatusCode::OK_200, res->status);
  3169. res = cli_.Get("/person/john1");
  3170. ASSERT_TRUE(res);
  3171. ASSERT_EQ(StatusCode::OK_200, res->status);
  3172. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3173. ASSERT_EQ("coder", res->body);
  3174. }
  3175. TEST_F(ServerTest, PostMethod2) {
  3176. auto res = cli_.Get("/person/john2");
  3177. ASSERT_TRUE(res);
  3178. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3179. Params params;
  3180. params.emplace("name", "john2");
  3181. params.emplace("note", "coder");
  3182. res = cli_.Post("/person", params);
  3183. ASSERT_TRUE(res);
  3184. ASSERT_EQ(StatusCode::OK_200, res->status);
  3185. res = cli_.Get("/person/john2");
  3186. ASSERT_TRUE(res);
  3187. ASSERT_EQ(StatusCode::OK_200, res->status);
  3188. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. ASSERT_EQ("coder", res->body);
  3190. }
  3191. TEST_F(ServerTest, PutMethod3) {
  3192. auto res = cli_.Get("/person/john3");
  3193. ASSERT_TRUE(res);
  3194. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3195. Params params;
  3196. params.emplace("name", "john3");
  3197. params.emplace("note", "coder");
  3198. res = cli_.Put("/person", params);
  3199. ASSERT_TRUE(res);
  3200. ASSERT_EQ(StatusCode::OK_200, res->status);
  3201. res = cli_.Get("/person/john3");
  3202. ASSERT_TRUE(res);
  3203. ASSERT_EQ(StatusCode::OK_200, res->status);
  3204. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3205. ASSERT_EQ("coder", res->body);
  3206. }
  3207. TEST_F(ServerTest, DeleteMethod1) {
  3208. auto res = cli_.Get("/person/john4");
  3209. ASSERT_TRUE(res);
  3210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3211. Params params;
  3212. params.emplace("name", "john4");
  3213. params.emplace("note", "coder");
  3214. res = cli_.Post("/person", params);
  3215. ASSERT_TRUE(res);
  3216. ASSERT_EQ(StatusCode::OK_200, res->status);
  3217. res = cli_.Get("/person/john4");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::OK_200, res->status);
  3220. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3221. ASSERT_EQ("coder", res->body);
  3222. Params delete_params;
  3223. delete_params.emplace("name", "john4");
  3224. res = cli_.Delete("/person", delete_params);
  3225. ASSERT_TRUE(res);
  3226. ASSERT_EQ(StatusCode::OK_200, res->status);
  3227. ASSERT_EQ("DELETED", res->body);
  3228. res = cli_.Get("/person/john4");
  3229. ASSERT_TRUE(res);
  3230. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3231. }
  3232. TEST_F(ServerTest, DeleteMethod2) {
  3233. auto res = cli_.Get("/person/john5");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. Params params;
  3237. params.emplace("name", "john5");
  3238. params.emplace("note", "developer");
  3239. res = cli_.Post("/person", params);
  3240. ASSERT_TRUE(res);
  3241. ASSERT_EQ(StatusCode::OK_200, res->status);
  3242. res = cli_.Get("/person/john5");
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3246. ASSERT_EQ("developer", res->body);
  3247. Params delete_params;
  3248. delete_params.emplace("name", "john5");
  3249. Headers headers;
  3250. headers.emplace("Custom-Header", "test-value");
  3251. res = cli_.Delete("/person", headers, delete_params);
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::OK_200, res->status);
  3254. ASSERT_EQ("DELETED", res->body);
  3255. res = cli_.Get("/person/john5");
  3256. ASSERT_TRUE(res);
  3257. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3258. }
  3259. TEST_F(ServerTest, DeleteMethod3) {
  3260. auto res = cli_.Get("/person/john6");
  3261. ASSERT_TRUE(res);
  3262. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3263. Params params;
  3264. params.emplace("name", "john6");
  3265. params.emplace("note", "tester");
  3266. res = cli_.Post("/person", params);
  3267. ASSERT_TRUE(res);
  3268. ASSERT_EQ(StatusCode::OK_200, res->status);
  3269. res = cli_.Get("/person/john6");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3273. ASSERT_EQ("tester", res->body);
  3274. Params delete_params;
  3275. delete_params.emplace("name", "john6");
  3276. Headers headers;
  3277. headers.emplace("Custom-Header", "test-value");
  3278. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3279. ASSERT_TRUE(res);
  3280. ASSERT_EQ(StatusCode::OK_200, res->status);
  3281. ASSERT_EQ("DELETED", res->body);
  3282. res = cli_.Get("/person/john6");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3285. }
  3286. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3287. Params params;
  3288. params.emplace("json", JSON_DATA);
  3289. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3290. ASSERT_TRUE(res);
  3291. ASSERT_EQ(StatusCode::OK_200, res->status);
  3292. ASSERT_EQ(JSON_DATA, res->body);
  3293. }
  3294. TEST_F(ServerTest, PostEmptyContent) {
  3295. auto res = cli_.Post("/empty", "", "text/plain");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("empty", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3301. auto res = cli_.Post("/empty-no-content-type");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::OK_200, res->status);
  3304. ASSERT_EQ("empty-no-content-type", res->body);
  3305. }
  3306. TEST_F(ServerTest, PostPathOnly) {
  3307. auto res = cli_.Post("/path-only");
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. ASSERT_EQ("path-only", res->body);
  3311. }
  3312. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3313. auto res = cli_.Post("/path-headers-only",
  3314. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3315. ASSERT_TRUE(res);
  3316. ASSERT_EQ(StatusCode::OK_200, res->status);
  3317. ASSERT_EQ("path-headers-only", res->body);
  3318. }
  3319. TEST_F(ServerTest, PostLarge) {
  3320. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3321. ASSERT_TRUE(res);
  3322. ASSERT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ(LARGE_DATA, res->body);
  3324. }
  3325. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3326. auto res = cli_.Put("/empty-no-content-type");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("empty-no-content-type", res->body);
  3330. }
  3331. TEST_F(ServerTest, GetMethodDir) {
  3332. auto res = cli_.Get("/dir/");
  3333. ASSERT_TRUE(res);
  3334. EXPECT_EQ(StatusCode::OK_200, res->status);
  3335. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3336. auto body = R"(<html>
  3337. <head>
  3338. </head>
  3339. <body>
  3340. <a href="/dir/test.html">Test</a>
  3341. <a href="/hi">hi</a>
  3342. </body>
  3343. </html>
  3344. )";
  3345. EXPECT_EQ(body, res->body);
  3346. }
  3347. TEST_F(ServerTest, GetMethodDirTest) {
  3348. auto res = cli_.Get("/dir/test.html");
  3349. ASSERT_TRUE(res);
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3352. EXPECT_EQ("test.html", res->body);
  3353. }
  3354. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3355. auto res = cli_.Get("/dir/../dir/test.html");
  3356. ASSERT_TRUE(res);
  3357. EXPECT_EQ(StatusCode::OK_200, res->status);
  3358. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3359. EXPECT_EQ("test.html", res->body);
  3360. }
  3361. TEST_F(ServerTest, GetMethodInvalidPath) {
  3362. auto res = cli_.Get("/dir/../test.html");
  3363. ASSERT_TRUE(res);
  3364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3365. }
  3366. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3367. auto res = cli_.Get("/../www/dir/test.html");
  3368. ASSERT_TRUE(res);
  3369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3370. }
  3371. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3372. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3375. }
  3376. TEST_F(ServerTest, GetMethodDirMountTest) {
  3377. auto res = cli_.Get("/mount/dir/test.html");
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3381. EXPECT_EQ("test.html", res->body);
  3382. }
  3383. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3384. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(StatusCode::OK_200, res->status);
  3387. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3388. EXPECT_EQ("test.html", res->body);
  3389. }
  3390. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3391. auto res = cli_.Get("/mount/dir/../test.html");
  3392. ASSERT_TRUE(res);
  3393. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3394. }
  3395. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3396. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3397. ASSERT_TRUE(res);
  3398. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3399. }
  3400. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3401. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3404. }
  3405. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3406. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3407. ASSERT_TRUE(res);
  3408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3409. }
  3410. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3411. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3414. }
  3415. TEST_F(ServerTest, PostMethod303) {
  3416. auto res = cli_.Post("/1", "body", "text/plain");
  3417. ASSERT_TRUE(res);
  3418. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3419. EXPECT_EQ("/2", res->get_header_value("Location"));
  3420. }
  3421. TEST_F(ServerTest, PostMethod303Redirect) {
  3422. cli_.set_follow_location(true);
  3423. auto res = cli_.Post("/1", "body", "text/plain");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("redirected.", res->body);
  3427. EXPECT_EQ("/2", res->location);
  3428. }
  3429. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3430. auto res = cli_.Get("/dir/test.abcde");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ("abcde", res->body);
  3435. }
  3436. TEST_F(ServerTest, StaticFileRange) {
  3437. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3440. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3442. EXPECT_EQ(true, res->has_header("Content-Range"));
  3443. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3444. EXPECT_EQ(std::string("cd"), res->body);
  3445. }
  3446. TEST_F(ServerTest, StaticFileRanges) {
  3447. auto res =
  3448. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3451. EXPECT_TRUE(
  3452. res->get_header_value("Content-Type")
  3453. .find(
  3454. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3455. 0);
  3456. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3457. }
  3458. TEST_F(ServerTest, StaticFileRangeHead) {
  3459. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3462. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3463. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3464. EXPECT_EQ(true, res->has_header("Content-Range"));
  3465. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3466. }
  3467. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3468. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3473. EXPECT_EQ(true, res->has_header("Content-Range"));
  3474. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3475. res->get_header_value("Content-Range"));
  3476. EXPECT_EQ("LAST\n", res->body);
  3477. }
  3478. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3479. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3480. ASSERT_TRUE(res);
  3481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3483. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3484. EXPECT_EQ(true, res->has_header("Content-Range"));
  3485. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3486. }
  3487. TEST_F(ServerTest, StaticFileBigFile) {
  3488. auto res = cli_.Get("/dir/1MB.txt");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3493. }
  3494. TEST_F(ServerTest, InvalidBaseDirMount) {
  3495. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3496. }
  3497. TEST_F(ServerTest, Binary) {
  3498. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3499. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3500. "application/octet-stream");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ(4U, res->body.size());
  3504. res = cli_.Put("/binary", binary.data(), binary.size(),
  3505. "application/octet-stream");
  3506. ASSERT_TRUE(res);
  3507. ASSERT_EQ(StatusCode::OK_200, res->status);
  3508. ASSERT_EQ(4U, res->body.size());
  3509. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3510. "application/octet-stream");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::OK_200, res->status);
  3513. ASSERT_EQ(4U, res->body.size());
  3514. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3515. "application/octet-stream");
  3516. ASSERT_TRUE(res);
  3517. ASSERT_EQ(StatusCode::OK_200, res->status);
  3518. ASSERT_EQ(4U, res->body.size());
  3519. }
  3520. TEST_F(ServerTest, BinaryString) {
  3521. auto binary = std::string("\x00\x01\x02\x03", 4);
  3522. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3523. ASSERT_TRUE(res);
  3524. ASSERT_EQ(StatusCode::OK_200, res->status);
  3525. ASSERT_EQ(4U, res->body.size());
  3526. res = cli_.Put("/binary", binary, "application/octet-stream");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::OK_200, res->status);
  3529. ASSERT_EQ(4U, res->body.size());
  3530. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. ASSERT_EQ(4U, res->body.size());
  3534. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. ASSERT_EQ(4U, res->body.size());
  3538. }
  3539. TEST_F(ServerTest, EmptyRequest) {
  3540. auto res = cli_.Get("");
  3541. ASSERT_TRUE(!res);
  3542. EXPECT_EQ(Error::Connection, res.error());
  3543. }
  3544. TEST_F(ServerTest, LongRequest) {
  3545. std::string request;
  3546. for (size_t i = 0; i < 545; i++) {
  3547. request += "/TooLongRequest";
  3548. }
  3549. request += "OK";
  3550. auto res = cli_.Get(request.c_str());
  3551. ASSERT_TRUE(res);
  3552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3553. }
  3554. TEST_F(ServerTest, TooLongRequest) {
  3555. std::string request;
  3556. for (size_t i = 0; i < 546; i++) {
  3557. request += "/TooLongRequest";
  3558. }
  3559. request += "_NG";
  3560. auto res = cli_.Get(request.c_str());
  3561. ASSERT_TRUE(res);
  3562. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3563. }
  3564. TEST_F(ServerTest, AlmostTooLongRequest) {
  3565. // test for #2046 - URI length check shouldn't include other content on req
  3566. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3567. // leading /, space, HTTP/1.1)
  3568. std::string request =
  3569. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3570. auto res = cli_.Get(request.c_str());
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, LongHeader) {
  3575. Request req;
  3576. req.method = "GET";
  3577. req.path = "/hi";
  3578. std::string host_and_port;
  3579. host_and_port += HOST;
  3580. host_and_port += ":";
  3581. host_and_port += std::to_string(PORT);
  3582. req.headers.emplace("Host", host_and_port.c_str());
  3583. req.headers.emplace("Accept", "*/*");
  3584. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3585. req.headers.emplace(
  3586. "Header-Name",
  3587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@");
  3616. auto res = std::make_shared<Response>();
  3617. auto error = Error::Success;
  3618. auto ret = cli_.send(req, *res, error);
  3619. ASSERT_TRUE(ret);
  3620. EXPECT_EQ(StatusCode::OK_200, res->status);
  3621. }
  3622. TEST_F(ServerTest, LongQueryValue) {
  3623. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3626. }
  3627. TEST_F(ServerTest, TooLongQueryValue) {
  3628. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3629. ASSERT_FALSE(res);
  3630. EXPECT_EQ(Error::Read, res.error());
  3631. }
  3632. TEST_F(ServerTest, TooLongHeader) {
  3633. Request req;
  3634. req.method = "GET";
  3635. req.path = "/hi";
  3636. std::string host_and_port;
  3637. host_and_port += HOST;
  3638. host_and_port += ":";
  3639. host_and_port += std::to_string(PORT);
  3640. req.headers.emplace("Host", host_and_port.c_str());
  3641. req.headers.emplace("Accept", "*/*");
  3642. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3643. req.headers.emplace(
  3644. "Header-Name",
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@");
  3674. auto res = std::make_shared<Response>();
  3675. auto error = Error::Success;
  3676. auto ret = cli_.send(req, *res, error);
  3677. ASSERT_TRUE(ret);
  3678. EXPECT_EQ(StatusCode::OK_200, res->status);
  3679. }
  3680. TEST_F(ServerTest, HeaderCountAtLimit) {
  3681. // Test with headers just under the 100 limit
  3682. httplib::Headers headers;
  3683. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3684. // This should keep us just under the 100 header limit
  3685. for (int i = 0; i < 95; i++) {
  3686. std::string name = "X-Test-Header-" + std::to_string(i);
  3687. std::string value = "value" + std::to_string(i);
  3688. headers.emplace(name, value);
  3689. }
  3690. // This should work fine as we're under the limit
  3691. auto res = cli_.Get("/hi", headers);
  3692. EXPECT_TRUE(res);
  3693. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3694. }
  3695. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3696. // Test with many headers to exceed the 100 limit
  3697. httplib::Headers headers;
  3698. // Add 150 headers to definitely exceed the 100 limit
  3699. for (int i = 0; i < 150; i++) {
  3700. std::string name = "X-Test-Header-" + std::to_string(i);
  3701. std::string value = "value" + std::to_string(i);
  3702. headers.emplace(name, value);
  3703. }
  3704. // This should fail due to exceeding header count limit
  3705. auto res = cli_.Get("/hi", headers);
  3706. // The request should either fail or return 400 Bad Request
  3707. if (res) {
  3708. // If we get a response, it should be 400 Bad Request
  3709. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3710. } else {
  3711. // Or the request should fail entirely
  3712. EXPECT_FALSE(res);
  3713. }
  3714. }
  3715. TEST_F(ServerTest, PercentEncoding) {
  3716. auto res = cli_.Get("/e%6edwith%");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::OK_200, res->status);
  3719. }
  3720. TEST_F(ServerTest, PercentEncodingUnicode) {
  3721. auto res = cli_.Get("/e%u006edwith%");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. }
  3725. TEST_F(ServerTest, InvalidPercentEncoding) {
  3726. auto res = cli_.Get("/%endwith%");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3731. auto res = cli_.Get("/%uendwith%");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3734. }
  3735. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3736. auto res = cli_.Get("/hello?aaa=bbb%");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3739. }
  3740. TEST_F(ServerTest, PlusSignEncoding) {
  3741. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. EXPECT_EQ("a +b", res->body);
  3745. }
  3746. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3747. // This test simulates a potential DoS attack using many headers
  3748. // to verify our security fix prevents memory exhaustion
  3749. httplib::Headers attack_headers;
  3750. // Attempt to add many headers like an attacker would (200 headers to far
  3751. // exceed limit)
  3752. for (int i = 0; i < 200; i++) {
  3753. std::string name = "X-Attack-Header-" + std::to_string(i);
  3754. std::string value = "attack_payload_" + std::to_string(i);
  3755. attack_headers.emplace(name, value);
  3756. }
  3757. // Try to POST with excessive headers
  3758. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3759. // Should either fail or return 400 Bad Request due to security limit
  3760. if (res) {
  3761. // If we get a response, it should be 400 Bad Request
  3762. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3763. } else {
  3764. // Request failed, which is the expected behavior for DoS protection
  3765. EXPECT_FALSE(res);
  3766. }
  3767. }
  3768. TEST_F(ServerTest, MultipartFormData) {
  3769. UploadFormDataItems items = {
  3770. {"text1", "text default", "", ""},
  3771. {"text2", "aωb", "", ""},
  3772. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3773. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3774. {"file3", "", "", "application/octet-stream"},
  3775. {"file4", "", "", " application/json tmp-string "}};
  3776. auto res = cli_.Post("/multipart", items);
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::OK_200, res->status);
  3779. }
  3780. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3781. UploadFormDataItems items = {
  3782. {"text", "default text", "", ""},
  3783. {"multi_text1", "aaaaa", "", ""},
  3784. {"multi_text1", "bbbbb", "", ""},
  3785. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3786. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3787. "application/json"},
  3788. };
  3789. auto res = cli_.Post("/multipart/multi_file_values", items);
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. }
  3793. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3794. auto res = cli_.Get("/hi");
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3798. EXPECT_EQ("Hello World!", res->body);
  3799. }
  3800. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3801. Request req;
  3802. req.method = "POST";
  3803. req.path = "/chunked";
  3804. std::string host_and_port;
  3805. host_and_port += HOST;
  3806. host_and_port += ":";
  3807. host_and_port += std::to_string(PORT);
  3808. req.headers.emplace("Host", host_and_port.c_str());
  3809. req.headers.emplace("Accept", "*/*");
  3810. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3811. req.headers.emplace("Content-Type", "text/plain");
  3812. req.headers.emplace("Content-Length", "0");
  3813. req.headers.emplace(
  3814. "Transfer-Encoding",
  3815. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3816. // Client does not chunk, so make a chunked body manually.
  3817. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3818. auto res = std::make_shared<Response>();
  3819. auto error = Error::Success;
  3820. auto ret = cli_.send(req, *res, error);
  3821. ASSERT_TRUE(ret);
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. }
  3824. TEST_F(ServerTest, GetStreamed2) {
  3825. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3826. ASSERT_TRUE(res);
  3827. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3829. EXPECT_EQ(true, res->has_header("Content-Range"));
  3830. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3831. EXPECT_EQ(std::string("ab"), res->body);
  3832. }
  3833. TEST_F(ServerTest, GetStreamed) {
  3834. auto res = cli_.Get("/streamed");
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(std::string("aaabbb"), res->body);
  3839. }
  3840. TEST_F(ServerTest, GetStreamedWithRange1) {
  3841. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3844. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3847. EXPECT_EQ(std::string("def"), res->body);
  3848. }
  3849. TEST_F(ServerTest, GetStreamedWithRange2) {
  3850. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3851. ASSERT_TRUE(res);
  3852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3853. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ(true, res->has_header("Content-Range"));
  3855. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3856. EXPECT_EQ(std::string("bcdefg"), res->body);
  3857. }
  3858. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3859. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3862. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3863. EXPECT_EQ(true, res->has_header("Content-Range"));
  3864. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3865. EXPECT_EQ(std::string("efg"), res->body);
  3866. }
  3867. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3868. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3871. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3872. EXPECT_EQ(false, res->has_header("Content-Range"));
  3873. EXPECT_EQ(0U, res->body.size());
  3874. }
  3875. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3876. auto res = cli_.Get("/streamed-with-range",
  3877. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3878. "92233720368547758079223372036854775807"}});
  3879. ASSERT_TRUE(res);
  3880. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3881. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3882. EXPECT_EQ(false, res->has_header("Content-Range"));
  3883. EXPECT_EQ(0U, res->body.size());
  3884. }
  3885. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3886. auto res = cli_.Get(
  3887. "/with-range",
  3888. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3889. {"Accept-Encoding", ""}});
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3892. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3893. EXPECT_EQ(true, res->has_header("Content-Range"));
  3894. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3895. EXPECT_EQ(std::string("abcdefg"), res->body);
  3896. }
  3897. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3898. auto res = cli_.Get("/with-range", {
  3899. {"Range", "bytes=0-"},
  3900. {"Accept-Encoding", ""},
  3901. });
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3904. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3905. EXPECT_EQ(true, res->has_header("Content-Range"));
  3906. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3907. EXPECT_EQ(std::string("abcdefg"), res->body);
  3908. }
  3909. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3910. auto res =
  3911. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3914. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3915. EXPECT_EQ(false, res->has_header("Content-Range"));
  3916. EXPECT_EQ(267U, res->body.size());
  3917. // Check that both range contents are present
  3918. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3919. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3920. // Check that Content-Range headers are present for both ranges
  3921. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3922. std::string::npos);
  3923. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3924. std::string::npos);
  3925. }
  3926. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3927. Ranges ranges;
  3928. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3929. ranges.emplace_back(0, -1);
  3930. }
  3931. auto res =
  3932. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3933. ASSERT_TRUE(res);
  3934. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3935. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3936. EXPECT_EQ(false, res->has_header("Content-Range"));
  3937. EXPECT_EQ(0U, res->body.size());
  3938. }
  3939. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3940. auto res =
  3941. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3942. ASSERT_TRUE(res);
  3943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3944. EXPECT_EQ(5U, res->body.size());
  3945. // Check that overlapping ranges are coalesced into a single range
  3946. EXPECT_EQ("bcdef", res->body);
  3947. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3948. // Should be single range, not multipart
  3949. EXPECT_TRUE(res->has_header("Content-Range"));
  3950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3951. }
  3952. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3953. auto res =
  3954. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ(268U, res->body.size());
  3958. // Check that both range contents are present
  3959. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3960. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3961. // Check that Content-Range headers are present for both ranges
  3962. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3963. std::string::npos);
  3964. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3965. std::string::npos);
  3966. }
  3967. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3968. auto res =
  3969. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ(269U, res->body.size());
  3973. // Check that both duplicate range contents are present
  3974. size_t first_abc = res->body.find("abc\r\n");
  3975. EXPECT_TRUE(first_abc != std::string::npos);
  3976. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3977. EXPECT_TRUE(second_abc != std::string::npos);
  3978. // Check that Content-Range headers are present for both ranges
  3979. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3980. EXPECT_TRUE(first_range != std::string::npos);
  3981. size_t second_range =
  3982. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3983. EXPECT_TRUE(second_range != std::string::npos);
  3984. }
  3985. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3986. auto res = cli_.Get("/streamed-with-range?error",
  3987. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3990. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3991. EXPECT_EQ(false, res->has_header("Content-Range"));
  3992. EXPECT_EQ(0U, res->body.size());
  3993. }
  3994. TEST_F(ServerTest, GetStreamedEndless) {
  3995. uint64_t offset = 0;
  3996. auto res = cli_.Get("/streamed-cancel",
  3997. [&](const char * /*data*/, uint64_t data_length) {
  3998. if (offset < 100) {
  3999. offset += data_length;
  4000. return true;
  4001. }
  4002. return false;
  4003. });
  4004. ASSERT_TRUE(!res);
  4005. EXPECT_EQ(Error::Canceled, res.error());
  4006. }
  4007. TEST_F(ServerTest, ClientStop) {
  4008. std::atomic_size_t count{4};
  4009. std::vector<std::thread> threads;
  4010. for (auto i = count.load(); i != 0; --i) {
  4011. threads.emplace_back([&]() {
  4012. auto res = cli_.Get("/streamed-cancel",
  4013. [&](const char *, uint64_t) { return true; });
  4014. --count;
  4015. ASSERT_TRUE(!res);
  4016. EXPECT_TRUE(res.error() == Error::Canceled ||
  4017. res.error() == Error::Read || res.error() == Error::Write);
  4018. });
  4019. }
  4020. std::this_thread::sleep_for(std::chrono::seconds(2));
  4021. while (count != 0) {
  4022. cli_.stop();
  4023. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4024. }
  4025. for (auto &t : threads) {
  4026. t.join();
  4027. }
  4028. }
  4029. TEST_F(ServerTest, GetWithRange1) {
  4030. auto res = cli_.Get("/with-range", {
  4031. make_range_header({{3, 5}}),
  4032. {"Accept-Encoding", ""},
  4033. });
  4034. ASSERT_TRUE(res);
  4035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4036. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4037. EXPECT_EQ(true, res->has_header("Content-Range"));
  4038. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4039. EXPECT_EQ(std::string("def"), res->body);
  4040. }
  4041. TEST_F(ServerTest, GetWithRange2) {
  4042. auto res = cli_.Get("/with-range", {
  4043. make_range_header({{1, -1}}),
  4044. {"Accept-Encoding", ""},
  4045. });
  4046. ASSERT_TRUE(res);
  4047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4048. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4049. EXPECT_EQ(true, res->has_header("Content-Range"));
  4050. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4051. EXPECT_EQ(std::string("bcdefg"), res->body);
  4052. }
  4053. TEST_F(ServerTest, GetWithRange3) {
  4054. auto res = cli_.Get("/with-range", {
  4055. make_range_header({{0, 0}}),
  4056. {"Accept-Encoding", ""},
  4057. });
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4060. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ(true, res->has_header("Content-Range"));
  4062. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4063. EXPECT_EQ(std::string("a"), res->body);
  4064. }
  4065. TEST_F(ServerTest, GetWithRange4) {
  4066. auto res = cli_.Get("/with-range", {
  4067. make_range_header({{-1, 2}}),
  4068. {"Accept-Encoding", ""},
  4069. });
  4070. ASSERT_TRUE(res);
  4071. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4072. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4073. EXPECT_EQ(true, res->has_header("Content-Range"));
  4074. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4075. EXPECT_EQ(std::string("fg"), res->body);
  4076. }
  4077. TEST_F(ServerTest, GetWithRange5) {
  4078. auto res = cli_.Get("/with-range", {
  4079. make_range_header({{0, 5}}),
  4080. {"Accept-Encoding", ""},
  4081. });
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4084. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(true, res->has_header("Content-Range"));
  4086. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4087. EXPECT_EQ(std::string("abcdef"), res->body);
  4088. }
  4089. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4090. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4093. }
  4094. TEST_F(ServerTest, GetWithRangeMultipart) {
  4095. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4096. ASSERT_TRUE(res);
  4097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4098. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4099. EXPECT_EQ(false, res->has_header("Content-Range"));
  4100. EXPECT_EQ(267U, res->body.size());
  4101. }
  4102. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4103. auto res =
  4104. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4107. }
  4108. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4109. auto res = cli_.Get("/with-range-customized-response",
  4110. {{make_range_header({{1, 2}})}});
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4113. EXPECT_EQ(true, res->has_header("Content-Length"));
  4114. EXPECT_EQ(false, res->has_header("Content-Range"));
  4115. EXPECT_EQ(JSON_DATA, res->body);
  4116. }
  4117. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4118. auto res = cli_.Get("/with-range-customized-response",
  4119. {{make_range_header({{1, 2}, {4, 5}})}});
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4122. EXPECT_EQ(true, res->has_header("Content-Length"));
  4123. EXPECT_EQ(false, res->has_header("Content-Range"));
  4124. EXPECT_EQ(JSON_DATA, res->body);
  4125. }
  4126. TEST_F(ServerTest, Issue1772) {
  4127. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4130. }
  4131. TEST_F(ServerTest, Issue609) {
  4132. auto res = cli_.Delete("/issue609");
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::OK_200, res->status);
  4135. EXPECT_EQ(std::string("ok"), res->body);
  4136. }
  4137. TEST_F(ServerTest, GetStreamedChunked) {
  4138. auto res = cli_.Get("/streamed-chunked");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. EXPECT_EQ(std::string("123456789"), res->body);
  4142. }
  4143. TEST_F(ServerTest, GetStreamedChunked2) {
  4144. auto res = cli_.Get("/streamed-chunked2");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ(std::string("123456789"), res->body);
  4148. }
  4149. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4150. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4151. ASSERT_TRUE(res);
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ(std::string("123456789"), res->body);
  4154. EXPECT_TRUE(res->has_header("Trailer"));
  4155. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4156. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4157. // Trailers are now stored separately from headers (security fix)
  4158. EXPECT_EQ(2U, res->trailers.size());
  4159. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4160. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4161. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4162. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4163. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4164. // Verify trailers are NOT in headers (security verification)
  4165. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4166. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4167. }
  4168. TEST_F(ServerTest, LargeChunkedPost) {
  4169. Request req;
  4170. req.method = "POST";
  4171. req.path = "/large-chunked";
  4172. std::string host_and_port;
  4173. host_and_port += HOST;
  4174. host_and_port += ":";
  4175. host_and_port += std::to_string(PORT);
  4176. req.headers.emplace("Host", host_and_port.c_str());
  4177. req.headers.emplace("Accept", "*/*");
  4178. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4179. req.headers.emplace("Content-Type", "text/plain");
  4180. req.headers.emplace("Content-Length", "0");
  4181. req.headers.emplace("Transfer-Encoding", "chunked");
  4182. std::string long_string(30 * 1024u, 'a');
  4183. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4184. // Attempt to make a large enough post to exceed OS buffers, to test that
  4185. // the server handles short reads if the full chunk data isn't available.
  4186. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4187. auto res = std::make_shared<Response>();
  4188. auto error = Error::Success;
  4189. auto ret = cli_.send(req, *res, error);
  4190. ASSERT_TRUE(ret);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. }
  4193. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4194. auto res = cli_.Get("/remote_addr");
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::OK_200, res->status);
  4197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4198. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4199. }
  4200. TEST_F(ServerTest, GetMethodLocalAddr) {
  4201. auto res = cli_.Get("/local_addr");
  4202. ASSERT_TRUE(res);
  4203. EXPECT_EQ(StatusCode::OK_200, res->status);
  4204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4205. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4206. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4207. }
  4208. TEST_F(ServerTest, HTTPResponseSplitting) {
  4209. auto res = cli_.Get("/http_response_splitting");
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. }
  4213. TEST_F(ServerTest, SlowRequest) {
  4214. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4215. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4216. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4217. }
  4218. #if 0
  4219. TEST_F(ServerTest, SlowPost) {
  4220. char buffer[64 * 1024];
  4221. memset(buffer, 0x42, sizeof(buffer));
  4222. auto res = cli_.Post(
  4223. "/slowpost", 64 * 1024 * 1024,
  4224. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4225. auto ret = sink.write(buffer, sizeof(buffer));
  4226. EXPECT_TRUE(ret);
  4227. return true;
  4228. },
  4229. "text/plain");
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::OK_200, res->status);
  4232. }
  4233. TEST_F(ServerTest, SlowPostFail) {
  4234. char buffer[64 * 1024];
  4235. memset(buffer, 0x42, sizeof(buffer));
  4236. cli_.set_write_timeout(std::chrono::seconds(0));
  4237. auto res = cli_.Post(
  4238. "/slowpost", 64 * 1024 * 1024,
  4239. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4240. sink.write(buffer, sizeof(buffer));
  4241. return true;
  4242. },
  4243. "text/plain");
  4244. ASSERT_TRUE(!res);
  4245. EXPECT_EQ(Error::Write, res.error());
  4246. }
  4247. #endif
  4248. TEST_F(ServerTest, Put) {
  4249. auto res = cli_.Put("/put", "PUT", "text/plain");
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("PUT", res->body);
  4253. }
  4254. TEST_F(ServerTest, PutWithContentProvider) {
  4255. auto res = cli_.Put(
  4256. "/put", 3,
  4257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4258. sink.os << "PUT";
  4259. return true;
  4260. },
  4261. "text/plain");
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("PUT", res->body);
  4265. }
  4266. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4267. auto res = cli_.Post(
  4268. "/post", 42,
  4269. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4270. return false;
  4271. },
  4272. "text/plain");
  4273. ASSERT_TRUE(!res);
  4274. EXPECT_EQ(Error::Canceled, res.error());
  4275. }
  4276. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4277. auto res = cli_.Put(
  4278. "/put",
  4279. [](size_t /*offset*/, DataSink &sink) {
  4280. sink.os << "PUT";
  4281. sink.done();
  4282. return true;
  4283. },
  4284. "text/plain");
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::OK_200, res->status);
  4287. EXPECT_EQ("PUT", res->body);
  4288. }
  4289. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4290. auto res = cli_.Post(
  4291. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4292. "text/plain");
  4293. ASSERT_TRUE(!res);
  4294. EXPECT_EQ(Error::Canceled, res.error());
  4295. }
  4296. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4297. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4298. cli_.set_compress(true);
  4299. auto res = cli_.Put(
  4300. "/put", 3,
  4301. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4302. sink.os << "PUT";
  4303. return true;
  4304. },
  4305. "text/plain");
  4306. ASSERT_TRUE(res);
  4307. EXPECT_EQ(StatusCode::OK_200, res->status);
  4308. EXPECT_EQ("PUT", res->body);
  4309. }
  4310. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4311. cli_.set_compress(true);
  4312. auto res = cli_.Post(
  4313. "/post", 42,
  4314. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4315. return false;
  4316. },
  4317. "text/plain");
  4318. ASSERT_TRUE(!res);
  4319. EXPECT_EQ(Error::Canceled, res.error());
  4320. }
  4321. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4322. cli_.set_compress(true);
  4323. auto res = cli_.Put(
  4324. "/put",
  4325. [](size_t /*offset*/, DataSink &sink) {
  4326. sink.os << "PUT";
  4327. sink.done();
  4328. return true;
  4329. },
  4330. "text/plain");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. EXPECT_EQ("PUT", res->body);
  4334. }
  4335. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4336. cli_.set_compress(true);
  4337. auto res = cli_.Post(
  4338. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4339. "text/plain");
  4340. ASSERT_TRUE(!res);
  4341. EXPECT_EQ(Error::Canceled, res.error());
  4342. }
  4343. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4344. cli_.set_compress(true);
  4345. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4346. ASSERT_TRUE(res);
  4347. EXPECT_EQ(StatusCode::OK_200, res->status);
  4348. EXPECT_EQ(LARGE_DATA, res->body);
  4349. }
  4350. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4351. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4352. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4353. Client cli(s.c_str());
  4354. cli.enable_server_certificate_verification(false);
  4355. #else
  4356. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4357. Client cli(s.c_str());
  4358. #endif
  4359. cli.set_compress(true);
  4360. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4361. ASSERT_TRUE(res);
  4362. EXPECT_EQ(StatusCode::OK_200, res->status);
  4363. EXPECT_EQ(LARGE_DATA, res->body);
  4364. // The compressed size should be less than a 10th of the original. May vary
  4365. // depending on the zlib library.
  4366. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4367. static_cast<uint64_t>(10 * 1024 * 1024));
  4368. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4369. }
  4370. TEST_F(ServerTest, PutContentWithDeflate) {
  4371. cli_.set_compress(false);
  4372. Headers headers;
  4373. headers.emplace("Content-Encoding", "deflate");
  4374. // PUT in deflate format:
  4375. auto res = cli_.Put("/put", headers,
  4376. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::OK_200, res->status);
  4379. EXPECT_EQ("PUT", res->body);
  4380. }
  4381. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4382. Headers headers;
  4383. headers.emplace("Accept-Encoding", "gzip, deflate");
  4384. auto res = cli_.Get("/streamed-chunked", headers);
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::OK_200, res->status);
  4387. EXPECT_EQ(std::string("123456789"), res->body);
  4388. }
  4389. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4390. Headers headers;
  4391. headers.emplace("Accept-Encoding", "gzip, deflate");
  4392. auto res = cli_.Get("/streamed-chunked2", headers);
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::OK_200, res->status);
  4395. EXPECT_EQ(std::string("123456789"), res->body);
  4396. }
  4397. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4398. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST(GzipDecompressor, ChunkedDecompression) {
  4403. std::string data;
  4404. for (size_t i = 0; i < 32 * 1024; ++i) {
  4405. data.push_back(static_cast<char>('a' + i % 26));
  4406. }
  4407. std::string compressed_data;
  4408. {
  4409. httplib::detail::gzip_compressor compressor;
  4410. bool result = compressor.compress(
  4411. data.data(), data.size(),
  4412. /*last=*/true,
  4413. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4414. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4415. compressed_data_size);
  4416. return true;
  4417. });
  4418. ASSERT_TRUE(result);
  4419. }
  4420. std::string decompressed_data;
  4421. {
  4422. httplib::detail::gzip_decompressor decompressor;
  4423. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4424. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4425. size_t chunk_size = 130;
  4426. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4427. chunk_begin += chunk_size) {
  4428. size_t current_chunk_size =
  4429. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4430. bool result = decompressor.decompress(
  4431. compressed_data.data() + chunk_begin, current_chunk_size,
  4432. [&](const char *decompressed_data_chunk,
  4433. size_t decompressed_data_chunk_size) {
  4434. decompressed_data.insert(decompressed_data.size(),
  4435. decompressed_data_chunk,
  4436. decompressed_data_chunk_size);
  4437. return true;
  4438. });
  4439. ASSERT_TRUE(result);
  4440. }
  4441. }
  4442. ASSERT_EQ(data, decompressed_data);
  4443. }
  4444. TEST(GzipDecompressor, DeflateDecompression) {
  4445. std::string original_text = "Raw deflate without gzip";
  4446. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4447. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4448. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4449. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4450. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4451. std::string decompressed_data;
  4452. {
  4453. httplib::detail::gzip_decompressor decompressor;
  4454. bool result = decompressor.decompress(
  4455. compressed_data.data(), compressed_data.size(),
  4456. [&](const char *decompressed_data_chunk,
  4457. size_t decompressed_data_chunk_size) {
  4458. decompressed_data.insert(decompressed_data.size(),
  4459. decompressed_data_chunk,
  4460. decompressed_data_chunk_size);
  4461. return true;
  4462. });
  4463. ASSERT_TRUE(result);
  4464. }
  4465. ASSERT_EQ(original_text, decompressed_data);
  4466. }
  4467. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4468. std::string original_text = "Raw deflate without gzip";
  4469. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4470. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4471. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4472. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4473. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4474. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4475. std::string decompressed_data;
  4476. {
  4477. httplib::detail::gzip_decompressor decompressor;
  4478. bool result = decompressor.decompress(
  4479. compressed_data.data(), compressed_data.size(),
  4480. [&](const char *decompressed_data_chunk,
  4481. size_t decompressed_data_chunk_size) {
  4482. decompressed_data.insert(decompressed_data.size(),
  4483. decompressed_data_chunk,
  4484. decompressed_data_chunk_size);
  4485. return true;
  4486. });
  4487. ASSERT_TRUE(result);
  4488. }
  4489. ASSERT_EQ(original_text, decompressed_data);
  4490. }
  4491. #ifdef _WIN32
  4492. TEST(GzipDecompressor, LargeRandomData) {
  4493. // prepare large random data that is difficult to be compressed and is
  4494. // expected to have large size even when compressed
  4495. std::random_device seed_gen;
  4496. std::mt19937 random(seed_gen());
  4497. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4498. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4499. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4500. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4501. // compress data over 4GiB
  4502. std::string compressed_data;
  4503. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4504. httplib::detail::gzip_compressor compressor;
  4505. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4506. data.size() * sizeof(std::uint32_t), true,
  4507. [&](const char *data, size_t size) {
  4508. compressed_data.insert(
  4509. compressed_data.size(), data, size);
  4510. return true;
  4511. });
  4512. ASSERT_TRUE(result);
  4513. // FIXME: compressed data size is expected to be greater than 4GiB,
  4514. // but there is no guarantee
  4515. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4516. // decompress data over 4GiB
  4517. std::string decompressed_data;
  4518. decompressed_data.reserve(data_size);
  4519. httplib::detail::gzip_decompressor decompressor;
  4520. result = decompressor.decompress(
  4521. compressed_data.data(), compressed_data.size(),
  4522. [&](const char *data, size_t size) {
  4523. decompressed_data.insert(decompressed_data.size(), data, size);
  4524. return true;
  4525. });
  4526. ASSERT_TRUE(result);
  4527. // compare
  4528. ASSERT_EQ(data_size, decompressed_data.size());
  4529. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4530. 0);
  4531. }
  4532. #endif
  4533. #endif
  4534. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4535. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4536. Headers headers;
  4537. headers.emplace("Accept-Encoding", "br");
  4538. auto res = cli_.Get("/streamed-chunked", headers);
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ(std::string("123456789"), res->body);
  4542. }
  4543. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4544. Headers headers;
  4545. headers.emplace("Accept-Encoding", "br");
  4546. auto res = cli_.Get("/streamed-chunked2", headers);
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::OK_200, res->status);
  4549. EXPECT_EQ(std::string("123456789"), res->body);
  4550. }
  4551. #endif
  4552. TEST_F(ServerTest, Patch) {
  4553. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4554. ASSERT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("PATCH", res->body);
  4557. }
  4558. TEST_F(ServerTest, Delete) {
  4559. auto res = cli_.Delete("/delete");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("DELETE", res->body);
  4563. }
  4564. TEST_F(ServerTest, DeleteContentReceiver) {
  4565. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4566. ASSERT_TRUE(res);
  4567. EXPECT_EQ(StatusCode::OK_200, res->status);
  4568. EXPECT_EQ("content", res->body);
  4569. }
  4570. TEST_F(ServerTest, Options) {
  4571. auto res = cli_.Options("*");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4575. EXPECT_TRUE(res->body.empty());
  4576. }
  4577. TEST_F(ServerTest, URL) {
  4578. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. }
  4582. TEST_F(ServerTest, ArrayParam) {
  4583. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. }
  4587. TEST_F(ServerTest, NoMultipleHeaders) {
  4588. Headers headers = {{"Content-Length", "5"}};
  4589. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4590. "text/plain");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. }
  4594. TEST_F(ServerTest, PostContentReceiver) {
  4595. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4596. ASSERT_TRUE(res);
  4597. ASSERT_EQ(StatusCode::OK_200, res->status);
  4598. ASSERT_EQ("content", res->body);
  4599. }
  4600. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4601. UploadFormDataItems items = {
  4602. {"text1", "text default", "", ""},
  4603. {"text2", "aωb", "", ""},
  4604. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4605. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4606. {"file3", "", "", "application/octet-stream"},
  4607. };
  4608. auto res = cli_.Post("/content_receiver", items);
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. }
  4612. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4613. UploadFormDataItems items = {
  4614. {"text1", "text default", "", ""},
  4615. {"text2", "aωb", "", ""},
  4616. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4617. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4618. {"file3", "", "", "application/octet-stream"},
  4619. };
  4620. auto boundary = std::string("+++++");
  4621. std::string body;
  4622. for (const auto &item : items) {
  4623. body += "--" + boundary + "\r\n";
  4624. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4625. if (!item.filename.empty()) {
  4626. body += "; filename=\"" + item.filename + "\"";
  4627. }
  4628. body += "\r\n";
  4629. if (!item.content_type.empty()) {
  4630. body += "Content-Type: " + item.content_type + "\r\n";
  4631. }
  4632. body += "\r\n";
  4633. body += item.content + "\r\n";
  4634. }
  4635. body += "--" + boundary + "--\r\n";
  4636. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4637. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::OK_200, res->status);
  4640. }
  4641. TEST_F(ServerTest, PostContentReceiverGzip) {
  4642. cli_.set_compress(true);
  4643. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4644. ASSERT_TRUE(res);
  4645. ASSERT_EQ(StatusCode::OK_200, res->status);
  4646. ASSERT_EQ("content", res->body);
  4647. }
  4648. TEST_F(ServerTest, PutContentReceiver) {
  4649. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4650. ASSERT_TRUE(res);
  4651. ASSERT_EQ(StatusCode::OK_200, res->status);
  4652. ASSERT_EQ("content", res->body);
  4653. }
  4654. TEST_F(ServerTest, PatchContentReceiver) {
  4655. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4656. ASSERT_TRUE(res);
  4657. ASSERT_EQ(StatusCode::OK_200, res->status);
  4658. ASSERT_EQ("content", res->body);
  4659. }
  4660. template <typename ClientType>
  4661. void TestWithHeadersAndContentReceiver(
  4662. ClientType &cli,
  4663. std::function<Result(ClientType &, const std::string &, const Headers &,
  4664. const std::string &, const std::string &,
  4665. ContentReceiver, DownloadProgress)>
  4666. request_func) {
  4667. Headers headers;
  4668. headers.emplace("X-Custom-Header", "test-value");
  4669. std::string received_body;
  4670. auto res = request_func(
  4671. cli, "/content_receiver", headers, "content", "application/json",
  4672. [&](const char *data, size_t data_length) {
  4673. received_body.append(data, data_length);
  4674. return true;
  4675. },
  4676. nullptr);
  4677. ASSERT_TRUE(res);
  4678. EXPECT_EQ(StatusCode::OK_200, res->status);
  4679. EXPECT_EQ("content", received_body);
  4680. }
  4681. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4683. using ClientT = SSLClient;
  4684. #else
  4685. using ClientT = Client;
  4686. #endif
  4687. TestWithHeadersAndContentReceiver<ClientT>(
  4688. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4689. const std::string &body, const std::string &content_type,
  4690. ContentReceiver receiver, DownloadProgress progress) {
  4691. return cli.Post(path, headers, body, content_type, receiver, progress);
  4692. });
  4693. }
  4694. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4696. using ClientT = SSLClient;
  4697. #else
  4698. using ClientT = Client;
  4699. #endif
  4700. TestWithHeadersAndContentReceiver<ClientT>(
  4701. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4702. const std::string &body, const std::string &content_type,
  4703. ContentReceiver receiver, DownloadProgress progress) {
  4704. return cli.Put(path, headers, body, content_type, receiver, progress);
  4705. });
  4706. }
  4707. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4708. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4709. using ClientT = SSLClient;
  4710. #else
  4711. using ClientT = Client;
  4712. #endif
  4713. TestWithHeadersAndContentReceiver<ClientT>(
  4714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4715. const std::string &body, const std::string &content_type,
  4716. ContentReceiver receiver, DownloadProgress progress) {
  4717. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4718. });
  4719. }
  4720. template <typename ClientType>
  4721. void TestWithHeadersAndContentReceiverWithProgress(
  4722. ClientType &cli,
  4723. std::function<Result(ClientType &, const std::string &, const Headers &,
  4724. const std::string &, const std::string &,
  4725. ContentReceiver, DownloadProgress)>
  4726. request_func) {
  4727. Headers headers;
  4728. headers.emplace("X-Test-Header", "progress-test");
  4729. std::string received_body;
  4730. auto progress_called = false;
  4731. auto res = request_func(
  4732. cli, "/content_receiver", headers, "content", "text/plain",
  4733. [&](const char *data, size_t data_length) {
  4734. received_body.append(data, data_length);
  4735. return true;
  4736. },
  4737. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4738. progress_called = true;
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("content", received_body);
  4744. EXPECT_TRUE(progress_called);
  4745. }
  4746. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4748. using ClientT = SSLClient;
  4749. #else
  4750. using ClientT = Client;
  4751. #endif
  4752. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4753. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4754. const std::string &body, const std::string &content_type,
  4755. ContentReceiver receiver, DownloadProgress progress) {
  4756. return cli.Post(path, headers, body, content_type, receiver, progress);
  4757. });
  4758. }
  4759. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4761. using ClientT = SSLClient;
  4762. #else
  4763. using ClientT = Client;
  4764. #endif
  4765. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4766. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4767. const std::string &body, const std::string &content_type,
  4768. ContentReceiver receiver, DownloadProgress progress) {
  4769. return cli.Put(path, headers, body, content_type, receiver, progress);
  4770. });
  4771. }
  4772. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4774. using ClientT = SSLClient;
  4775. #else
  4776. using ClientT = Client;
  4777. #endif
  4778. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4779. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4780. const std::string &body, const std::string &content_type,
  4781. ContentReceiver receiver, DownloadProgress progress) {
  4782. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4783. });
  4784. }
  4785. template <typename ClientType>
  4786. void TestWithHeadersAndContentReceiverError(
  4787. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4788. const Headers &, const std::string &,
  4789. const std::string &, ContentReceiver)>
  4790. request_func) {
  4791. Headers headers;
  4792. headers.emplace("X-Error-Test", "true");
  4793. std::string received_body;
  4794. auto receiver_failed = false;
  4795. auto res =
  4796. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4797. [&](const char *data, size_t data_length) {
  4798. received_body.append(data, data_length);
  4799. receiver_failed = true;
  4800. return false;
  4801. });
  4802. ASSERT_FALSE(res);
  4803. EXPECT_TRUE(receiver_failed);
  4804. }
  4805. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4806. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4807. using ClientT = SSLClient;
  4808. #else
  4809. using ClientT = Client;
  4810. #endif
  4811. TestWithHeadersAndContentReceiverError<ClientT>(
  4812. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4813. const std::string &body, const std::string &content_type,
  4814. ContentReceiver receiver) {
  4815. return cli.Post(path, headers, body, content_type, receiver);
  4816. });
  4817. }
  4818. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4820. using ClientT = SSLClient;
  4821. #else
  4822. using ClientT = Client;
  4823. #endif
  4824. TestWithHeadersAndContentReceiverError<ClientT>(
  4825. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4826. const std::string &body, const std::string &content_type,
  4827. ContentReceiver receiver) {
  4828. return cli.Put(path, headers, body, content_type, receiver);
  4829. });
  4830. }
  4831. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4833. using ClientT = SSLClient;
  4834. #else
  4835. using ClientT = Client;
  4836. #endif
  4837. TestWithHeadersAndContentReceiverError<ClientT>(
  4838. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4839. const std::string &body, const std::string &content_type,
  4840. ContentReceiver receiver) {
  4841. return cli.Patch(path, headers, body, content_type, receiver);
  4842. });
  4843. }
  4844. TEST_F(ServerTest, PostQueryStringAndBody) {
  4845. auto res =
  4846. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4847. ASSERT_TRUE(res);
  4848. ASSERT_EQ(StatusCode::OK_200, res->status);
  4849. }
  4850. TEST_F(ServerTest, HTTP2Magic) {
  4851. Request req;
  4852. req.method = "PRI";
  4853. req.path = "*";
  4854. req.body = "SM";
  4855. auto res = std::make_shared<Response>();
  4856. auto error = Error::Success;
  4857. auto ret = cli_.send(req, *res, error);
  4858. ASSERT_TRUE(ret);
  4859. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4860. }
  4861. TEST_F(ServerTest, KeepAlive) {
  4862. auto res = cli_.Get("/hi");
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. EXPECT_EQ("Hello World!", res->body);
  4867. res = cli_.Get("/hi");
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4871. EXPECT_EQ("Hello World!", res->body);
  4872. res = cli_.Get("/hi");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4876. EXPECT_EQ("Hello World!", res->body);
  4877. res = cli_.Get("/not-exist");
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4880. res = cli_.Post("/empty", "", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::OK_200, res->status);
  4883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4884. EXPECT_EQ("empty", res->body);
  4885. EXPECT_EQ("close", res->get_header_value("Connection"));
  4886. res = cli_.Post(
  4887. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4888. "text/plain");
  4889. ASSERT_TRUE(res);
  4890. EXPECT_EQ(StatusCode::OK_200, res->status);
  4891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4892. EXPECT_EQ("empty", res->body);
  4893. cli_.set_keep_alive(false);
  4894. res = cli_.Get("/last-request");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("close", res->get_header_value("Connection"));
  4898. }
  4899. TEST_F(ServerTest, TooManyRedirect) {
  4900. cli_.set_follow_location(true);
  4901. auto res = cli_.Get("/redirect/0");
  4902. ASSERT_TRUE(!res);
  4903. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4904. }
  4905. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4906. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4907. TEST_F(ServerTest, Gzip) {
  4908. Headers headers;
  4909. headers.emplace("Accept-Encoding", "gzip, deflate");
  4910. auto res = cli_.Get("/compress", headers);
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4914. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4916. "7890123456789012345678901234567890",
  4917. res->body);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. }
  4920. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4921. Headers headers;
  4922. headers.emplace("Accept-Encoding", "");
  4923. auto res = cli_.Get("/compress", headers);
  4924. ASSERT_TRUE(res);
  4925. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4929. "7890123456789012345678901234567890",
  4930. res->body);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. }
  4933. TEST_F(ServerTest, GzipWithContentReceiver) {
  4934. Headers headers;
  4935. headers.emplace("Accept-Encoding", "gzip, deflate");
  4936. std::string body;
  4937. auto res = cli_.Get("/compress", headers,
  4938. [&](const char *data, uint64_t data_length) {
  4939. EXPECT_EQ(100U, data_length);
  4940. body.append(data, data_length);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4948. "7890123456789012345678901234567890",
  4949. body);
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. }
  4952. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4953. Headers headers;
  4954. headers.emplace("Accept-Encoding", "gzip, deflate");
  4955. cli_.set_decompress(false);
  4956. auto res = cli_.Get("/compress", headers);
  4957. ASSERT_TRUE(res);
  4958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4960. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4961. EXPECT_EQ(33U, res->body.size());
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. }
  4964. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4965. Headers headers;
  4966. headers.emplace("Accept-Encoding", "");
  4967. std::string body;
  4968. auto res = cli_.Get("/compress", headers,
  4969. [&](const char *data, uint64_t data_length) {
  4970. EXPECT_EQ(100U, data_length);
  4971. body.append(data, data_length);
  4972. return true;
  4973. });
  4974. ASSERT_TRUE(res);
  4975. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4977. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4979. "7890123456789012345678901234567890",
  4980. body);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. }
  4983. TEST_F(ServerTest, NoGzip) {
  4984. Headers headers;
  4985. headers.emplace("Accept-Encoding", "gzip, deflate");
  4986. auto res = cli_.Get("/nocompress", headers);
  4987. ASSERT_TRUE(res);
  4988. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4989. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4990. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4992. "7890123456789012345678901234567890",
  4993. res->body);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4997. Headers headers;
  4998. headers.emplace("Accept-Encoding", "gzip, deflate");
  4999. std::string body;
  5000. auto res = cli_.Get("/nocompress", headers,
  5001. [&](const char *data, uint64_t data_length) {
  5002. EXPECT_EQ(100U, data_length);
  5003. body.append(data, data_length);
  5004. return true;
  5005. });
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5008. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5009. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5011. "7890123456789012345678901234567890",
  5012. body);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. }
  5015. TEST_F(ServerTest, MultipartFormDataGzip) {
  5016. UploadFormDataItems items = {
  5017. {"key1", "test", "", ""},
  5018. {"key2", "--abcdefg123", "", ""},
  5019. };
  5020. cli_.set_compress(true);
  5021. auto res = cli_.Post("/compress-multipart", items);
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. #endif
  5026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5027. TEST_F(ServerTest, Brotli) {
  5028. Headers headers;
  5029. headers.emplace("Accept-Encoding", "br");
  5030. auto res = cli_.Get("/compress", headers);
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5034. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5035. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5036. "7890123456789012345678901234567890",
  5037. res->body);
  5038. EXPECT_EQ(StatusCode::OK_200, res->status);
  5039. }
  5040. #endif
  5041. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5042. TEST_F(ServerTest, Zstd) {
  5043. Headers headers;
  5044. headers.emplace("Accept-Encoding", "zstd");
  5045. auto res = cli_.Get("/compress", headers);
  5046. ASSERT_TRUE(res);
  5047. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5048. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5049. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5050. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5051. "7890123456789012345678901234567890",
  5052. res->body);
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. }
  5055. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5056. Headers headers;
  5057. headers.emplace("Accept-Encoding", "");
  5058. auto res = cli_.Get("/compress", headers);
  5059. ASSERT_TRUE(res);
  5060. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5061. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5062. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5063. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5064. "7890123456789012345678901234567890",
  5065. res->body);
  5066. EXPECT_EQ(StatusCode::OK_200, res->status);
  5067. }
  5068. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5069. Headers headers;
  5070. headers.emplace("Accept-Encoding", "zstd");
  5071. std::string body;
  5072. auto res = cli_.Get("/compress", headers,
  5073. [&](const char *data, uint64_t data_length) {
  5074. EXPECT_EQ(100U, data_length);
  5075. body.append(data, data_length);
  5076. return true;
  5077. });
  5078. ASSERT_TRUE(res);
  5079. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5080. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5081. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5082. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5083. "7890123456789012345678901234567890",
  5084. body);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5088. Headers headers;
  5089. headers.emplace("Accept-Encoding", "zstd");
  5090. cli_.set_decompress(false);
  5091. auto res = cli_.Get("/compress", headers);
  5092. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5093. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5094. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5095. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5099. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5100. EXPECT_EQ(StatusCode::OK_200, res->status);
  5101. ASSERT_EQ(26U, res->body.size());
  5102. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5103. 0);
  5104. }
  5105. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5106. Headers headers;
  5107. headers.emplace("Accept-Encoding", "");
  5108. std::string body;
  5109. auto res = cli_.Get("/compress", headers,
  5110. [&](const char *data, uint64_t data_length) {
  5111. EXPECT_EQ(100U, data_length);
  5112. body.append(data, data_length);
  5113. return true;
  5114. });
  5115. ASSERT_TRUE(res);
  5116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5120. "7890123456789012345678901234567890",
  5121. body);
  5122. EXPECT_EQ(StatusCode::OK_200, res->status);
  5123. }
  5124. TEST_F(ServerTest, NoZstd) {
  5125. Headers headers;
  5126. headers.emplace("Accept-Encoding", "zstd");
  5127. auto res = cli_.Get("/nocompress", headers);
  5128. ASSERT_TRUE(res);
  5129. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5130. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5133. "7890123456789012345678901234567890",
  5134. res->body);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. }
  5137. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5138. Headers headers;
  5139. headers.emplace("Accept-Encoding", "zstd");
  5140. std::string body;
  5141. auto res = cli_.Get("/nocompress", headers,
  5142. [&](const char *data, uint64_t data_length) {
  5143. EXPECT_EQ(100U, data_length);
  5144. body.append(data, data_length);
  5145. return true;
  5146. });
  5147. ASSERT_TRUE(res);
  5148. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5149. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5150. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5152. "7890123456789012345678901234567890",
  5153. body);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. // TODO: How to enable zstd ??
  5157. TEST_F(ServerTest, MultipartFormDataZstd) {
  5158. UploadFormDataItems items = {
  5159. {"key1", "test", "", ""},
  5160. {"key2", "--abcdefg123", "", ""},
  5161. };
  5162. Headers headers;
  5163. headers.emplace("Accept-Encoding", "zstd");
  5164. cli_.set_compress(true);
  5165. auto res = cli_.Post("/compress-multipart", headers, items);
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. }
  5169. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5170. Headers headers;
  5171. headers.emplace("Accept-Encoding", "zstd");
  5172. cli_.set_compress(true);
  5173. auto res = cli_.Put(
  5174. "/put", headers, 3,
  5175. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5176. sink.os << "PUT";
  5177. return true;
  5178. },
  5179. "text/plain");
  5180. ASSERT_TRUE(res);
  5181. EXPECT_EQ(StatusCode::OK_200, res->status);
  5182. EXPECT_EQ("PUT", res->body);
  5183. }
  5184. // Pre-compression logging tests
  5185. TEST_F(ServerTest, PreCompressionLogging) {
  5186. // Test data for compression (matches the actual /compress endpoint content)
  5187. const std::string test_content =
  5188. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5189. "3456789012345678901234567890";
  5190. // Variables to capture logging data
  5191. std::string pre_compression_body;
  5192. std::string pre_compression_content_type;
  5193. std::string pre_compression_content_encoding;
  5194. std::string post_compression_body;
  5195. std::string post_compression_content_type;
  5196. std::string post_compression_content_encoding;
  5197. // Set up pre-compression logger
  5198. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5199. const Response &res) {
  5200. pre_compression_body = res.body;
  5201. pre_compression_content_type = res.get_header_value("Content-Type");
  5202. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5203. });
  5204. // Set up post-compression logger
  5205. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5206. post_compression_body = res.body;
  5207. post_compression_content_type = res.get_header_value("Content-Type");
  5208. post_compression_content_encoding =
  5209. res.get_header_value("Content-Encoding");
  5210. });
  5211. // Test with gzip compression
  5212. Headers headers;
  5213. headers.emplace("Accept-Encoding", "gzip");
  5214. auto res = cli_.Get("/compress", headers);
  5215. // Verify response was compressed
  5216. ASSERT_TRUE(res);
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5219. // Verify pre-compression logger captured uncompressed content
  5220. EXPECT_EQ(test_content, pre_compression_body);
  5221. EXPECT_EQ("text/plain", pre_compression_content_type);
  5222. EXPECT_TRUE(pre_compression_content_encoding
  5223. .empty()); // No encoding header before compression
  5224. // Verify post-compression logger captured compressed content
  5225. EXPECT_NE(test_content,
  5226. post_compression_body); // Should be different after compression
  5227. EXPECT_EQ("text/plain", post_compression_content_type);
  5228. EXPECT_EQ("gzip", post_compression_content_encoding);
  5229. // Verify compressed content is smaller
  5230. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5231. }
  5232. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5233. const std::string test_content =
  5234. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5235. "3456789012345678901234567890";
  5236. std::string pre_compression_body;
  5237. std::string post_compression_body;
  5238. svr_.set_pre_compression_logger(
  5239. [&](const Request & /*req*/, const Response &res) {
  5240. pre_compression_body = res.body;
  5241. });
  5242. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5243. post_compression_body = res.body;
  5244. });
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "br");
  5247. auto res = cli_.Get("/compress", headers);
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5251. // Verify pre-compression content is uncompressed
  5252. EXPECT_EQ(test_content, pre_compression_body);
  5253. // Verify post-compression content is compressed
  5254. EXPECT_NE(test_content, post_compression_body);
  5255. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5256. }
  5257. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5258. const std::string test_content =
  5259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5260. "3456789012345678901234567890";
  5261. std::string pre_compression_body;
  5262. std::string post_compression_body;
  5263. svr_.set_pre_compression_logger(
  5264. [&](const Request & /*req*/, const Response &res) {
  5265. pre_compression_body = res.body;
  5266. });
  5267. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5268. post_compression_body = res.body;
  5269. });
  5270. // Request without compression (use /nocompress endpoint)
  5271. Headers headers;
  5272. auto res = cli_.Get("/nocompress", headers);
  5273. ASSERT_TRUE(res);
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5276. // Pre-compression logger should not be called when no compression is applied
  5277. EXPECT_TRUE(
  5278. pre_compression_body.empty()); // Pre-compression logger not called
  5279. EXPECT_EQ(
  5280. test_content,
  5281. post_compression_body); // Post-compression logger captures final content
  5282. }
  5283. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5284. const std::string test_content =
  5285. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5286. "3456789012345678901234567890";
  5287. std::string pre_compression_body;
  5288. bool pre_logger_called = false;
  5289. // Set only pre-compression logger
  5290. svr_.set_pre_compression_logger(
  5291. [&](const Request & /*req*/, const Response &res) {
  5292. pre_compression_body = res.body;
  5293. pre_logger_called = true;
  5294. });
  5295. Headers headers;
  5296. headers.emplace("Accept-Encoding", "gzip");
  5297. auto res = cli_.Get("/compress", headers);
  5298. ASSERT_TRUE(res);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5301. // Verify pre-compression logger was called
  5302. EXPECT_TRUE(pre_logger_called);
  5303. EXPECT_EQ(test_content, pre_compression_body);
  5304. }
  5305. TEST(ZstdDecompressor, ChunkedDecompression) {
  5306. std::string data;
  5307. for (size_t i = 0; i < 32 * 1024; ++i) {
  5308. data.push_back(static_cast<char>('a' + i % 26));
  5309. }
  5310. std::string compressed_data;
  5311. {
  5312. httplib::detail::zstd_compressor compressor;
  5313. bool result = compressor.compress(
  5314. data.data(), data.size(),
  5315. /*last=*/true,
  5316. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5317. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5318. compressed_data_size);
  5319. return true;
  5320. });
  5321. ASSERT_TRUE(result);
  5322. }
  5323. std::string decompressed_data;
  5324. {
  5325. httplib::detail::zstd_decompressor decompressor;
  5326. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5327. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5328. size_t chunk_size = 130;
  5329. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5330. chunk_begin += chunk_size) {
  5331. size_t current_chunk_size =
  5332. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5333. bool result = decompressor.decompress(
  5334. compressed_data.data() + chunk_begin, current_chunk_size,
  5335. [&](const char *decompressed_data_chunk,
  5336. size_t decompressed_data_chunk_size) {
  5337. decompressed_data.insert(decompressed_data.size(),
  5338. decompressed_data_chunk,
  5339. decompressed_data_chunk_size);
  5340. return true;
  5341. });
  5342. ASSERT_TRUE(result);
  5343. }
  5344. }
  5345. ASSERT_EQ(data, decompressed_data);
  5346. }
  5347. TEST(ZstdDecompressor, Decompress) {
  5348. std::string original_text = "Compressed with ZSTD";
  5349. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5350. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5351. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5352. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5353. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5354. std::string decompressed_data;
  5355. {
  5356. httplib::detail::zstd_decompressor decompressor;
  5357. bool result = decompressor.decompress(
  5358. compressed_data.data(), compressed_data.size(),
  5359. [&](const char *decompressed_data_chunk,
  5360. size_t decompressed_data_chunk_size) {
  5361. decompressed_data.insert(decompressed_data.size(),
  5362. decompressed_data_chunk,
  5363. decompressed_data_chunk_size);
  5364. return true;
  5365. });
  5366. ASSERT_TRUE(result);
  5367. }
  5368. ASSERT_EQ(original_text, decompressed_data);
  5369. }
  5370. #endif
  5371. // Sends a raw request to a server listening at HOST:PORT.
  5372. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5373. std::string *resp = nullptr) {
  5374. auto error = Error::Success;
  5375. auto client_sock = detail::create_client_socket(
  5376. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5377. /*connection_timeout_sec=*/5, 0,
  5378. /*read_timeout_sec=*/5, 0,
  5379. /*write_timeout_sec=*/5, 0, std::string(), error);
  5380. if (client_sock == INVALID_SOCKET) { return false; }
  5381. auto ret = detail::process_client_socket(
  5382. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5383. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5384. if (req.size() !=
  5385. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5386. return false;
  5387. }
  5388. char buf[512];
  5389. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5390. while (line_reader.getline()) {
  5391. if (resp) { *resp += line_reader.ptr(); }
  5392. }
  5393. return true;
  5394. });
  5395. detail::close_socket(client_sock);
  5396. return ret;
  5397. }
  5398. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5399. Server svr;
  5400. std::string header_value;
  5401. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5402. header_value = req.get_header_value("foo");
  5403. res.set_content("ok", "text/plain");
  5404. });
  5405. thread t = thread([&] { svr.listen(HOST, PORT); });
  5406. auto se = detail::scope_exit([&] {
  5407. svr.stop();
  5408. t.join();
  5409. ASSERT_FALSE(svr.is_running());
  5410. });
  5411. svr.wait_until_ready();
  5412. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5413. // like characters are not treated the same - use vertical tab and escape.
  5414. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5415. "foo: \t \v bar \x1B\t \r\n"
  5416. "Connection: close\r\n"
  5417. "\r\n";
  5418. std::string res;
  5419. ASSERT_TRUE(send_request(5, req, &res));
  5420. EXPECT_EQ(header_value, "");
  5421. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5422. }
  5423. // Sends a raw request and verifies that there isn't a crash or exception.
  5424. static void test_raw_request(const std::string &req,
  5425. std::string *out = nullptr) {
  5426. Server svr;
  5427. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5428. res.set_content("ok", "text/plain");
  5429. });
  5430. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5431. res.set_content("ok", "text/plain");
  5432. });
  5433. svr.Get("/header_field_value_check",
  5434. [&](const Request & /*req*/, Response &res) {
  5435. res.set_content("ok", "text/plain");
  5436. });
  5437. // Server read timeout must be longer than the client read timeout for the
  5438. // bug to reproduce, probably to force the server to process a request
  5439. // without a trailing blank line.
  5440. const time_t client_read_timeout_sec = 1;
  5441. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5442. bool listen_thread_ok = false;
  5443. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5444. auto se = detail::scope_exit([&] {
  5445. svr.stop();
  5446. t.join();
  5447. ASSERT_FALSE(svr.is_running());
  5448. EXPECT_TRUE(listen_thread_ok);
  5449. });
  5450. svr.wait_until_ready();
  5451. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5452. }
  5453. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5454. // A certain header line causes an exception if the header property is parsed
  5455. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5456. test_raw_request(
  5457. "GET /hi HTTP/1.1\r\n"
  5458. " : "
  5459. " "
  5460. " ");
  5461. }
  5462. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5463. // A certain header line causes an exception if the header property *name* is
  5464. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5465. // greedy matcher and requires backtracking when there are a lot of ":"
  5466. // characters.
  5467. // This occurs with libc++ but not libstdc++.
  5468. test_raw_request(
  5469. "GET /hi HTTP/1.1\r\n"
  5470. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5471. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5472. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5473. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5474. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5475. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5476. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5477. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5478. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5479. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5480. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5481. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5482. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5483. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5484. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5485. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5486. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5487. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5488. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5489. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5490. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5491. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5492. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5493. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5494. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5495. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5496. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5497. "&&&%%%");
  5498. }
  5499. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5500. // Make sure this doesn't crash the server.
  5501. // In a previous version of the header line regex, the "\r" rendered the line
  5502. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5503. // a new position where the leading white space ended and the field value
  5504. // began.
  5505. // The crash occurs with libc++ but not libstdc++.
  5506. test_raw_request("GET /hi HTTP/1.1\r\n"
  5507. "a:" +
  5508. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5509. "\r\n"
  5510. "\r\n");
  5511. }
  5512. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5513. std::string out;
  5514. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5515. "Content-Type: text/plain\r\n"
  5516. "Transfer-Encoding: chunked\r\n"
  5517. "\r\n"
  5518. "nothex\r\n",
  5519. &out);
  5520. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5521. }
  5522. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5523. std::string out;
  5524. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5525. "Content-Type: text/plain\r\n"
  5526. "Transfer-Encoding: chunked\r\n"
  5527. "\r\n"
  5528. "3\r\n"
  5529. "xyz\r\n"
  5530. "NaN\r\n",
  5531. &out);
  5532. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5533. }
  5534. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5535. std::string out;
  5536. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5537. "Content-Type: text/plain\r\n"
  5538. "Transfer-Encoding: chunked\r\n"
  5539. "\r\n"
  5540. // Length is too large for 64 bits.
  5541. "1ffffffffffffffff\r\n"
  5542. "xyz\r\n",
  5543. &out);
  5544. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5545. }
  5546. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5547. test_raw_request("GET /hi HTTP/1.1\r\n"
  5548. "Content-Type: text/plain\r\n\r");
  5549. }
  5550. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5551. std::string out;
  5552. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5553. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5554. }
  5555. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5556. std::string out;
  5557. std::string request(
  5558. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5559. test_raw_request(request, &out);
  5560. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5561. }
  5562. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5563. std::string out;
  5564. std::string request(
  5565. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5566. test_raw_request(request, &out);
  5567. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5568. }
  5569. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5570. std::string out;
  5571. std::string request(
  5572. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5573. test_raw_request(request, &out);
  5574. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5575. }
  5576. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5577. std::string out;
  5578. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5579. "Test: \r\n\r\n",
  5580. &out);
  5581. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5582. }
  5583. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5584. Server svr;
  5585. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5586. res.set_header("Cache-Control", "no-cache");
  5587. res.set_chunked_content_provider(
  5588. "text/event-stream", [](size_t offset, DataSink &sink) {
  5589. std::string s = "data:";
  5590. s += std::to_string(offset);
  5591. s += "\n\n";
  5592. auto ret = sink.write(s.data(), s.size());
  5593. EXPECT_TRUE(ret);
  5594. std::this_thread::sleep_for(std::chrono::seconds(1));
  5595. return true;
  5596. });
  5597. });
  5598. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5599. svr.wait_until_ready();
  5600. Client client(HOST, PORT);
  5601. const Headers headers = {{"Accept", "text/event-stream"}};
  5602. auto get_thread = std::thread([&client, &headers]() {
  5603. auto res = client.Get(
  5604. "/events", headers,
  5605. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5606. });
  5607. auto se = detail::scope_exit([&] {
  5608. svr.stop();
  5609. get_thread.join();
  5610. listen_thread.join();
  5611. ASSERT_FALSE(svr.is_running());
  5612. });
  5613. // Give GET time to get a few messages.
  5614. std::this_thread::sleep_for(std::chrono::seconds(2));
  5615. }
  5616. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5617. httplib::Server svr;
  5618. svr.Post("/hi",
  5619. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5620. res.status = StatusCode::OK_200;
  5621. });
  5622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5623. svr.wait_until_ready();
  5624. Client cli(HOST, PORT);
  5625. auto res = cli.Post("/hi", "data", "text/plain");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. svr.stop();
  5629. thread.join();
  5630. ASSERT_FALSE(svr.is_running());
  5631. res = cli.Post("/hi", "data", "text/plain");
  5632. ASSERT_FALSE(res);
  5633. }
  5634. TEST(ServerStopTest, ListenFailure) {
  5635. Server svr;
  5636. auto t = thread([&]() {
  5637. auto ret = svr.listen("????", PORT);
  5638. EXPECT_FALSE(ret);
  5639. });
  5640. svr.wait_until_ready();
  5641. svr.stop();
  5642. t.join();
  5643. }
  5644. TEST(ServerStopTest, Decommision) {
  5645. Server svr;
  5646. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5647. for (int i = 0; i < 4; i++) {
  5648. auto is_even = !(i % 2);
  5649. std::thread t{[&] {
  5650. try {
  5651. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5652. if (is_even) {
  5653. throw std::runtime_error("Some thing that happens to go wrong.");
  5654. }
  5655. svr.listen(HOST, PORT);
  5656. } catch (...) { svr.decommission(); }
  5657. }};
  5658. svr.wait_until_ready();
  5659. // Server is up
  5660. {
  5661. Client cli(HOST, PORT);
  5662. auto res = cli.Get("/hi");
  5663. if (is_even) {
  5664. EXPECT_FALSE(res);
  5665. } else {
  5666. EXPECT_TRUE(res);
  5667. EXPECT_EQ("hi...", res->body);
  5668. }
  5669. }
  5670. svr.stop();
  5671. t.join();
  5672. // Server is down...
  5673. {
  5674. Client cli(HOST, PORT);
  5675. auto res = cli.Get("/hi");
  5676. EXPECT_FALSE(res);
  5677. }
  5678. }
  5679. }
  5680. // Helper function for string body upload progress tests
  5681. template <typename SetupHandler, typename ClientCall>
  5682. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5683. ClientCall &&client_call,
  5684. const string &body) {
  5685. Server svr;
  5686. setup_handler(svr);
  5687. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5688. auto se = detail::scope_exit([&] {
  5689. svr.stop();
  5690. t.join();
  5691. });
  5692. svr.wait_until_ready();
  5693. Client cli(HOST, PORT);
  5694. vector<uint64_t> progress_values;
  5695. bool progress_called = false;
  5696. auto res =
  5697. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5698. progress_values.push_back(current);
  5699. progress_called = true;
  5700. return true;
  5701. });
  5702. ASSERT_TRUE(res);
  5703. EXPECT_EQ(200, res->status);
  5704. EXPECT_TRUE(progress_called);
  5705. }
  5706. TEST(UploadProgressTest, PostStringBodyBasic) {
  5707. TestStringBodyUploadProgress(
  5708. [](Server &svr) {
  5709. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5710. res.set_content("received", "text/plain");
  5711. });
  5712. },
  5713. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5714. return cli.Post("/test", body, "text/plain", progress_callback);
  5715. },
  5716. "test data for upload progress");
  5717. }
  5718. TEST(UploadProgressTest, PutStringBodyBasic) {
  5719. TestStringBodyUploadProgress(
  5720. [](Server &svr) {
  5721. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5722. res.set_content("put received", "text/plain");
  5723. });
  5724. },
  5725. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5726. return cli.Put("/test", body, "text/plain", progress_callback);
  5727. },
  5728. "put test data for upload progress");
  5729. }
  5730. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5731. TestStringBodyUploadProgress(
  5732. [](Server &svr) {
  5733. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5734. res.set_content("patch received", "text/plain");
  5735. });
  5736. },
  5737. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5738. return cli.Patch("/test", body, "text/plain", progress_callback);
  5739. },
  5740. "patch test data for upload progress");
  5741. }
  5742. // Helper function for content provider upload progress tests
  5743. template <typename SetupHandler, typename ClientCall>
  5744. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5745. ClientCall &&client_call) {
  5746. Server svr;
  5747. setup_handler(svr);
  5748. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5749. auto se = detail::scope_exit([&] {
  5750. svr.stop();
  5751. t.join();
  5752. });
  5753. svr.wait_until_ready();
  5754. Client cli(HOST, PORT);
  5755. vector<uint64_t> progress_values;
  5756. auto res =
  5757. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5758. progress_values.push_back(current);
  5759. return true;
  5760. });
  5761. ASSERT_TRUE(res);
  5762. EXPECT_EQ(200, res->status);
  5763. EXPECT_FALSE(progress_values.empty());
  5764. }
  5765. TEST(UploadProgressTest, PostContentProviderProgress) {
  5766. TestContentProviderUploadProgress(
  5767. [](Server &svr) {
  5768. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5769. res.set_content("provider received", "text/plain");
  5770. });
  5771. },
  5772. [](Client &cli, UploadProgress progress_callback) {
  5773. return cli.Post(
  5774. "/test", 10,
  5775. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5776. sink.os << "test data";
  5777. return true;
  5778. },
  5779. "text/plain", progress_callback);
  5780. });
  5781. }
  5782. // Helper function for multipart upload progress tests
  5783. template <typename SetupHandler, typename ClientCall>
  5784. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5785. ClientCall &&client_call,
  5786. const string &endpoint) {
  5787. Server svr;
  5788. setup_handler(svr);
  5789. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5790. auto se = detail::scope_exit([&] {
  5791. svr.stop();
  5792. t.join();
  5793. });
  5794. svr.wait_until_ready();
  5795. Client cli(HOST, PORT);
  5796. vector<uint64_t> progress_values;
  5797. UploadFormDataItems items = {
  5798. {"field1", "value1", "", ""},
  5799. {"field2", "longer value for progress tracking test", "", ""},
  5800. {"file1", "file content data for upload progress", "test.txt",
  5801. "text/plain"}};
  5802. auto res = client_call(cli, endpoint, items,
  5803. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5804. progress_values.push_back(current);
  5805. return true;
  5806. });
  5807. ASSERT_TRUE(res);
  5808. EXPECT_EQ(200, res->status);
  5809. EXPECT_FALSE(progress_values.empty());
  5810. }
  5811. TEST(UploadProgressTest, PostMultipartProgress) {
  5812. TestMultipartUploadProgress(
  5813. [](Server &svr) {
  5814. svr.Post("/multipart", [](const Request &req, Response &res) {
  5815. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5816. res.set_content("multipart received", "text/plain");
  5817. });
  5818. },
  5819. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5820. UploadProgress progress_callback) {
  5821. return cli.Post(endpoint, items, progress_callback);
  5822. },
  5823. "/multipart");
  5824. }
  5825. // Helper function for basic download progress tests
  5826. template <typename SetupHandler, typename ClientCall>
  5827. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5828. ClientCall &&client_call, const string &endpoint,
  5829. size_t expected_content_size) {
  5830. Server svr;
  5831. setup_handler(svr);
  5832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5833. auto se = detail::scope_exit([&] {
  5834. svr.stop();
  5835. t.join();
  5836. });
  5837. svr.wait_until_ready();
  5838. Client cli(HOST, PORT);
  5839. vector<uint64_t> progress_values;
  5840. auto res = client_call(cli, endpoint,
  5841. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5842. progress_values.push_back(current);
  5843. return true;
  5844. });
  5845. ASSERT_TRUE(res);
  5846. EXPECT_EQ(200, res->status);
  5847. EXPECT_FALSE(progress_values.empty());
  5848. EXPECT_EQ(expected_content_size, res->body.size());
  5849. }
  5850. TEST(DownloadProgressTest, GetBasic) {
  5851. TestBasicDownloadProgress(
  5852. [](Server &svr) {
  5853. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5854. string content(1000, 'D');
  5855. res.set_content(content, "text/plain");
  5856. });
  5857. },
  5858. [](Client &cli, const string &endpoint,
  5859. DownloadProgress progress_callback) {
  5860. return cli.Get(endpoint, progress_callback);
  5861. },
  5862. "/download", 1000u);
  5863. }
  5864. // Helper function for content receiver download progress tests
  5865. template <typename SetupHandler, typename ClientCall>
  5866. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5867. ClientCall &&client_call,
  5868. const string &endpoint,
  5869. size_t expected_content_size) {
  5870. Server svr;
  5871. setup_handler(svr);
  5872. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5873. auto se = detail::scope_exit([&] {
  5874. svr.stop();
  5875. t.join();
  5876. });
  5877. svr.wait_until_ready();
  5878. Client cli(HOST, PORT);
  5879. vector<uint64_t> progress_values;
  5880. string received_body;
  5881. auto res = client_call(
  5882. cli, endpoint,
  5883. [&](const char *data, size_t data_length) -> bool {
  5884. received_body.append(data, data_length);
  5885. return true;
  5886. },
  5887. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5888. progress_values.push_back(current);
  5889. return true;
  5890. });
  5891. ASSERT_TRUE(res);
  5892. EXPECT_EQ(200, res->status);
  5893. EXPECT_FALSE(progress_values.empty());
  5894. EXPECT_EQ(expected_content_size, received_body.size());
  5895. EXPECT_TRUE(res->body.empty());
  5896. }
  5897. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5898. TestContentReceiverDownloadProgress(
  5899. [](Server &svr) {
  5900. svr.Get("/download-receiver",
  5901. [](const Request & /*req*/, Response &res) {
  5902. string content(2000, 'R');
  5903. res.set_content(content, "text/plain");
  5904. });
  5905. },
  5906. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5907. DownloadProgress progress_callback) {
  5908. return cli.Get(endpoint, content_receiver, progress_callback);
  5909. },
  5910. "/download-receiver", 2000u);
  5911. }
  5912. TEST(StreamingTest, NoContentLengthStreaming) {
  5913. Server svr;
  5914. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5915. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5916. if (offset < 6) {
  5917. sink.os << (offset < 3 ? "a" : "b");
  5918. } else {
  5919. sink.done();
  5920. }
  5921. return true;
  5922. });
  5923. });
  5924. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5925. auto listen_se = detail::scope_exit([&] {
  5926. svr.stop();
  5927. listen_thread.join();
  5928. ASSERT_FALSE(svr.is_running());
  5929. });
  5930. svr.wait_until_ready();
  5931. Client client(HOST, PORT);
  5932. auto get_thread = std::thread([&client]() {
  5933. std::string s;
  5934. auto res =
  5935. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5936. s += std::string(data, len);
  5937. return true;
  5938. });
  5939. ASSERT_TRUE(res);
  5940. EXPECT_EQ(StatusCode::OK_200, res->status);
  5941. EXPECT_EQ("aaabbb", s);
  5942. });
  5943. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5944. // Give GET time to get a few messages.
  5945. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5946. }
  5947. TEST(MountTest, Unmount) {
  5948. Server svr;
  5949. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5950. auto se = detail::scope_exit([&] {
  5951. svr.stop();
  5952. listen_thread.join();
  5953. ASSERT_FALSE(svr.is_running());
  5954. });
  5955. svr.wait_until_ready();
  5956. Client cli("localhost", PORT);
  5957. svr.set_mount_point("/mount2", "./www2");
  5958. auto res = cli.Get("/");
  5959. ASSERT_TRUE(res);
  5960. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5961. res = cli.Get("/mount2/dir/test.html");
  5962. ASSERT_TRUE(res);
  5963. EXPECT_EQ(StatusCode::OK_200, res->status);
  5964. svr.set_mount_point("/", "./www");
  5965. res = cli.Get("/dir/");
  5966. ASSERT_TRUE(res);
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. svr.remove_mount_point("/");
  5969. res = cli.Get("/dir/");
  5970. ASSERT_TRUE(res);
  5971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5972. svr.remove_mount_point("/mount2");
  5973. res = cli.Get("/mount2/dir/test.html");
  5974. ASSERT_TRUE(res);
  5975. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5976. }
  5977. TEST(MountTest, Redicect) {
  5978. Server svr;
  5979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5980. auto se = detail::scope_exit([&] {
  5981. svr.stop();
  5982. listen_thread.join();
  5983. ASSERT_FALSE(svr.is_running());
  5984. });
  5985. svr.set_mount_point("/", "./www");
  5986. svr.wait_until_ready();
  5987. Client cli("localhost", PORT);
  5988. auto res = cli.Get("/dir/");
  5989. ASSERT_TRUE(res);
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. res = cli.Get("/dir");
  5992. ASSERT_TRUE(res);
  5993. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5994. res = cli.Get("/file");
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. res = cli.Get("/file/");
  5998. ASSERT_TRUE(res);
  5999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6000. cli.set_follow_location(true);
  6001. res = cli.Get("/dir");
  6002. ASSERT_TRUE(res);
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. }
  6005. TEST(MountTest, MultibytesPathName) {
  6006. Server svr;
  6007. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6008. auto se = detail::scope_exit([&] {
  6009. svr.stop();
  6010. listen_thread.join();
  6011. ASSERT_FALSE(svr.is_running());
  6012. });
  6013. svr.set_mount_point("/", "./www");
  6014. svr.wait_until_ready();
  6015. Client cli("localhost", PORT);
  6016. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6017. ASSERT_TRUE(res);
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6020. }
  6021. TEST(KeepAliveTest, ReadTimeout) {
  6022. Server svr;
  6023. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6024. std::this_thread::sleep_for(std::chrono::seconds(2));
  6025. res.set_content("a", "text/plain");
  6026. });
  6027. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6028. res.set_content("b", "text/plain");
  6029. });
  6030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6031. auto se = detail::scope_exit([&] {
  6032. svr.stop();
  6033. listen_thread.join();
  6034. ASSERT_FALSE(svr.is_running());
  6035. });
  6036. svr.wait_until_ready();
  6037. Client cli("localhost", PORT);
  6038. cli.set_keep_alive(true);
  6039. cli.set_read_timeout(std::chrono::seconds(1));
  6040. auto resa = cli.Get("/a");
  6041. ASSERT_FALSE(resa);
  6042. EXPECT_EQ(Error::Read, resa.error());
  6043. auto resb = cli.Get("/b");
  6044. ASSERT_TRUE(resb);
  6045. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6046. EXPECT_EQ("b", resb->body);
  6047. }
  6048. TEST(KeepAliveTest, MaxCount) {
  6049. size_t keep_alive_max_count = 3;
  6050. Server svr;
  6051. svr.set_keep_alive_max_count(keep_alive_max_count);
  6052. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6053. res.set_content("Hello World!", "text/plain");
  6054. });
  6055. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6056. auto se = detail::scope_exit([&] {
  6057. svr.stop();
  6058. listen_thread.join();
  6059. ASSERT_FALSE(svr.is_running());
  6060. });
  6061. svr.wait_until_ready();
  6062. Client cli(HOST, PORT);
  6063. cli.set_keep_alive(true);
  6064. for (size_t i = 0; i < 5; i++) {
  6065. auto result = cli.Get("/hi");
  6066. ASSERT_TRUE(result);
  6067. EXPECT_EQ(StatusCode::OK_200, result->status);
  6068. if (i == keep_alive_max_count - 1) {
  6069. EXPECT_EQ("close", result->get_header_value("Connection"));
  6070. } else {
  6071. EXPECT_FALSE(result->has_header("Connection"));
  6072. }
  6073. }
  6074. }
  6075. TEST(KeepAliveTest, Issue1041) {
  6076. Server svr;
  6077. svr.set_keep_alive_timeout(3);
  6078. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6079. res.set_content("Hello World!", "text/plain");
  6080. });
  6081. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6082. auto se = detail::scope_exit([&] {
  6083. svr.stop();
  6084. listen_thread.join();
  6085. ASSERT_FALSE(svr.is_running());
  6086. });
  6087. svr.wait_until_ready();
  6088. Client cli(HOST, PORT);
  6089. cli.set_keep_alive(true);
  6090. auto result = cli.Get("/hi");
  6091. ASSERT_TRUE(result);
  6092. EXPECT_EQ(StatusCode::OK_200, result->status);
  6093. std::this_thread::sleep_for(std::chrono::seconds(5));
  6094. result = cli.Get("/hi");
  6095. ASSERT_TRUE(result);
  6096. EXPECT_EQ(StatusCode::OK_200, result->status);
  6097. }
  6098. TEST(KeepAliveTest, Issue1959) {
  6099. Server svr;
  6100. svr.set_keep_alive_timeout(5);
  6101. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6102. res.set_content("a", "text/plain");
  6103. });
  6104. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6105. auto se = detail::scope_exit([&] {
  6106. if (!svr.is_running()) return;
  6107. svr.stop();
  6108. listen_thread.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. Client cli("localhost", PORT);
  6113. cli.set_keep_alive(true);
  6114. using namespace std::chrono;
  6115. auto start = steady_clock::now();
  6116. cli.Get("/a");
  6117. svr.stop();
  6118. listen_thread.join();
  6119. auto end = steady_clock::now();
  6120. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6121. EXPECT_LT(elapsed, 5000);
  6122. }
  6123. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6124. TEST(KeepAliveTest, SSLClientReconnection) {
  6125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6126. ASSERT_TRUE(svr.is_valid());
  6127. svr.set_keep_alive_timeout(1);
  6128. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6129. res.set_content("Hello World!", "text/plain");
  6130. });
  6131. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6132. auto se = detail::scope_exit([&] {
  6133. svr.stop();
  6134. listen_thread.join();
  6135. ASSERT_FALSE(svr.is_running());
  6136. });
  6137. svr.wait_until_ready();
  6138. SSLClient cli(HOST, PORT);
  6139. cli.enable_server_certificate_verification(false);
  6140. cli.set_keep_alive(true);
  6141. auto result = cli.Get("/hi");
  6142. ASSERT_TRUE(result);
  6143. EXPECT_EQ(StatusCode::OK_200, result->status);
  6144. result = cli.Get("/hi");
  6145. ASSERT_TRUE(result);
  6146. EXPECT_EQ(StatusCode::OK_200, result->status);
  6147. std::this_thread::sleep_for(std::chrono::seconds(2));
  6148. // Recoonect
  6149. result = cli.Get("/hi");
  6150. ASSERT_TRUE(result);
  6151. EXPECT_EQ(StatusCode::OK_200, result->status);
  6152. result = cli.Get("/hi");
  6153. ASSERT_TRUE(result);
  6154. EXPECT_EQ(StatusCode::OK_200, result->status);
  6155. }
  6156. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6158. ASSERT_TRUE(svr.is_valid());
  6159. svr.set_keep_alive_timeout(1);
  6160. std::string content = "reconnect";
  6161. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6162. res.set_content("Hello World!", "text/plain");
  6163. });
  6164. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6165. auto se = detail::scope_exit([&] {
  6166. svr.stop();
  6167. listen_thread.join();
  6168. ASSERT_FALSE(svr.is_running());
  6169. });
  6170. svr.wait_until_ready();
  6171. SSLClient cli(HOST, PORT);
  6172. cli.enable_server_certificate_verification(false);
  6173. cli.set_keep_alive(true);
  6174. auto result = cli.Post(
  6175. "/hi", content.size(),
  6176. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6177. sink.write(content.c_str(), content.size());
  6178. return true;
  6179. },
  6180. "text/plain");
  6181. ASSERT_TRUE(result);
  6182. EXPECT_EQ(200, result->status);
  6183. std::this_thread::sleep_for(std::chrono::seconds(2));
  6184. // Recoonect
  6185. result = cli.Post(
  6186. "/hi", content.size(),
  6187. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6188. sink.write(content.c_str(), content.size());
  6189. return true;
  6190. },
  6191. "text/plain");
  6192. ASSERT_TRUE(result);
  6193. EXPECT_EQ(200, result->status);
  6194. result = cli.Post(
  6195. "/hi", content.size(),
  6196. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6197. sink.write(content.c_str(), content.size());
  6198. return true;
  6199. },
  6200. "text/plain");
  6201. ASSERT_TRUE(result);
  6202. EXPECT_EQ(200, result->status);
  6203. }
  6204. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6205. {
  6206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6207. ASSERT_TRUE(svr.is_valid());
  6208. svr.Get("/sni", [&](const Request &req, Response &res) {
  6209. std::string expected;
  6210. if (req.ssl) {
  6211. if (const char *sni =
  6212. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6213. expected = sni;
  6214. }
  6215. }
  6216. EXPECT_EQ(expected, req.get_param_value("expected"));
  6217. res.set_content("ok", "text/plain");
  6218. });
  6219. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.wait_until_ready();
  6226. {
  6227. SSLClient cli("localhost", PORT);
  6228. cli.enable_server_certificate_verification(false);
  6229. auto res = cli.Get("/sni?expected=localhost");
  6230. ASSERT_TRUE(res);
  6231. }
  6232. {
  6233. SSLClient cli("::1", PORT);
  6234. cli.enable_server_certificate_verification(false);
  6235. auto res = cli.Get("/sni?expected=");
  6236. ASSERT_TRUE(res);
  6237. }
  6238. }
  6239. }
  6240. #endif
  6241. TEST(ClientProblemDetectionTest, ContentProvider) {
  6242. Server svr;
  6243. size_t content_length = 1024 * 1024;
  6244. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6245. res.set_content_provider(
  6246. content_length, "text/plain",
  6247. [&](size_t offset, size_t length, DataSink &sink) {
  6248. auto out_len = std::min(length, static_cast<size_t>(1024));
  6249. std::string out(out_len, '@');
  6250. sink.write(out.data(), out_len);
  6251. return offset < 4096;
  6252. },
  6253. [](bool success) { ASSERT_FALSE(success); });
  6254. });
  6255. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6256. res.set_content_provider(
  6257. 0, "text/plain",
  6258. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6259. EXPECT_TRUE(false);
  6260. return true;
  6261. },
  6262. [](bool success) { ASSERT_FALSE(success); });
  6263. });
  6264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6265. auto se = detail::scope_exit([&] {
  6266. svr.stop();
  6267. listen_thread.join();
  6268. ASSERT_FALSE(svr.is_running());
  6269. });
  6270. svr.wait_until_ready();
  6271. Client cli("localhost", PORT);
  6272. {
  6273. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6274. size_t /*data_length*/) { return false; });
  6275. ASSERT_FALSE(res);
  6276. }
  6277. {
  6278. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6279. size_t /*data_length*/) { return false; });
  6280. ASSERT_TRUE(res);
  6281. }
  6282. }
  6283. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6284. Server svr;
  6285. svr.set_error_handler([](Request const &, Response &res) -> void {
  6286. res.set_chunked_content_provider(
  6287. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6288. sink.os << "hello";
  6289. sink.os << "world";
  6290. sink.done();
  6291. return true;
  6292. });
  6293. });
  6294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6295. auto se = detail::scope_exit([&] {
  6296. svr.stop();
  6297. listen_thread.join();
  6298. ASSERT_FALSE(svr.is_running());
  6299. });
  6300. svr.wait_until_ready();
  6301. Client cli("localhost", PORT);
  6302. auto res = cli.Get("/");
  6303. ASSERT_TRUE(res);
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. EXPECT_EQ("helloworld", res->body);
  6306. }
  6307. TEST(LongPollingTest, ClientCloseDetection) {
  6308. Server svr;
  6309. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6310. res.set_chunked_content_provider(
  6311. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6312. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6313. sink.os << "hello";
  6314. auto count = 10;
  6315. while (count > 0 && sink.is_writable()) {
  6316. this_thread::sleep_for(chrono::milliseconds(10));
  6317. count--;
  6318. }
  6319. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6320. return true;
  6321. });
  6322. });
  6323. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6324. auto se = detail::scope_exit([&] {
  6325. svr.stop();
  6326. listen_thread.join();
  6327. ASSERT_FALSE(svr.is_running());
  6328. });
  6329. svr.wait_until_ready();
  6330. Client cli("localhost", PORT);
  6331. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6332. EXPECT_EQ("hello", string(data, data_length));
  6333. return false; // close the socket immediately.
  6334. });
  6335. ASSERT_FALSE(res);
  6336. }
  6337. TEST(GetWithParametersTest, GetWithParameters) {
  6338. Server svr;
  6339. svr.Get("/", [&](const Request &req, Response &) {
  6340. EXPECT_EQ("world", req.get_param_value("hello"));
  6341. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6342. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6343. });
  6344. svr.Get("/params", [&](const Request &req, Response &) {
  6345. EXPECT_EQ("world", req.get_param_value("hello"));
  6346. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6347. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6348. });
  6349. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6350. EXPECT_EQ("resource-id", req.matches[1]);
  6351. EXPECT_EQ("foo", req.get_param_value("param1"));
  6352. EXPECT_EQ("bar", req.get_param_value("param2"));
  6353. });
  6354. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6355. EXPECT_EQ("user-id", req.path_params.at("id"));
  6356. EXPECT_EQ("foo", req.get_param_value("param1"));
  6357. EXPECT_EQ("bar", req.get_param_value("param2"));
  6358. });
  6359. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6360. auto se = detail::scope_exit([&] {
  6361. svr.stop();
  6362. listen_thread.join();
  6363. ASSERT_FALSE(svr.is_running());
  6364. });
  6365. svr.wait_until_ready();
  6366. {
  6367. Client cli(HOST, PORT);
  6368. Params params;
  6369. params.emplace("hello", "world");
  6370. params.emplace("hello2", "world2");
  6371. params.emplace("hello3", "world3");
  6372. auto res = cli.Get("/", params, Headers{});
  6373. ASSERT_TRUE(res);
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. }
  6376. {
  6377. Client cli(HOST, PORT);
  6378. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6379. ASSERT_TRUE(res);
  6380. EXPECT_EQ(StatusCode::OK_200, res->status);
  6381. }
  6382. {
  6383. Client cli(HOST, PORT);
  6384. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6385. ASSERT_TRUE(res);
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. }
  6388. {
  6389. Client cli(HOST, PORT);
  6390. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6391. ASSERT_TRUE(res);
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. }
  6395. TEST(GetWithParametersTest, GetWithParameters2) {
  6396. Server svr;
  6397. svr.Get("/", [&](const Request &req, Response &res) {
  6398. auto text = req.get_param_value("hello");
  6399. res.set_content(text, "text/plain");
  6400. });
  6401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6402. auto se = detail::scope_exit([&] {
  6403. svr.stop();
  6404. listen_thread.join();
  6405. ASSERT_FALSE(svr.is_running());
  6406. });
  6407. svr.wait_until_ready();
  6408. Client cli("localhost", PORT);
  6409. Params params;
  6410. params.emplace("hello", "world");
  6411. std::string body;
  6412. auto res = cli.Get("/", params, Headers{},
  6413. [&](const char *data, size_t data_length) {
  6414. body.append(data, data_length);
  6415. return true;
  6416. });
  6417. ASSERT_TRUE(res);
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("world", body);
  6420. }
  6421. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6422. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6423. auto host = "httpbin.org";
  6424. auto path = std::string{"/range/32"};
  6425. #else
  6426. auto host = "nghttp2.org";
  6427. auto path = std::string{"/httpbin/range/32"};
  6428. #endif
  6429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6430. SSLClient cli(host);
  6431. #else
  6432. Client cli(host);
  6433. #endif
  6434. cli.set_default_headers({make_range_header({{1, 10}})});
  6435. cli.set_connection_timeout(5);
  6436. {
  6437. auto res = cli.Get(path);
  6438. ASSERT_TRUE(res);
  6439. EXPECT_EQ("bcdefghijk", res->body);
  6440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6441. }
  6442. {
  6443. auto res = cli.Get(path);
  6444. ASSERT_TRUE(res);
  6445. EXPECT_EQ("bcdefghijk", res->body);
  6446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6447. }
  6448. }
  6449. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6450. Server svr;
  6451. svr.set_default_headers({{"Hello", "World"}});
  6452. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6453. res.set_content("ok", "text/plain");
  6454. });
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client cli("localhost", PORT);
  6463. auto res = cli.Get("/");
  6464. ASSERT_TRUE(res);
  6465. EXPECT_EQ(StatusCode::OK_200, res->status);
  6466. EXPECT_EQ("ok", res->body);
  6467. EXPECT_EQ("World", res->get_header_value("Hello"));
  6468. }
  6469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6470. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6472. ASSERT_TRUE(svr.is_valid());
  6473. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6474. std::this_thread::sleep_for(std::chrono::seconds(2));
  6475. res.set_content("a", "text/plain");
  6476. });
  6477. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6478. res.set_content("b", "text/plain");
  6479. });
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. SSLClient cli("localhost", PORT);
  6488. cli.enable_server_certificate_verification(false);
  6489. cli.set_keep_alive(true);
  6490. cli.set_read_timeout(std::chrono::seconds(1));
  6491. auto resa = cli.Get("/a");
  6492. ASSERT_TRUE(!resa);
  6493. EXPECT_EQ(Error::Read, resa.error());
  6494. auto resb = cli.Get("/b");
  6495. ASSERT_TRUE(resb);
  6496. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6497. EXPECT_EQ("b", resb->body);
  6498. }
  6499. #endif
  6500. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6501. protected:
  6502. ServerTestWithAI_PASSIVE()
  6503. : cli_(HOST, PORT)
  6504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6505. ,
  6506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6507. #endif
  6508. {
  6509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6510. cli_.enable_server_certificate_verification(false);
  6511. #endif
  6512. }
  6513. virtual void SetUp() {
  6514. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6515. res.set_content("Hello World!", "text/plain");
  6516. });
  6517. t_ = thread(
  6518. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6519. svr_.wait_until_ready();
  6520. }
  6521. virtual void TearDown() {
  6522. svr_.stop();
  6523. t_.join();
  6524. }
  6525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6526. SSLClient cli_;
  6527. SSLServer svr_;
  6528. #else
  6529. Client cli_;
  6530. Server svr_;
  6531. #endif
  6532. thread t_;
  6533. };
  6534. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6535. auto res = cli_.Get("/hi");
  6536. ASSERT_TRUE(res);
  6537. EXPECT_EQ(StatusCode::OK_200, res->status);
  6538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6539. EXPECT_EQ("Hello World!", res->body);
  6540. }
  6541. class ServerUpDownTest : public ::testing::Test {
  6542. protected:
  6543. ServerUpDownTest() : cli_(HOST, PORT) {}
  6544. virtual void SetUp() {
  6545. t_ = thread([&]() {
  6546. svr_.bind_to_any_port(HOST);
  6547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6548. ASSERT_TRUE(svr_.listen_after_bind());
  6549. });
  6550. svr_.wait_until_ready();
  6551. }
  6552. virtual void TearDown() {
  6553. svr_.stop();
  6554. t_.join();
  6555. }
  6556. Client cli_;
  6557. Server svr_;
  6558. thread t_;
  6559. };
  6560. TEST_F(ServerUpDownTest, QuickStartStop) {
  6561. // Should not crash, especially when run with
  6562. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6563. }
  6564. class PayloadMaxLengthTest : public ::testing::Test {
  6565. protected:
  6566. PayloadMaxLengthTest()
  6567. : cli_(HOST, PORT)
  6568. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6569. ,
  6570. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6571. #endif
  6572. {
  6573. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6574. cli_.enable_server_certificate_verification(false);
  6575. #endif
  6576. }
  6577. virtual void SetUp() {
  6578. svr_.set_payload_max_length(8);
  6579. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6580. res.set_content("test", "text/plain");
  6581. });
  6582. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6583. svr_.wait_until_ready();
  6584. }
  6585. virtual void TearDown() {
  6586. svr_.stop();
  6587. t_.join();
  6588. }
  6589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6590. SSLClient cli_;
  6591. SSLServer svr_;
  6592. #else
  6593. Client cli_;
  6594. Server svr_;
  6595. #endif
  6596. thread t_;
  6597. };
  6598. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6599. auto res = cli_.Post("/test", "123456789", "text/plain");
  6600. ASSERT_TRUE(res);
  6601. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6602. res = cli_.Post("/test", "12345678", "text/plain");
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. }
  6606. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6607. // Test chunked encoding with payload exceeding the 8-byte limit
  6608. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6609. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6610. ASSERT_TRUE(res);
  6611. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6612. }
  6613. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6614. // Test chunked encoding with payload within the 8-byte limit
  6615. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6616. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6617. ASSERT_TRUE(res);
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. }
  6620. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6621. // Test using send_request to send chunked data exceeding payload limit
  6622. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6623. "Host: " +
  6624. std::string(HOST) + ":" + std::to_string(PORT) +
  6625. "\r\n"
  6626. "Transfer-Encoding: chunked\r\n"
  6627. "Connection: close\r\n"
  6628. "\r\n"
  6629. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6630. "0123456789\r\n"
  6631. "0\r\n" // End chunk
  6632. "\r\n";
  6633. std::string response;
  6634. bool result = send_request(1, chunked_request, &response);
  6635. if (!result) {
  6636. // If send_request fails, it might be because the server closed the
  6637. // connection due to payload limit enforcement, which is acceptable
  6638. SUCCEED()
  6639. << "Server rejected oversized chunked request (connection closed)";
  6640. } else {
  6641. // If we got a response, check if it's an error response or connection was
  6642. // closed early Short response length indicates connection was closed due to
  6643. // payload limit
  6644. if (response.length() <= 10) {
  6645. SUCCEED() << "Server closed connection for oversized chunked request";
  6646. } else {
  6647. // Check for error status codes
  6648. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6649. response.find("Payload Too Large") != std::string::npos ||
  6650. response.find("400") != std::string::npos);
  6651. }
  6652. }
  6653. }
  6654. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6655. // Test request without Content-Length header exceeding payload limit
  6656. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6657. "Host: " +
  6658. std::string(HOST) + ":" +
  6659. std::to_string(PORT) +
  6660. "\r\n"
  6661. "Connection: close\r\n"
  6662. "\r\n";
  6663. // Add payload exceeding the 8-byte limit
  6664. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6665. request_without_content_length += large_payload;
  6666. std::string response;
  6667. bool result = send_request(1, request_without_content_length, &response);
  6668. if (!result) {
  6669. // If send_request fails, server likely closed connection due to payload
  6670. // limit
  6671. SUCCEED() << "Server rejected oversized request without Content-Length "
  6672. "(connection closed)";
  6673. } else {
  6674. // Check if server responded with error or closed connection early
  6675. if (response.length() <= 10) {
  6676. SUCCEED() << "Server closed connection for oversized request without "
  6677. "Content-Length";
  6678. } else {
  6679. // Check for error status codes
  6680. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6681. response.find("Payload Too Large") != std::string::npos ||
  6682. response.find("400") != std::string::npos);
  6683. }
  6684. }
  6685. }
  6686. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6687. // Test request without Content-Length header within payload limit
  6688. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6689. "Host: " +
  6690. std::string(HOST) + ":" +
  6691. std::to_string(PORT) +
  6692. "\r\n"
  6693. "Connection: close\r\n"
  6694. "\r\n";
  6695. // Add payload within the 8-byte limit
  6696. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6697. request_without_content_length += small_payload;
  6698. std::string response;
  6699. bool result = send_request(1, request_without_content_length, &response);
  6700. // For requests without Content-Length, the server may have different behavior
  6701. // The key is that it should not reject due to payload limit for small
  6702. // payloads
  6703. if (result) {
  6704. // Check for any HTTP response (success or error, but not connection closed)
  6705. if (response.length() > 10) {
  6706. SUCCEED()
  6707. << "Server processed request without Content-Length within limit";
  6708. } else {
  6709. // Short response might indicate connection closed, which is acceptable
  6710. SUCCEED() << "Server closed connection for request without "
  6711. "Content-Length (acceptable behavior)";
  6712. }
  6713. } else {
  6714. // Connection failure might be due to protocol requirements
  6715. SUCCEED() << "Connection issue with request without Content-Length "
  6716. "(environment-specific)";
  6717. }
  6718. }
  6719. class LargePayloadMaxLengthTest : public ::testing::Test {
  6720. protected:
  6721. LargePayloadMaxLengthTest()
  6722. : cli_(HOST, PORT)
  6723. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6724. ,
  6725. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6726. #endif
  6727. {
  6728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6729. cli_.enable_server_certificate_verification(false);
  6730. #endif
  6731. }
  6732. virtual void SetUp() {
  6733. // Set 10MB payload limit
  6734. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6735. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6736. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6737. res.set_content("Large payload test", "text/plain");
  6738. });
  6739. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6740. svr_.wait_until_ready();
  6741. }
  6742. virtual void TearDown() {
  6743. svr_.stop();
  6744. t_.join();
  6745. }
  6746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6747. SSLClient cli_;
  6748. SSLServer svr_;
  6749. #else
  6750. Client cli_;
  6751. Server svr_;
  6752. #endif
  6753. thread t_;
  6754. };
  6755. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6756. // Test chunked encoding with payload within 10MB limit
  6757. std::string medium_payload(5 * 1024 * 1024,
  6758. 'A'); // 5MB payload, within 10MB limit
  6759. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6760. ASSERT_TRUE(res);
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6764. // Test chunked encoding with payload exceeding 10MB limit
  6765. std::string large_payload(12 * 1024 * 1024,
  6766. 'B'); // 12MB payload, exceeds 10MB limit
  6767. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6768. ASSERT_TRUE(res);
  6769. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6770. }
  6771. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6772. // Test request without Content-Length header within 10MB limit
  6773. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6774. "Host: " +
  6775. std::string(HOST) + ":" +
  6776. std::to_string(PORT) +
  6777. "\r\n"
  6778. "Connection: close\r\n"
  6779. "\r\n";
  6780. // Add 1MB payload (within 10MB limit)
  6781. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6782. request_without_content_length += medium_payload;
  6783. std::string response;
  6784. bool result = send_request(5, request_without_content_length, &response);
  6785. if (result) {
  6786. // Should get a proper HTTP response for payloads within limit
  6787. if (response.length() > 10) {
  6788. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6789. "10MB limit";
  6790. } else {
  6791. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6792. "Content-Length)";
  6793. }
  6794. } else {
  6795. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6796. }
  6797. }
  6798. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6799. // Test request without Content-Length header exceeding 10MB limit
  6800. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6801. "Host: " +
  6802. std::string(HOST) + ":" +
  6803. std::to_string(PORT) +
  6804. "\r\n"
  6805. "Connection: close\r\n"
  6806. "\r\n";
  6807. // Add 12MB payload (exceeds 10MB limit)
  6808. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6809. request_without_content_length += large_payload;
  6810. std::string response;
  6811. bool result = send_request(10, request_without_content_length, &response);
  6812. if (!result) {
  6813. // Server should close connection due to payload limit
  6814. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6815. "(connection closed)";
  6816. } else {
  6817. // Check for error response
  6818. if (response.length() <= 10) {
  6819. SUCCEED()
  6820. << "Server closed connection for 12MB request exceeding 10MB limit";
  6821. } else {
  6822. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6823. response.find("Payload Too Large") != std::string::npos ||
  6824. response.find("400") != std::string::npos);
  6825. }
  6826. }
  6827. }
  6828. TEST(HostAndPortPropertiesTest, NoSSL) {
  6829. httplib::Client cli("www.google.com", 1234);
  6830. ASSERT_EQ("www.google.com", cli.host());
  6831. ASSERT_EQ(1234, cli.port());
  6832. }
  6833. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6834. httplib::Client cli("www.google.com:1234");
  6835. ASSERT_EQ("www.google.com", cli.host());
  6836. ASSERT_EQ(1234, cli.port());
  6837. }
  6838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6839. TEST(HostAndPortPropertiesTest, SSL) {
  6840. httplib::SSLClient cli("www.google.com");
  6841. ASSERT_EQ("www.google.com", cli.host());
  6842. ASSERT_EQ(443, cli.port());
  6843. }
  6844. #endif
  6845. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6846. TEST(SSLClientTest, UpdateCAStore) {
  6847. httplib::SSLClient httplib_client("www.google.com");
  6848. auto ca_store_1 = X509_STORE_new();
  6849. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6850. nullptr);
  6851. httplib_client.set_ca_cert_store(ca_store_1);
  6852. auto ca_store_2 = X509_STORE_new();
  6853. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6854. nullptr);
  6855. httplib_client.set_ca_cert_store(ca_store_2);
  6856. }
  6857. TEST(SSLClientTest, ServerNameIndication_Online) {
  6858. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6859. auto host = "httpbin.org";
  6860. auto path = std::string{"/get"};
  6861. #else
  6862. auto host = "nghttp2.org";
  6863. auto path = std::string{"/httpbin/get"};
  6864. #endif
  6865. SSLClient cli(host, 443);
  6866. auto res = cli.Get(path);
  6867. ASSERT_TRUE(res);
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6871. // Use a site that will cause SSL verification failure due to self-signed cert
  6872. SSLClient cli("self-signed.badssl.com", 443);
  6873. cli.enable_server_certificate_verification(true);
  6874. auto res = cli.Get("/");
  6875. ASSERT_TRUE(!res);
  6876. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6877. // For SSL server verification errors, ssl_error should be 0, only
  6878. // ssl_openssl_error should be set
  6879. EXPECT_EQ(0, res.ssl_error());
  6880. // Verify OpenSSL error is captured for SSLServerVerification
  6881. // This occurs when SSL_get_verify_result() returns a verification failure
  6882. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6883. res.ssl_openssl_error());
  6884. }
  6885. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6886. // Use a site where hostname doesn't match the certificate
  6887. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6888. SSLClient cli("wrong.host.badssl.com", 443);
  6889. cli.enable_server_certificate_verification(true);
  6890. cli.enable_server_hostname_verification(true);
  6891. auto res = cli.Get("/");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6894. // For SSL hostname verification errors, ssl_error should be 0, only
  6895. // ssl_openssl_error should be set
  6896. EXPECT_EQ(0, res.ssl_error());
  6897. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6898. // This occurs when verify_host() fails due to hostname mismatch
  6899. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6900. res.ssl_openssl_error());
  6901. }
  6902. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6903. Client cli("https://google.com");
  6904. auto res = cli.Get("/");
  6905. ASSERT_TRUE(res);
  6906. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6907. }
  6908. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6909. SSLClient cli("google.com");
  6910. cli.set_ca_cert_path(CA_CERT_FILE);
  6911. auto res = cli.Get("/");
  6912. ASSERT_TRUE(res);
  6913. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6914. }
  6915. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6916. SSLClient cli("google.com");
  6917. cli.enable_server_certificate_verification(true);
  6918. cli.set_ca_cert_path("hello");
  6919. auto res = cli.Get("/");
  6920. ASSERT_TRUE(!res);
  6921. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6922. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6923. // should be set
  6924. EXPECT_EQ(0, res.ssl_error());
  6925. // Verify OpenSSL error is captured for SSLLoadingCerts
  6926. // This error occurs when SSL_CTX_load_verify_locations() fails
  6927. // > openssl errstr 0x80000002
  6928. // error:80000002:system library::No such file or directory
  6929. // > openssl errstr 0xA000126
  6930. // error:0A000126:SSL routines::unexpected eof while reading
  6931. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6932. res.ssl_openssl_error() == 0xA000126);
  6933. }
  6934. TEST(SSLClientTest, ServerCertificateVerification4) {
  6935. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6936. ASSERT_TRUE(svr.is_valid());
  6937. svr.Get("/test", [&](const Request &, Response &res) {
  6938. res.set_content("test", "text/plain");
  6939. svr.stop();
  6940. ASSERT_TRUE(true);
  6941. });
  6942. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6943. auto se = detail::scope_exit([&] {
  6944. t.join();
  6945. ASSERT_FALSE(svr.is_running());
  6946. });
  6947. svr.wait_until_ready();
  6948. SSLClient cli("127.0.0.1", PORT);
  6949. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6950. cli.enable_server_certificate_verification(true);
  6951. cli.set_connection_timeout(30);
  6952. auto res = cli.Get("/test");
  6953. ASSERT_TRUE(res);
  6954. ASSERT_EQ(StatusCode::OK_200, res->status);
  6955. }
  6956. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6957. std::string cert;
  6958. read_file(CA_CERT_FILE, cert);
  6959. SSLClient cli("google.com");
  6960. cli.load_ca_cert_store(cert.data(), cert.size());
  6961. const auto res = cli.Get("/");
  6962. ASSERT_TRUE(res);
  6963. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6964. }
  6965. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6966. // clang-format off
  6967. static constexpr char cert[] =
  6968. "GlobalSign Root CA\n"
  6969. "==================\n"
  6970. "-----BEGIN CERTIFICATE-----\n"
  6971. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6972. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6973. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6974. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6975. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6976. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6977. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6978. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6979. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6980. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6981. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6982. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6983. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6984. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6985. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6986. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6987. "-----END CERTIFICATE-----\n";
  6988. // clang-format on
  6989. SSLClient cli("google.com");
  6990. cli.load_ca_cert_store(cert, sizeof(cert));
  6991. const auto res = cli.Get("/");
  6992. ASSERT_TRUE(res);
  6993. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6994. }
  6995. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6996. SSLClient cli("www.youtube.com");
  6997. cli.set_ca_cert_path(CA_CERT_FILE);
  6998. cli.enable_server_certificate_verification(true);
  6999. cli.set_follow_location(true);
  7000. auto res = cli.Get("/");
  7001. ASSERT_TRUE(res);
  7002. ASSERT_EQ(StatusCode::OK_200, res->status);
  7003. }
  7004. TEST(SSLClientTest, Issue2004_Online) {
  7005. Client client("https://google.com");
  7006. client.set_follow_location(true);
  7007. auto res = client.Get("/");
  7008. ASSERT_TRUE(res);
  7009. ASSERT_EQ(StatusCode::OK_200, res->status);
  7010. auto body = res->body;
  7011. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7012. }
  7013. #if 0
  7014. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7015. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7016. ASSERT_TRUE(cli != nullptr);
  7017. cli->set_address_family(AF_INET6);
  7018. cli->set_interface("en0");
  7019. auto res = cli->Get("/get");
  7020. ASSERT_TRUE(res);
  7021. ASSERT_EQ(StatusCode::OK_200, res->status);
  7022. }
  7023. #endif
  7024. void ClientCertPresent(
  7025. const std::string &client_cert_file,
  7026. const std::string &client_private_key_file,
  7027. const std::string &client_encrypted_private_key_pass = std::string()) {
  7028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7029. CLIENT_CA_CERT_DIR);
  7030. ASSERT_TRUE(svr.is_valid());
  7031. svr.Get("/test", [&](const Request &req, Response &res) {
  7032. res.set_content("test", "text/plain");
  7033. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7034. ASSERT_TRUE(peer_cert != nullptr);
  7035. auto subject_name = X509_get_subject_name(peer_cert);
  7036. ASSERT_TRUE(subject_name != nullptr);
  7037. std::string common_name;
  7038. {
  7039. char name[BUFSIZ];
  7040. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7041. name, sizeof(name));
  7042. common_name.assign(name, static_cast<size_t>(name_len));
  7043. }
  7044. EXPECT_EQ("Common Name", common_name);
  7045. X509_free(peer_cert);
  7046. });
  7047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7048. auto se = detail::scope_exit([&] {
  7049. svr.stop();
  7050. t.join();
  7051. ASSERT_FALSE(svr.is_running());
  7052. });
  7053. svr.wait_until_ready();
  7054. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7055. client_encrypted_private_key_pass);
  7056. cli.enable_server_certificate_verification(false);
  7057. cli.set_connection_timeout(30);
  7058. auto res = cli.Get("/test");
  7059. ASSERT_TRUE(res);
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST(SSLClientServerTest, ClientCertPresent) {
  7063. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7064. }
  7065. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7066. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7067. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7068. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7069. }
  7070. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7071. void MemoryClientCertPresent(
  7072. const std::string &client_cert_file,
  7073. const std::string &client_private_key_file,
  7074. const std::string &client_encrypted_private_key_pass = std::string()) {
  7075. auto f = fopen(SERVER_CERT_FILE, "r+");
  7076. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7077. fclose(f);
  7078. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7079. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7080. fclose(f);
  7081. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7082. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7083. auto client_ca_cert_store = X509_STORE_new();
  7084. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7085. X509_free(client_cert);
  7086. fclose(f);
  7087. f = fopen(client_cert_file.c_str(), "r+");
  7088. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7089. fclose(f);
  7090. f = fopen(client_private_key_file.c_str(), "r+");
  7091. auto client_private_key = PEM_read_PrivateKey(
  7092. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7093. fclose(f);
  7094. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7095. ASSERT_TRUE(svr.is_valid());
  7096. svr.Get("/test", [&](const Request &req, Response &res) {
  7097. res.set_content("test", "text/plain");
  7098. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7099. ASSERT_TRUE(peer_cert != nullptr);
  7100. auto subject_name = X509_get_subject_name(peer_cert);
  7101. ASSERT_TRUE(subject_name != nullptr);
  7102. std::string common_name;
  7103. {
  7104. char name[BUFSIZ];
  7105. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7106. name, sizeof(name));
  7107. common_name.assign(name, static_cast<size_t>(name_len));
  7108. }
  7109. EXPECT_EQ("Common Name", common_name);
  7110. X509_free(peer_cert);
  7111. });
  7112. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7113. auto se = detail::scope_exit([&] {
  7114. svr.stop();
  7115. t.join();
  7116. ASSERT_FALSE(svr.is_running());
  7117. });
  7118. svr.wait_until_ready();
  7119. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7120. client_encrypted_private_key_pass);
  7121. cli.enable_server_certificate_verification(false);
  7122. cli.set_connection_timeout(30);
  7123. auto res = cli.Get("/test");
  7124. ASSERT_TRUE(res);
  7125. ASSERT_EQ(StatusCode::OK_200, res->status);
  7126. X509_free(server_cert);
  7127. EVP_PKEY_free(server_private_key);
  7128. X509_free(client_cert);
  7129. EVP_PKEY_free(client_private_key);
  7130. }
  7131. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7132. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7133. }
  7134. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7135. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7136. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7137. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7138. }
  7139. #endif
  7140. TEST(SSLClientServerTest, ClientCertMissing) {
  7141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7142. CLIENT_CA_CERT_DIR);
  7143. ASSERT_TRUE(svr.is_valid());
  7144. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7146. auto se = detail::scope_exit([&] {
  7147. svr.stop();
  7148. t.join();
  7149. ASSERT_FALSE(svr.is_running());
  7150. });
  7151. svr.wait_until_ready();
  7152. SSLClient cli(HOST, PORT);
  7153. cli.set_connection_timeout(30);
  7154. auto res = cli.Get("/test");
  7155. ASSERT_TRUE(!res);
  7156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7157. // For SSL server verification errors, ssl_error should be 0, only
  7158. // ssl_openssl_error should be set
  7159. EXPECT_EQ(0, res.ssl_error());
  7160. // Verify OpenSSL error is captured for SSLServerVerification
  7161. // Note: This test may have different error codes depending on the exact
  7162. // verification failure
  7163. EXPECT_NE(0UL, res.ssl_openssl_error());
  7164. }
  7165. TEST(SSLClientServerTest, TrustDirOptional) {
  7166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7167. ASSERT_TRUE(svr.is_valid());
  7168. svr.Get("/test", [&](const Request &, Response &res) {
  7169. res.set_content("test", "text/plain");
  7170. });
  7171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7172. auto se = detail::scope_exit([&] {
  7173. svr.stop();
  7174. t.join();
  7175. ASSERT_FALSE(svr.is_running());
  7176. });
  7177. svr.wait_until_ready();
  7178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7179. cli.enable_server_certificate_verification(false);
  7180. cli.set_connection_timeout(30);
  7181. auto res = cli.Get("/test");
  7182. ASSERT_TRUE(res);
  7183. ASSERT_EQ(StatusCode::OK_200, res->status);
  7184. }
  7185. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7186. class NoListenSSLServer : public SSLServer {
  7187. public:
  7188. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7189. const char *client_ca_cert_file_path,
  7190. const char *client_ca_cert_dir_path = nullptr)
  7191. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7192. client_ca_cert_dir_path),
  7193. stop_(false) {}
  7194. std::atomic_bool stop_;
  7195. private:
  7196. bool process_and_close_socket(socket_t /*sock*/) override {
  7197. // Don't create SSL context
  7198. while (!stop_.load()) {
  7199. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7200. }
  7201. return true;
  7202. }
  7203. };
  7204. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7205. CLIENT_CA_CERT_FILE);
  7206. ASSERT_TRUE(svr.is_valid());
  7207. svr.Get("/test", [&](const Request &, Response &res) {
  7208. res.set_content("test", "text/plain");
  7209. });
  7210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7211. auto se = detail::scope_exit([&] {
  7212. svr.stop_ = true;
  7213. svr.stop();
  7214. t.join();
  7215. ASSERT_FALSE(svr.is_running());
  7216. });
  7217. svr.wait_until_ready();
  7218. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7219. cli.enable_server_certificate_verification(false);
  7220. cli.set_connection_timeout(1);
  7221. auto res = cli.Get("/test");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::SSLConnection, res.error());
  7224. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7225. }
  7226. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7227. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7228. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7229. SSL_CTX_set_options(&ssl_ctx,
  7230. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7231. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7232. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7233. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7234. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7235. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7236. "ECDHE-DSS-AES128-SHA256:"
  7237. "ECDHE-RSA-AES256-SHA256:"
  7238. "ECDHE-DSS-AES256-SHA256:";
  7239. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7240. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7241. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7242. SSL_FILETYPE_PEM) != 1) {
  7243. return false;
  7244. }
  7245. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7246. CLIENT_CA_CERT_DIR);
  7247. SSL_CTX_set_verify(
  7248. &ssl_ctx,
  7249. SSL_VERIFY_PEER |
  7250. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7251. nullptr);
  7252. return true;
  7253. };
  7254. SSLServer svr(setup_ssl_ctx_callback);
  7255. ASSERT_TRUE(svr.is_valid());
  7256. svr.Get("/test", [&](const Request &req, Response &res) {
  7257. res.set_content("test", "text/plain");
  7258. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7259. ASSERT_TRUE(peer_cert != nullptr);
  7260. auto subject_name = X509_get_subject_name(peer_cert);
  7261. ASSERT_TRUE(subject_name != nullptr);
  7262. std::string common_name;
  7263. {
  7264. char name[BUFSIZ];
  7265. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7266. name, sizeof(name));
  7267. common_name.assign(name, static_cast<size_t>(name_len));
  7268. }
  7269. EXPECT_EQ("Common Name", common_name);
  7270. X509_free(peer_cert);
  7271. });
  7272. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7273. auto se = detail::scope_exit([&] {
  7274. svr.stop();
  7275. t.join();
  7276. ASSERT_FALSE(svr.is_running());
  7277. });
  7278. svr.wait_until_ready();
  7279. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7280. cli.enable_server_certificate_verification(false);
  7281. cli.set_connection_timeout(30);
  7282. auto res = cli.Get("/test");
  7283. ASSERT_TRUE(res);
  7284. ASSERT_EQ(StatusCode::OK_200, res->status);
  7285. }
  7286. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7287. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7288. // prepare large data
  7289. std::random_device seed_gen;
  7290. std::mt19937 random(seed_gen());
  7291. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7292. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7293. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7294. // server
  7295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7296. ASSERT_TRUE(svr.is_valid());
  7297. svr.Post("/binary", [&](const Request &req, Response &res) {
  7298. EXPECT_EQ(large_size_byte, req.body.size());
  7299. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7300. res.set_content(req.body, "application/octet-stream");
  7301. });
  7302. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7303. auto se = detail::scope_exit([&] {
  7304. svr.stop();
  7305. listen_thread.join();
  7306. ASSERT_FALSE(svr.is_running());
  7307. });
  7308. svr.wait_until_ready();
  7309. // client POST
  7310. SSLClient cli("localhost", PORT);
  7311. cli.enable_server_certificate_verification(false);
  7312. cli.set_read_timeout(std::chrono::seconds(100));
  7313. cli.set_write_timeout(std::chrono::seconds(100));
  7314. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7315. large_size_byte, "application/octet-stream");
  7316. // compare
  7317. EXPECT_EQ(StatusCode::OK_200, res->status);
  7318. EXPECT_EQ(large_size_byte, res->body.size());
  7319. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7320. }
  7321. #endif
  7322. #ifdef _WIN32
  7323. TEST(CleanupTest, WSACleanup) {
  7324. int ret = WSACleanup();
  7325. ASSERT_EQ(0, ret);
  7326. }
  7327. #endif
  7328. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7329. TEST(NoSSLSupport, SimpleInterface) {
  7330. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7331. }
  7332. #endif
  7333. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7334. TEST(InvalidScheme, SimpleInterface) {
  7335. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7336. }
  7337. #endif
  7338. TEST(NoScheme, SimpleInterface) {
  7339. Client cli("yahoo.com:80");
  7340. ASSERT_TRUE(cli.is_valid());
  7341. }
  7342. TEST(SendAPI, SimpleInterface_Online) {
  7343. Client cli("http://yahoo.com");
  7344. Request req;
  7345. req.method = "GET";
  7346. req.path = "/";
  7347. auto res = cli.send(req);
  7348. ASSERT_TRUE(res);
  7349. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7350. }
  7351. TEST(SendAPI, WithParamsInRequest) {
  7352. Server svr;
  7353. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7354. EXPECT_TRUE(req.has_param("test"));
  7355. EXPECT_EQ("test_value", req.get_param_value("test"));
  7356. });
  7357. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7358. auto se = detail::scope_exit([&] {
  7359. svr.stop();
  7360. t.join();
  7361. ASSERT_FALSE(svr.is_running());
  7362. });
  7363. svr.wait_until_ready();
  7364. Client cli(HOST, PORT);
  7365. {
  7366. Request req;
  7367. req.method = "GET";
  7368. req.path = "/";
  7369. req.params.emplace("test", "test_value");
  7370. auto res = cli.send(req);
  7371. ASSERT_TRUE(res);
  7372. }
  7373. {
  7374. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7375. ASSERT_TRUE(res);
  7376. }
  7377. }
  7378. TEST(ClientImplMethods, GetSocketTest) {
  7379. httplib::Server svr;
  7380. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7381. res.status = StatusCode::OK_200;
  7382. });
  7383. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. thread.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. {
  7391. httplib::Client cli("http://127.0.0.1:3333");
  7392. cli.set_keep_alive(true);
  7393. // Use the behavior of cpp-httplib of opening the connection
  7394. // only when the first request happens. If that changes,
  7395. // this test would be obsolete.
  7396. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7397. // This also implicitly tests the server. But other tests would fail much
  7398. // earlier than this one to be considered.
  7399. auto res = cli.Get("/");
  7400. ASSERT_TRUE(res);
  7401. EXPECT_EQ(StatusCode::OK_200, res->status);
  7402. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7403. }
  7404. }
  7405. // Disabled due to out-of-memory problem on GitHub Actions
  7406. #ifdef _WIN64
  7407. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7408. // allocate content size larger than 2GB in memory
  7409. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7410. char *content = (char *)malloc(content_size);
  7411. ASSERT_TRUE(content);
  7412. Server svr;
  7413. svr.Get("/foo",
  7414. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7415. res.set_content(content, content_size, "application/octet-stream");
  7416. });
  7417. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7418. auto se = detail::scope_exit([&] {
  7419. svr.stop();
  7420. listen_thread.join();
  7421. if (content) free(content);
  7422. ASSERT_FALSE(svr.is_running());
  7423. });
  7424. svr.wait_until_ready();
  7425. Client cli(HOST, PORT);
  7426. auto res = cli.Get("/foo");
  7427. ASSERT_TRUE(res);
  7428. EXPECT_EQ(StatusCode::OK_200, res->status);
  7429. EXPECT_EQ(content_size, res->body.length());
  7430. }
  7431. #endif
  7432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7433. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7434. Client cli("http://yahoo.com");
  7435. auto res = cli.Get("/");
  7436. ASSERT_TRUE(res);
  7437. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7438. cli.set_follow_location(true);
  7439. res = cli.Get("/");
  7440. ASSERT_TRUE(res);
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7443. }
  7444. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7445. Client cli("https://yahoo.com");
  7446. auto res = cli.Get("/");
  7447. ASSERT_TRUE(res);
  7448. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7449. cli.set_follow_location(true);
  7450. res = cli.Get("/");
  7451. ASSERT_TRUE(res);
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7454. }
  7455. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7456. Client cli("https://yahoo.com");
  7457. auto res = cli.Get("/");
  7458. ASSERT_TRUE(res);
  7459. ASSERT_FALSE(!res);
  7460. ASSERT_TRUE(res);
  7461. ASSERT_FALSE(res == nullptr);
  7462. ASSERT_TRUE(res != nullptr);
  7463. EXPECT_EQ(Error::Success, res.error());
  7464. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7465. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7466. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7467. cli.set_follow_location(true);
  7468. res = cli.Get("/");
  7469. ASSERT_TRUE(res);
  7470. EXPECT_EQ(Error::Success, res.error());
  7471. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7472. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7475. }
  7476. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7477. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7478. Client cli("https://cdnjs.cloudflare.com");
  7479. auto res =
  7480. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7481. ASSERT_TRUE(res);
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ(287630U, res->body.size());
  7484. EXPECT_EQ("application/javascript; charset=utf-8",
  7485. res->get_header_value("Content-Type"));
  7486. }
  7487. #endif
  7488. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7489. #undef REDIR_HOST // Silence compiler warning
  7490. #define REDIR_HOST "https://httpbingo.org"
  7491. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7492. Client cli(REDIR_HOST);
  7493. cli.set_follow_location(true);
  7494. auto res =
  7495. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(StatusCode::OK_200, res->status);
  7498. }
  7499. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7500. Client cli(REDIR_HOST);
  7501. cli.set_follow_location(true);
  7502. Params params;
  7503. params.emplace("url", "http://example.com");
  7504. params.emplace("status_code", "302");
  7505. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7506. ASSERT_TRUE(res);
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7510. Client cli(REDIR_HOST);
  7511. cli.set_follow_location(true);
  7512. Params params;
  7513. params.emplace("url", "http://example.com");
  7514. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7515. ASSERT_TRUE(res);
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST(HttpToHttpsRedirectTest, CertFile) {
  7519. Server svr;
  7520. ASSERT_TRUE(svr.is_valid());
  7521. svr.Get("/index", [&](const Request &, Response &res) {
  7522. res.set_redirect("https://127.0.0.1:1235/index");
  7523. svr.stop();
  7524. });
  7525. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7526. ASSERT_TRUE(ssl_svr.is_valid());
  7527. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7528. res.set_content("test", "text/plain");
  7529. ssl_svr.stop();
  7530. });
  7531. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7532. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7533. auto se = detail::scope_exit([&] {
  7534. t2.join();
  7535. t.join();
  7536. ASSERT_FALSE(svr.is_running());
  7537. });
  7538. svr.wait_until_ready();
  7539. ssl_svr.wait_until_ready();
  7540. Client cli("127.0.0.1", PORT);
  7541. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7542. cli.enable_server_certificate_verification(true);
  7543. cli.set_follow_location(true);
  7544. cli.set_connection_timeout(30);
  7545. auto res = cli.Get("/index");
  7546. ASSERT_TRUE(res);
  7547. ASSERT_EQ(StatusCode::OK_200, res->status);
  7548. }
  7549. TEST(MultipartFormDataTest, LargeData) {
  7550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7551. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7552. const ContentReader &content_reader) {
  7553. if (req.is_multipart_form_data()) {
  7554. std::vector<FormData> items;
  7555. content_reader(
  7556. [&](const FormData &file) {
  7557. items.push_back(file);
  7558. return true;
  7559. },
  7560. [&](const char *data, size_t data_length) {
  7561. items.back().content.append(data, data_length);
  7562. return true;
  7563. });
  7564. EXPECT_TRUE(std::string(items[0].name) == "document");
  7565. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7566. EXPECT_TRUE(items[0].filename == "2MB_data");
  7567. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7568. EXPECT_TRUE(items[1].name == "hello");
  7569. EXPECT_TRUE(items[1].content == "world");
  7570. EXPECT_TRUE(items[1].filename == "");
  7571. EXPECT_TRUE(items[1].content_type == "");
  7572. } else {
  7573. std::string body;
  7574. content_reader([&](const char *data, size_t data_length) {
  7575. body.append(data, data_length);
  7576. return true;
  7577. });
  7578. }
  7579. });
  7580. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7581. auto se = detail::scope_exit([&] {
  7582. svr.stop();
  7583. t.join();
  7584. ASSERT_FALSE(svr.is_running());
  7585. });
  7586. svr.wait_until_ready();
  7587. {
  7588. std::string data(1024 * 1024 * 2, '.');
  7589. std::stringstream buffer;
  7590. buffer << data;
  7591. Client cli("https://localhost:8080");
  7592. cli.enable_server_certificate_verification(false);
  7593. UploadFormDataItems items{
  7594. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7595. {"hello", "world", "", ""},
  7596. };
  7597. auto res = cli.Post("/post", items);
  7598. ASSERT_TRUE(res);
  7599. ASSERT_EQ(StatusCode::OK_200, res->status);
  7600. }
  7601. }
  7602. TEST(MultipartFormDataTest, DataProviderItems) {
  7603. std::random_device seed_gen;
  7604. std::mt19937 random(seed_gen());
  7605. std::string rand1;
  7606. rand1.resize(1000);
  7607. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7608. std::string rand2;
  7609. rand2.resize(3000);
  7610. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7612. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7613. const ContentReader &content_reader) {
  7614. ASSERT_FALSE(req.is_multipart_form_data());
  7615. std::string body;
  7616. content_reader([&](const char *data, size_t data_length) {
  7617. body.append(data, data_length);
  7618. return true;
  7619. });
  7620. EXPECT_EQ(body, "");
  7621. });
  7622. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7623. const ContentReader &content_reader) {
  7624. ASSERT_TRUE(req.is_multipart_form_data());
  7625. std::vector<FormData> items;
  7626. content_reader(
  7627. [&](const FormData &file) {
  7628. items.push_back(file);
  7629. return true;
  7630. },
  7631. [&](const char *data, size_t data_length) {
  7632. items.back().content.append(data, data_length);
  7633. return true;
  7634. });
  7635. ASSERT_TRUE(items.size() == 2);
  7636. EXPECT_EQ(std::string(items[0].name), "name1");
  7637. EXPECT_EQ(items[0].content, "Testing123");
  7638. EXPECT_EQ(items[0].filename, "filename1");
  7639. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7640. EXPECT_EQ(items[1].name, "name2");
  7641. EXPECT_EQ(items[1].content, "Testing456");
  7642. EXPECT_EQ(items[1].filename, "");
  7643. EXPECT_EQ(items[1].content_type, "");
  7644. });
  7645. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7646. const ContentReader &content_reader) {
  7647. ASSERT_TRUE(req.is_multipart_form_data());
  7648. std::vector<FormData> items;
  7649. content_reader(
  7650. [&](const FormData &file) {
  7651. items.push_back(file);
  7652. return true;
  7653. },
  7654. [&](const char *data, size_t data_length) {
  7655. items.back().content.append(data, data_length);
  7656. return true;
  7657. });
  7658. ASSERT_TRUE(items.size() == 2);
  7659. EXPECT_EQ(items[0].name, "name3");
  7660. EXPECT_EQ(items[0].content, rand1);
  7661. EXPECT_EQ(items[0].filename, "filename3");
  7662. EXPECT_EQ(items[0].content_type, "");
  7663. EXPECT_EQ(items[1].name, "name4");
  7664. EXPECT_EQ(items[1].content, rand2);
  7665. EXPECT_EQ(items[1].filename, "filename4");
  7666. EXPECT_EQ(items[1].content_type, "");
  7667. });
  7668. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7669. const ContentReader &content_reader) {
  7670. ASSERT_TRUE(req.is_multipart_form_data());
  7671. std::vector<FormData> items;
  7672. content_reader(
  7673. [&](const FormData &file) {
  7674. items.push_back(file);
  7675. return true;
  7676. },
  7677. [&](const char *data, size_t data_length) {
  7678. items.back().content.append(data, data_length);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(items.size() == 4);
  7682. EXPECT_EQ(std::string(items[0].name), "name1");
  7683. EXPECT_EQ(items[0].content, "Testing123");
  7684. EXPECT_EQ(items[0].filename, "filename1");
  7685. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7686. EXPECT_EQ(items[1].name, "name2");
  7687. EXPECT_EQ(items[1].content, "Testing456");
  7688. EXPECT_EQ(items[1].filename, "");
  7689. EXPECT_EQ(items[1].content_type, "");
  7690. EXPECT_EQ(items[2].name, "name3");
  7691. EXPECT_EQ(items[2].content, rand1);
  7692. EXPECT_EQ(items[2].filename, "filename3");
  7693. EXPECT_EQ(items[2].content_type, "");
  7694. EXPECT_EQ(items[3].name, "name4");
  7695. EXPECT_EQ(items[3].content, rand2);
  7696. EXPECT_EQ(items[3].filename, "filename4");
  7697. EXPECT_EQ(items[3].content_type, "");
  7698. });
  7699. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7700. auto se = detail::scope_exit([&] {
  7701. svr.stop();
  7702. t.join();
  7703. ASSERT_FALSE(svr.is_running());
  7704. });
  7705. svr.wait_until_ready();
  7706. {
  7707. Client cli("https://localhost:8080");
  7708. cli.enable_server_certificate_verification(false);
  7709. UploadFormDataItems items{
  7710. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7711. {"name2", "Testing456", "", ""}, // not a file
  7712. };
  7713. {
  7714. auto res = cli.Post("/post-none", {}, {}, {});
  7715. ASSERT_TRUE(res);
  7716. ASSERT_EQ(StatusCode::OK_200, res->status);
  7717. }
  7718. FormDataProviderItems providers;
  7719. {
  7720. auto res =
  7721. cli.Post("/post-items", {}, items, providers); // empty providers
  7722. ASSERT_TRUE(res);
  7723. ASSERT_EQ(StatusCode::OK_200, res->status);
  7724. }
  7725. providers.push_back({"name3",
  7726. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7727. // test the offset is given correctly at each step
  7728. if (!offset)
  7729. sink.os.write(rand1.data(), 30);
  7730. else if (offset == 30)
  7731. sink.os.write(rand1.data() + 30, 300);
  7732. else if (offset == 330)
  7733. sink.os.write(rand1.data() + 330, 670);
  7734. else if (offset == rand1.size())
  7735. sink.done();
  7736. return true;
  7737. },
  7738. "filename3",
  7739. {}});
  7740. providers.push_back({"name4",
  7741. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7742. // test the offset is given correctly at each step
  7743. if (!offset)
  7744. sink.os.write(rand2.data(), 2000);
  7745. else if (offset == 2000)
  7746. sink.os.write(rand2.data() + 2000, 1);
  7747. else if (offset == 2001)
  7748. sink.os.write(rand2.data() + 2001, 999);
  7749. else if (offset == rand2.size())
  7750. sink.done();
  7751. return true;
  7752. },
  7753. "filename4",
  7754. {}});
  7755. {
  7756. auto res = cli.Post("/post-providers", {}, {}, providers);
  7757. ASSERT_TRUE(res);
  7758. ASSERT_EQ(StatusCode::OK_200, res->status);
  7759. }
  7760. {
  7761. auto res = cli.Post("/post-both", {}, items, providers);
  7762. ASSERT_TRUE(res);
  7763. ASSERT_EQ(StatusCode::OK_200, res->status);
  7764. }
  7765. }
  7766. }
  7767. TEST(MultipartFormDataTest, BadHeader) {
  7768. Server svr;
  7769. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7770. res.set_content("ok", "text/plain");
  7771. });
  7772. thread t = thread([&] { svr.listen(HOST, PORT); });
  7773. auto se = detail::scope_exit([&] {
  7774. svr.stop();
  7775. t.join();
  7776. ASSERT_FALSE(svr.is_running());
  7777. });
  7778. svr.wait_until_ready();
  7779. const std::string body =
  7780. "This is the preamble. It is to be ignored, though it\r\n"
  7781. "is a handy place for composition agents to include an\r\n"
  7782. "explanatory note to non-MIME conformant readers.\r\n"
  7783. "\r\n"
  7784. "\r\n"
  7785. "--simple boundary\r\n"
  7786. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7787. ": BAD...\r\n"
  7788. "\r\n"
  7789. "value1\r\n"
  7790. "--simple boundary\r\n"
  7791. "Content-Disposition: form-data; name=\"field2\"; "
  7792. "filename=\"example.txt\"\r\n"
  7793. "\r\n"
  7794. "value2\r\n"
  7795. "--simple boundary--\r\n"
  7796. "This is the epilogue. It is also to be ignored.\r\n";
  7797. std::string content_type =
  7798. R"(multipart/form-data; boundary="simple boundary")";
  7799. Client cli(HOST, PORT);
  7800. auto res = cli.Post("/post", body, content_type.c_str());
  7801. ASSERT_TRUE(res);
  7802. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7803. }
  7804. TEST(MultipartFormDataTest, WithPreamble) {
  7805. Server svr;
  7806. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7807. res.set_content("ok", "text/plain");
  7808. });
  7809. thread t = thread([&] { svr.listen(HOST, PORT); });
  7810. auto se = detail::scope_exit([&] {
  7811. svr.stop();
  7812. t.join();
  7813. ASSERT_FALSE(svr.is_running());
  7814. });
  7815. svr.wait_until_ready();
  7816. const std::string body =
  7817. "This is the preamble. It is to be ignored, though it\r\n"
  7818. "is a handy place for composition agents to include an\r\n"
  7819. "explanatory note to non-MIME conformant readers.\r\n"
  7820. "\r\n"
  7821. "\r\n"
  7822. "--simple boundary\r\n"
  7823. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7824. "\r\n"
  7825. "value1\r\n"
  7826. "--simple boundary\r\n"
  7827. "Content-Disposition: form-data; name=\"field2\"; "
  7828. "filename=\"example.txt\"\r\n"
  7829. "\r\n"
  7830. "value2\r\n"
  7831. "--simple boundary--\r\n"
  7832. "This is the epilogue. It is also to be ignored.\r\n";
  7833. std::string content_type =
  7834. R"(multipart/form-data; boundary="simple boundary")";
  7835. Client cli(HOST, PORT);
  7836. auto res = cli.Post("/post", body, content_type.c_str());
  7837. ASSERT_TRUE(res);
  7838. EXPECT_EQ(StatusCode::OK_200, res->status);
  7839. }
  7840. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7842. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7843. const ContentReader &content_reader) {
  7844. if (req.is_multipart_form_data()) {
  7845. std::vector<FormData> items;
  7846. content_reader(
  7847. [&](const FormData &file) {
  7848. items.push_back(file);
  7849. return true;
  7850. },
  7851. [&](const char *data, size_t data_length) {
  7852. items.back().content.append(data, data_length);
  7853. return true;
  7854. });
  7855. EXPECT_TRUE(std::string(items[0].name) == "document");
  7856. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7857. EXPECT_TRUE(items[0].filename == "2MB_data");
  7858. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7859. EXPECT_TRUE(items[1].name == "hello");
  7860. EXPECT_TRUE(items[1].content == "world");
  7861. EXPECT_TRUE(items[1].filename == "");
  7862. EXPECT_TRUE(items[1].content_type == "");
  7863. } else {
  7864. std::string body;
  7865. content_reader([&](const char *data, size_t data_length) {
  7866. body.append(data, data_length);
  7867. return true;
  7868. });
  7869. }
  7870. });
  7871. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7872. auto se = detail::scope_exit([&] {
  7873. svr.stop();
  7874. t.join();
  7875. ASSERT_FALSE(svr.is_running());
  7876. });
  7877. svr.wait_until_ready();
  7878. {
  7879. std::string data(1024 * 1024 * 2, '.');
  7880. std::stringstream buffer;
  7881. buffer << data;
  7882. Client cli("https://localhost:8080");
  7883. cli.enable_server_certificate_verification(false);
  7884. UploadFormDataItems items{
  7885. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7886. {"hello", "world", "", ""},
  7887. };
  7888. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7889. ASSERT_TRUE(res);
  7890. ASSERT_EQ(StatusCode::OK_200, res->status);
  7891. }
  7892. }
  7893. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7894. std::string data(1024 * 1024 * 2, '&');
  7895. std::stringstream buffer;
  7896. buffer << data;
  7897. Client cli("https://localhost:8080");
  7898. UploadFormDataItems items{
  7899. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7900. {"hello", "world", "", ""},
  7901. };
  7902. for (const char &c : " \t\r\n") {
  7903. auto res =
  7904. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7905. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7906. ASSERT_FALSE(res);
  7907. }
  7908. }
  7909. TEST(MultipartFormDataTest, PutFormData) {
  7910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7911. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7912. const ContentReader &content_reader) {
  7913. if (req.is_multipart_form_data()) {
  7914. std::vector<FormData> items;
  7915. content_reader(
  7916. [&](const FormData &file) {
  7917. items.push_back(file);
  7918. return true;
  7919. },
  7920. [&](const char *data, size_t data_length) {
  7921. items.back().content.append(data, data_length);
  7922. return true;
  7923. });
  7924. EXPECT_TRUE(std::string(items[0].name) == "document");
  7925. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7926. EXPECT_TRUE(items[0].filename == "2MB_data");
  7927. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7928. EXPECT_TRUE(items[1].name == "hello");
  7929. EXPECT_TRUE(items[1].content == "world");
  7930. EXPECT_TRUE(items[1].filename == "");
  7931. EXPECT_TRUE(items[1].content_type == "");
  7932. } else {
  7933. std::string body;
  7934. content_reader([&](const char *data, size_t data_length) {
  7935. body.append(data, data_length);
  7936. return true;
  7937. });
  7938. }
  7939. });
  7940. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7941. auto se = detail::scope_exit([&] {
  7942. svr.stop();
  7943. t.join();
  7944. ASSERT_FALSE(svr.is_running());
  7945. });
  7946. svr.wait_until_ready();
  7947. {
  7948. std::string data(1024 * 1024 * 2, '&');
  7949. std::stringstream buffer;
  7950. buffer << data;
  7951. Client cli("https://localhost:8080");
  7952. cli.enable_server_certificate_verification(false);
  7953. UploadFormDataItems items{
  7954. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7955. {"hello", "world", "", ""},
  7956. };
  7957. auto res = cli.Put("/put", items);
  7958. ASSERT_TRUE(res);
  7959. ASSERT_EQ(StatusCode::OK_200, res->status);
  7960. }
  7961. }
  7962. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7964. svr.Put("/put_customboundary",
  7965. [&](const Request &req, const Response & /*res*/,
  7966. const ContentReader &content_reader) {
  7967. if (req.is_multipart_form_data()) {
  7968. std::vector<FormData> items;
  7969. content_reader(
  7970. [&](const FormData &file) {
  7971. items.push_back(file);
  7972. return true;
  7973. },
  7974. [&](const char *data, size_t data_length) {
  7975. items.back().content.append(data, data_length);
  7976. return true;
  7977. });
  7978. EXPECT_TRUE(std::string(items[0].name) == "document");
  7979. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7980. EXPECT_TRUE(items[0].filename == "2MB_data");
  7981. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7982. EXPECT_TRUE(items[1].name == "hello");
  7983. EXPECT_TRUE(items[1].content == "world");
  7984. EXPECT_TRUE(items[1].filename == "");
  7985. EXPECT_TRUE(items[1].content_type == "");
  7986. } else {
  7987. std::string body;
  7988. content_reader([&](const char *data, size_t data_length) {
  7989. body.append(data, data_length);
  7990. return true;
  7991. });
  7992. }
  7993. });
  7994. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7995. auto se = detail::scope_exit([&] {
  7996. svr.stop();
  7997. t.join();
  7998. ASSERT_FALSE(svr.is_running());
  7999. });
  8000. svr.wait_until_ready();
  8001. {
  8002. std::string data(1024 * 1024 * 2, '&');
  8003. std::stringstream buffer;
  8004. buffer << data;
  8005. Client cli("https://localhost:8080");
  8006. cli.enable_server_certificate_verification(false);
  8007. UploadFormDataItems items{
  8008. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8009. {"hello", "world", "", ""},
  8010. };
  8011. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8012. ASSERT_TRUE(res);
  8013. ASSERT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. }
  8016. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8017. std::string data(1024 * 1024 * 2, '&');
  8018. std::stringstream buffer;
  8019. buffer << data;
  8020. Client cli("https://localhost:8080");
  8021. cli.enable_server_certificate_verification(false);
  8022. UploadFormDataItems items{
  8023. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8024. {"hello", "world", "", ""},
  8025. };
  8026. for (const char &c : " \t\r\n") {
  8027. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8028. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8029. ASSERT_FALSE(res);
  8030. }
  8031. }
  8032. TEST(MultipartFormDataTest, AlternateFilename) {
  8033. auto handled = false;
  8034. Server svr;
  8035. svr.Post("/test", [&](const Request &req, Response &res) {
  8036. ASSERT_EQ(2u, req.form.files.size());
  8037. ASSERT_EQ(1u, req.form.fields.size());
  8038. // Test files
  8039. const auto &file1 = req.form.get_file("file1");
  8040. ASSERT_EQ("file1", file1.name);
  8041. ASSERT_EQ("A.txt", file1.filename);
  8042. ASSERT_EQ("text/plain", file1.content_type);
  8043. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8044. const auto &file2 = req.form.get_file("file2");
  8045. ASSERT_EQ("file2", file2.name);
  8046. ASSERT_EQ("a.html", file2.filename);
  8047. ASSERT_EQ("text/html", file2.content_type);
  8048. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8049. file2.content);
  8050. // Test text field
  8051. const auto &text = req.form.get_field("text");
  8052. ASSERT_EQ("text default", text);
  8053. res.set_content("ok", "text/plain");
  8054. handled = true;
  8055. });
  8056. thread t = thread([&] { svr.listen(HOST, PORT); });
  8057. auto se = detail::scope_exit([&] {
  8058. svr.stop();
  8059. t.join();
  8060. ASSERT_FALSE(svr.is_running());
  8061. ASSERT_TRUE(handled);
  8062. });
  8063. svr.wait_until_ready();
  8064. auto req = "POST /test HTTP/1.1\r\n"
  8065. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8066. "Content-Length: 399\r\n"
  8067. "\r\n"
  8068. "----------\r\n"
  8069. "Content-Disposition: form-data; name=\"text\"\r\n"
  8070. "\r\n"
  8071. "text default\r\n"
  8072. "----------\r\n"
  8073. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8074. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8075. "Content-Type: text/plain\r\n"
  8076. "\r\n"
  8077. "Content of a.txt.\r\n"
  8078. "\r\n"
  8079. "----------\r\n"
  8080. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8081. "\"a.html\"\r\n"
  8082. "Content-Type: text/html\r\n"
  8083. "\r\n"
  8084. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8085. "\r\n"
  8086. "------------\r\n";
  8087. ASSERT_TRUE(send_request(1, req));
  8088. }
  8089. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8090. auto handled = false;
  8091. Server svr;
  8092. svr.Post("/test", [&](const Request &req, Response &) {
  8093. ASSERT_EQ(2u, req.form.fields.size());
  8094. const auto &text1 = req.form.get_field("text1");
  8095. ASSERT_EQ("text1", text1);
  8096. const auto &text2 = req.form.get_field("text2");
  8097. ASSERT_EQ("text2", text2);
  8098. handled = true;
  8099. });
  8100. thread t = thread([&] { svr.listen(HOST, PORT); });
  8101. auto se = detail::scope_exit([&] {
  8102. svr.stop();
  8103. t.join();
  8104. ASSERT_FALSE(svr.is_running());
  8105. ASSERT_TRUE(handled);
  8106. });
  8107. svr.wait_until_ready();
  8108. auto req = "POST /test HTTP/1.1\r\n"
  8109. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8110. "Content-Length: 146\r\n"
  8111. "\r\n----------\r\n"
  8112. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8113. "\r\n"
  8114. "text1"
  8115. "\r\n----------\r\n"
  8116. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8117. "\r\n"
  8118. "text2"
  8119. "\r\n------------";
  8120. std::string response;
  8121. ASSERT_TRUE(send_request(1, req, &response));
  8122. ASSERT_EQ("200", response.substr(9, 3));
  8123. }
  8124. TEST(MultipartFormDataTest, ContentLength) {
  8125. auto handled = false;
  8126. Server svr;
  8127. svr.Post("/test", [&](const Request &req, Response &) {
  8128. ASSERT_EQ(2u, req.form.fields.size());
  8129. const auto &text1 = req.form.get_field("text1");
  8130. ASSERT_EQ("text1", text1);
  8131. const auto &text2 = req.form.get_field("text2");
  8132. ASSERT_EQ("text2", text2);
  8133. handled = true;
  8134. });
  8135. thread t = thread([&] { svr.listen(HOST, PORT); });
  8136. auto se = detail::scope_exit([&] {
  8137. svr.stop();
  8138. t.join();
  8139. ASSERT_FALSE(svr.is_running());
  8140. ASSERT_TRUE(handled);
  8141. });
  8142. svr.wait_until_ready();
  8143. auto req = "POST /test HTTP/1.1\r\n"
  8144. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8145. "Content-Length: 167\r\n"
  8146. "\r\n----------\r\n"
  8147. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8148. "Content-Length: 5\r\n"
  8149. "\r\n"
  8150. "text1"
  8151. "\r\n----------\r\n"
  8152. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8153. "\r\n"
  8154. "text2"
  8155. "\r\n------------\r\n";
  8156. std::string response;
  8157. ASSERT_TRUE(send_request(1, req, &response));
  8158. ASSERT_EQ("200", response.substr(9, 3));
  8159. }
  8160. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8161. auto handled = false;
  8162. Server svr;
  8163. svr.Post("/test", [&](const Request &req, Response &) {
  8164. ASSERT_EQ(2u, req.form.fields.size());
  8165. const auto &text1 = req.form.get_field("text1");
  8166. ASSERT_EQ("text1", text1);
  8167. // TODO: Add header access for text fields if needed
  8168. const auto &text2 = req.form.get_field("text2");
  8169. ASSERT_EQ("text2", text2);
  8170. // TODO: Header access for text fields needs to be implemented
  8171. // auto &headers = it->second.headers;
  8172. // ASSERT_EQ(3U, headers.size());
  8173. // auto custom_header = headers.find("x-whatever");
  8174. // ASSERT_TRUE(custom_header != headers.end());
  8175. // ASSERT_NE("customvalue", custom_header->second);
  8176. // ASSERT_EQ("CustomValue", custom_header->second);
  8177. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8178. handled = true;
  8179. });
  8180. thread t = thread([&] { svr.listen(HOST, PORT); });
  8181. auto se = detail::scope_exit([&] {
  8182. svr.stop();
  8183. t.join();
  8184. ASSERT_FALSE(svr.is_running());
  8185. ASSERT_TRUE(handled);
  8186. });
  8187. svr.wait_until_ready();
  8188. auto req = "POST /test HTTP/1.1\r\n"
  8189. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8190. "Content-Length: 232\r\n"
  8191. "\r\n----------\r\n"
  8192. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8193. "Content-Length: 5\r\n"
  8194. "X-Test: 1\r\n"
  8195. "\r\n"
  8196. "text1"
  8197. "\r\n----------\r\n"
  8198. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8199. "Content-Type: text/plain\r\n"
  8200. "X-Whatever: CustomValue\r\n"
  8201. "\r\n"
  8202. "text2"
  8203. "\r\n------------\r\n"
  8204. "That should be disregarded. Not even read";
  8205. std::string response;
  8206. ASSERT_TRUE(send_request(1, req, &response));
  8207. ASSERT_EQ("200", response.substr(9, 3));
  8208. }
  8209. #endif
  8210. TEST(MultipartFormDataTest, LargeHeader) {
  8211. auto handled = false;
  8212. Server svr;
  8213. svr.Post("/test", [&](const Request &req, Response &) {
  8214. ASSERT_EQ(1u, req.form.fields.size());
  8215. const auto &text = req.form.get_field("name1");
  8216. ASSERT_EQ("text1", text);
  8217. handled = true;
  8218. });
  8219. thread t = thread([&] { svr.listen(HOST, PORT); });
  8220. auto se = detail::scope_exit([&] {
  8221. svr.stop();
  8222. t.join();
  8223. ASSERT_FALSE(svr.is_running());
  8224. ASSERT_TRUE(handled);
  8225. });
  8226. svr.wait_until_ready();
  8227. auto boundary = std::string("cpp-httplib-multipart-data");
  8228. std::string content = "--" + boundary +
  8229. "\r\n"
  8230. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8231. "\r\n"
  8232. "text1\r\n"
  8233. "--" +
  8234. boundary + "--\r\n";
  8235. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8236. "Content-Type: multipart/form-data;boundary=" +
  8237. boundary +
  8238. "\r\n"
  8239. "Content-Length: " +
  8240. std::to_string(content.size()) +
  8241. "\r\n"
  8242. "Dummy-Header: ";
  8243. std::string header_suffix = "\r\n"
  8244. "\r\n";
  8245. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8246. size_t header_dummy_size =
  8247. read_buff_size -
  8248. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8249. auto header_dummy = std::string(header_dummy_size, '@');
  8250. auto req = header_prefix + header_dummy + header_suffix + content;
  8251. std::string response;
  8252. ASSERT_TRUE(send_request(1, req, &response));
  8253. ASSERT_EQ("200", response.substr(9, 3));
  8254. }
  8255. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8256. static constexpr unsigned int number_of_tasks{1000000};
  8257. std::atomic_uint count{0};
  8258. std::unique_ptr<TaskQueue> task_queue{
  8259. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8260. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8261. auto queued = task_queue->enqueue(
  8262. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8263. EXPECT_TRUE(queued);
  8264. }
  8265. EXPECT_NO_THROW(task_queue->shutdown());
  8266. EXPECT_EQ(number_of_tasks, count.load());
  8267. }
  8268. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8269. static constexpr unsigned int number_of_tasks{1000000};
  8270. static constexpr unsigned int qlimit{2};
  8271. unsigned int queued_count{0};
  8272. std::atomic_uint count{0};
  8273. std::unique_ptr<TaskQueue> task_queue{
  8274. new ThreadPool{/*num_threads=*/1, qlimit}};
  8275. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8276. if (task_queue->enqueue(
  8277. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8278. queued_count++;
  8279. }
  8280. }
  8281. EXPECT_NO_THROW(task_queue->shutdown());
  8282. EXPECT_EQ(queued_count, count.load());
  8283. EXPECT_TRUE(queued_count <= number_of_tasks);
  8284. EXPECT_TRUE(queued_count >= qlimit);
  8285. }
  8286. TEST(TaskQueueTest, MaxQueuedRequests) {
  8287. static constexpr unsigned int qlimit{3};
  8288. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8289. std::condition_variable sem_cv;
  8290. std::mutex sem_mtx;
  8291. int credits = 0;
  8292. bool queued;
  8293. /* Fill up the queue with tasks that will block until we give them credits to
  8294. * complete. */
  8295. for (unsigned int n = 0; n <= qlimit;) {
  8296. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8297. std::unique_lock<std::mutex> lock(sem_mtx);
  8298. while (credits <= 0) {
  8299. sem_cv.wait(lock);
  8300. }
  8301. /* Consume the credit and signal the test code if they are all gone. */
  8302. if (--credits == 0) { sem_cv.notify_one(); }
  8303. });
  8304. if (n < qlimit) {
  8305. /* The first qlimit enqueues must succeed. */
  8306. EXPECT_TRUE(queued);
  8307. } else {
  8308. /* The last one will succeed only when the worker thread
  8309. * starts and dequeues the first blocking task. Although
  8310. * not necessary for the correctness of this test, we sleep for
  8311. * a short while to avoid busy waiting. */
  8312. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8313. }
  8314. if (queued) { n++; }
  8315. }
  8316. /* Further enqueues must fail since the queue is full. */
  8317. for (auto i = 0; i < 4; i++) {
  8318. queued = task_queue->enqueue([] {});
  8319. EXPECT_FALSE(queued);
  8320. }
  8321. /* Give the credits to allow the previous tasks to complete. */
  8322. {
  8323. std::unique_lock<std::mutex> lock(sem_mtx);
  8324. credits += qlimit + 1;
  8325. }
  8326. sem_cv.notify_all();
  8327. /* Wait for all the credits to be consumed. */
  8328. {
  8329. std::unique_lock<std::mutex> lock(sem_mtx);
  8330. while (credits > 0) {
  8331. sem_cv.wait(lock);
  8332. }
  8333. }
  8334. /* Check that we are able again to enqueue at least qlimit tasks. */
  8335. for (unsigned int i = 0; i < qlimit; i++) {
  8336. queued = task_queue->enqueue([] {});
  8337. EXPECT_TRUE(queued);
  8338. }
  8339. EXPECT_NO_THROW(task_queue->shutdown());
  8340. }
  8341. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8342. Server svr;
  8343. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8344. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8345. });
  8346. svr.Get("/hello", [](const Request &req, Response &res) {
  8347. res.set_content(req.get_param_value("key"), "text/plain");
  8348. });
  8349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8350. auto se = detail::scope_exit([&] {
  8351. svr.stop();
  8352. thread.join();
  8353. ASSERT_FALSE(svr.is_running());
  8354. });
  8355. svr.wait_until_ready();
  8356. {
  8357. Client cli(HOST, PORT);
  8358. cli.set_follow_location(true);
  8359. auto res = cli.Get("/");
  8360. ASSERT_TRUE(res);
  8361. EXPECT_EQ(StatusCode::OK_200, res->status);
  8362. EXPECT_EQ("val&key2=val2", res->body);
  8363. }
  8364. }
  8365. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8366. Server svr;
  8367. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8368. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8369. });
  8370. svr.Get("/hello", [](const Request &req, Response &res) {
  8371. res.set_content(req.get_param_value("key"), "text/plain");
  8372. });
  8373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8374. auto se = detail::scope_exit([&] {
  8375. svr.stop();
  8376. thread.join();
  8377. ASSERT_FALSE(svr.is_running());
  8378. });
  8379. svr.wait_until_ready();
  8380. {
  8381. Client cli(HOST, PORT);
  8382. cli.set_follow_location(true);
  8383. auto res = cli.Get("/");
  8384. ASSERT_TRUE(res);
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8387. }
  8388. }
  8389. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8390. TEST(RedirectTest, Issue2185_Online) {
  8391. SSLClient client("github.com");
  8392. client.set_follow_location(true);
  8393. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8394. "Coollab-Windows.zip");
  8395. ASSERT_TRUE(res);
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. EXPECT_EQ(9920427U, res->body.size());
  8398. }
  8399. #endif
  8400. TEST(VulnerabilityTest, CRLFInjection) {
  8401. Server svr;
  8402. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8403. res.set_content("Hello 1", "text/plain");
  8404. });
  8405. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8406. res.set_content("Hello 2", "text/plain");
  8407. });
  8408. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8409. res.set_content("Hello 3", "text/plain");
  8410. });
  8411. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8412. res.set_content("Hello 4", "text/plain");
  8413. });
  8414. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8415. for (const auto &x : req.headers) {
  8416. auto key = x.first;
  8417. EXPECT_STRNE("evil", key.c_str());
  8418. }
  8419. });
  8420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8421. auto se = detail::scope_exit([&] {
  8422. svr.stop();
  8423. thread.join();
  8424. ASSERT_FALSE(svr.is_running());
  8425. });
  8426. svr.wait_until_ready();
  8427. {
  8428. Client cli(HOST, PORT);
  8429. cli.Post("/test1", "A=B",
  8430. "application/x-www-form-urlencoded\r\nevil: hello1");
  8431. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8432. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8433. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8434. }
  8435. }
  8436. TEST(PathParamsTest, StaticMatch) {
  8437. const auto pattern = "/users/all";
  8438. detail::PathParamsMatcher matcher(pattern);
  8439. Request request;
  8440. request.path = "/users/all";
  8441. ASSERT_TRUE(matcher.match(request));
  8442. std::unordered_map<std::string, std::string> expected_params = {};
  8443. EXPECT_EQ(request.path_params, expected_params);
  8444. }
  8445. TEST(PathParamsTest, StaticMismatch) {
  8446. const auto pattern = "/users/all";
  8447. detail::PathParamsMatcher matcher(pattern);
  8448. Request request;
  8449. request.path = "/users/1";
  8450. ASSERT_FALSE(matcher.match(request));
  8451. }
  8452. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8453. const auto pattern = "/users/:id/subscriptions";
  8454. detail::PathParamsMatcher matcher(pattern);
  8455. Request request;
  8456. request.path = "/users/42/subscriptions";
  8457. ASSERT_TRUE(matcher.match(request));
  8458. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8459. EXPECT_EQ(request.path_params, expected_params);
  8460. }
  8461. TEST(PathParamsTest, SingleParamInTheEnd) {
  8462. const auto pattern = "/users/:id";
  8463. detail::PathParamsMatcher matcher(pattern);
  8464. Request request;
  8465. request.path = "/users/24";
  8466. ASSERT_TRUE(matcher.match(request));
  8467. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8468. EXPECT_EQ(request.path_params, expected_params);
  8469. }
  8470. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8471. const auto pattern = "/users/:id/";
  8472. detail::PathParamsMatcher matcher(pattern);
  8473. Request request;
  8474. request.path = "/users/42/";
  8475. ASSERT_TRUE(matcher.match(request));
  8476. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8477. EXPECT_EQ(request.path_params, expected_params);
  8478. }
  8479. TEST(PathParamsTest, EmptyParam) {
  8480. const auto pattern = "/users/:id/";
  8481. detail::PathParamsMatcher matcher(pattern);
  8482. Request request;
  8483. request.path = "/users//";
  8484. ASSERT_TRUE(matcher.match(request));
  8485. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8486. EXPECT_EQ(request.path_params, expected_params);
  8487. }
  8488. TEST(PathParamsTest, FragmentMismatch) {
  8489. const auto pattern = "/users/:id/";
  8490. detail::PathParamsMatcher matcher(pattern);
  8491. Request request;
  8492. request.path = "/admins/24/";
  8493. ASSERT_FALSE(matcher.match(request));
  8494. }
  8495. TEST(PathParamsTest, ExtraFragments) {
  8496. const auto pattern = "/users/:id";
  8497. detail::PathParamsMatcher matcher(pattern);
  8498. Request request;
  8499. request.path = "/users/42/subscriptions";
  8500. ASSERT_FALSE(matcher.match(request));
  8501. }
  8502. TEST(PathParamsTest, MissingTrailingParam) {
  8503. const auto pattern = "/users/:id";
  8504. detail::PathParamsMatcher matcher(pattern);
  8505. Request request;
  8506. request.path = "/users";
  8507. ASSERT_FALSE(matcher.match(request));
  8508. }
  8509. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8510. const auto pattern = "/users/:id/subscriptions";
  8511. detail::PathParamsMatcher matcher(pattern);
  8512. Request request;
  8513. request.path = "/users/subscriptions";
  8514. ASSERT_FALSE(matcher.match(request));
  8515. }
  8516. TEST(PathParamsTest, MultipleParams) {
  8517. const auto pattern = "/users/:userid/subscriptions/:subid";
  8518. detail::PathParamsMatcher matcher(pattern);
  8519. Request request;
  8520. request.path = "/users/42/subscriptions/2";
  8521. ASSERT_TRUE(matcher.match(request));
  8522. std::unordered_map<std::string, std::string> expected_params = {
  8523. {"userid", "42"}, {"subid", "2"}};
  8524. EXPECT_EQ(request.path_params, expected_params);
  8525. }
  8526. TEST(PathParamsTest, SequenceOfParams) {
  8527. const auto pattern = "/values/:x/:y/:z";
  8528. detail::PathParamsMatcher matcher(pattern);
  8529. Request request;
  8530. request.path = "/values/1/2/3";
  8531. ASSERT_TRUE(matcher.match(request));
  8532. std::unordered_map<std::string, std::string> expected_params = {
  8533. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8534. EXPECT_EQ(request.path_params, expected_params);
  8535. }
  8536. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8537. const auto pattern = "/prefix:suffix";
  8538. detail::PathParamsMatcher matcher(pattern);
  8539. Request request;
  8540. request.path = "/prefix:suffix";
  8541. ASSERT_TRUE(matcher.match(request));
  8542. const std::unordered_map<std::string, std::string> expected_params = {};
  8543. EXPECT_EQ(request.path_params, expected_params);
  8544. }
  8545. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8546. // If ipv6 regex working, regex match codepath is taken.
  8547. // else port will default to 80 in Client impl
  8548. int clientImplMagicPort = 80;
  8549. int port = 4321;
  8550. // above ports must be different to avoid false negative
  8551. EXPECT_NE(clientImplMagicPort, port);
  8552. std::string ipV6TestURL = "http://[ff06::c3]";
  8553. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8554. CLIENT_PRIVATE_KEY_FILE);
  8555. EXPECT_EQ(cli.port(), port);
  8556. }
  8557. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8558. auto file_path = "./www/dir/index.html";
  8559. auto dir_path = "./www/dir";
  8560. detail::FileStat stat_file(file_path);
  8561. EXPECT_TRUE(stat_file.is_file());
  8562. EXPECT_FALSE(stat_file.is_dir());
  8563. detail::FileStat stat_dir(dir_path);
  8564. EXPECT_FALSE(stat_dir.is_file());
  8565. EXPECT_TRUE(stat_dir.is_dir());
  8566. }
  8567. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8568. Server svr;
  8569. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8570. EXPECT_EQ(res.status, 400);
  8571. });
  8572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8573. auto se = detail::scope_exit([&] {
  8574. svr.stop();
  8575. thread.join();
  8576. ASSERT_FALSE(svr.is_running());
  8577. });
  8578. svr.wait_until_ready();
  8579. Client cli(HOST, PORT);
  8580. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8581. }
  8582. TEST(InvalidHeaderCharsTest, is_field_name) {
  8583. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8584. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8585. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8586. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8587. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8588. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8589. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8590. EXPECT_FALSE(detail::fields::is_field_name(""));
  8591. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8592. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8593. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8594. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8595. }
  8596. TEST(InvalidHeaderCharsTest, is_field_value) {
  8597. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8598. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8599. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8600. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8601. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8602. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8603. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8604. EXPECT_TRUE(detail::fields::is_field_value(""));
  8605. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8606. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8607. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8608. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8609. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8610. }
  8611. TEST(InvalidHeaderCharsTest, OnServer) {
  8612. Server svr;
  8613. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8614. std::string header = "Not Set";
  8615. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8616. res.set_header(header, "value");
  8617. res.set_content("Page Content Page Content", "text/plain");
  8618. });
  8619. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8620. std::string header = "Not Set";
  8621. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8622. res.set_header("X-Test", header);
  8623. res.set_content("Page Content Page Content", "text/plain");
  8624. });
  8625. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. thread.join();
  8629. ASSERT_FALSE(svr.is_running());
  8630. });
  8631. svr.wait_until_ready();
  8632. Client cli(HOST, PORT);
  8633. {
  8634. auto res = cli.Get(
  8635. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8636. ASSERT_TRUE(res);
  8637. EXPECT_EQ("Page Content Page Content", res->body);
  8638. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8639. }
  8640. {
  8641. auto res = cli.Get(
  8642. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8643. ASSERT_TRUE(res);
  8644. EXPECT_EQ("Page Content Page Content", res->body);
  8645. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8646. }
  8647. }
  8648. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8649. auto handled = false;
  8650. Server svr;
  8651. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8652. thread t = thread([&] { svr.listen(HOST, PORT); });
  8653. auto se = detail::scope_exit([&] {
  8654. svr.stop();
  8655. t.join();
  8656. ASSERT_FALSE(svr.is_running());
  8657. ASSERT_FALSE(handled);
  8658. });
  8659. svr.wait_until_ready();
  8660. auto req = "POST /test HTTP/1.1\r\n"
  8661. "Content-Length: x\r\n"
  8662. "\r\n";
  8663. std::string response;
  8664. ASSERT_TRUE(send_request(1, req, &response));
  8665. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8666. response.substr(0, response.find("\r\n")));
  8667. }
  8668. #ifndef _WIN32
  8669. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8670. static constexpr char reject[] = "Unauthorized";
  8671. static constexpr char accept[] = "Upload accepted";
  8672. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8673. Server svr;
  8674. svr.set_expect_100_continue_handler(
  8675. [](const Request & /*req*/, Response &res) {
  8676. res.status = StatusCode::Unauthorized_401;
  8677. res.set_content(reject, "text/plain");
  8678. return res.status;
  8679. });
  8680. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8681. res.set_content(accept, "text/plain");
  8682. });
  8683. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8684. auto se = detail::scope_exit([&] {
  8685. svr.stop();
  8686. thread.join();
  8687. ASSERT_FALSE(svr.is_running());
  8688. });
  8689. svr.wait_until_ready();
  8690. {
  8691. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8692. curl_easy_init(), &curl_easy_cleanup};
  8693. ASSERT_NE(curl, nullptr);
  8694. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8695. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8696. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8697. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8698. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8699. &curl_slist_free_all};
  8700. ASSERT_NE(list, nullptr);
  8701. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8702. struct read_data {
  8703. size_t read_size;
  8704. size_t total_size;
  8705. } data = {0, total_size};
  8706. using read_callback_t =
  8707. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8708. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8709. void *userdata) -> size_t {
  8710. read_data *data = (read_data *)userdata;
  8711. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8712. std::fill_n(ptr, size * nmemb, 'A');
  8713. data->read_size += size * nmemb;
  8714. return size * nmemb;
  8715. };
  8716. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8717. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8718. std::vector<char> buffer;
  8719. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8720. using write_callback_t =
  8721. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8722. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8723. void *userdata) -> size_t {
  8724. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8725. buffer->reserve(buffer->size() + size * nmemb + 1);
  8726. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8727. return size * nmemb;
  8728. };
  8729. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8730. {
  8731. const auto res = curl_easy_perform(curl.get());
  8732. ASSERT_EQ(res, CURLE_OK);
  8733. }
  8734. {
  8735. auto response_code = long{};
  8736. const auto res =
  8737. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8738. ASSERT_EQ(res, CURLE_OK);
  8739. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8740. }
  8741. {
  8742. auto dl = curl_off_t{};
  8743. const auto res =
  8744. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8745. ASSERT_EQ(res, CURLE_OK);
  8746. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8747. }
  8748. {
  8749. buffer.push_back('\0');
  8750. ASSERT_STRCASEEQ(buffer.data(), reject);
  8751. }
  8752. }
  8753. }
  8754. #endif
  8755. template <typename S, typename C>
  8756. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8757. svr.Get("/stream", [&](const Request &, Response &res) {
  8758. auto data = new std::string("01234567890123456789");
  8759. res.set_content_provider(
  8760. data->size(), "text/plain",
  8761. [&, data](size_t offset, size_t length, DataSink &sink) {
  8762. const size_t DATA_CHUNK_SIZE = 4;
  8763. const auto &d = *data;
  8764. std::this_thread::sleep_for(std::chrono::seconds(1));
  8765. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8766. return true;
  8767. },
  8768. [data](bool success) {
  8769. EXPECT_FALSE(success);
  8770. delete data;
  8771. });
  8772. });
  8773. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8774. auto i = new size_t(0);
  8775. res.set_content_provider(
  8776. "text/plain",
  8777. [i](size_t, DataSink &sink) {
  8778. if (*i < 5) {
  8779. std::this_thread::sleep_for(std::chrono::seconds(1));
  8780. sink.write("abcd", 4);
  8781. (*i)++;
  8782. } else {
  8783. sink.done();
  8784. }
  8785. return true;
  8786. },
  8787. [i](bool success) {
  8788. EXPECT_FALSE(success);
  8789. delete i;
  8790. });
  8791. });
  8792. svr.Get("/chunked", [&](const Request &, Response &res) {
  8793. auto i = new size_t(0);
  8794. res.set_chunked_content_provider(
  8795. "text/plain",
  8796. [i](size_t, DataSink &sink) {
  8797. if (*i < 5) {
  8798. std::this_thread::sleep_for(std::chrono::seconds(1));
  8799. sink.os << "abcd";
  8800. (*i)++;
  8801. } else {
  8802. sink.done();
  8803. }
  8804. return true;
  8805. },
  8806. [i](bool success) {
  8807. EXPECT_FALSE(success);
  8808. delete i;
  8809. });
  8810. });
  8811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8812. auto se = detail::scope_exit([&] {
  8813. svr.stop();
  8814. listen_thread.join();
  8815. ASSERT_FALSE(svr.is_running());
  8816. });
  8817. svr.wait_until_ready();
  8818. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8819. {
  8820. auto start = std::chrono::steady_clock::now();
  8821. auto res = cli.Get("/stream");
  8822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8823. std::chrono::steady_clock::now() - start)
  8824. .count();
  8825. ASSERT_FALSE(res);
  8826. EXPECT_EQ(Error::Read, res.error());
  8827. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8828. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8829. }
  8830. {
  8831. auto start = std::chrono::steady_clock::now();
  8832. auto res = cli.Get("/stream_without_length");
  8833. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8834. std::chrono::steady_clock::now() - start)
  8835. .count();
  8836. ASSERT_FALSE(res);
  8837. EXPECT_EQ(Error::Read, res.error());
  8838. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8839. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8840. }
  8841. {
  8842. auto start = std::chrono::steady_clock::now();
  8843. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8844. EXPECT_EQ("abcd", string(data, data_length));
  8845. return true;
  8846. });
  8847. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8848. std::chrono::steady_clock::now() - start)
  8849. .count();
  8850. ASSERT_FALSE(res);
  8851. EXPECT_EQ(Error::Read, res.error());
  8852. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8853. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8854. }
  8855. }
  8856. TEST(MaxTimeoutTest, ContentStream) {
  8857. time_t timeout = 2000;
  8858. time_t threshold = 200;
  8859. Server svr;
  8860. Client cli("localhost", PORT);
  8861. max_timeout_test(svr, cli, timeout, threshold);
  8862. }
  8863. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8864. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8865. time_t timeout = 2000;
  8866. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8868. SSLClient cli("localhost", PORT);
  8869. cli.enable_server_certificate_verification(false);
  8870. max_timeout_test(svr, cli, timeout, threshold);
  8871. }
  8872. #endif
  8873. class EventDispatcher {
  8874. public:
  8875. EventDispatcher() {}
  8876. void wait_event(DataSink *sink) {
  8877. unique_lock<mutex> lk(m_);
  8878. int id = id_;
  8879. cv_.wait(lk, [&] { return cid_ == id; });
  8880. sink->write(message_.data(), message_.size());
  8881. }
  8882. void send_event(const string &message) {
  8883. lock_guard<mutex> lk(m_);
  8884. cid_ = id_++;
  8885. message_ = message;
  8886. cv_.notify_all();
  8887. }
  8888. private:
  8889. mutex m_;
  8890. condition_variable cv_;
  8891. atomic_int id_{0};
  8892. atomic_int cid_{-1};
  8893. string message_;
  8894. };
  8895. TEST(ClientInThreadTest, Issue2068) {
  8896. EventDispatcher ed;
  8897. Server svr;
  8898. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8899. res.set_chunked_content_provider("text/event-stream",
  8900. [&](size_t /*offset*/, DataSink &sink) {
  8901. ed.wait_event(&sink);
  8902. return true;
  8903. });
  8904. });
  8905. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8906. svr.wait_until_ready();
  8907. thread event_thread([&] {
  8908. int id = 0;
  8909. while (svr.is_running()) {
  8910. this_thread::sleep_for(chrono::milliseconds(500));
  8911. std::stringstream ss;
  8912. ss << "data: " << id << "\n\n";
  8913. ed.send_event(ss.str());
  8914. id++;
  8915. }
  8916. });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. listen_thread.join();
  8920. event_thread.join();
  8921. ASSERT_FALSE(svr.is_running());
  8922. });
  8923. {
  8924. auto client = detail::make_unique<Client>(HOST, PORT);
  8925. client->set_read_timeout(std::chrono::minutes(10));
  8926. std::atomic<bool> stop{false};
  8927. std::thread t([&] {
  8928. client->Get("/event1",
  8929. [&](const char *, size_t) -> bool { return !stop; });
  8930. });
  8931. std::this_thread::sleep_for(std::chrono::seconds(2));
  8932. stop = true;
  8933. client->stop();
  8934. client.reset();
  8935. t.join();
  8936. }
  8937. }
  8938. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8939. Server svr;
  8940. svr.Get("/", [](const Request &req, Response &res) {
  8941. EXPECT_EQ(2U, req.trailers.size());
  8942. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8943. // Denied
  8944. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8945. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8946. // Accepted
  8947. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8948. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  8949. EXPECT_TRUE(req.has_trailer("X-World"));
  8950. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  8951. res.set_content("ok", "text/plain");
  8952. });
  8953. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8954. auto se = detail::scope_exit([&] {
  8955. svr.stop();
  8956. t.join();
  8957. ASSERT_FALSE(svr.is_running());
  8958. });
  8959. svr.wait_until_ready();
  8960. const std::string req = "GET / HTTP/1.1\r\n"
  8961. "Transfer-Encoding: chunked\r\n"
  8962. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  8963. "\r\n"
  8964. "0\r\n"
  8965. "Content-Length: 10\r\n"
  8966. "Host: internal.local\r\n"
  8967. "Content-Type: malicious/content\r\n"
  8968. "Cookie: any\r\n"
  8969. "Set-Cookie: any\r\n"
  8970. "X-Forwarded-For: attacker.com\r\n"
  8971. "X-Real-Ip: 1.1.1.1\r\n"
  8972. "X-Hello: hello\r\n"
  8973. "X-World: world\r\n"
  8974. "\r\n";
  8975. std::string res;
  8976. ASSERT_TRUE(send_request(1, req, &res));
  8977. }