test.cc 327 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676
  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. detail::decode_path(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  255. false),
  256. u8"descrip=Gastos áéíóúñÑ 6");
  257. }
  258. TEST(DecodePathTest, PercentCharacterNUL) {
  259. string expected;
  260. expected.push_back('x');
  261. expected.push_back('\0');
  262. expected.push_back('x');
  263. EXPECT_EQ(detail::decode_path("x%00x", false), expected);
  264. }
  265. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  266. string unescapedCharacters = "-_.!~*'()";
  267. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  268. }
  269. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  270. string reservedCharacters = ";,/?:@&=+$";
  271. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  272. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  273. }
  274. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  275. string chineseCharacters = u8"中国語";
  276. string russianCharacters = u8"дом";
  277. string brazilianCharacters = u8"óculos";
  278. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  279. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  280. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  281. "%D0%B4%D0%BE%D0%BC");
  282. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  283. }
  284. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  285. string unescapedCharacters = "-_.!~*'()";
  286. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  287. }
  288. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  289. string reservedCharacters = ";,/?:@&=+$";
  290. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  291. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  292. }
  293. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  294. string chineseCharacters = u8"中国語";
  295. string russianCharacters = u8"дом";
  296. string brazilianCharacters = u8"óculos";
  297. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  298. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  299. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  300. "%D0%B4%D0%BE%D0%BC");
  301. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  302. }
  303. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  304. // Issue #2082 use case: encoding path component with ampersand
  305. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  306. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  307. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  308. }
  309. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  310. string unescapedCharacters = "-_.!~*'()";
  311. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  312. }
  313. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  314. string reservedCharacters = ";,/?:@&=+$#";
  315. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  316. }
  317. TEST(EncodeUriTest, TestUTF8Characters) {
  318. string chineseCharacters = u8"中国語";
  319. string russianCharacters = u8"дом";
  320. string brazilianCharacters = u8"óculos";
  321. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  322. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  323. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  324. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  325. }
  326. TEST(EncodeUriTest, TestCompleteUri) {
  327. string uri =
  328. "https://example.com/path/to/resource?query=value&param=test#fragment";
  329. EXPECT_EQ(
  330. httplib::encode_uri(uri),
  331. "https://example.com/path/to/resource?query=value&param=test#fragment");
  332. }
  333. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  334. string uri =
  335. "https://example.com/path with spaces/file name.html?q=hello world";
  336. EXPECT_EQ(httplib::encode_uri(uri),
  337. "https://example.com/path%20with%20spaces/"
  338. "file%20name.html?q=hello%20world");
  339. }
  340. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  341. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  342. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  343. }
  344. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  345. string unescapedCharacters = "-_.!~*'()";
  346. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  347. }
  348. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  349. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  350. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  351. string encodedBrazilian = "%C3%B3culos";
  352. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  354. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  355. }
  356. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  357. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  358. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  359. "Piri Tommy Villiers - on & on");
  360. }
  361. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  362. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  363. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  364. }
  365. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  366. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  367. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  368. }
  369. TEST(DecodeUriTest, TestUTF8Characters) {
  370. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  371. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  372. string encodedBrazilian = "%C3%B3culos";
  373. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  374. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  375. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  376. }
  377. TEST(DecodeUriTest, TestCompleteUri) {
  378. string encodedUri = "https://example.com/path%20with%20spaces/"
  379. "file%20name.html?q=hello%20world";
  380. EXPECT_EQ(
  381. httplib::decode_uri(encodedUri),
  382. "https://example.com/path with spaces/file name.html?q=hello world");
  383. }
  384. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  385. string original =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. string encoded = httplib::encode_uri(original);
  388. string decoded = httplib::decode_uri(encoded);
  389. EXPECT_EQ(decoded, original);
  390. }
  391. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  392. string original = "Piri Tommy Villiers - on & on";
  393. string encoded = httplib::encode_uri_component(original);
  394. string decoded = httplib::decode_uri_component(encoded);
  395. EXPECT_EQ(decoded, original);
  396. }
  397. TEST(TrimTests, TrimStringTests) {
  398. EXPECT_EQ("abc", detail::trim_copy("abc"));
  399. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  400. EXPECT_TRUE(detail::trim_copy("").empty());
  401. }
  402. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  403. // Simple case without quality values
  404. std::vector<std::string> result1;
  405. EXPECT_TRUE(detail::parse_accept_header(
  406. "text/html,application/json,text/plain", result1));
  407. EXPECT_EQ(result1.size(), 3U);
  408. EXPECT_EQ(result1[0], "text/html");
  409. EXPECT_EQ(result1[1], "application/json");
  410. EXPECT_EQ(result1[2], "text/plain");
  411. // With quality values
  412. std::vector<std::string> result2;
  413. EXPECT_TRUE(detail::parse_accept_header(
  414. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  415. EXPECT_EQ(result2.size(), 3U);
  416. EXPECT_EQ(result2[0], "application/json"); // highest q value
  417. EXPECT_EQ(result2[1], "text/html");
  418. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  419. }
  420. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  421. // Mixed with and without quality values
  422. std::vector<std::string> result;
  423. EXPECT_TRUE(detail::parse_accept_header(
  424. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  425. EXPECT_EQ(result.size(), 3U);
  426. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  427. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  428. EXPECT_EQ(result[2], "application/json"); // q=0.5
  429. }
  430. TEST(ParseAcceptHeaderTest, EdgeCases) {
  431. // Empty header
  432. std::vector<std::string> empty_result;
  433. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  434. EXPECT_TRUE(empty_result.empty());
  435. // Single type
  436. std::vector<std::string> single_result;
  437. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  438. EXPECT_EQ(single_result.size(), 1U);
  439. EXPECT_EQ(single_result[0], "application/json");
  440. // Wildcard types
  441. std::vector<std::string> wildcard_result;
  442. EXPECT_TRUE(detail::parse_accept_header(
  443. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  444. EXPECT_EQ(wildcard_result.size(), 3U);
  445. EXPECT_EQ(wildcard_result[0], "application/json");
  446. EXPECT_EQ(wildcard_result[1], "text/*");
  447. EXPECT_EQ(wildcard_result[2], "*/*");
  448. }
  449. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  450. // Common browser Accept header
  451. std::vector<std::string> browser_result;
  452. EXPECT_TRUE(
  453. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  454. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  455. browser_result));
  456. EXPECT_EQ(browser_result.size(), 6U);
  457. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  461. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  462. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  463. // API client header
  464. std::vector<std::string> api_result;
  465. EXPECT_TRUE(detail::parse_accept_header(
  466. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  467. api_result));
  468. EXPECT_EQ(api_result.size(), 3U);
  469. EXPECT_EQ(api_result[0], "application/json");
  470. EXPECT_EQ(api_result[1], "application/xml");
  471. EXPECT_EQ(api_result[2], "text/plain");
  472. }
  473. TEST(ParseAcceptHeaderTest, SpecialCases) {
  474. // Quality value with 3 decimal places
  475. std::vector<std::string> decimal_result;
  476. EXPECT_TRUE(detail::parse_accept_header(
  477. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  478. EXPECT_EQ(decimal_result.size(), 2U);
  479. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  480. EXPECT_EQ(decimal_result[1], "text/html");
  481. // Zero quality (should still be included but with lowest priority)
  482. std::vector<std::string> zero_q_result;
  483. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  484. zero_q_result));
  485. EXPECT_EQ(zero_q_result.size(), 2U);
  486. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  487. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  488. // No spaces around commas
  489. std::vector<std::string> no_space_result;
  490. EXPECT_TRUE(detail::parse_accept_header(
  491. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  492. no_space_result));
  493. EXPECT_EQ(no_space_result.size(), 3U);
  494. EXPECT_EQ(no_space_result[0], "text/html");
  495. EXPECT_EQ(no_space_result[1], "application/json");
  496. EXPECT_EQ(no_space_result[2], "text/plain");
  497. }
  498. TEST(ParseAcceptHeaderTest, InvalidCases) {
  499. std::vector<std::string> result;
  500. // Invalid quality value (> 1.0)
  501. EXPECT_FALSE(
  502. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  503. // Invalid quality value (< 0.0)
  504. EXPECT_FALSE(
  505. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  506. // Invalid quality value (not a number)
  507. EXPECT_FALSE(detail::parse_accept_header(
  508. "text/html;q=invalid,application/json", result));
  509. // Empty quality value
  510. EXPECT_FALSE(
  511. detail::parse_accept_header("text/html;q=,application/json", result));
  512. // Invalid media type format (no slash and not wildcard)
  513. EXPECT_FALSE(
  514. detail::parse_accept_header("invalidtype,application/json", result));
  515. // Empty media type
  516. result.clear();
  517. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  518. // Only commas
  519. result.clear();
  520. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  521. // Valid cases should still work
  522. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  523. EXPECT_EQ(result.size(), 1U);
  524. EXPECT_EQ(result[0], "*/*");
  525. EXPECT_TRUE(detail::parse_accept_header("*", result));
  526. EXPECT_EQ(result.size(), 1U);
  527. EXPECT_EQ(result[0], "*");
  528. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  529. EXPECT_EQ(result.size(), 1U);
  530. EXPECT_EQ(result[0], "text/*");
  531. }
  532. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  533. Server svr;
  534. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  535. EXPECT_EQ(req.accept_content_types.size(), 3U);
  536. EXPECT_EQ(req.accept_content_types[0], "application/json");
  537. EXPECT_EQ(req.accept_content_types[1], "text/html");
  538. EXPECT_EQ(req.accept_content_types[2], "*/*");
  539. res.set_content("ok", "text/plain");
  540. });
  541. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  542. EXPECT_TRUE(false);
  543. res.set_content("bad request", "text/plain");
  544. });
  545. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  546. auto se = detail::scope_exit([&] {
  547. svr.stop();
  548. listen_thread.join();
  549. ASSERT_FALSE(svr.is_running());
  550. });
  551. svr.wait_until_ready();
  552. Client cli("localhost", PORT);
  553. {
  554. auto res =
  555. cli.Get("/accept_ok",
  556. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  557. ASSERT_TRUE(res);
  558. EXPECT_EQ(StatusCode::OK_200, res->status);
  559. }
  560. {
  561. auto res = cli.Get("/accept_bad_request",
  562. {{"Accept", "text/html;q=abc,application/json"}});
  563. ASSERT_TRUE(res);
  564. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  565. }
  566. }
  567. TEST(DivideTest, DivideStringTests) {
  568. auto divide = [](const std::string &str, char d) {
  569. std::string lhs;
  570. std::string rhs;
  571. detail::divide(str, d,
  572. [&](const char *lhs_data, std::size_t lhs_size,
  573. const char *rhs_data, std::size_t rhs_size) {
  574. lhs.assign(lhs_data, lhs_size);
  575. rhs.assign(rhs_data, rhs_size);
  576. });
  577. return std::make_pair(std::move(lhs), std::move(rhs));
  578. };
  579. {
  580. const auto res = divide("", '=');
  581. EXPECT_EQ(res.first, "");
  582. EXPECT_EQ(res.second, "");
  583. }
  584. {
  585. const auto res = divide("=", '=');
  586. EXPECT_EQ(res.first, "");
  587. EXPECT_EQ(res.second, "");
  588. }
  589. {
  590. const auto res = divide(" ", '=');
  591. EXPECT_EQ(res.first, " ");
  592. EXPECT_EQ(res.second, "");
  593. }
  594. {
  595. const auto res = divide("a", '=');
  596. EXPECT_EQ(res.first, "a");
  597. EXPECT_EQ(res.second, "");
  598. }
  599. {
  600. const auto res = divide("a=", '=');
  601. EXPECT_EQ(res.first, "a");
  602. EXPECT_EQ(res.second, "");
  603. }
  604. {
  605. const auto res = divide("=b", '=');
  606. EXPECT_EQ(res.first, "");
  607. EXPECT_EQ(res.second, "b");
  608. }
  609. {
  610. const auto res = divide("a=b", '=');
  611. EXPECT_EQ(res.first, "a");
  612. EXPECT_EQ(res.second, "b");
  613. }
  614. {
  615. const auto res = divide("a=b=", '=');
  616. EXPECT_EQ(res.first, "a");
  617. EXPECT_EQ(res.second, "b=");
  618. }
  619. {
  620. const auto res = divide("a=b=c", '=');
  621. EXPECT_EQ(res.first, "a");
  622. EXPECT_EQ(res.second, "b=c");
  623. }
  624. }
  625. TEST(SplitTest, ParseQueryString) {
  626. string s = "key1=val1&key2=val2&key3=val3";
  627. Params dic;
  628. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  629. [&](const char *b, const char *e) {
  630. string key, val;
  631. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  632. if (key.empty()) {
  633. key.assign(b2, e2);
  634. } else {
  635. val.assign(b2, e2);
  636. }
  637. });
  638. dic.emplace(key, val);
  639. });
  640. EXPECT_EQ("val1", dic.find("key1")->second);
  641. EXPECT_EQ("val2", dic.find("key2")->second);
  642. EXPECT_EQ("val3", dic.find("key3")->second);
  643. }
  644. TEST(SplitTest, ParseInvalidQueryTests) {
  645. {
  646. string s = " ";
  647. Params dict;
  648. detail::parse_query_text(s, dict);
  649. EXPECT_TRUE(dict.empty());
  650. }
  651. {
  652. string s = " = =";
  653. Params dict;
  654. detail::parse_query_text(s, dict);
  655. EXPECT_TRUE(dict.empty());
  656. }
  657. }
  658. TEST(ParseQueryTest, ParseQueryString) {
  659. {
  660. std::string s = "key1=val1&key2=val2&key3=val3";
  661. Params dic;
  662. detail::parse_query_text(s, dic);
  663. EXPECT_EQ("val1", dic.find("key1")->second);
  664. EXPECT_EQ("val2", dic.find("key2")->second);
  665. EXPECT_EQ("val3", dic.find("key3")->second);
  666. }
  667. {
  668. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  669. Params dic;
  670. detail::parse_query_text(s, dic);
  671. EXPECT_EQ("", dic.find("key1")->second);
  672. EXPECT_EQ("val1", dic.find("key2")->second);
  673. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  674. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  675. }
  676. }
  677. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  678. Params dic;
  679. EXPECT_EQ(detail::params_to_query_str(dic), "");
  680. dic.emplace("key1", "val1");
  681. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  682. dic.emplace("key2", "val2");
  683. dic.emplace("key3", "val3");
  684. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  685. }
  686. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  687. string content_type = "multipart/form-data; boundary=something";
  688. string boundary;
  689. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  690. EXPECT_TRUE(ret);
  691. EXPECT_EQ(boundary, "something");
  692. }
  693. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  694. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  695. string boundary;
  696. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  697. EXPECT_TRUE(ret);
  698. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  699. }
  700. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  701. string content_type =
  702. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  703. string boundary;
  704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  705. EXPECT_TRUE(ret);
  706. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  707. }
  708. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  709. string content_type =
  710. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  711. string boundary;
  712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  713. EXPECT_TRUE(ret);
  714. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  715. }
  716. TEST(GetHeaderValueTest, DefaultValue) {
  717. Headers headers = {{"Dummy", "Dummy"}};
  718. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  719. EXPECT_STREQ("text/plain", val);
  720. }
  721. TEST(GetHeaderValueTest, DefaultValueInt) {
  722. Headers headers = {{"Dummy", "Dummy"}};
  723. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  724. EXPECT_EQ(100ull, val);
  725. }
  726. TEST(GetHeaderValueTest, RegularValue) {
  727. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  728. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  729. EXPECT_STREQ("text/html", val);
  730. }
  731. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  732. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  733. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  734. EXPECT_STREQ("text/html", val);
  735. }
  736. TEST(GetHeaderValueTest, SetContent) {
  737. Response res;
  738. res.set_content("html", "text/html");
  739. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  740. res.set_content("text", "text/plain");
  741. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  742. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  743. }
  744. TEST(GetHeaderValueTest, RegularValueInt) {
  745. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  746. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  747. EXPECT_EQ(100ull, val);
  748. }
  749. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  750. Headers headers = {{"Content-Length", "x"}};
  751. auto is_invalid_value = false;
  752. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  753. is_invalid_value);
  754. EXPECT_EQ(0ull, val);
  755. EXPECT_TRUE(is_invalid_value);
  756. }
  757. TEST(GetHeaderValueTest, Range) {
  758. {
  759. Headers headers = {make_range_header({{1, -1}})};
  760. auto val = detail::get_header_value(headers, "Range", 0, 0);
  761. EXPECT_STREQ("bytes=1-", val);
  762. }
  763. {
  764. Headers headers = {make_range_header({{-1, 1}})};
  765. auto val = detail::get_header_value(headers, "Range", 0, 0);
  766. EXPECT_STREQ("bytes=-1", val);
  767. }
  768. {
  769. Headers headers = {make_range_header({{1, 10}})};
  770. auto val = detail::get_header_value(headers, "Range", 0, 0);
  771. EXPECT_STREQ("bytes=1-10", val);
  772. }
  773. {
  774. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  775. auto val = detail::get_header_value(headers, "Range", 0, 0);
  776. EXPECT_STREQ("bytes=1-10, 100-", val);
  777. }
  778. {
  779. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  780. auto val = detail::get_header_value(headers, "Range", 0, 0);
  781. EXPECT_STREQ("bytes=1-10, 100-200", val);
  782. }
  783. {
  784. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  785. auto val = detail::get_header_value(headers, "Range", 0, 0);
  786. EXPECT_STREQ("bytes=0-0, -1", val);
  787. }
  788. }
  789. TEST(ParseHeaderValueTest, Range) {
  790. {
  791. Ranges ranges;
  792. auto ret = detail::parse_range_header("bytes=1-", ranges);
  793. EXPECT_TRUE(ret);
  794. EXPECT_EQ(1u, ranges.size());
  795. EXPECT_EQ(1u, ranges[0].first);
  796. EXPECT_EQ(-1, ranges[0].second);
  797. }
  798. {
  799. Ranges ranges;
  800. auto ret = detail::parse_range_header("bytes=-1", ranges);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(1u, ranges.size());
  803. EXPECT_EQ(-1, ranges[0].first);
  804. EXPECT_EQ(1u, ranges[0].second);
  805. }
  806. {
  807. Ranges ranges;
  808. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(1u, ranges.size());
  811. EXPECT_EQ(1u, ranges[0].first);
  812. EXPECT_EQ(10u, ranges[0].second);
  813. }
  814. {
  815. Ranges ranges;
  816. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  817. EXPECT_FALSE(ret);
  818. }
  819. {
  820. Ranges ranges;
  821. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  822. EXPECT_TRUE(ret);
  823. EXPECT_EQ(2u, ranges.size());
  824. EXPECT_EQ(1u, ranges[0].first);
  825. EXPECT_EQ(10u, ranges[0].second);
  826. EXPECT_EQ(100u, ranges[1].first);
  827. EXPECT_EQ(-1, ranges[1].second);
  828. }
  829. {
  830. Ranges ranges;
  831. auto ret =
  832. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  833. EXPECT_TRUE(ret);
  834. EXPECT_EQ(3u, ranges.size());
  835. EXPECT_EQ(1u, ranges[0].first);
  836. EXPECT_EQ(10u, ranges[0].second);
  837. EXPECT_EQ(100u, ranges[1].first);
  838. EXPECT_EQ(200u, ranges[1].second);
  839. EXPECT_EQ(300u, ranges[2].first);
  840. EXPECT_EQ(400u, ranges[2].second);
  841. }
  842. {
  843. Ranges ranges;
  844. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", 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_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  857. EXPECT_TRUE(ranges.empty());
  858. }
  859. }
  860. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  861. Request req;
  862. req.set_header("Accept-Encoding", "gzip");
  863. Response res;
  864. res.set_header("Content-Type", "text/plain");
  865. auto ret = detail::encoding_type(req, res);
  866. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  867. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  868. #else
  869. EXPECT_TRUE(ret == detail::EncodingType::None);
  870. #endif
  871. }
  872. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  873. Request req;
  874. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  875. Response res;
  876. res.set_header("Content-Type", "text/plain");
  877. auto ret = detail::encoding_type(req, res);
  878. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  879. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  880. #elif CPPHTTPLIB_ZLIB_SUPPORT
  881. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  882. #elif CPPHTTPLIB_ZSTD_SUPPORT
  883. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  884. #else
  885. EXPECT_TRUE(ret == detail::EncodingType::None);
  886. #endif
  887. }
  888. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  889. Request req;
  890. req.set_header("Accept-Encoding",
  891. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  892. Response res;
  893. res.set_header("Content-Type", "text/plain");
  894. auto ret = detail::encoding_type(req, res);
  895. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  896. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  897. #elif CPPHTTPLIB_ZLIB_SUPPORT
  898. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  899. #elif CPPHTTPLIB_ZSTD_SUPPORT
  900. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  901. #else
  902. EXPECT_TRUE(ret == detail::EncodingType::None);
  903. #endif
  904. }
  905. TEST(BufferStreamTest, read) {
  906. detail::BufferStream strm1;
  907. Stream &strm = strm1;
  908. EXPECT_EQ(5, strm.write("hello"));
  909. char buf[512];
  910. EXPECT_EQ(2, strm.read(buf, 2));
  911. EXPECT_EQ('h', buf[0]);
  912. EXPECT_EQ('e', buf[1]);
  913. EXPECT_EQ(2, strm.read(buf, 2));
  914. EXPECT_EQ('l', buf[0]);
  915. EXPECT_EQ('l', buf[1]);
  916. EXPECT_EQ(1, strm.read(buf, 1));
  917. EXPECT_EQ('o', buf[0]);
  918. EXPECT_EQ(0, strm.read(buf, 1));
  919. }
  920. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  921. auto host = "www.httpwatch.com";
  922. auto ip = hosted_at(host);
  923. EXPECT_EQ("23.96.13.243", ip);
  924. std::vector<std::string> addrs;
  925. hosted_at(host, addrs);
  926. EXPECT_EQ(1u, addrs.size());
  927. }
  928. #if 0 // It depends on each test environment...
  929. TEST(HostnameToIPConversionTest, YouTube_Online) {
  930. auto host = "www.youtube.com";
  931. std::vector<std::string> addrs;
  932. hosted_at(host, addrs);
  933. EXPECT_EQ(20u, addrs.size());
  934. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  935. EXPECT_TRUE(it != addrs.end());
  936. }
  937. #endif
  938. class ChunkedEncodingTest : public ::testing::Test {
  939. protected:
  940. ChunkedEncodingTest()
  941. : cli_(HOST, PORT)
  942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  943. ,
  944. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  945. #endif
  946. {
  947. cli_.set_connection_timeout(2);
  948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  949. cli_.enable_server_certificate_verification(false);
  950. #endif
  951. }
  952. virtual void SetUp() {
  953. read_file("./image.jpg", image_data_);
  954. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  955. res.set_content("Hello World!", "text/plain");
  956. });
  957. svr_.Get(
  958. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  959. res.set_chunked_content_provider(
  960. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  961. size_t remaining = image_data_.size() - offset;
  962. if (remaining == 0) {
  963. sink.done();
  964. } else {
  965. constexpr size_t CHUNK_SIZE = 1024;
  966. size_t send_size = std::min(CHUNK_SIZE, remaining);
  967. sink.write(&image_data_[offset], send_size);
  968. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  969. }
  970. return true;
  971. });
  972. });
  973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  974. svr_.wait_until_ready();
  975. }
  976. virtual void TearDown() {
  977. svr_.stop();
  978. if (!request_threads_.empty()) {
  979. std::this_thread::sleep_for(std::chrono::seconds(1));
  980. for (auto &t : request_threads_) {
  981. t.join();
  982. }
  983. }
  984. t_.join();
  985. }
  986. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  987. SSLClient cli_;
  988. SSLServer svr_;
  989. #else
  990. Client cli_;
  991. Server svr_;
  992. #endif
  993. thread t_;
  994. std::vector<thread> request_threads_;
  995. std::string image_data_;
  996. };
  997. TEST_F(ChunkedEncodingTest, NormalGet) {
  998. auto res = cli_.Get("/chunked");
  999. ASSERT_TRUE(res);
  1000. std::string out;
  1001. read_file("./image.jpg", out);
  1002. EXPECT_EQ(StatusCode::OK_200, res->status);
  1003. EXPECT_EQ(out, res->body);
  1004. }
  1005. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1006. std::string body;
  1007. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1008. body.append(data, data_length);
  1009. return true;
  1010. });
  1011. ASSERT_TRUE(res);
  1012. std::string out;
  1013. read_file("./image.jpg", out);
  1014. EXPECT_EQ(StatusCode::OK_200, res->status);
  1015. EXPECT_EQ(out, body);
  1016. }
  1017. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1018. std::string body;
  1019. auto res = cli_.Get(
  1020. "/chunked",
  1021. [&](const Response &response) {
  1022. EXPECT_EQ(StatusCode::OK_200, response.status);
  1023. return true;
  1024. },
  1025. [&](const char *data, size_t data_length) {
  1026. body.append(data, data_length);
  1027. return true;
  1028. });
  1029. ASSERT_TRUE(res);
  1030. std::string out;
  1031. read_file("./image.jpg", out);
  1032. EXPECT_EQ(StatusCode::OK_200, res->status);
  1033. EXPECT_EQ(out, body);
  1034. }
  1035. TEST(RangeTest, FromHTTPBin_Online) {
  1036. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1037. auto host = "httpbin.org";
  1038. auto path = std::string{"/range/32"};
  1039. #else
  1040. auto host = "nghttp2.org";
  1041. auto path = std::string{"/httpbin/range/32"};
  1042. #endif
  1043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1044. auto port = 443;
  1045. SSLClient cli(host, port);
  1046. #else
  1047. auto port = 80;
  1048. Client cli(host, port);
  1049. #endif
  1050. cli.set_connection_timeout(5);
  1051. {
  1052. auto res = cli.Get(path);
  1053. ASSERT_TRUE(res);
  1054. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1055. EXPECT_EQ(StatusCode::OK_200, res->status);
  1056. }
  1057. {
  1058. Headers headers = {make_range_header({{1, -1}})};
  1059. auto res = cli.Get(path, headers);
  1060. ASSERT_TRUE(res);
  1061. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1063. }
  1064. {
  1065. Headers headers = {make_range_header({{1, 10}})};
  1066. auto res = cli.Get(path, headers);
  1067. ASSERT_TRUE(res);
  1068. EXPECT_EQ("bcdefghijk", res->body);
  1069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1070. }
  1071. {
  1072. Headers headers = {make_range_header({{0, 31}})};
  1073. auto res = cli.Get(path, headers);
  1074. ASSERT_TRUE(res);
  1075. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1076. EXPECT_EQ(StatusCode::OK_200, res->status);
  1077. }
  1078. {
  1079. Headers headers = {make_range_header({{0, -1}})};
  1080. auto res = cli.Get(path, headers);
  1081. ASSERT_TRUE(res);
  1082. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. }
  1085. {
  1086. Headers headers = {make_range_header({{0, 32}})};
  1087. auto res = cli.Get(path, headers);
  1088. ASSERT_TRUE(res);
  1089. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1090. }
  1091. }
  1092. TEST(ConnectionErrorTest, InvalidHost) {
  1093. auto host = "-abcde.com";
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(std::chrono::seconds(2));
  1102. auto res = cli.Get("/");
  1103. ASSERT_TRUE(!res);
  1104. EXPECT_EQ(Error::Connection, res.error());
  1105. }
  1106. TEST(ConnectionErrorTest, InvalidHost2) {
  1107. auto host = "httpbin.org/";
  1108. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1109. SSLClient cli(host);
  1110. #else
  1111. Client cli(host);
  1112. #endif
  1113. cli.set_connection_timeout(std::chrono::seconds(2));
  1114. auto res = cli.Get("/");
  1115. ASSERT_TRUE(!res);
  1116. EXPECT_EQ(Error::Connection, res.error());
  1117. }
  1118. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1119. auto host = "httpbin.org/";
  1120. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1121. SSLClient cli(host);
  1122. #else
  1123. Client cli(host);
  1124. #endif
  1125. cli.set_connection_timeout(std::chrono::seconds(2));
  1126. auto res = cli.Get("/");
  1127. ASSERT_TRUE(!res);
  1128. stringstream s;
  1129. s << "error code: " << res.error();
  1130. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1131. }
  1132. TEST(ConnectionErrorTest, InvalidPort) {
  1133. auto host = "localhost";
  1134. auto port = 44380;
  1135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1136. SSLClient cli(host, port);
  1137. #else
  1138. Client cli(host, port);
  1139. #endif
  1140. cli.set_connection_timeout(std::chrono::seconds(2));
  1141. auto res = cli.Get("/");
  1142. ASSERT_TRUE(!res);
  1143. EXPECT_TRUE(Error::Connection == res.error() ||
  1144. Error::ConnectionTimeout == res.error());
  1145. }
  1146. TEST(ConnectionErrorTest, Timeout_Online) {
  1147. auto host = "google.com";
  1148. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1149. auto port = 44380;
  1150. SSLClient cli(host, port);
  1151. #else
  1152. auto port = 8080;
  1153. Client cli(host, port);
  1154. #endif
  1155. cli.set_connection_timeout(std::chrono::seconds(2));
  1156. // only probe one address type so that the error reason
  1157. // correlates to the timed-out IPv4, not the unsupported
  1158. // IPv6 connection attempt
  1159. cli.set_address_family(AF_INET);
  1160. auto res = cli.Get("/");
  1161. ASSERT_TRUE(!res);
  1162. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1163. }
  1164. TEST(CancelTest, NoCancel_Online) {
  1165. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1166. auto host = "httpbin.org";
  1167. auto path = std::string{"/range/32"};
  1168. #else
  1169. auto host = "nghttp2.org";
  1170. auto path = std::string{"/httpbin/range/32"};
  1171. #endif
  1172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1173. auto port = 443;
  1174. SSLClient cli(host, port);
  1175. #else
  1176. auto port = 80;
  1177. Client cli(host, port);
  1178. #endif
  1179. cli.set_connection_timeout(std::chrono::seconds(5));
  1180. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1181. ASSERT_TRUE(res);
  1182. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1183. EXPECT_EQ(StatusCode::OK_200, res->status);
  1184. }
  1185. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1186. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1187. auto host = "httpbin.org";
  1188. auto path = std::string{"/range/32"};
  1189. #else
  1190. auto host = "nghttp2.org";
  1191. auto path = std::string{"/httpbin/range/32"};
  1192. #endif
  1193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1194. auto port = 443;
  1195. SSLClient cli(host, port);
  1196. #else
  1197. auto port = 80;
  1198. Client cli(host, port);
  1199. #endif
  1200. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1201. cli.set_connection_timeout(std::chrono::seconds(5));
  1202. ASSERT_TRUE(!res);
  1203. EXPECT_EQ(Error::Canceled, res.error());
  1204. }
  1205. TEST(CancelTest, WithCancelLargePayload_Online) {
  1206. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1207. auto host = "httpbin.org";
  1208. auto path = std::string{"/range/65536"};
  1209. #else
  1210. auto host = "nghttp2.org";
  1211. auto path = std::string{"/httpbin/range/65536"};
  1212. #endif
  1213. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1214. auto port = 443;
  1215. SSLClient cli(host, port);
  1216. #else
  1217. auto port = 80;
  1218. Client cli(host, port);
  1219. #endif
  1220. cli.set_connection_timeout(std::chrono::seconds(5));
  1221. uint32_t count = 0;
  1222. auto res =
  1223. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Canceled, res.error());
  1226. }
  1227. TEST(CancelTest, NoCancelPost) {
  1228. Server svr;
  1229. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1230. res.set_content("Hello World!", "text/plain");
  1231. });
  1232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1233. auto se = detail::scope_exit([&] {
  1234. svr.stop();
  1235. thread.join();
  1236. ASSERT_FALSE(svr.is_running());
  1237. });
  1238. svr.wait_until_ready();
  1239. Client cli(HOST, PORT);
  1240. cli.set_connection_timeout(std::chrono::seconds(5));
  1241. auto res =
  1242. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1243. "application/json", [](uint64_t, uint64_t) { return true; });
  1244. ASSERT_TRUE(res);
  1245. EXPECT_EQ("Hello World!", res->body);
  1246. EXPECT_EQ(StatusCode::OK_200, res->status);
  1247. }
  1248. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1249. Server svr;
  1250. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1251. res.set_content("Hello World!", "text/plain");
  1252. });
  1253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1254. auto se = detail::scope_exit([&] {
  1255. svr.stop();
  1256. thread.join();
  1257. ASSERT_FALSE(svr.is_running());
  1258. });
  1259. svr.wait_until_ready();
  1260. Client cli(HOST, PORT);
  1261. cli.set_connection_timeout(std::chrono::seconds(5));
  1262. auto res =
  1263. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1264. "application/json", [](uint64_t, uint64_t) { return false; });
  1265. ASSERT_TRUE(!res);
  1266. EXPECT_EQ(Error::Canceled, res.error());
  1267. }
  1268. TEST(CancelTest, WithCancelLargePayloadPost) {
  1269. Server svr;
  1270. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1271. res.set_content(LARGE_DATA, "text/plain");
  1272. });
  1273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1274. auto se = detail::scope_exit([&] {
  1275. svr.stop();
  1276. thread.join();
  1277. ASSERT_FALSE(svr.is_running());
  1278. });
  1279. svr.wait_until_ready();
  1280. Client cli(HOST, PORT);
  1281. cli.set_connection_timeout(std::chrono::seconds(5));
  1282. auto res =
  1283. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1284. "application/json", [](uint64_t, uint64_t) { return false; });
  1285. ASSERT_TRUE(!res);
  1286. EXPECT_EQ(Error::Canceled, res.error());
  1287. }
  1288. TEST(CancelTest, NoCancelPut) {
  1289. Server svr;
  1290. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1291. res.set_content("Hello World!", "text/plain");
  1292. });
  1293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1294. auto se = detail::scope_exit([&] {
  1295. svr.stop();
  1296. thread.join();
  1297. ASSERT_FALSE(svr.is_running());
  1298. });
  1299. svr.wait_until_ready();
  1300. Client cli(HOST, PORT);
  1301. cli.set_connection_timeout(std::chrono::seconds(5));
  1302. auto res =
  1303. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1304. "application/json", [](uint64_t, uint64_t) { return true; });
  1305. ASSERT_TRUE(res);
  1306. EXPECT_EQ("Hello World!", res->body);
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1310. Server svr;
  1311. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1312. res.set_content("Hello World!", "text/plain");
  1313. });
  1314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1315. auto se = detail::scope_exit([&] {
  1316. svr.stop();
  1317. thread.join();
  1318. ASSERT_FALSE(svr.is_running());
  1319. });
  1320. svr.wait_until_ready();
  1321. Client cli(HOST, PORT);
  1322. cli.set_connection_timeout(std::chrono::seconds(5));
  1323. auto res =
  1324. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1325. "application/json", [](uint64_t, uint64_t) { return false; });
  1326. ASSERT_TRUE(!res);
  1327. EXPECT_EQ(Error::Canceled, res.error());
  1328. }
  1329. TEST(CancelTest, WithCancelLargePayloadPut) {
  1330. Server svr;
  1331. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1332. res.set_content(LARGE_DATA, "text/plain");
  1333. });
  1334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1335. auto se = detail::scope_exit([&] {
  1336. svr.stop();
  1337. thread.join();
  1338. ASSERT_FALSE(svr.is_running());
  1339. });
  1340. svr.wait_until_ready();
  1341. Client cli(HOST, PORT);
  1342. cli.set_connection_timeout(std::chrono::seconds(5));
  1343. auto res =
  1344. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1345. "application/json", [](uint64_t, uint64_t) { return false; });
  1346. ASSERT_TRUE(!res);
  1347. EXPECT_EQ(Error::Canceled, res.error());
  1348. }
  1349. TEST(CancelTest, NoCancelPatch) {
  1350. Server svr;
  1351. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1352. res.set_content("Hello World!", "text/plain");
  1353. });
  1354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1355. auto se = detail::scope_exit([&] {
  1356. svr.stop();
  1357. thread.join();
  1358. ASSERT_FALSE(svr.is_running());
  1359. });
  1360. svr.wait_until_ready();
  1361. Client cli(HOST, PORT);
  1362. cli.set_connection_timeout(std::chrono::seconds(5));
  1363. auto res =
  1364. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1365. "application/json", [](uint64_t, uint64_t) { return true; });
  1366. ASSERT_TRUE(res);
  1367. EXPECT_EQ("Hello World!", res->body);
  1368. EXPECT_EQ(StatusCode::OK_200, res->status);
  1369. }
  1370. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1371. Server svr;
  1372. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1373. res.set_content("Hello World!", "text/plain");
  1374. });
  1375. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1376. auto se = detail::scope_exit([&] {
  1377. svr.stop();
  1378. thread.join();
  1379. ASSERT_FALSE(svr.is_running());
  1380. });
  1381. svr.wait_until_ready();
  1382. Client cli(HOST, PORT);
  1383. cli.set_connection_timeout(std::chrono::seconds(5));
  1384. auto res =
  1385. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1386. "application/json", [](uint64_t, uint64_t) { return false; });
  1387. ASSERT_TRUE(!res);
  1388. EXPECT_EQ(Error::Canceled, res.error());
  1389. }
  1390. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1391. Server svr;
  1392. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(LARGE_DATA, "text/plain");
  1394. });
  1395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. thread.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, PORT);
  1403. cli.set_connection_timeout(std::chrono::seconds(5));
  1404. auto res =
  1405. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1406. "application/json", [](uint64_t, uint64_t) { return false; });
  1407. ASSERT_TRUE(!res);
  1408. EXPECT_EQ(Error::Canceled, res.error());
  1409. }
  1410. TEST(CancelTest, NoCancelDelete) {
  1411. Server svr;
  1412. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1413. res.set_content("Hello World!", "text/plain");
  1414. });
  1415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1416. auto se = detail::scope_exit([&] {
  1417. svr.stop();
  1418. thread.join();
  1419. ASSERT_FALSE(svr.is_running());
  1420. });
  1421. svr.wait_until_ready();
  1422. Client cli(HOST, PORT);
  1423. cli.set_connection_timeout(std::chrono::seconds(5));
  1424. auto res =
  1425. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1426. "application/json", [](uint64_t, uint64_t) { return true; });
  1427. ASSERT_TRUE(res);
  1428. EXPECT_EQ("Hello World!", res->body);
  1429. EXPECT_EQ(StatusCode::OK_200, res->status);
  1430. }
  1431. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1432. Server svr;
  1433. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1434. res.set_content("Hello World!", "text/plain");
  1435. });
  1436. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1437. auto se = detail::scope_exit([&] {
  1438. svr.stop();
  1439. thread.join();
  1440. ASSERT_FALSE(svr.is_running());
  1441. });
  1442. svr.wait_until_ready();
  1443. Client cli(HOST, PORT);
  1444. cli.set_connection_timeout(std::chrono::seconds(5));
  1445. auto res =
  1446. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1447. "application/json", [](uint64_t, uint64_t) { return false; });
  1448. ASSERT_TRUE(!res);
  1449. EXPECT_EQ(Error::Canceled, res.error());
  1450. }
  1451. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1452. Server svr;
  1453. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1454. res.set_content(LARGE_DATA, "text/plain");
  1455. });
  1456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. thread.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. Client cli(HOST, PORT);
  1464. cli.set_connection_timeout(std::chrono::seconds(5));
  1465. auto res =
  1466. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1467. "application/json", [](uint64_t, uint64_t) { return false; });
  1468. ASSERT_TRUE(!res);
  1469. EXPECT_EQ(Error::Canceled, res.error());
  1470. }
  1471. static std::string remove_whitespace(const std::string &input) {
  1472. std::string output;
  1473. output.reserve(input.size());
  1474. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1475. [](unsigned char c) { return !std::isspace(c); });
  1476. return output;
  1477. }
  1478. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1479. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1480. auto host = "httpbin.org";
  1481. auto path = std::string{"/basic-auth/hello/world"};
  1482. #else
  1483. auto host = "nghttp2.org";
  1484. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1485. #endif
  1486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1487. auto port = 443;
  1488. SSLClient cli(host, port);
  1489. #else
  1490. auto port = 80;
  1491. Client cli(host, port);
  1492. #endif
  1493. {
  1494. auto res = cli.Get(path);
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1497. }
  1498. {
  1499. auto res =
  1500. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1501. ASSERT_TRUE(res);
  1502. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1503. remove_whitespace(res->body));
  1504. EXPECT_EQ(StatusCode::OK_200, res->status);
  1505. }
  1506. {
  1507. cli.set_basic_auth("hello", "world");
  1508. auto res = cli.Get(path);
  1509. ASSERT_TRUE(res);
  1510. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1511. remove_whitespace(res->body));
  1512. EXPECT_EQ(StatusCode::OK_200, res->status);
  1513. }
  1514. {
  1515. cli.set_basic_auth("hello", "bad");
  1516. auto res = cli.Get(path);
  1517. ASSERT_TRUE(res);
  1518. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1519. }
  1520. {
  1521. cli.set_basic_auth("bad", "world");
  1522. auto res = cli.Get(path);
  1523. ASSERT_TRUE(res);
  1524. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1525. }
  1526. }
  1527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1528. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1529. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1530. auto host = "httpbin.org";
  1531. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1532. auto paths = std::vector<std::string>{
  1533. "/digest-auth/auth/hello/world/MD5",
  1534. "/digest-auth/auth/hello/world/SHA-256",
  1535. "/digest-auth/auth/hello/world/SHA-512",
  1536. "/digest-auth/auth-int/hello/world/MD5",
  1537. };
  1538. #else
  1539. auto host = "nghttp2.org";
  1540. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1541. auto paths = std::vector<std::string>{
  1542. "/httpbin/digest-auth/auth/hello/world/MD5",
  1543. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1544. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1545. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1546. };
  1547. #endif
  1548. auto port = 443;
  1549. SSLClient cli(host, port);
  1550. {
  1551. auto res = cli.Get(unauth_path);
  1552. ASSERT_TRUE(res);
  1553. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1554. }
  1555. {
  1556. cli.set_digest_auth("hello", "world");
  1557. for (const auto &path : paths) {
  1558. auto res = cli.Get(path.c_str());
  1559. ASSERT_TRUE(res);
  1560. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1561. remove_whitespace(res->body));
  1562. EXPECT_EQ(StatusCode::OK_200, res->status);
  1563. }
  1564. cli.set_digest_auth("hello", "bad");
  1565. for (const auto &path : paths) {
  1566. auto res = cli.Get(path.c_str());
  1567. ASSERT_TRUE(res);
  1568. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1569. }
  1570. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1571. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1572. // cli.set_digest_auth("bad", "world");
  1573. // for (const auto& path : paths) {
  1574. // auto res = cli.Get(path.c_str());
  1575. // ASSERT_TRUE(res);
  1576. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1577. // }
  1578. }
  1579. }
  1580. #endif
  1581. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1582. auto host = "google.com";
  1583. auto another_host = "example.com";
  1584. auto wrong_ip = "0.0.0.0";
  1585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1586. SSLClient cli(host);
  1587. #else
  1588. Client cli(host);
  1589. #endif
  1590. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1591. auto res = cli.Get("/");
  1592. ASSERT_TRUE(res);
  1593. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1594. }
  1595. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1596. auto host = "google.com";
  1597. auto wrong_ip = "0.0.0.0";
  1598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1599. SSLClient cli(host);
  1600. #else
  1601. Client cli(host);
  1602. #endif
  1603. cli.set_hostname_addr_map({{host, wrong_ip}});
  1604. auto res = cli.Get("/");
  1605. ASSERT_TRUE(!res);
  1606. EXPECT_EQ(Error::Connection, res.error());
  1607. }
  1608. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1609. auto host = "nghttp2.org";
  1610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1611. SSLClient cli(host);
  1612. #else
  1613. Client cli(host);
  1614. #endif
  1615. cli.set_follow_location(true);
  1616. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1617. ASSERT_TRUE(res);
  1618. EXPECT_EQ(StatusCode::OK_200, res->status);
  1619. }
  1620. TEST(RedirectTest, Redirect_Online) {
  1621. auto host = "nghttp2.org";
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. SSLClient cli(host);
  1624. #else
  1625. Client cli(host);
  1626. #endif
  1627. cli.set_follow_location(true);
  1628. auto res = cli.Get("/httpbin/redirect/3");
  1629. ASSERT_TRUE(res);
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. TEST(RelativeRedirectTest, Redirect_Online) {
  1633. auto host = "nghttp2.org";
  1634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1635. SSLClient cli(host);
  1636. #else
  1637. Client cli(host);
  1638. #endif
  1639. cli.set_follow_location(true);
  1640. auto res = cli.Get("/httpbin/relative-redirect/3");
  1641. ASSERT_TRUE(res);
  1642. EXPECT_EQ(StatusCode::OK_200, res->status);
  1643. }
  1644. TEST(TooManyRedirectTest, Redirect_Online) {
  1645. auto host = "nghttp2.org";
  1646. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1647. SSLClient cli(host);
  1648. #else
  1649. Client cli(host);
  1650. #endif
  1651. cli.set_follow_location(true);
  1652. auto res = cli.Get("/httpbin/redirect/21");
  1653. ASSERT_TRUE(!res);
  1654. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1655. }
  1656. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1657. TEST(YahooRedirectTest, Redirect_Online) {
  1658. Client cli("yahoo.com");
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. cli.set_follow_location(true);
  1663. res = cli.Get("/");
  1664. ASSERT_TRUE(res);
  1665. EXPECT_EQ(StatusCode::OK_200, res->status);
  1666. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1667. }
  1668. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1669. #define REDIR_HOST "httpbingo.org"
  1670. #define REDIR_PATH "/redirect-to"
  1671. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1672. SSLClient cli(REDIR_HOST);
  1673. cli.set_follow_location(true);
  1674. auto res =
  1675. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::OK_200, res->status);
  1678. }
  1679. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1680. SSLClient cli(REDIR_HOST);
  1681. cli.set_follow_location(true);
  1682. Params params;
  1683. params.emplace("url", "http://example.com");
  1684. params.emplace("status_code", "302");
  1685. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1686. ASSERT_TRUE(res);
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1690. SSLClient cli(REDIR_HOST);
  1691. cli.set_follow_location(true);
  1692. Params params;
  1693. params.emplace("url", "http://example.com");
  1694. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1695. ASSERT_TRUE(res);
  1696. EXPECT_EQ(StatusCode::OK_200, res->status);
  1697. }
  1698. TEST(UrlWithSpace, Redirect_Online) {
  1699. SSLClient cli("edge.forgecdn.net");
  1700. cli.set_follow_location(true);
  1701. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1702. ASSERT_TRUE(res);
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1705. }
  1706. #endif
  1707. #if !defined(_WIN32) && !defined(_WIN64)
  1708. TEST(ReceiveSignals, Signal) {
  1709. auto setupSignalHandlers = []() {
  1710. struct sigaction act;
  1711. sigemptyset(&act.sa_mask);
  1712. act.sa_flags = SA_SIGINFO;
  1713. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1714. switch (sig) {
  1715. case SIGINT:
  1716. default: break;
  1717. }
  1718. };
  1719. ::sigaction(SIGINT, &act, nullptr);
  1720. };
  1721. Server svr;
  1722. int port = 0;
  1723. auto thread = std::thread([&]() {
  1724. setupSignalHandlers();
  1725. port = svr.bind_to_any_port("localhost");
  1726. svr.listen_after_bind();
  1727. });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. ASSERT_TRUE(svr.is_running());
  1735. pthread_kill(thread.native_handle(), SIGINT);
  1736. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1737. ASSERT_TRUE(svr.is_running());
  1738. }
  1739. #endif
  1740. TEST(RedirectToDifferentPort, Redirect) {
  1741. Server svr1;
  1742. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1743. res.set_content("Hello World!", "text/plain");
  1744. });
  1745. int svr1_port = 0;
  1746. auto thread1 = std::thread([&]() {
  1747. svr1_port = svr1.bind_to_any_port("localhost");
  1748. svr1.listen_after_bind();
  1749. });
  1750. Server svr2;
  1751. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1752. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1753. });
  1754. int svr2_port = 0;
  1755. auto thread2 = std::thread([&]() {
  1756. svr2_port = svr2.bind_to_any_port("localhost");
  1757. svr2.listen_after_bind();
  1758. });
  1759. auto se = detail::scope_exit([&] {
  1760. svr2.stop();
  1761. thread2.join();
  1762. svr1.stop();
  1763. thread1.join();
  1764. ASSERT_FALSE(svr2.is_running());
  1765. ASSERT_FALSE(svr1.is_running());
  1766. });
  1767. svr1.wait_until_ready();
  1768. svr2.wait_until_ready();
  1769. Client cli("localhost", svr2_port);
  1770. cli.set_follow_location(true);
  1771. auto res = cli.Get("/2");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. EXPECT_EQ("Hello World!", res->body);
  1775. }
  1776. TEST(RedirectFromPageWithContent, Redirect) {
  1777. Server svr;
  1778. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1779. res.set_content("___", "text/plain");
  1780. res.set_redirect("/2");
  1781. });
  1782. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1783. res.set_content("Hello World!", "text/plain");
  1784. });
  1785. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1786. auto se = detail::scope_exit([&] {
  1787. svr.stop();
  1788. th.join();
  1789. ASSERT_FALSE(svr.is_running());
  1790. });
  1791. svr.wait_until_ready();
  1792. {
  1793. Client cli("localhost", PORT);
  1794. cli.set_follow_location(true);
  1795. std::string body;
  1796. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1797. body.append(data, data_length);
  1798. return true;
  1799. });
  1800. ASSERT_TRUE(res);
  1801. EXPECT_EQ(StatusCode::OK_200, res->status);
  1802. EXPECT_EQ("Hello World!", body);
  1803. }
  1804. {
  1805. Client cli("localhost", PORT);
  1806. std::string body;
  1807. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1808. body.append(data, data_length);
  1809. return true;
  1810. });
  1811. ASSERT_TRUE(res);
  1812. EXPECT_EQ(StatusCode::Found_302, res->status);
  1813. EXPECT_EQ("___", body);
  1814. }
  1815. }
  1816. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1817. Server svr;
  1818. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1819. res.set_content("___", "text/plain");
  1820. // res.set_redirect("/2");
  1821. res.set_redirect("http://[::1]:1234/2");
  1822. });
  1823. svr.Get("/2", [&](const Request &req, Response &res) {
  1824. auto host_header = req.headers.find("Host");
  1825. ASSERT_TRUE(host_header != req.headers.end());
  1826. EXPECT_EQ("[::1]:1234", host_header->second);
  1827. res.set_content("Hello World!", "text/plain");
  1828. });
  1829. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1830. auto se = detail::scope_exit([&] {
  1831. svr.stop();
  1832. th.join();
  1833. ASSERT_FALSE(svr.is_running());
  1834. });
  1835. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1836. // actually starts anything, so the condition !svr.is_running() will
  1837. // always remain true, and the loop never stops.
  1838. // This basically counts how many milliseconds have passed since the
  1839. // call to svr.listen(), and if after 5 seconds nothing started yet
  1840. // aborts the test.
  1841. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1842. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1843. ASSERT_LT(milliseconds, 5000U);
  1844. }
  1845. {
  1846. Client cli("http://[::1]:1234");
  1847. cli.set_follow_location(true);
  1848. std::string body;
  1849. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1850. body.append(data, data_length);
  1851. return true;
  1852. });
  1853. ASSERT_TRUE(res);
  1854. EXPECT_EQ(StatusCode::OK_200, res->status);
  1855. EXPECT_EQ("Hello World!", body);
  1856. }
  1857. {
  1858. Client cli("http://[::1]:1234");
  1859. std::string body;
  1860. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1861. body.append(data, data_length);
  1862. return true;
  1863. });
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(StatusCode::Found_302, res->status);
  1866. EXPECT_EQ("___", body);
  1867. }
  1868. }
  1869. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1870. Server svr;
  1871. svr.Get("/foo", [](const Request &req, Response &res) {
  1872. auto a = req.params.find("a");
  1873. if (a != req.params.end()) {
  1874. res.set_content((*a).second, "text/plain");
  1875. res.status = StatusCode::OK_200;
  1876. } else {
  1877. res.status = StatusCode::BadRequest_400;
  1878. }
  1879. });
  1880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1881. auto se = detail::scope_exit([&] {
  1882. svr.stop();
  1883. thread.join();
  1884. ASSERT_FALSE(svr.is_running());
  1885. });
  1886. svr.wait_until_ready();
  1887. {
  1888. Client cli(HOST, PORT);
  1889. cli.set_path_encode(false);
  1890. auto res = cli.Get("/foo?a=explicitly+encoded");
  1891. ASSERT_TRUE(res);
  1892. EXPECT_EQ(StatusCode::OK_200, res->status);
  1893. // This expects it back with a space, as the `+` won't have been
  1894. // url-encoded, and server-side the params get decoded turning `+`
  1895. // into spaces.
  1896. EXPECT_EQ("explicitly encoded", res->body);
  1897. }
  1898. }
  1899. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1900. Server svr;
  1901. svr.Get("/", [](const Request &req, Response &) {
  1902. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1903. });
  1904. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1905. auto se = detail::scope_exit([&] {
  1906. svr.stop();
  1907. thread.join();
  1908. ASSERT_FALSE(svr.is_running());
  1909. });
  1910. svr.wait_until_ready();
  1911. {
  1912. Client cli(HOST, PORT);
  1913. cli.set_path_encode(false);
  1914. auto res = cli.Get("/?something=%0A");
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. }
  1919. TEST(BindServerTest, DISABLED_BindDualStack) {
  1920. Server svr;
  1921. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1922. res.set_content("Hello World!", "text/plain");
  1923. });
  1924. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1925. auto se = detail::scope_exit([&] {
  1926. svr.stop();
  1927. thread.join();
  1928. ASSERT_FALSE(svr.is_running());
  1929. });
  1930. svr.wait_until_ready();
  1931. {
  1932. Client cli("127.0.0.1", PORT);
  1933. auto res = cli.Get("/1");
  1934. ASSERT_TRUE(res);
  1935. EXPECT_EQ(StatusCode::OK_200, res->status);
  1936. EXPECT_EQ("Hello World!", res->body);
  1937. }
  1938. {
  1939. Client cli("::1", PORT);
  1940. auto res = cli.Get("/1");
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(StatusCode::OK_200, res->status);
  1943. EXPECT_EQ("Hello World!", res->body);
  1944. }
  1945. }
  1946. TEST(BindServerTest, BindAndListenSeparately) {
  1947. Server svr;
  1948. int port = svr.bind_to_any_port("0.0.0.0");
  1949. ASSERT_TRUE(svr.is_valid());
  1950. ASSERT_TRUE(port > 0);
  1951. svr.stop();
  1952. }
  1953. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1954. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1956. CLIENT_CA_CERT_DIR);
  1957. int port = svr.bind_to_any_port("0.0.0.0");
  1958. ASSERT_TRUE(svr.is_valid());
  1959. ASSERT_TRUE(port > 0);
  1960. svr.stop();
  1961. }
  1962. #endif
  1963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1964. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1965. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1966. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1967. int port = svr.bind_to_any_port("0.0.0.0");
  1968. ASSERT_TRUE(svr.is_valid());
  1969. ASSERT_TRUE(port > 0);
  1970. svr.stop();
  1971. }
  1972. #endif
  1973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1974. X509 *readCertificate(const std::string &strFileName) {
  1975. std::ifstream inStream(strFileName);
  1976. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1977. std::istreambuf_iterator<char>());
  1978. if (strCertPEM.empty()) return (nullptr);
  1979. BIO *pbCert = BIO_new(BIO_s_mem());
  1980. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1981. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1982. BIO_free(pbCert);
  1983. return (pCert);
  1984. }
  1985. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1986. std::ifstream inStream(strFileName);
  1987. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1988. std::istreambuf_iterator<char>());
  1989. if (strPrivateKeyPEM.empty()) return (nullptr);
  1990. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1991. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1992. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1993. BIO_free(pbPrivKey);
  1994. return (pPrivateKey);
  1995. }
  1996. TEST(BindServerTest, UpdateCerts) {
  1997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1998. int port = svr.bind_to_any_port("0.0.0.0");
  1999. ASSERT_TRUE(svr.is_valid());
  2000. ASSERT_TRUE(port > 0);
  2001. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2002. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2003. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2004. ASSERT_TRUE(cert != nullptr);
  2005. ASSERT_TRUE(ca_cert != nullptr);
  2006. ASSERT_TRUE(key != nullptr);
  2007. X509_STORE *cert_store = X509_STORE_new();
  2008. X509_STORE_add_cert(cert_store, ca_cert);
  2009. svr.update_certs(cert, key, cert_store);
  2010. ASSERT_TRUE(svr.is_valid());
  2011. svr.stop();
  2012. X509_free(cert);
  2013. X509_free(ca_cert);
  2014. EVP_PKEY_free(key);
  2015. }
  2016. #endif
  2017. TEST(ErrorHandlerTest, ContentLength) {
  2018. Server svr;
  2019. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2020. res.status = StatusCode::OK_200;
  2021. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2022. "text/html"); // <= Content-Length still 13
  2023. });
  2024. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2025. res.set_content("Hello World!\n", "text/plain");
  2026. res.status = 524;
  2027. });
  2028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. thread.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli(HOST, PORT);
  2037. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2042. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2043. }
  2044. }
  2045. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2046. TEST(ExceptionTest, WithoutExceptionHandler) {
  2047. Server svr;
  2048. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2049. throw std::runtime_error("exception...");
  2050. });
  2051. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2052. throw std::runtime_error("exception\r\n...");
  2053. });
  2054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. listen_thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. Client cli("localhost", PORT);
  2062. {
  2063. auto res = cli.Get("/exception");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2066. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2067. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2068. }
  2069. {
  2070. auto res = cli.Get("/unknown");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2073. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2074. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2075. }
  2076. }
  2077. TEST(ExceptionTest, WithExceptionHandler) {
  2078. Server svr;
  2079. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2080. std::exception_ptr ep) {
  2081. EXPECT_FALSE(ep == nullptr);
  2082. try {
  2083. std::rethrow_exception(ep);
  2084. } catch (std::exception &e) {
  2085. EXPECT_EQ("abc", std::string(e.what()));
  2086. } catch (...) {}
  2087. res.status = StatusCode::InternalServerError_500;
  2088. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2089. "text/html"); // <= Content-Length still 13 at this point
  2090. });
  2091. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2092. res.set_content("Hello World!\n", "text/plain");
  2093. throw std::runtime_error("abc");
  2094. });
  2095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2096. auto se = detail::scope_exit([&] {
  2097. svr.stop();
  2098. thread.join();
  2099. ASSERT_FALSE(svr.is_running());
  2100. });
  2101. svr.wait_until_ready();
  2102. for (size_t i = 0; i < 10; i++) {
  2103. Client cli(HOST, PORT);
  2104. for (size_t j = 0; j < 100; j++) {
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. cli.set_keep_alive(true);
  2113. for (size_t j = 0; j < 100; j++) {
  2114. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2115. ASSERT_TRUE(res);
  2116. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2117. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2118. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2119. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2120. }
  2121. }
  2122. }
  2123. TEST(ExceptionTest, AndErrorHandler) {
  2124. Server svr;
  2125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2126. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2127. });
  2128. svr.set_exception_handler(
  2129. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2130. EXPECT_FALSE(ep == nullptr);
  2131. try {
  2132. std::rethrow_exception(ep);
  2133. } catch (std::exception &e) {
  2134. res.set_content(e.what(), "text/html");
  2135. } catch (...) {}
  2136. res.status = StatusCode::InternalServerError_500;
  2137. });
  2138. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2139. throw std::runtime_error("EXCEPTION");
  2140. });
  2141. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2142. res.set_content("ERROR", "text/html");
  2143. res.status = StatusCode::InternalServerError_500;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. Client cli(HOST, PORT);
  2153. {
  2154. auto res = cli.Get("/exception");
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2157. EXPECT_EQ("EXCEPTION", res->body);
  2158. }
  2159. {
  2160. auto res = cli.Get("/error");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2163. EXPECT_EQ("ERROR", res->body);
  2164. }
  2165. {
  2166. auto res = cli.Get("/invalid");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2169. EXPECT_EQ("NOT_FOUND", res->body);
  2170. }
  2171. }
  2172. #endif
  2173. TEST(NoContentTest, ContentLength) {
  2174. Server svr;
  2175. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2176. res.status = StatusCode::NoContent_204;
  2177. });
  2178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2179. auto se = detail::scope_exit([&] {
  2180. svr.stop();
  2181. thread.join();
  2182. ASSERT_FALSE(svr.is_running());
  2183. });
  2184. svr.wait_until_ready();
  2185. {
  2186. Client cli(HOST, PORT);
  2187. auto res = cli.Get("/hi");
  2188. ASSERT_TRUE(res);
  2189. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2190. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2191. }
  2192. }
  2193. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2194. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2196. ASSERT_TRUE(svr.is_valid());
  2197. #else
  2198. Server svr;
  2199. #endif
  2200. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2201. if (req.path == "/routing_handler") {
  2202. res.set_header("PRE_ROUTING", "on");
  2203. res.set_content("Routing Handler", "text/plain");
  2204. return httplib::Server::HandlerResponse::Handled;
  2205. }
  2206. return httplib::Server::HandlerResponse::Unhandled;
  2207. });
  2208. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2209. res.set_content("Error", "text/html");
  2210. });
  2211. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2212. if (req.path == "/routing_handler") {
  2213. res.set_header("POST_ROUTING", "on");
  2214. }
  2215. });
  2216. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2217. res.set_content("Hello World!\n", "text/plain");
  2218. });
  2219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2220. auto se = detail::scope_exit([&] {
  2221. svr.stop();
  2222. thread.join();
  2223. ASSERT_FALSE(svr.is_running());
  2224. });
  2225. svr.wait_until_ready();
  2226. {
  2227. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2228. SSLClient cli(HOST, PORT);
  2229. cli.enable_server_certificate_verification(false);
  2230. #else
  2231. Client cli(HOST, PORT);
  2232. #endif
  2233. auto res = cli.Get("/routing_handler");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. EXPECT_EQ("Routing Handler", res->body);
  2237. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2238. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2239. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2240. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2241. }
  2242. {
  2243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2244. SSLClient cli(HOST, PORT);
  2245. cli.enable_server_certificate_verification(false);
  2246. #else
  2247. Client cli(HOST, PORT);
  2248. #endif
  2249. auto res = cli.Get("/hi");
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(StatusCode::OK_200, res->status);
  2252. EXPECT_EQ("Hello World!\n", res->body);
  2253. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2254. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2255. }
  2256. {
  2257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2258. SSLClient cli(HOST, PORT);
  2259. cli.enable_server_certificate_verification(false);
  2260. #else
  2261. Client cli(HOST, PORT);
  2262. #endif
  2263. auto res = cli.Get("/aaa");
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2266. EXPECT_EQ("Error", res->body);
  2267. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2268. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2269. }
  2270. }
  2271. TEST(RequestHandlerTest, PreRequestHandler) {
  2272. auto route_path = "/user/:user";
  2273. Server svr;
  2274. svr.Get("/hi", [](const Request &, Response &res) {
  2275. res.set_content("hi", "text/plain");
  2276. });
  2277. svr.Get(route_path, [](const Request &req, Response &res) {
  2278. res.set_content(req.path_params.at("user"), "text/plain");
  2279. });
  2280. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2281. if (req.matched_route == route_path) {
  2282. auto user = req.path_params.at("user");
  2283. if (user != "john") {
  2284. res.status = StatusCode::Forbidden_403;
  2285. res.set_content("error", "text/html");
  2286. return Server::HandlerResponse::Handled;
  2287. }
  2288. }
  2289. return Server::HandlerResponse::Unhandled;
  2290. });
  2291. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. Client cli(HOST, PORT);
  2299. {
  2300. auto res = cli.Get("/hi");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::OK_200, res->status);
  2303. EXPECT_EQ("hi", res->body);
  2304. }
  2305. {
  2306. auto res = cli.Get("/user/john");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::OK_200, res->status);
  2309. EXPECT_EQ("john", res->body);
  2310. }
  2311. {
  2312. auto res = cli.Get("/user/invalid-user");
  2313. ASSERT_TRUE(res);
  2314. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2315. EXPECT_EQ("error", res->body);
  2316. }
  2317. }
  2318. TEST(InvalidFormatTest, StatusCode) {
  2319. Server svr;
  2320. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2321. res.set_content("Hello World!\n", "text/plain");
  2322. res.status = 9999; // Status should be a three-digit code...
  2323. });
  2324. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. thread.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. {
  2332. Client cli(HOST, PORT);
  2333. auto res = cli.Get("/hi");
  2334. ASSERT_FALSE(res);
  2335. }
  2336. }
  2337. TEST(URLFragmentTest, WithFragment) {
  2338. Server svr;
  2339. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2340. EXPECT_TRUE(req.target == "/hi");
  2341. });
  2342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2343. auto se = detail::scope_exit([&] {
  2344. svr.stop();
  2345. thread.join();
  2346. ASSERT_FALSE(svr.is_running());
  2347. });
  2348. svr.wait_until_ready();
  2349. {
  2350. Client cli(HOST, PORT);
  2351. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2352. EXPECT_TRUE(res);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. res = cli.Get("/hi%23key1=val1=key2=val2");
  2355. EXPECT_TRUE(res);
  2356. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2357. }
  2358. }
  2359. TEST(HeaderWriter, SetHeaderWriter) {
  2360. Server svr;
  2361. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2362. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2363. return detail::write_headers(strm, hdrs);
  2364. });
  2365. svr.Get("/hi", [](const Request &req, Response &res) {
  2366. auto it = req.headers.find("CustomClientHeader");
  2367. EXPECT_TRUE(it != req.headers.end());
  2368. EXPECT_EQ(it->second, "CustomClientValue");
  2369. res.set_content("Hello World!\n", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. {
  2379. Client cli(HOST, PORT);
  2380. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2381. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2382. return detail::write_headers(strm, hdrs);
  2383. });
  2384. auto res = cli.Get("/hi");
  2385. EXPECT_TRUE(res);
  2386. EXPECT_EQ(StatusCode::OK_200, res->status);
  2387. auto it = res->headers.find("CustomServerHeader");
  2388. EXPECT_TRUE(it != res->headers.end());
  2389. EXPECT_EQ(it->second, "CustomServerValue");
  2390. }
  2391. }
  2392. class ServerTest : public ::testing::Test {
  2393. protected:
  2394. ServerTest()
  2395. : cli_(HOST, PORT)
  2396. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2397. ,
  2398. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2399. #endif
  2400. {
  2401. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2402. cli_.enable_server_certificate_verification(false);
  2403. #endif
  2404. }
  2405. virtual void SetUp() {
  2406. svr_.set_mount_point("/", "./www");
  2407. svr_.set_mount_point("/mount", "./www2");
  2408. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2409. svr_.Get("/hi",
  2410. [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. })
  2413. .Get("/file_content",
  2414. [&](const Request & /*req*/, Response &res) {
  2415. res.set_file_content("./www/dir/test.html");
  2416. })
  2417. .Get("/file_content_with_content_type",
  2418. [&](const Request & /*req*/, Response &res) {
  2419. res.set_file_content("./www/file", "text/plain");
  2420. })
  2421. .Get("/invalid_file_content",
  2422. [&](const Request & /*req*/, Response &res) {
  2423. res.set_file_content("./www/dir/invalid_file_path");
  2424. })
  2425. .Get("/http_response_splitting",
  2426. [&](const Request & /*req*/, Response &res) {
  2427. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2428. EXPECT_EQ(0U, res.headers.size());
  2429. EXPECT_FALSE(res.has_header("a"));
  2430. res.set_header("a", "1\nSet-Cookie: a=1");
  2431. EXPECT_EQ(0U, res.headers.size());
  2432. EXPECT_FALSE(res.has_header("a"));
  2433. res.set_header("a", "1\rSet-Cookie: a=1");
  2434. EXPECT_EQ(0U, res.headers.size());
  2435. EXPECT_FALSE(res.has_header("a"));
  2436. res.set_header("a\r\nb", "0");
  2437. EXPECT_EQ(0U, res.headers.size());
  2438. EXPECT_FALSE(res.has_header("a"));
  2439. res.set_header("a\rb", "0");
  2440. EXPECT_EQ(0U, res.headers.size());
  2441. EXPECT_FALSE(res.has_header("a"));
  2442. res.set_header("a\nb", "0");
  2443. EXPECT_EQ(0U, res.headers.size());
  2444. EXPECT_FALSE(res.has_header("a"));
  2445. res.set_redirect("1\r\nSet-Cookie: a=1");
  2446. EXPECT_EQ(0U, res.headers.size());
  2447. EXPECT_FALSE(res.has_header("Location"));
  2448. })
  2449. .Get("/slow",
  2450. [&](const Request & /*req*/, Response &res) {
  2451. std::this_thread::sleep_for(std::chrono::seconds(2));
  2452. res.set_content("slow", "text/plain");
  2453. })
  2454. #if 0
  2455. .Post("/slowpost",
  2456. [&](const Request & /*req*/, Response &res) {
  2457. std::this_thread::sleep_for(std::chrono::seconds(2));
  2458. res.set_content("slow", "text/plain");
  2459. })
  2460. #endif
  2461. .Get("/remote_addr",
  2462. [&](const Request &req, Response &res) {
  2463. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2464. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2465. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2466. EXPECT_EQ(req.remote_port,
  2467. std::stoi(req.get_header_value("REMOTE_PORT")));
  2468. res.set_content(remote_addr.c_str(), "text/plain");
  2469. })
  2470. .Get("/local_addr",
  2471. [&](const Request &req, Response &res) {
  2472. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2473. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2474. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2475. auto local_port = req.get_header_value("LOCAL_PORT");
  2476. EXPECT_EQ(req.local_addr, local_addr);
  2477. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2478. res.set_content(local_addr.append(":").append(local_port),
  2479. "text/plain");
  2480. })
  2481. .Get("/endwith%",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_content("Hello World!", "text/plain");
  2484. })
  2485. .Get("/a\\+\\+b",
  2486. [&](const Request &req, Response &res) {
  2487. ASSERT_TRUE(req.has_param("a +b"));
  2488. auto val = req.get_param_value("a +b");
  2489. res.set_content(val, "text/plain");
  2490. })
  2491. .Get("/", [&](const Request & /*req*/,
  2492. Response &res) { res.set_redirect("/hi"); })
  2493. .Post("/1",
  2494. [](const Request & /*req*/, Response &res) {
  2495. res.set_redirect("/2", StatusCode::SeeOther_303);
  2496. })
  2497. .Get("/2",
  2498. [](const Request & /*req*/, Response &res) {
  2499. res.set_content("redirected.", "text/plain");
  2500. res.status = StatusCode::OK_200;
  2501. })
  2502. .Post("/person",
  2503. [&](const Request &req, Response &res) {
  2504. if (req.has_param("name") && req.has_param("note")) {
  2505. persons_[req.get_param_value("name")] =
  2506. req.get_param_value("note");
  2507. } else {
  2508. res.status = StatusCode::BadRequest_400;
  2509. }
  2510. })
  2511. .Put("/person",
  2512. [&](const Request &req, Response &res) {
  2513. if (req.has_param("name") && req.has_param("note")) {
  2514. persons_[req.get_param_value("name")] =
  2515. req.get_param_value("note");
  2516. } else {
  2517. res.status = StatusCode::BadRequest_400;
  2518. }
  2519. })
  2520. .Get("/person/(.*)",
  2521. [&](const Request &req, Response &res) {
  2522. string name = req.matches[1];
  2523. if (persons_.find(name) != persons_.end()) {
  2524. auto note = persons_[name];
  2525. res.set_content(note, "text/plain");
  2526. } else {
  2527. res.status = StatusCode::NotFound_404;
  2528. }
  2529. })
  2530. .Delete("/person",
  2531. [&](const Request &req, Response &res) {
  2532. if (req.has_param("name")) {
  2533. string name = req.get_param_value("name");
  2534. if (persons_.find(name) != persons_.end()) {
  2535. persons_.erase(name);
  2536. res.set_content("DELETED", "text/plain");
  2537. } else {
  2538. res.status = StatusCode::NotFound_404;
  2539. }
  2540. } else {
  2541. res.status = StatusCode::BadRequest_400;
  2542. }
  2543. })
  2544. .Post("/x-www-form-urlencoded-json",
  2545. [&](const Request &req, Response &res) {
  2546. auto json = req.get_param_value("json");
  2547. ASSERT_EQ(JSON_DATA, json);
  2548. res.set_content(json, "appliation/json");
  2549. res.status = StatusCode::OK_200;
  2550. })
  2551. .Get("/streamed-chunked",
  2552. [&](const Request & /*req*/, Response &res) {
  2553. res.set_chunked_content_provider(
  2554. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2555. sink.os << "123";
  2556. sink.os << "456";
  2557. sink.os << "789";
  2558. sink.done();
  2559. return true;
  2560. });
  2561. })
  2562. .Get("/streamed-chunked2",
  2563. [&](const Request & /*req*/, Response &res) {
  2564. auto i = new int(0);
  2565. res.set_chunked_content_provider(
  2566. "text/plain",
  2567. [i](size_t /*offset*/, DataSink &sink) {
  2568. switch (*i) {
  2569. case 0: sink.os << "123"; break;
  2570. case 1: sink.os << "456"; break;
  2571. case 2: sink.os << "789"; break;
  2572. case 3: sink.done(); break;
  2573. }
  2574. (*i)++;
  2575. return true;
  2576. },
  2577. [i](bool success) {
  2578. EXPECT_TRUE(success);
  2579. delete i;
  2580. });
  2581. })
  2582. .Get("/streamed-chunked-with-trailer",
  2583. [&](const Request & /*req*/, Response &res) {
  2584. auto i = new int(0);
  2585. res.set_header("Trailer", "Dummy1, Dummy2");
  2586. res.set_chunked_content_provider(
  2587. "text/plain",
  2588. [i](size_t /*offset*/, DataSink &sink) {
  2589. switch (*i) {
  2590. case 0: sink.os << "123"; break;
  2591. case 1: sink.os << "456"; break;
  2592. case 2: sink.os << "789"; break;
  2593. case 3: {
  2594. sink.done_with_trailer(
  2595. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2596. } break;
  2597. }
  2598. (*i)++;
  2599. return true;
  2600. },
  2601. [i](bool success) {
  2602. EXPECT_TRUE(success);
  2603. delete i;
  2604. });
  2605. })
  2606. .Get("/streamed",
  2607. [&](const Request & /*req*/, Response &res) {
  2608. res.set_content_provider(
  2609. 6, "text/plain",
  2610. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2611. sink.os << (offset < 3 ? "a" : "b");
  2612. return true;
  2613. });
  2614. })
  2615. .Get("/streamed-with-range",
  2616. [&](const Request &req, Response &res) {
  2617. auto data = new std::string("abcdefg");
  2618. res.set_content_provider(
  2619. data->size(), "text/plain",
  2620. [data](size_t offset, size_t length, DataSink &sink) {
  2621. size_t DATA_CHUNK_SIZE = 4;
  2622. const auto &d = *data;
  2623. auto out_len =
  2624. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2625. auto ret =
  2626. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2627. EXPECT_TRUE(ret);
  2628. return true;
  2629. },
  2630. [data, &req](bool success) {
  2631. EXPECT_EQ(success, !req.has_param("error"));
  2632. delete data;
  2633. });
  2634. })
  2635. .Get("/streamed-cancel",
  2636. [&](const Request & /*req*/, Response &res) {
  2637. res.set_content_provider(
  2638. size_t(-1), "text/plain",
  2639. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2640. sink.os << "data_chunk";
  2641. return true;
  2642. });
  2643. })
  2644. .Get("/regex-with-delimiter",
  2645. [&](const Request &req, Response & /*res*/) {
  2646. ASSERT_TRUE(req.has_param("key"));
  2647. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2648. })
  2649. .Get("/with-range",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. res.set_content("abcdefg", "text/plain");
  2652. })
  2653. .Get("/with-range-customized-response",
  2654. [&](const Request & /*req*/, Response &res) {
  2655. res.status = StatusCode::BadRequest_400;
  2656. res.set_content(JSON_DATA, "application/json");
  2657. })
  2658. .Post("/chunked",
  2659. [&](const Request &req, Response & /*res*/) {
  2660. EXPECT_EQ(req.body, "dechunked post body");
  2661. })
  2662. .Post("/large-chunked",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. std::string expected(6 * 30 * 1024u, 'a');
  2665. EXPECT_EQ(req.body, expected);
  2666. })
  2667. .Post("/multipart",
  2668. [&](const Request &req, Response & /*res*/) {
  2669. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2670. req.form.get_field_count("text2") +
  2671. req.form.get_field_count("file3") +
  2672. req.form.get_field_count("file4"));
  2673. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2674. req.form.get_file_count("file2"));
  2675. ASSERT_TRUE(!req.form.has_file("???"));
  2676. ASSERT_TRUE(!req.form.has_field("???"));
  2677. ASSERT_TRUE(req.body.empty());
  2678. {
  2679. const auto &text = req.form.get_field("text1");
  2680. EXPECT_EQ("text default", text);
  2681. }
  2682. {
  2683. const auto &text = req.form.get_field("text2");
  2684. EXPECT_EQ("aωb", text);
  2685. }
  2686. {
  2687. const auto &file = req.form.get_file("file1");
  2688. EXPECT_EQ("hello.txt", file.filename);
  2689. EXPECT_EQ("text/plain", file.content_type);
  2690. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2691. }
  2692. {
  2693. const auto &file = req.form.get_file("file2");
  2694. EXPECT_EQ("world.json", file.filename);
  2695. EXPECT_EQ("application/json", file.content_type);
  2696. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2697. }
  2698. {
  2699. const auto &text = req.form.get_field("file3");
  2700. EXPECT_EQ(0u, text.size());
  2701. }
  2702. {
  2703. const auto &text = req.form.get_field("file4");
  2704. EXPECT_EQ(0u, text.size());
  2705. }
  2706. })
  2707. .Post("/multipart/multi_file_values",
  2708. [&](const Request &req, Response & /*res*/) {
  2709. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2710. req.form.get_field_count("multi_text1"));
  2711. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2712. ASSERT_TRUE(!req.form.has_file("???"));
  2713. ASSERT_TRUE(!req.form.has_field("???"));
  2714. ASSERT_TRUE(req.body.empty());
  2715. {
  2716. const auto &text = req.form.get_field("text");
  2717. EXPECT_EQ("default text", text);
  2718. }
  2719. {
  2720. const auto &text1_values = req.form.get_fields("multi_text1");
  2721. EXPECT_EQ(2u, text1_values.size());
  2722. EXPECT_EQ("aaaaa", text1_values[0]);
  2723. EXPECT_EQ("bbbbb", text1_values[1]);
  2724. }
  2725. {
  2726. const auto &file1_values = req.form.get_files("multi_file1");
  2727. EXPECT_EQ(2u, file1_values.size());
  2728. auto file1 = file1_values[0];
  2729. EXPECT_EQ(file1.filename, "hello.txt");
  2730. EXPECT_EQ(file1.content_type, "text/plain");
  2731. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2732. auto file2 = file1_values[1];
  2733. EXPECT_EQ(file2.filename, "world.json");
  2734. EXPECT_EQ(file2.content_type, "application/json");
  2735. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2736. }
  2737. })
  2738. .Post("/empty",
  2739. [&](const Request &req, Response &res) {
  2740. EXPECT_EQ(req.body, "");
  2741. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2742. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2743. res.set_content("empty", "text/plain");
  2744. })
  2745. .Post("/empty-no-content-type",
  2746. [&](const Request &req, Response &res) {
  2747. EXPECT_EQ(req.body, "");
  2748. EXPECT_FALSE(req.has_header("Content-Type"));
  2749. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2750. res.set_content("empty-no-content-type", "text/plain");
  2751. })
  2752. .Post("/path-only",
  2753. [&](const Request &req, Response &res) {
  2754. EXPECT_EQ(req.body, "");
  2755. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2756. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2757. res.set_content("path-only", "text/plain");
  2758. })
  2759. .Post("/path-headers-only",
  2760. [&](const Request &req, Response &res) {
  2761. EXPECT_EQ(req.body, "");
  2762. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2763. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2764. EXPECT_EQ("world", req.get_header_value("hello"));
  2765. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2766. res.set_content("path-headers-only", "text/plain");
  2767. })
  2768. .Post("/post-large",
  2769. [&](const Request &req, Response &res) {
  2770. EXPECT_EQ(req.body, LARGE_DATA);
  2771. res.set_content(req.body, "text/plain");
  2772. })
  2773. .Put("/empty-no-content-type",
  2774. [&](const Request &req, Response &res) {
  2775. EXPECT_EQ(req.body, "");
  2776. EXPECT_FALSE(req.has_header("Content-Type"));
  2777. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2778. res.set_content("empty-no-content-type", "text/plain");
  2779. })
  2780. .Put("/put",
  2781. [&](const Request &req, Response &res) {
  2782. EXPECT_EQ(req.body, "PUT");
  2783. res.set_content(req.body, "text/plain");
  2784. })
  2785. .Put("/put-large",
  2786. [&](const Request &req, Response &res) {
  2787. EXPECT_EQ(req.body, LARGE_DATA);
  2788. res.set_content(req.body, "text/plain");
  2789. })
  2790. .Patch("/patch",
  2791. [&](const Request &req, Response &res) {
  2792. EXPECT_EQ(req.body, "PATCH");
  2793. res.set_content(req.body, "text/plain");
  2794. })
  2795. .Delete("/delete",
  2796. [&](const Request & /*req*/, Response &res) {
  2797. res.set_content("DELETE", "text/plain");
  2798. })
  2799. .Delete("/delete-body",
  2800. [&](const Request &req, Response &res) {
  2801. EXPECT_EQ(req.body, "content");
  2802. res.set_content(req.body, "text/plain");
  2803. })
  2804. .Options(R"(\*)",
  2805. [&](const Request & /*req*/, Response &res) {
  2806. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2807. })
  2808. .Get("/request-target",
  2809. [&](const Request &req, Response & /*res*/) {
  2810. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2811. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2812. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2813. })
  2814. .Get("/long-query-value",
  2815. [&](const Request &req, Response & /*res*/) {
  2816. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2817. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2818. })
  2819. .Get("/too-long-query-value",
  2820. [&](const Request &req, Response & /*res*/) {
  2821. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2822. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2823. })
  2824. .Get("/array-param",
  2825. [&](const Request &req, Response & /*res*/) {
  2826. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2827. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2828. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2829. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2830. })
  2831. .Post("/validate-no-multiple-headers",
  2832. [&](const Request &req, Response & /*res*/) {
  2833. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2834. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2835. })
  2836. .Post("/content_receiver",
  2837. [&](const Request &req, Response &res,
  2838. const ContentReader &content_reader) {
  2839. if (req.is_multipart_form_data()) {
  2840. std::vector<FormData> items;
  2841. content_reader(
  2842. [&](const FormData &file) {
  2843. items.push_back(file);
  2844. return true;
  2845. },
  2846. [&](const char *data, size_t data_length) {
  2847. items.back().content.append(data, data_length);
  2848. return true;
  2849. });
  2850. EXPECT_EQ(5u, items.size());
  2851. {
  2852. const auto &file = get_file_value(items, "text1");
  2853. EXPECT_TRUE(file.filename.empty());
  2854. EXPECT_EQ("text default", file.content);
  2855. }
  2856. {
  2857. const auto &file = get_file_value(items, "text2");
  2858. EXPECT_TRUE(file.filename.empty());
  2859. EXPECT_EQ("aωb", file.content);
  2860. }
  2861. {
  2862. const auto &file = get_file_value(items, "file1");
  2863. EXPECT_EQ("hello.txt", file.filename);
  2864. EXPECT_EQ("text/plain", file.content_type);
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2866. }
  2867. {
  2868. const auto &file = get_file_value(items, "file2");
  2869. EXPECT_EQ("world.json", file.filename);
  2870. EXPECT_EQ("application/json", file.content_type);
  2871. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2872. }
  2873. {
  2874. const auto &file = get_file_value(items, "file3");
  2875. EXPECT_TRUE(file.filename.empty());
  2876. EXPECT_EQ("application/octet-stream", file.content_type);
  2877. EXPECT_EQ(0u, file.content.size());
  2878. }
  2879. } else {
  2880. std::string body;
  2881. content_reader([&](const char *data, size_t data_length) {
  2882. EXPECT_EQ(7U, data_length);
  2883. body.append(data, data_length);
  2884. return true;
  2885. });
  2886. EXPECT_EQ(body, "content");
  2887. res.set_content(body, "text/plain");
  2888. }
  2889. })
  2890. .Put("/content_receiver",
  2891. [&](const Request & /*req*/, Response &res,
  2892. const ContentReader &content_reader) {
  2893. std::string body;
  2894. content_reader([&](const char *data, size_t data_length) {
  2895. body.append(data, data_length);
  2896. return true;
  2897. });
  2898. EXPECT_EQ(body, "content");
  2899. res.set_content(body, "text/plain");
  2900. })
  2901. .Patch("/content_receiver",
  2902. [&](const Request & /*req*/, Response &res,
  2903. const ContentReader &content_reader) {
  2904. std::string body;
  2905. content_reader([&](const char *data, size_t data_length) {
  2906. body.append(data, data_length);
  2907. return true;
  2908. });
  2909. EXPECT_EQ(body, "content");
  2910. res.set_content(body, "text/plain");
  2911. })
  2912. .Post("/query-string-and-body",
  2913. [&](const Request &req, Response & /*res*/) {
  2914. ASSERT_TRUE(req.has_param("key"));
  2915. EXPECT_EQ(req.get_param_value("key"), "value");
  2916. EXPECT_EQ(req.body, "content");
  2917. })
  2918. .Get("/last-request",
  2919. [&](const Request &req, Response & /*res*/) {
  2920. EXPECT_EQ("close", req.get_header_value("Connection"));
  2921. })
  2922. .Get(R"(/redirect/(\d+))",
  2923. [&](const Request &req, Response &res) {
  2924. auto num = std::stoi(req.matches[1]) + 1;
  2925. std::string url = "/redirect/" + std::to_string(num);
  2926. res.set_redirect(url);
  2927. })
  2928. .Post("/binary",
  2929. [&](const Request &req, Response &res) {
  2930. EXPECT_EQ(4U, req.body.size());
  2931. EXPECT_EQ("application/octet-stream",
  2932. req.get_header_value("Content-Type"));
  2933. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2934. res.set_content(req.body, "application/octet-stream");
  2935. })
  2936. .Put("/binary",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(4U, req.body.size());
  2939. EXPECT_EQ("application/octet-stream",
  2940. req.get_header_value("Content-Type"));
  2941. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2942. res.set_content(req.body, "application/octet-stream");
  2943. })
  2944. .Patch("/binary",
  2945. [&](const Request &req, Response &res) {
  2946. EXPECT_EQ(4U, req.body.size());
  2947. EXPECT_EQ("application/octet-stream",
  2948. req.get_header_value("Content-Type"));
  2949. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2950. res.set_content(req.body, "application/octet-stream");
  2951. })
  2952. .Delete("/binary",
  2953. [&](const Request &req, Response &res) {
  2954. EXPECT_EQ(4U, req.body.size());
  2955. EXPECT_EQ("application/octet-stream",
  2956. req.get_header_value("Content-Type"));
  2957. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2958. res.set_content(req.body, "application/octet-stream");
  2959. })
  2960. .Get("/issue1772",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.status = 401;
  2963. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2964. })
  2965. .Delete("/issue609",
  2966. [](const httplib::Request &, httplib::Response &res,
  2967. const httplib::ContentReader &) {
  2968. res.set_content("ok", "text/plain");
  2969. })
  2970. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2971. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2972. .Get("/compress",
  2973. [&](const Request & /*req*/, Response &res) {
  2974. res.set_content(
  2975. "12345678901234567890123456789012345678901234567890123456789"
  2976. "01234567890123456789012345678901234567890",
  2977. "text/plain");
  2978. })
  2979. .Get("/nocompress",
  2980. [&](const Request & /*req*/, Response &res) {
  2981. res.set_content(
  2982. "12345678901234567890123456789012345678901234567890123456789"
  2983. "01234567890123456789012345678901234567890",
  2984. "application/octet-stream");
  2985. })
  2986. .Post("/compress-multipart",
  2987. [&](const Request &req, Response & /*res*/) {
  2988. EXPECT_EQ(2u, req.form.fields.size());
  2989. ASSERT_TRUE(!req.form.has_field("???"));
  2990. {
  2991. const auto &text = req.form.get_field("key1");
  2992. EXPECT_EQ("test", text);
  2993. }
  2994. {
  2995. const auto &text = req.form.get_field("key2");
  2996. EXPECT_EQ("--abcdefg123", text);
  2997. }
  2998. })
  2999. #endif
  3000. ;
  3001. persons_["john"] = "programmer";
  3002. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3003. svr_.wait_until_ready();
  3004. }
  3005. virtual void TearDown() {
  3006. svr_.stop();
  3007. if (!request_threads_.empty()) {
  3008. std::this_thread::sleep_for(std::chrono::seconds(1));
  3009. for (auto &t : request_threads_) {
  3010. t.join();
  3011. }
  3012. }
  3013. t_.join();
  3014. }
  3015. map<string, string> persons_;
  3016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3017. SSLClient cli_;
  3018. SSLServer svr_;
  3019. #else
  3020. Client cli_;
  3021. Server svr_;
  3022. #endif
  3023. thread t_;
  3024. std::vector<thread> request_threads_;
  3025. };
  3026. TEST_F(ServerTest, GetMethod200) {
  3027. auto res = cli_.Get("/hi");
  3028. ASSERT_TRUE(res);
  3029. EXPECT_EQ("HTTP/1.1", res->version);
  3030. EXPECT_EQ(StatusCode::OK_200, res->status);
  3031. EXPECT_EQ("OK", res->reason);
  3032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3033. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3034. EXPECT_EQ("Hello World!", res->body);
  3035. }
  3036. void performance_test(const char *host) {
  3037. auto port = 1234;
  3038. Server svr;
  3039. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3040. res.set_content("Benchmark Response", "text/plain");
  3041. });
  3042. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3043. auto se = detail::scope_exit([&] {
  3044. svr.stop();
  3045. listen_thread.join();
  3046. ASSERT_FALSE(svr.is_running());
  3047. });
  3048. svr.wait_until_ready();
  3049. Client cli(host, port);
  3050. auto start = std::chrono::high_resolution_clock::now();
  3051. auto res = cli.Get("/benchmark");
  3052. ASSERT_TRUE(res);
  3053. EXPECT_EQ(StatusCode::OK_200, res->status);
  3054. auto end = std::chrono::high_resolution_clock::now();
  3055. auto elapsed =
  3056. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3057. .count();
  3058. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3059. << "ms (Issue #1777)";
  3060. }
  3061. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3062. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3063. TEST_F(ServerTest, GetEmptyFile) {
  3064. auto res = cli_.Get("/empty_file");
  3065. ASSERT_TRUE(res);
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3068. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3069. EXPECT_EQ("", res->body);
  3070. }
  3071. TEST_F(ServerTest, GetFileContent) {
  3072. auto res = cli_.Get("/file_content");
  3073. ASSERT_TRUE(res);
  3074. EXPECT_EQ(StatusCode::OK_200, res->status);
  3075. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3076. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3077. EXPECT_EQ("test.html", res->body);
  3078. }
  3079. TEST_F(ServerTest, GetFileContentWithRange) {
  3080. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3081. ASSERT_TRUE(res);
  3082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3083. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3084. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3085. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3086. EXPECT_EQ("est", res->body);
  3087. }
  3088. TEST_F(ServerTest, GetFileContentWithContentType) {
  3089. auto res = cli_.Get("/file_content_with_content_type");
  3090. ASSERT_TRUE(res);
  3091. EXPECT_EQ(StatusCode::OK_200, res->status);
  3092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3093. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3094. EXPECT_EQ("file\n", res->body);
  3095. }
  3096. TEST_F(ServerTest, GetInvalidFileContent) {
  3097. auto res = cli_.Get("/invalid_file_content");
  3098. ASSERT_TRUE(res);
  3099. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3100. }
  3101. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3102. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3103. ASSERT_TRUE(res);
  3104. EXPECT_EQ("HTTP/1.1", res->version);
  3105. EXPECT_EQ(StatusCode::OK_200, res->status);
  3106. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3107. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3108. EXPECT_EQ("Hello World!", res->body);
  3109. }
  3110. TEST_F(ServerTest, GetMethod302) {
  3111. auto res = cli_.Get("/");
  3112. ASSERT_TRUE(res);
  3113. EXPECT_EQ(StatusCode::Found_302, res->status);
  3114. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3115. }
  3116. TEST_F(ServerTest, GetMethod302Redirect) {
  3117. cli_.set_follow_location(true);
  3118. auto res = cli_.Get("/");
  3119. ASSERT_TRUE(res);
  3120. EXPECT_EQ(StatusCode::OK_200, res->status);
  3121. EXPECT_EQ("Hello World!", res->body);
  3122. EXPECT_EQ("/hi", res->location);
  3123. }
  3124. TEST_F(ServerTest, GetMethod404) {
  3125. auto res = cli_.Get("/invalid");
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3128. }
  3129. TEST_F(ServerTest, HeadMethod200) {
  3130. auto res = cli_.Head("/hi");
  3131. ASSERT_TRUE(res);
  3132. EXPECT_EQ(StatusCode::OK_200, res->status);
  3133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3134. EXPECT_TRUE(res->body.empty());
  3135. }
  3136. TEST_F(ServerTest, HeadMethod200Static) {
  3137. auto res = cli_.Head("/mount/dir/index.html");
  3138. ASSERT_TRUE(res);
  3139. EXPECT_EQ(StatusCode::OK_200, res->status);
  3140. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3141. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3142. EXPECT_TRUE(res->body.empty());
  3143. }
  3144. TEST_F(ServerTest, HeadMethod404) {
  3145. auto res = cli_.Head("/invalid");
  3146. ASSERT_TRUE(res);
  3147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3148. EXPECT_TRUE(res->body.empty());
  3149. }
  3150. TEST_F(ServerTest, GetMethodPersonJohn) {
  3151. auto res = cli_.Get("/person/john");
  3152. ASSERT_TRUE(res);
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3155. EXPECT_EQ("programmer", res->body);
  3156. }
  3157. TEST_F(ServerTest, PostMethod1) {
  3158. auto res = cli_.Get("/person/john1");
  3159. ASSERT_TRUE(res);
  3160. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3161. res = cli_.Post("/person", "name=john1&note=coder",
  3162. "application/x-www-form-urlencoded");
  3163. ASSERT_TRUE(res);
  3164. ASSERT_EQ(StatusCode::OK_200, res->status);
  3165. res = cli_.Get("/person/john1");
  3166. ASSERT_TRUE(res);
  3167. ASSERT_EQ(StatusCode::OK_200, res->status);
  3168. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3169. ASSERT_EQ("coder", res->body);
  3170. }
  3171. TEST_F(ServerTest, PostMethod2) {
  3172. auto res = cli_.Get("/person/john2");
  3173. ASSERT_TRUE(res);
  3174. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3175. Params params;
  3176. params.emplace("name", "john2");
  3177. params.emplace("note", "coder");
  3178. res = cli_.Post("/person", params);
  3179. ASSERT_TRUE(res);
  3180. ASSERT_EQ(StatusCode::OK_200, res->status);
  3181. res = cli_.Get("/person/john2");
  3182. ASSERT_TRUE(res);
  3183. ASSERT_EQ(StatusCode::OK_200, res->status);
  3184. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3185. ASSERT_EQ("coder", res->body);
  3186. }
  3187. TEST_F(ServerTest, PutMethod3) {
  3188. auto res = cli_.Get("/person/john3");
  3189. ASSERT_TRUE(res);
  3190. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3191. Params params;
  3192. params.emplace("name", "john3");
  3193. params.emplace("note", "coder");
  3194. res = cli_.Put("/person", params);
  3195. ASSERT_TRUE(res);
  3196. ASSERT_EQ(StatusCode::OK_200, res->status);
  3197. res = cli_.Get("/person/john3");
  3198. ASSERT_TRUE(res);
  3199. ASSERT_EQ(StatusCode::OK_200, res->status);
  3200. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3201. ASSERT_EQ("coder", res->body);
  3202. }
  3203. TEST_F(ServerTest, DeleteMethod1) {
  3204. auto res = cli_.Get("/person/john4");
  3205. ASSERT_TRUE(res);
  3206. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3207. Params params;
  3208. params.emplace("name", "john4");
  3209. params.emplace("note", "coder");
  3210. res = cli_.Post("/person", params);
  3211. ASSERT_TRUE(res);
  3212. ASSERT_EQ(StatusCode::OK_200, res->status);
  3213. res = cli_.Get("/person/john4");
  3214. ASSERT_TRUE(res);
  3215. ASSERT_EQ(StatusCode::OK_200, res->status);
  3216. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3217. ASSERT_EQ("coder", res->body);
  3218. Params delete_params;
  3219. delete_params.emplace("name", "john4");
  3220. res = cli_.Delete("/person", delete_params);
  3221. ASSERT_TRUE(res);
  3222. ASSERT_EQ(StatusCode::OK_200, res->status);
  3223. ASSERT_EQ("DELETED", res->body);
  3224. res = cli_.Get("/person/john4");
  3225. ASSERT_TRUE(res);
  3226. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3227. }
  3228. TEST_F(ServerTest, DeleteMethod2) {
  3229. auto res = cli_.Get("/person/john5");
  3230. ASSERT_TRUE(res);
  3231. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3232. Params params;
  3233. params.emplace("name", "john5");
  3234. params.emplace("note", "developer");
  3235. res = cli_.Post("/person", params);
  3236. ASSERT_TRUE(res);
  3237. ASSERT_EQ(StatusCode::OK_200, res->status);
  3238. res = cli_.Get("/person/john5");
  3239. ASSERT_TRUE(res);
  3240. ASSERT_EQ(StatusCode::OK_200, res->status);
  3241. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3242. ASSERT_EQ("developer", res->body);
  3243. Params delete_params;
  3244. delete_params.emplace("name", "john5");
  3245. Headers headers;
  3246. headers.emplace("Custom-Header", "test-value");
  3247. res = cli_.Delete("/person", headers, delete_params);
  3248. ASSERT_TRUE(res);
  3249. ASSERT_EQ(StatusCode::OK_200, res->status);
  3250. ASSERT_EQ("DELETED", res->body);
  3251. res = cli_.Get("/person/john5");
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, DeleteMethod3) {
  3256. auto res = cli_.Get("/person/john6");
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3259. Params params;
  3260. params.emplace("name", "john6");
  3261. params.emplace("note", "tester");
  3262. res = cli_.Post("/person", params);
  3263. ASSERT_TRUE(res);
  3264. ASSERT_EQ(StatusCode::OK_200, res->status);
  3265. res = cli_.Get("/person/john6");
  3266. ASSERT_TRUE(res);
  3267. ASSERT_EQ(StatusCode::OK_200, res->status);
  3268. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3269. ASSERT_EQ("tester", res->body);
  3270. Params delete_params;
  3271. delete_params.emplace("name", "john6");
  3272. Headers headers;
  3273. headers.emplace("Custom-Header", "test-value");
  3274. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3275. ASSERT_TRUE(res);
  3276. ASSERT_EQ(StatusCode::OK_200, res->status);
  3277. ASSERT_EQ("DELETED", res->body);
  3278. res = cli_.Get("/person/john6");
  3279. ASSERT_TRUE(res);
  3280. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3281. }
  3282. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3283. Params params;
  3284. params.emplace("json", JSON_DATA);
  3285. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3286. ASSERT_TRUE(res);
  3287. ASSERT_EQ(StatusCode::OK_200, res->status);
  3288. ASSERT_EQ(JSON_DATA, res->body);
  3289. }
  3290. TEST_F(ServerTest, PostEmptyContent) {
  3291. auto res = cli_.Post("/empty", "", "text/plain");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::OK_200, res->status);
  3294. ASSERT_EQ("empty", res->body);
  3295. }
  3296. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3297. auto res = cli_.Post("/empty-no-content-type");
  3298. ASSERT_TRUE(res);
  3299. ASSERT_EQ(StatusCode::OK_200, res->status);
  3300. ASSERT_EQ("empty-no-content-type", res->body);
  3301. }
  3302. TEST_F(ServerTest, PostPathOnly) {
  3303. auto res = cli_.Post("/path-only");
  3304. ASSERT_TRUE(res);
  3305. ASSERT_EQ(StatusCode::OK_200, res->status);
  3306. ASSERT_EQ("path-only", res->body);
  3307. }
  3308. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3309. auto res = cli_.Post("/path-headers-only",
  3310. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("path-headers-only", res->body);
  3314. }
  3315. TEST_F(ServerTest, PostLarge) {
  3316. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3317. ASSERT_TRUE(res);
  3318. ASSERT_EQ(StatusCode::OK_200, res->status);
  3319. EXPECT_EQ(LARGE_DATA, res->body);
  3320. }
  3321. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3322. auto res = cli_.Put("/empty-no-content-type");
  3323. ASSERT_TRUE(res);
  3324. ASSERT_EQ(StatusCode::OK_200, res->status);
  3325. ASSERT_EQ("empty-no-content-type", res->body);
  3326. }
  3327. TEST_F(ServerTest, GetMethodDir) {
  3328. auto res = cli_.Get("/dir/");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3332. auto body = R"(<html>
  3333. <head>
  3334. </head>
  3335. <body>
  3336. <a href="/dir/test.html">Test</a>
  3337. <a href="/hi">hi</a>
  3338. </body>
  3339. </html>
  3340. )";
  3341. EXPECT_EQ(body, res->body);
  3342. }
  3343. TEST_F(ServerTest, GetMethodDirTest) {
  3344. auto res = cli_.Get("/dir/test.html");
  3345. ASSERT_TRUE(res);
  3346. EXPECT_EQ(StatusCode::OK_200, res->status);
  3347. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3348. EXPECT_EQ("test.html", res->body);
  3349. }
  3350. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3351. auto res = cli_.Get("/dir/../dir/test.html");
  3352. ASSERT_TRUE(res);
  3353. EXPECT_EQ(StatusCode::OK_200, res->status);
  3354. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3355. EXPECT_EQ("test.html", res->body);
  3356. }
  3357. TEST_F(ServerTest, GetMethodInvalidPath) {
  3358. auto res = cli_.Get("/dir/../test.html");
  3359. ASSERT_TRUE(res);
  3360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3361. }
  3362. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3363. auto res = cli_.Get("/../www/dir/test.html");
  3364. ASSERT_TRUE(res);
  3365. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3366. }
  3367. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3368. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3369. ASSERT_TRUE(res);
  3370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3371. }
  3372. TEST_F(ServerTest, GetMethodDirMountTest) {
  3373. auto res = cli_.Get("/mount/dir/test.html");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3377. EXPECT_EQ("test.html", res->body);
  3378. }
  3379. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3380. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3381. ASSERT_TRUE(res);
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3384. EXPECT_EQ("test.html", res->body);
  3385. }
  3386. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3387. auto res = cli_.Get("/mount/dir/../test.html");
  3388. ASSERT_TRUE(res);
  3389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3390. }
  3391. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3392. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3395. }
  3396. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3397. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3398. ASSERT_TRUE(res);
  3399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3400. }
  3401. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3402. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3405. }
  3406. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3407. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3408. ASSERT_TRUE(res);
  3409. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, PostMethod303) {
  3412. auto res = cli_.Post("/1", "body", "text/plain");
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3415. EXPECT_EQ("/2", res->get_header_value("Location"));
  3416. }
  3417. TEST_F(ServerTest, PostMethod303Redirect) {
  3418. cli_.set_follow_location(true);
  3419. auto res = cli_.Post("/1", "body", "text/plain");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("redirected.", res->body);
  3423. EXPECT_EQ("/2", res->location);
  3424. }
  3425. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3426. auto res = cli_.Get("/dir/test.abcde");
  3427. ASSERT_TRUE(res);
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3430. EXPECT_EQ("abcde", res->body);
  3431. }
  3432. TEST_F(ServerTest, StaticFileRange) {
  3433. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3436. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3437. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3438. EXPECT_EQ(true, res->has_header("Content-Range"));
  3439. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3440. EXPECT_EQ(std::string("cd"), res->body);
  3441. }
  3442. TEST_F(ServerTest, StaticFileRanges) {
  3443. auto res =
  3444. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3445. ASSERT_TRUE(res);
  3446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3447. EXPECT_TRUE(
  3448. res->get_header_value("Content-Type")
  3449. .find(
  3450. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3451. 0);
  3452. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3453. }
  3454. TEST_F(ServerTest, StaticFileRangeHead) {
  3455. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3458. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3460. EXPECT_EQ(true, res->has_header("Content-Range"));
  3461. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3462. }
  3463. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3464. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3468. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3469. EXPECT_EQ(true, res->has_header("Content-Range"));
  3470. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3471. res->get_header_value("Content-Range"));
  3472. EXPECT_EQ("LAST\n", res->body);
  3473. }
  3474. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3475. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3478. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3479. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3480. EXPECT_EQ(true, res->has_header("Content-Range"));
  3481. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3482. }
  3483. TEST_F(ServerTest, StaticFileBigFile) {
  3484. auto res = cli_.Get("/dir/1MB.txt");
  3485. ASSERT_TRUE(res);
  3486. EXPECT_EQ(StatusCode::OK_200, res->status);
  3487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3488. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3489. }
  3490. TEST_F(ServerTest, InvalidBaseDirMount) {
  3491. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3492. }
  3493. TEST_F(ServerTest, Binary) {
  3494. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3495. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3496. "application/octet-stream");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::OK_200, res->status);
  3499. ASSERT_EQ(4U, res->body.size());
  3500. res = cli_.Put("/binary", binary.data(), binary.size(),
  3501. "application/octet-stream");
  3502. ASSERT_TRUE(res);
  3503. ASSERT_EQ(StatusCode::OK_200, res->status);
  3504. ASSERT_EQ(4U, res->body.size());
  3505. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3506. "application/octet-stream");
  3507. ASSERT_TRUE(res);
  3508. ASSERT_EQ(StatusCode::OK_200, res->status);
  3509. ASSERT_EQ(4U, res->body.size());
  3510. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3511. "application/octet-stream");
  3512. ASSERT_TRUE(res);
  3513. ASSERT_EQ(StatusCode::OK_200, res->status);
  3514. ASSERT_EQ(4U, res->body.size());
  3515. }
  3516. TEST_F(ServerTest, BinaryString) {
  3517. auto binary = std::string("\x00\x01\x02\x03", 4);
  3518. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3519. ASSERT_TRUE(res);
  3520. ASSERT_EQ(StatusCode::OK_200, res->status);
  3521. ASSERT_EQ(4U, res->body.size());
  3522. res = cli_.Put("/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_.Patch("/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_.Delete("/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. }
  3535. TEST_F(ServerTest, EmptyRequest) {
  3536. auto res = cli_.Get("");
  3537. ASSERT_TRUE(!res);
  3538. EXPECT_EQ(Error::Connection, res.error());
  3539. }
  3540. TEST_F(ServerTest, LongRequest) {
  3541. std::string request;
  3542. for (size_t i = 0; i < 545; i++) {
  3543. request += "/TooLongRequest";
  3544. }
  3545. request += "OK";
  3546. auto res = cli_.Get(request.c_str());
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, TooLongRequest) {
  3551. std::string request;
  3552. for (size_t i = 0; i < 546; i++) {
  3553. request += "/TooLongRequest";
  3554. }
  3555. request += "_NG";
  3556. auto res = cli_.Get(request.c_str());
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3559. }
  3560. TEST_F(ServerTest, AlmostTooLongRequest) {
  3561. // test for #2046 - URI length check shouldn't include other content on req
  3562. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3563. // leading /, space, HTTP/1.1)
  3564. std::string request =
  3565. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3566. auto res = cli_.Get(request.c_str());
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3569. }
  3570. TEST_F(ServerTest, LongHeader) {
  3571. Request req;
  3572. req.method = "GET";
  3573. req.path = "/hi";
  3574. std::string host_and_port;
  3575. host_and_port += HOST;
  3576. host_and_port += ":";
  3577. host_and_port += std::to_string(PORT);
  3578. req.headers.emplace("Host", host_and_port.c_str());
  3579. req.headers.emplace("Accept", "*/*");
  3580. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3581. req.headers.emplace(
  3582. "Header-Name",
  3583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3613. auto error = Error::Success;
  3614. auto ret = cli_.send(req, *res, error);
  3615. ASSERT_TRUE(ret);
  3616. EXPECT_EQ(StatusCode::OK_200, res->status);
  3617. }
  3618. TEST_F(ServerTest, LongQueryValue) {
  3619. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3622. }
  3623. TEST_F(ServerTest, TooLongQueryValue) {
  3624. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3625. ASSERT_FALSE(res);
  3626. EXPECT_EQ(Error::Read, res.error());
  3627. }
  3628. TEST_F(ServerTest, TooLongHeader) {
  3629. Request req;
  3630. req.method = "GET";
  3631. req.path = "/hi";
  3632. std::string host_and_port;
  3633. host_and_port += HOST;
  3634. host_and_port += ":";
  3635. host_and_port += std::to_string(PORT);
  3636. req.headers.emplace("Host", host_and_port.c_str());
  3637. req.headers.emplace("Accept", "*/*");
  3638. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3639. req.headers.emplace(
  3640. "Header-Name",
  3641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3671. auto error = Error::Success;
  3672. auto ret = cli_.send(req, *res, error);
  3673. ASSERT_TRUE(ret);
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. }
  3676. TEST_F(ServerTest, HeaderCountAtLimit) {
  3677. // Test with headers just under the 100 limit
  3678. httplib::Headers headers;
  3679. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3680. // This should keep us just under the 100 header limit
  3681. for (int i = 0; i < 95; i++) {
  3682. std::string name = "X-Test-Header-" + std::to_string(i);
  3683. std::string value = "value" + std::to_string(i);
  3684. headers.emplace(name, value);
  3685. }
  3686. // This should work fine as we're under the limit
  3687. auto res = cli_.Get("/hi", headers);
  3688. EXPECT_TRUE(res);
  3689. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3690. }
  3691. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3692. // Test with many headers to exceed the 100 limit
  3693. httplib::Headers headers;
  3694. // Add 150 headers to definitely exceed the 100 limit
  3695. for (int i = 0; i < 150; i++) {
  3696. std::string name = "X-Test-Header-" + std::to_string(i);
  3697. std::string value = "value" + std::to_string(i);
  3698. headers.emplace(name, value);
  3699. }
  3700. // This should fail due to exceeding header count limit
  3701. auto res = cli_.Get("/hi", headers);
  3702. // The request should either fail or return 400 Bad Request
  3703. if (res) {
  3704. // If we get a response, it should be 400 Bad Request
  3705. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3706. } else {
  3707. // Or the request should fail entirely
  3708. EXPECT_FALSE(res);
  3709. }
  3710. }
  3711. TEST_F(ServerTest, PercentEncoding) {
  3712. auto res = cli_.Get("/e%6edwith%");
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::OK_200, res->status);
  3715. }
  3716. TEST_F(ServerTest, PercentEncodingUnicode) {
  3717. auto res = cli_.Get("/e%u006edwith%");
  3718. ASSERT_TRUE(res);
  3719. EXPECT_EQ(StatusCode::OK_200, res->status);
  3720. }
  3721. TEST_F(ServerTest, InvalidPercentEncoding) {
  3722. auto res = cli_.Get("/%endwith%");
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3725. }
  3726. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3727. auto res = cli_.Get("/%uendwith%");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3730. }
  3731. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3732. auto res = cli_.Get("/hello?aaa=bbb%");
  3733. ASSERT_TRUE(res);
  3734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3735. }
  3736. TEST_F(ServerTest, PlusSignEncoding) {
  3737. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3738. ASSERT_TRUE(res);
  3739. EXPECT_EQ(StatusCode::OK_200, res->status);
  3740. EXPECT_EQ("a +b", res->body);
  3741. }
  3742. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3743. // This test simulates a potential DoS attack using many headers
  3744. // to verify our security fix prevents memory exhaustion
  3745. httplib::Headers attack_headers;
  3746. // Attempt to add many headers like an attacker would (200 headers to far
  3747. // exceed limit)
  3748. for (int i = 0; i < 200; i++) {
  3749. std::string name = "X-Attack-Header-" + std::to_string(i);
  3750. std::string value = "attack_payload_" + std::to_string(i);
  3751. attack_headers.emplace(name, value);
  3752. }
  3753. // Try to POST with excessive headers
  3754. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3755. // Should either fail or return 400 Bad Request due to security limit
  3756. if (res) {
  3757. // If we get a response, it should be 400 Bad Request
  3758. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3759. } else {
  3760. // Request failed, which is the expected behavior for DoS protection
  3761. EXPECT_FALSE(res);
  3762. }
  3763. }
  3764. TEST_F(ServerTest, MultipartFormData) {
  3765. UploadFormDataItems items = {
  3766. {"text1", "text default", "", ""},
  3767. {"text2", "aωb", "", ""},
  3768. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3769. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3770. {"file3", "", "", "application/octet-stream"},
  3771. {"file4", "", "", " application/json tmp-string "}};
  3772. auto res = cli_.Post("/multipart", items);
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::OK_200, res->status);
  3775. }
  3776. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3777. UploadFormDataItems items = {
  3778. {"text", "default text", "", ""},
  3779. {"multi_text1", "aaaaa", "", ""},
  3780. {"multi_text1", "bbbbb", "", ""},
  3781. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3782. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3783. "application/json"},
  3784. };
  3785. auto res = cli_.Post("/multipart/multi_file_values", items);
  3786. ASSERT_TRUE(res);
  3787. EXPECT_EQ(StatusCode::OK_200, res->status);
  3788. }
  3789. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3790. auto res = cli_.Get("/hi");
  3791. ASSERT_TRUE(res);
  3792. EXPECT_EQ(StatusCode::OK_200, res->status);
  3793. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3794. EXPECT_EQ("Hello World!", res->body);
  3795. }
  3796. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3797. Request req;
  3798. req.method = "POST";
  3799. req.path = "/chunked";
  3800. std::string host_and_port;
  3801. host_and_port += HOST;
  3802. host_and_port += ":";
  3803. host_and_port += std::to_string(PORT);
  3804. req.headers.emplace("Host", host_and_port.c_str());
  3805. req.headers.emplace("Accept", "*/*");
  3806. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3807. req.headers.emplace("Content-Type", "text/plain");
  3808. req.headers.emplace("Content-Length", "0");
  3809. req.headers.emplace(
  3810. "Transfer-Encoding",
  3811. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3812. // Client does not chunk, so make a chunked body manually.
  3813. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3814. auto res = std::make_shared<Response>();
  3815. auto error = Error::Success;
  3816. auto ret = cli_.send(req, *res, error);
  3817. ASSERT_TRUE(ret);
  3818. EXPECT_EQ(StatusCode::OK_200, res->status);
  3819. }
  3820. TEST_F(ServerTest, GetStreamed2) {
  3821. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3824. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3825. EXPECT_EQ(true, res->has_header("Content-Range"));
  3826. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3827. EXPECT_EQ(std::string("ab"), res->body);
  3828. }
  3829. TEST_F(ServerTest, GetStreamed) {
  3830. auto res = cli_.Get("/streamed");
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3834. EXPECT_EQ(std::string("aaabbb"), res->body);
  3835. }
  3836. TEST_F(ServerTest, GetStreamedWithRange1) {
  3837. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3838. ASSERT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3840. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3841. EXPECT_EQ(true, res->has_header("Content-Range"));
  3842. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3843. EXPECT_EQ(std::string("def"), res->body);
  3844. }
  3845. TEST_F(ServerTest, GetStreamedWithRange2) {
  3846. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3847. ASSERT_TRUE(res);
  3848. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3849. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3850. EXPECT_EQ(true, res->has_header("Content-Range"));
  3851. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3852. EXPECT_EQ(std::string("bcdefg"), res->body);
  3853. }
  3854. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3855. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3856. ASSERT_TRUE(res);
  3857. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3858. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3859. EXPECT_EQ(true, res->has_header("Content-Range"));
  3860. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3861. EXPECT_EQ(std::string("efg"), res->body);
  3862. }
  3863. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3864. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3865. ASSERT_TRUE(res);
  3866. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3867. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3868. EXPECT_EQ(false, res->has_header("Content-Range"));
  3869. EXPECT_EQ(0U, res->body.size());
  3870. }
  3871. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3872. auto res = cli_.Get("/streamed-with-range",
  3873. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3874. "92233720368547758079223372036854775807"}});
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3877. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3878. EXPECT_EQ(false, res->has_header("Content-Range"));
  3879. EXPECT_EQ(0U, res->body.size());
  3880. }
  3881. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3882. auto res = cli_.Get(
  3883. "/with-range",
  3884. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3885. {"Accept-Encoding", ""}});
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3888. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(true, res->has_header("Content-Range"));
  3890. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3891. EXPECT_EQ(std::string("abcdefg"), res->body);
  3892. }
  3893. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3894. auto res = cli_.Get("/with-range", {
  3895. {"Range", "bytes=0-"},
  3896. {"Accept-Encoding", ""},
  3897. });
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3900. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3901. EXPECT_EQ(true, res->has_header("Content-Range"));
  3902. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3903. EXPECT_EQ(std::string("abcdefg"), res->body);
  3904. }
  3905. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3906. auto res =
  3907. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3910. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3911. EXPECT_EQ(false, res->has_header("Content-Range"));
  3912. EXPECT_EQ(267U, res->body.size());
  3913. // Check that both range contents are present
  3914. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3915. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3916. // Check that Content-Range headers are present for both ranges
  3917. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3918. std::string::npos);
  3919. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3920. std::string::npos);
  3921. }
  3922. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3923. Ranges ranges;
  3924. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3925. ranges.emplace_back(0, -1);
  3926. }
  3927. auto res =
  3928. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3929. ASSERT_TRUE(res);
  3930. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3931. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(false, res->has_header("Content-Range"));
  3933. EXPECT_EQ(0U, res->body.size());
  3934. }
  3935. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3936. auto res =
  3937. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3938. ASSERT_TRUE(res);
  3939. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3940. EXPECT_EQ(5U, res->body.size());
  3941. // Check that overlapping ranges are coalesced into a single range
  3942. EXPECT_EQ("bcdef", res->body);
  3943. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3944. // Should be single range, not multipart
  3945. EXPECT_TRUE(res->has_header("Content-Range"));
  3946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3947. }
  3948. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3949. auto res =
  3950. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3953. EXPECT_EQ(268U, res->body.size());
  3954. // Check that both range contents are present
  3955. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3956. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3957. // Check that Content-Range headers are present for both ranges
  3958. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3959. std::string::npos);
  3960. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3961. std::string::npos);
  3962. }
  3963. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3964. auto res =
  3965. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3966. ASSERT_TRUE(res);
  3967. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3968. EXPECT_EQ(269U, res->body.size());
  3969. // Check that both duplicate range contents are present
  3970. size_t first_abc = res->body.find("abc\r\n");
  3971. EXPECT_TRUE(first_abc != std::string::npos);
  3972. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3973. EXPECT_TRUE(second_abc != std::string::npos);
  3974. // Check that Content-Range headers are present for both ranges
  3975. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3976. EXPECT_TRUE(first_range != std::string::npos);
  3977. size_t second_range =
  3978. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3979. EXPECT_TRUE(second_range != std::string::npos);
  3980. }
  3981. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3982. auto res = cli_.Get("/streamed-with-range?error",
  3983. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3986. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3987. EXPECT_EQ(false, res->has_header("Content-Range"));
  3988. EXPECT_EQ(0U, res->body.size());
  3989. }
  3990. TEST_F(ServerTest, GetStreamedEndless) {
  3991. uint64_t offset = 0;
  3992. auto res = cli_.Get("/streamed-cancel",
  3993. [&](const char * /*data*/, uint64_t data_length) {
  3994. if (offset < 100) {
  3995. offset += data_length;
  3996. return true;
  3997. }
  3998. return false;
  3999. });
  4000. ASSERT_TRUE(!res);
  4001. EXPECT_EQ(Error::Canceled, res.error());
  4002. }
  4003. TEST_F(ServerTest, ClientStop) {
  4004. std::atomic_size_t count{4};
  4005. std::vector<std::thread> threads;
  4006. for (auto i = count.load(); i != 0; --i) {
  4007. threads.emplace_back([&]() {
  4008. auto res = cli_.Get("/streamed-cancel",
  4009. [&](const char *, uint64_t) { return true; });
  4010. --count;
  4011. ASSERT_TRUE(!res);
  4012. EXPECT_TRUE(res.error() == Error::Canceled ||
  4013. res.error() == Error::Read || res.error() == Error::Write);
  4014. });
  4015. }
  4016. std::this_thread::sleep_for(std::chrono::seconds(2));
  4017. while (count != 0) {
  4018. cli_.stop();
  4019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4020. }
  4021. for (auto &t : threads) {
  4022. t.join();
  4023. }
  4024. }
  4025. TEST_F(ServerTest, GetWithRange1) {
  4026. auto res = cli_.Get("/with-range", {
  4027. make_range_header({{3, 5}}),
  4028. {"Accept-Encoding", ""},
  4029. });
  4030. ASSERT_TRUE(res);
  4031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4032. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4033. EXPECT_EQ(true, res->has_header("Content-Range"));
  4034. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4035. EXPECT_EQ(std::string("def"), res->body);
  4036. }
  4037. TEST_F(ServerTest, GetWithRange2) {
  4038. auto res = cli_.Get("/with-range", {
  4039. make_range_header({{1, -1}}),
  4040. {"Accept-Encoding", ""},
  4041. });
  4042. ASSERT_TRUE(res);
  4043. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4044. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4045. EXPECT_EQ(true, res->has_header("Content-Range"));
  4046. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4047. EXPECT_EQ(std::string("bcdefg"), res->body);
  4048. }
  4049. TEST_F(ServerTest, GetWithRange3) {
  4050. auto res = cli_.Get("/with-range", {
  4051. make_range_header({{0, 0}}),
  4052. {"Accept-Encoding", ""},
  4053. });
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4056. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4057. EXPECT_EQ(true, res->has_header("Content-Range"));
  4058. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4059. EXPECT_EQ(std::string("a"), res->body);
  4060. }
  4061. TEST_F(ServerTest, GetWithRange4) {
  4062. auto res = cli_.Get("/with-range", {
  4063. make_range_header({{-1, 2}}),
  4064. {"Accept-Encoding", ""},
  4065. });
  4066. ASSERT_TRUE(res);
  4067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4068. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4069. EXPECT_EQ(true, res->has_header("Content-Range"));
  4070. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4071. EXPECT_EQ(std::string("fg"), res->body);
  4072. }
  4073. TEST_F(ServerTest, GetWithRange5) {
  4074. auto res = cli_.Get("/with-range", {
  4075. make_range_header({{0, 5}}),
  4076. {"Accept-Encoding", ""},
  4077. });
  4078. ASSERT_TRUE(res);
  4079. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4080. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4081. EXPECT_EQ(true, res->has_header("Content-Range"));
  4082. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4083. EXPECT_EQ(std::string("abcdef"), res->body);
  4084. }
  4085. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4086. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4089. }
  4090. TEST_F(ServerTest, GetWithRangeMultipart) {
  4091. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4094. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4095. EXPECT_EQ(false, res->has_header("Content-Range"));
  4096. EXPECT_EQ(267U, res->body.size());
  4097. }
  4098. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4099. auto res =
  4100. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4101. ASSERT_TRUE(res);
  4102. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4103. }
  4104. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4105. auto res = cli_.Get("/with-range-customized-response",
  4106. {{make_range_header({{1, 2}})}});
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4109. EXPECT_EQ(true, res->has_header("Content-Length"));
  4110. EXPECT_EQ(false, res->has_header("Content-Range"));
  4111. EXPECT_EQ(JSON_DATA, res->body);
  4112. }
  4113. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4114. auto res = cli_.Get("/with-range-customized-response",
  4115. {{make_range_header({{1, 2}, {4, 5}})}});
  4116. ASSERT_TRUE(res);
  4117. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4118. EXPECT_EQ(true, res->has_header("Content-Length"));
  4119. EXPECT_EQ(false, res->has_header("Content-Range"));
  4120. EXPECT_EQ(JSON_DATA, res->body);
  4121. }
  4122. TEST_F(ServerTest, Issue1772) {
  4123. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4126. }
  4127. TEST_F(ServerTest, Issue609) {
  4128. auto res = cli_.Delete("/issue609");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ(std::string("ok"), res->body);
  4132. }
  4133. TEST_F(ServerTest, GetStreamedChunked) {
  4134. auto res = cli_.Get("/streamed-chunked");
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::OK_200, res->status);
  4137. EXPECT_EQ(std::string("123456789"), res->body);
  4138. }
  4139. TEST_F(ServerTest, GetStreamedChunked2) {
  4140. auto res = cli_.Get("/streamed-chunked2");
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::OK_200, res->status);
  4143. EXPECT_EQ(std::string("123456789"), res->body);
  4144. }
  4145. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4146. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. EXPECT_EQ(std::string("123456789"), res->body);
  4150. EXPECT_TRUE(res->has_header("Trailer"));
  4151. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4152. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4153. // Trailers are now stored separately from headers (security fix)
  4154. EXPECT_EQ(2U, res->trailers.size());
  4155. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4156. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4157. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4158. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4159. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4160. // Verify trailers are NOT in headers (security verification)
  4161. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4162. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4163. }
  4164. TEST_F(ServerTest, LargeChunkedPost) {
  4165. Request req;
  4166. req.method = "POST";
  4167. req.path = "/large-chunked";
  4168. std::string host_and_port;
  4169. host_and_port += HOST;
  4170. host_and_port += ":";
  4171. host_and_port += std::to_string(PORT);
  4172. req.headers.emplace("Host", host_and_port.c_str());
  4173. req.headers.emplace("Accept", "*/*");
  4174. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4175. req.headers.emplace("Content-Type", "text/plain");
  4176. req.headers.emplace("Content-Length", "0");
  4177. req.headers.emplace("Transfer-Encoding", "chunked");
  4178. std::string long_string(30 * 1024u, 'a');
  4179. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4180. // Attempt to make a large enough post to exceed OS buffers, to test that
  4181. // the server handles short reads if the full chunk data isn't available.
  4182. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4183. auto res = std::make_shared<Response>();
  4184. auto error = Error::Success;
  4185. auto ret = cli_.send(req, *res, error);
  4186. ASSERT_TRUE(ret);
  4187. EXPECT_EQ(StatusCode::OK_200, res->status);
  4188. }
  4189. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4190. auto res = cli_.Get("/remote_addr");
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::OK_200, res->status);
  4193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4194. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4195. }
  4196. TEST_F(ServerTest, GetMethodLocalAddr) {
  4197. auto res = cli_.Get("/local_addr");
  4198. ASSERT_TRUE(res);
  4199. EXPECT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4201. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4202. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4203. }
  4204. TEST_F(ServerTest, HTTPResponseSplitting) {
  4205. auto res = cli_.Get("/http_response_splitting");
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::OK_200, res->status);
  4208. }
  4209. TEST_F(ServerTest, SlowRequest) {
  4210. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4211. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4212. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4213. }
  4214. #if 0
  4215. TEST_F(ServerTest, SlowPost) {
  4216. char buffer[64 * 1024];
  4217. memset(buffer, 0x42, sizeof(buffer));
  4218. auto res = cli_.Post(
  4219. "/slowpost", 64 * 1024 * 1024,
  4220. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4221. auto ret = sink.write(buffer, sizeof(buffer));
  4222. EXPECT_TRUE(ret);
  4223. return true;
  4224. },
  4225. "text/plain");
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. }
  4229. TEST_F(ServerTest, SlowPostFail) {
  4230. char buffer[64 * 1024];
  4231. memset(buffer, 0x42, sizeof(buffer));
  4232. cli_.set_write_timeout(std::chrono::seconds(0));
  4233. auto res = cli_.Post(
  4234. "/slowpost", 64 * 1024 * 1024,
  4235. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4236. sink.write(buffer, sizeof(buffer));
  4237. return true;
  4238. },
  4239. "text/plain");
  4240. ASSERT_TRUE(!res);
  4241. EXPECT_EQ(Error::Write, res.error());
  4242. }
  4243. #endif
  4244. TEST_F(ServerTest, Put) {
  4245. auto res = cli_.Put("/put", "PUT", "text/plain");
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::OK_200, res->status);
  4248. EXPECT_EQ("PUT", res->body);
  4249. }
  4250. TEST_F(ServerTest, PutWithContentProvider) {
  4251. auto res = cli_.Put(
  4252. "/put", 3,
  4253. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4254. sink.os << "PUT";
  4255. return true;
  4256. },
  4257. "text/plain");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::OK_200, res->status);
  4260. EXPECT_EQ("PUT", res->body);
  4261. }
  4262. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4263. auto res = cli_.Post(
  4264. "/post", 42,
  4265. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4266. return false;
  4267. },
  4268. "text/plain");
  4269. ASSERT_TRUE(!res);
  4270. EXPECT_EQ(Error::Canceled, res.error());
  4271. }
  4272. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4273. auto res = cli_.Put(
  4274. "/put",
  4275. [](size_t /*offset*/, DataSink &sink) {
  4276. sink.os << "PUT";
  4277. sink.done();
  4278. return true;
  4279. },
  4280. "text/plain");
  4281. ASSERT_TRUE(res);
  4282. EXPECT_EQ(StatusCode::OK_200, res->status);
  4283. EXPECT_EQ("PUT", res->body);
  4284. }
  4285. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4286. auto res = cli_.Post(
  4287. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4288. "text/plain");
  4289. ASSERT_TRUE(!res);
  4290. EXPECT_EQ(Error::Canceled, res.error());
  4291. }
  4292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4293. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4294. cli_.set_compress(true);
  4295. auto res = cli_.Put(
  4296. "/put", 3,
  4297. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4298. sink.os << "PUT";
  4299. return true;
  4300. },
  4301. "text/plain");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("PUT", res->body);
  4305. }
  4306. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4307. cli_.set_compress(true);
  4308. auto res = cli_.Post(
  4309. "/post", 42,
  4310. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4311. return false;
  4312. },
  4313. "text/plain");
  4314. ASSERT_TRUE(!res);
  4315. EXPECT_EQ(Error::Canceled, res.error());
  4316. }
  4317. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4318. cli_.set_compress(true);
  4319. auto res = cli_.Put(
  4320. "/put",
  4321. [](size_t /*offset*/, DataSink &sink) {
  4322. sink.os << "PUT";
  4323. sink.done();
  4324. return true;
  4325. },
  4326. "text/plain");
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. EXPECT_EQ("PUT", res->body);
  4330. }
  4331. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4332. cli_.set_compress(true);
  4333. auto res = cli_.Post(
  4334. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4335. "text/plain");
  4336. ASSERT_TRUE(!res);
  4337. EXPECT_EQ(Error::Canceled, res.error());
  4338. }
  4339. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4340. cli_.set_compress(true);
  4341. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. EXPECT_EQ(LARGE_DATA, res->body);
  4345. }
  4346. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4348. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4349. Client cli(s.c_str());
  4350. cli.enable_server_certificate_verification(false);
  4351. #else
  4352. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4353. Client cli(s.c_str());
  4354. #endif
  4355. cli.set_compress(true);
  4356. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. EXPECT_EQ(LARGE_DATA, res->body);
  4360. // The compressed size should be less than a 10th of the original. May vary
  4361. // depending on the zlib library.
  4362. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4363. static_cast<uint64_t>(10 * 1024 * 1024));
  4364. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4365. }
  4366. TEST_F(ServerTest, PutContentWithDeflate) {
  4367. cli_.set_compress(false);
  4368. Headers headers;
  4369. headers.emplace("Content-Encoding", "deflate");
  4370. // PUT in deflate format:
  4371. auto res = cli_.Put("/put", headers,
  4372. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4373. ASSERT_TRUE(res);
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. EXPECT_EQ("PUT", res->body);
  4376. }
  4377. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4378. Headers headers;
  4379. headers.emplace("Accept-Encoding", "gzip, deflate");
  4380. auto res = cli_.Get("/streamed-chunked", headers);
  4381. ASSERT_TRUE(res);
  4382. EXPECT_EQ(StatusCode::OK_200, res->status);
  4383. EXPECT_EQ(std::string("123456789"), res->body);
  4384. }
  4385. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4386. Headers headers;
  4387. headers.emplace("Accept-Encoding", "gzip, deflate");
  4388. auto res = cli_.Get("/streamed-chunked2", headers);
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ(std::string("123456789"), res->body);
  4392. }
  4393. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4394. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. }
  4398. TEST(GzipDecompressor, ChunkedDecompression) {
  4399. std::string data;
  4400. for (size_t i = 0; i < 32 * 1024; ++i) {
  4401. data.push_back(static_cast<char>('a' + i % 26));
  4402. }
  4403. std::string compressed_data;
  4404. {
  4405. httplib::detail::gzip_compressor compressor;
  4406. bool result = compressor.compress(
  4407. data.data(), data.size(),
  4408. /*last=*/true,
  4409. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4410. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4411. compressed_data_size);
  4412. return true;
  4413. });
  4414. ASSERT_TRUE(result);
  4415. }
  4416. std::string decompressed_data;
  4417. {
  4418. httplib::detail::gzip_decompressor decompressor;
  4419. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4420. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4421. size_t chunk_size = 130;
  4422. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4423. chunk_begin += chunk_size) {
  4424. size_t current_chunk_size =
  4425. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4426. bool result = decompressor.decompress(
  4427. compressed_data.data() + chunk_begin, current_chunk_size,
  4428. [&](const char *decompressed_data_chunk,
  4429. size_t decompressed_data_chunk_size) {
  4430. decompressed_data.insert(decompressed_data.size(),
  4431. decompressed_data_chunk,
  4432. decompressed_data_chunk_size);
  4433. return true;
  4434. });
  4435. ASSERT_TRUE(result);
  4436. }
  4437. }
  4438. ASSERT_EQ(data, decompressed_data);
  4439. }
  4440. TEST(GzipDecompressor, DeflateDecompression) {
  4441. std::string original_text = "Raw deflate without gzip";
  4442. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4443. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4444. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4445. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4446. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4447. std::string decompressed_data;
  4448. {
  4449. httplib::detail::gzip_decompressor decompressor;
  4450. bool result = decompressor.decompress(
  4451. compressed_data.data(), compressed_data.size(),
  4452. [&](const char *decompressed_data_chunk,
  4453. size_t decompressed_data_chunk_size) {
  4454. decompressed_data.insert(decompressed_data.size(),
  4455. decompressed_data_chunk,
  4456. decompressed_data_chunk_size);
  4457. return true;
  4458. });
  4459. ASSERT_TRUE(result);
  4460. }
  4461. ASSERT_EQ(original_text, decompressed_data);
  4462. }
  4463. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4464. std::string original_text = "Raw deflate without gzip";
  4465. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4466. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4467. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4468. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4469. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4470. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4471. std::string decompressed_data;
  4472. {
  4473. httplib::detail::gzip_decompressor decompressor;
  4474. bool result = decompressor.decompress(
  4475. compressed_data.data(), compressed_data.size(),
  4476. [&](const char *decompressed_data_chunk,
  4477. size_t decompressed_data_chunk_size) {
  4478. decompressed_data.insert(decompressed_data.size(),
  4479. decompressed_data_chunk,
  4480. decompressed_data_chunk_size);
  4481. return true;
  4482. });
  4483. ASSERT_TRUE(result);
  4484. }
  4485. ASSERT_EQ(original_text, decompressed_data);
  4486. }
  4487. #ifdef _WIN32
  4488. TEST(GzipDecompressor, LargeRandomData) {
  4489. // prepare large random data that is difficult to be compressed and is
  4490. // expected to have large size even when compressed
  4491. std::random_device seed_gen;
  4492. std::mt19937 random(seed_gen());
  4493. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4494. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4495. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4496. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4497. // compress data over 4GiB
  4498. std::string compressed_data;
  4499. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4500. httplib::detail::gzip_compressor compressor;
  4501. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4502. data.size() * sizeof(std::uint32_t), true,
  4503. [&](const char *data, size_t size) {
  4504. compressed_data.insert(
  4505. compressed_data.size(), data, size);
  4506. return true;
  4507. });
  4508. ASSERT_TRUE(result);
  4509. // FIXME: compressed data size is expected to be greater than 4GiB,
  4510. // but there is no guarantee
  4511. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4512. // decompress data over 4GiB
  4513. std::string decompressed_data;
  4514. decompressed_data.reserve(data_size);
  4515. httplib::detail::gzip_decompressor decompressor;
  4516. result = decompressor.decompress(
  4517. compressed_data.data(), compressed_data.size(),
  4518. [&](const char *data, size_t size) {
  4519. decompressed_data.insert(decompressed_data.size(), data, size);
  4520. return true;
  4521. });
  4522. ASSERT_TRUE(result);
  4523. // compare
  4524. ASSERT_EQ(data_size, decompressed_data.size());
  4525. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4526. 0);
  4527. }
  4528. #endif
  4529. #endif
  4530. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4531. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4532. Headers headers;
  4533. headers.emplace("Accept-Encoding", "br");
  4534. auto res = cli_.Get("/streamed-chunked", headers);
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ(std::string("123456789"), res->body);
  4538. }
  4539. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4540. Headers headers;
  4541. headers.emplace("Accept-Encoding", "br");
  4542. auto res = cli_.Get("/streamed-chunked2", headers);
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::OK_200, res->status);
  4545. EXPECT_EQ(std::string("123456789"), res->body);
  4546. }
  4547. #endif
  4548. TEST_F(ServerTest, Patch) {
  4549. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4550. ASSERT_TRUE(res);
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("PATCH", res->body);
  4553. }
  4554. TEST_F(ServerTest, Delete) {
  4555. auto res = cli_.Delete("/delete");
  4556. ASSERT_TRUE(res);
  4557. EXPECT_EQ(StatusCode::OK_200, res->status);
  4558. EXPECT_EQ("DELETE", res->body);
  4559. }
  4560. TEST_F(ServerTest, DeleteContentReceiver) {
  4561. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. EXPECT_EQ("content", res->body);
  4565. }
  4566. TEST_F(ServerTest, Options) {
  4567. auto res = cli_.Options("*");
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4571. EXPECT_TRUE(res->body.empty());
  4572. }
  4573. TEST_F(ServerTest, URL) {
  4574. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. }
  4578. TEST_F(ServerTest, ArrayParam) {
  4579. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, NoMultipleHeaders) {
  4584. Headers headers = {{"Content-Length", "5"}};
  4585. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4586. "text/plain");
  4587. ASSERT_TRUE(res);
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. }
  4590. TEST_F(ServerTest, PostContentReceiver) {
  4591. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4592. ASSERT_TRUE(res);
  4593. ASSERT_EQ(StatusCode::OK_200, res->status);
  4594. ASSERT_EQ("content", res->body);
  4595. }
  4596. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4597. UploadFormDataItems items = {
  4598. {"text1", "text default", "", ""},
  4599. {"text2", "aωb", "", ""},
  4600. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4601. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4602. {"file3", "", "", "application/octet-stream"},
  4603. };
  4604. auto res = cli_.Post("/content_receiver", items);
  4605. ASSERT_TRUE(res);
  4606. EXPECT_EQ(StatusCode::OK_200, res->status);
  4607. }
  4608. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4609. UploadFormDataItems items = {
  4610. {"text1", "text default", "", ""},
  4611. {"text2", "aωb", "", ""},
  4612. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4613. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4614. {"file3", "", "", "application/octet-stream"},
  4615. };
  4616. auto boundary = std::string("+++++");
  4617. std::string body;
  4618. for (const auto &item : items) {
  4619. body += "--" + boundary + "\r\n";
  4620. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4621. if (!item.filename.empty()) {
  4622. body += "; filename=\"" + item.filename + "\"";
  4623. }
  4624. body += "\r\n";
  4625. if (!item.content_type.empty()) {
  4626. body += "Content-Type: " + item.content_type + "\r\n";
  4627. }
  4628. body += "\r\n";
  4629. body += item.content + "\r\n";
  4630. }
  4631. body += "--" + boundary + "--\r\n";
  4632. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4633. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::OK_200, res->status);
  4636. }
  4637. TEST_F(ServerTest, PostContentReceiverGzip) {
  4638. cli_.set_compress(true);
  4639. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4640. ASSERT_TRUE(res);
  4641. ASSERT_EQ(StatusCode::OK_200, res->status);
  4642. ASSERT_EQ("content", res->body);
  4643. }
  4644. TEST_F(ServerTest, PutContentReceiver) {
  4645. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4646. ASSERT_TRUE(res);
  4647. ASSERT_EQ(StatusCode::OK_200, res->status);
  4648. ASSERT_EQ("content", res->body);
  4649. }
  4650. TEST_F(ServerTest, PatchContentReceiver) {
  4651. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4652. ASSERT_TRUE(res);
  4653. ASSERT_EQ(StatusCode::OK_200, res->status);
  4654. ASSERT_EQ("content", res->body);
  4655. }
  4656. template <typename ClientType>
  4657. void TestWithHeadersAndContentReceiver(
  4658. ClientType &cli,
  4659. std::function<Result(ClientType &, const std::string &, const Headers &,
  4660. const std::string &, const std::string &,
  4661. ContentReceiver, DownloadProgress)>
  4662. request_func) {
  4663. Headers headers;
  4664. headers.emplace("X-Custom-Header", "test-value");
  4665. std::string received_body;
  4666. auto res = request_func(
  4667. cli, "/content_receiver", headers, "content", "application/json",
  4668. [&](const char *data, size_t data_length) {
  4669. received_body.append(data, data_length);
  4670. return true;
  4671. },
  4672. nullptr);
  4673. ASSERT_TRUE(res);
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. EXPECT_EQ("content", received_body);
  4676. }
  4677. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4679. using ClientT = SSLClient;
  4680. #else
  4681. using ClientT = Client;
  4682. #endif
  4683. TestWithHeadersAndContentReceiver<ClientT>(
  4684. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4685. const std::string &body, const std::string &content_type,
  4686. ContentReceiver receiver, DownloadProgress progress) {
  4687. return cli.Post(path, headers, body, content_type, receiver, progress);
  4688. });
  4689. }
  4690. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4691. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4692. using ClientT = SSLClient;
  4693. #else
  4694. using ClientT = Client;
  4695. #endif
  4696. TestWithHeadersAndContentReceiver<ClientT>(
  4697. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4698. const std::string &body, const std::string &content_type,
  4699. ContentReceiver receiver, DownloadProgress progress) {
  4700. return cli.Put(path, headers, body, content_type, receiver, progress);
  4701. });
  4702. }
  4703. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4705. using ClientT = SSLClient;
  4706. #else
  4707. using ClientT = Client;
  4708. #endif
  4709. TestWithHeadersAndContentReceiver<ClientT>(
  4710. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4711. const std::string &body, const std::string &content_type,
  4712. ContentReceiver receiver, DownloadProgress progress) {
  4713. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4714. });
  4715. }
  4716. template <typename ClientType>
  4717. void TestWithHeadersAndContentReceiverWithProgress(
  4718. ClientType &cli,
  4719. std::function<Result(ClientType &, const std::string &, const Headers &,
  4720. const std::string &, const std::string &,
  4721. ContentReceiver, DownloadProgress)>
  4722. request_func) {
  4723. Headers headers;
  4724. headers.emplace("X-Test-Header", "progress-test");
  4725. std::string received_body;
  4726. auto progress_called = false;
  4727. auto res = request_func(
  4728. cli, "/content_receiver", headers, "content", "text/plain",
  4729. [&](const char *data, size_t data_length) {
  4730. received_body.append(data, data_length);
  4731. return true;
  4732. },
  4733. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4734. progress_called = true;
  4735. return true;
  4736. });
  4737. ASSERT_TRUE(res);
  4738. EXPECT_EQ(StatusCode::OK_200, res->status);
  4739. EXPECT_EQ("content", received_body);
  4740. EXPECT_TRUE(progress_called);
  4741. }
  4742. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4744. using ClientT = SSLClient;
  4745. #else
  4746. using ClientT = Client;
  4747. #endif
  4748. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4749. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4750. const std::string &body, const std::string &content_type,
  4751. ContentReceiver receiver, DownloadProgress progress) {
  4752. return cli.Post(path, headers, body, content_type, receiver, progress);
  4753. });
  4754. }
  4755. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4757. using ClientT = SSLClient;
  4758. #else
  4759. using ClientT = Client;
  4760. #endif
  4761. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4762. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4763. const std::string &body, const std::string &content_type,
  4764. ContentReceiver receiver, DownloadProgress progress) {
  4765. return cli.Put(path, headers, body, content_type, receiver, progress);
  4766. });
  4767. }
  4768. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4770. using ClientT = SSLClient;
  4771. #else
  4772. using ClientT = Client;
  4773. #endif
  4774. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4775. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4776. const std::string &body, const std::string &content_type,
  4777. ContentReceiver receiver, DownloadProgress progress) {
  4778. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4779. });
  4780. }
  4781. template <typename ClientType>
  4782. void TestWithHeadersAndContentReceiverError(
  4783. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4784. const Headers &, const std::string &,
  4785. const std::string &, ContentReceiver)>
  4786. request_func) {
  4787. Headers headers;
  4788. headers.emplace("X-Error-Test", "true");
  4789. std::string received_body;
  4790. auto receiver_failed = false;
  4791. auto res =
  4792. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4793. [&](const char *data, size_t data_length) {
  4794. received_body.append(data, data_length);
  4795. receiver_failed = true;
  4796. return false;
  4797. });
  4798. ASSERT_FALSE(res);
  4799. EXPECT_TRUE(receiver_failed);
  4800. }
  4801. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4803. using ClientT = SSLClient;
  4804. #else
  4805. using ClientT = Client;
  4806. #endif
  4807. TestWithHeadersAndContentReceiverError<ClientT>(
  4808. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4809. const std::string &body, const std::string &content_type,
  4810. ContentReceiver receiver) {
  4811. return cli.Post(path, headers, body, content_type, receiver);
  4812. });
  4813. }
  4814. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4816. using ClientT = SSLClient;
  4817. #else
  4818. using ClientT = Client;
  4819. #endif
  4820. TestWithHeadersAndContentReceiverError<ClientT>(
  4821. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4822. const std::string &body, const std::string &content_type,
  4823. ContentReceiver receiver) {
  4824. return cli.Put(path, headers, body, content_type, receiver);
  4825. });
  4826. }
  4827. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4828. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4829. using ClientT = SSLClient;
  4830. #else
  4831. using ClientT = Client;
  4832. #endif
  4833. TestWithHeadersAndContentReceiverError<ClientT>(
  4834. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4835. const std::string &body, const std::string &content_type,
  4836. ContentReceiver receiver) {
  4837. return cli.Patch(path, headers, body, content_type, receiver);
  4838. });
  4839. }
  4840. TEST_F(ServerTest, PostQueryStringAndBody) {
  4841. auto res =
  4842. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4843. ASSERT_TRUE(res);
  4844. ASSERT_EQ(StatusCode::OK_200, res->status);
  4845. }
  4846. TEST_F(ServerTest, HTTP2Magic) {
  4847. Request req;
  4848. req.method = "PRI";
  4849. req.path = "*";
  4850. req.body = "SM";
  4851. auto res = std::make_shared<Response>();
  4852. auto error = Error::Success;
  4853. auto ret = cli_.send(req, *res, error);
  4854. ASSERT_TRUE(ret);
  4855. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4856. }
  4857. TEST_F(ServerTest, KeepAlive) {
  4858. auto res = cli_.Get("/hi");
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::OK_200, res->status);
  4861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4862. EXPECT_EQ("Hello World!", res->body);
  4863. res = cli_.Get("/hi");
  4864. ASSERT_TRUE(res);
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4867. EXPECT_EQ("Hello World!", res->body);
  4868. res = cli_.Get("/hi");
  4869. ASSERT_TRUE(res);
  4870. EXPECT_EQ(StatusCode::OK_200, res->status);
  4871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4872. EXPECT_EQ("Hello World!", res->body);
  4873. res = cli_.Get("/not-exist");
  4874. ASSERT_TRUE(res);
  4875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4876. res = cli_.Post("/empty", "", "text/plain");
  4877. ASSERT_TRUE(res);
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4880. EXPECT_EQ("empty", res->body);
  4881. EXPECT_EQ("close", res->get_header_value("Connection"));
  4882. res = cli_.Post(
  4883. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4884. "text/plain");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("empty", res->body);
  4889. cli_.set_keep_alive(false);
  4890. res = cli_.Get("/last-request");
  4891. ASSERT_TRUE(res);
  4892. EXPECT_EQ(StatusCode::OK_200, res->status);
  4893. EXPECT_EQ("close", res->get_header_value("Connection"));
  4894. }
  4895. TEST_F(ServerTest, TooManyRedirect) {
  4896. cli_.set_follow_location(true);
  4897. auto res = cli_.Get("/redirect/0");
  4898. ASSERT_TRUE(!res);
  4899. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4900. }
  4901. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4902. TEST_F(ServerTest, Gzip) {
  4903. Headers headers;
  4904. headers.emplace("Accept-Encoding", "gzip, deflate");
  4905. auto res = cli_.Get("/compress", headers);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4911. "7890123456789012345678901234567890",
  4912. res->body);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. }
  4915. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4916. Headers headers;
  4917. headers.emplace("Accept-Encoding", "");
  4918. auto res = cli_.Get("/compress", headers);
  4919. ASSERT_TRUE(res);
  4920. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4922. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4923. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4924. "7890123456789012345678901234567890",
  4925. res->body);
  4926. EXPECT_EQ(StatusCode::OK_200, res->status);
  4927. }
  4928. TEST_F(ServerTest, GzipWithContentReceiver) {
  4929. Headers headers;
  4930. headers.emplace("Accept-Encoding", "gzip, deflate");
  4931. std::string body;
  4932. auto res = cli_.Get("/compress", headers,
  4933. [&](const char *data, uint64_t data_length) {
  4934. EXPECT_EQ(100U, data_length);
  4935. body.append(data, data_length);
  4936. return true;
  4937. });
  4938. ASSERT_TRUE(res);
  4939. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4941. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4942. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4943. "7890123456789012345678901234567890",
  4944. body);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. }
  4947. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4948. Headers headers;
  4949. headers.emplace("Accept-Encoding", "gzip, deflate");
  4950. cli_.set_decompress(false);
  4951. auto res = cli_.Get("/compress", headers);
  4952. ASSERT_TRUE(res);
  4953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4955. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4956. EXPECT_EQ(33U, res->body.size());
  4957. EXPECT_EQ(StatusCode::OK_200, res->status);
  4958. }
  4959. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4960. Headers headers;
  4961. headers.emplace("Accept-Encoding", "");
  4962. std::string body;
  4963. auto res = cli_.Get("/compress", headers,
  4964. [&](const char *data, uint64_t data_length) {
  4965. EXPECT_EQ(100U, data_length);
  4966. body.append(data, data_length);
  4967. return true;
  4968. });
  4969. ASSERT_TRUE(res);
  4970. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4972. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4973. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4974. "7890123456789012345678901234567890",
  4975. body);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. }
  4978. TEST_F(ServerTest, NoGzip) {
  4979. Headers headers;
  4980. headers.emplace("Accept-Encoding", "gzip, deflate");
  4981. auto res = cli_.Get("/nocompress", headers);
  4982. ASSERT_TRUE(res);
  4983. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4984. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4985. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4986. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4987. "7890123456789012345678901234567890",
  4988. res->body);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. }
  4991. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4992. Headers headers;
  4993. headers.emplace("Accept-Encoding", "gzip, deflate");
  4994. std::string body;
  4995. auto res = cli_.Get("/nocompress", headers,
  4996. [&](const char *data, uint64_t data_length) {
  4997. EXPECT_EQ(100U, data_length);
  4998. body.append(data, data_length);
  4999. return true;
  5000. });
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5003. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5004. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5005. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5006. "7890123456789012345678901234567890",
  5007. body);
  5008. EXPECT_EQ(StatusCode::OK_200, res->status);
  5009. }
  5010. TEST_F(ServerTest, MultipartFormDataGzip) {
  5011. UploadFormDataItems items = {
  5012. {"key1", "test", "", ""},
  5013. {"key2", "--abcdefg123", "", ""},
  5014. };
  5015. cli_.set_compress(true);
  5016. auto res = cli_.Post("/compress-multipart", items);
  5017. ASSERT_TRUE(res);
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. }
  5020. #endif
  5021. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5022. TEST_F(ServerTest, Brotli) {
  5023. Headers headers;
  5024. headers.emplace("Accept-Encoding", "br");
  5025. auto res = cli_.Get("/compress", headers);
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5029. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5030. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5031. "7890123456789012345678901234567890",
  5032. res->body);
  5033. EXPECT_EQ(StatusCode::OK_200, res->status);
  5034. }
  5035. #endif
  5036. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5037. TEST_F(ServerTest, Zstd) {
  5038. Headers headers;
  5039. headers.emplace("Accept-Encoding", "zstd");
  5040. auto res = cli_.Get("/compress", headers);
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5043. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5044. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5045. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5046. "7890123456789012345678901234567890",
  5047. res->body);
  5048. EXPECT_EQ(StatusCode::OK_200, res->status);
  5049. }
  5050. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5051. Headers headers;
  5052. headers.emplace("Accept-Encoding", "");
  5053. auto res = cli_.Get("/compress", headers);
  5054. ASSERT_TRUE(res);
  5055. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5056. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5057. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5058. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5059. "7890123456789012345678901234567890",
  5060. res->body);
  5061. EXPECT_EQ(StatusCode::OK_200, res->status);
  5062. }
  5063. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5064. Headers headers;
  5065. headers.emplace("Accept-Encoding", "zstd");
  5066. std::string body;
  5067. auto res = cli_.Get("/compress", headers,
  5068. [&](const char *data, uint64_t data_length) {
  5069. EXPECT_EQ(100U, data_length);
  5070. body.append(data, data_length);
  5071. return true;
  5072. });
  5073. ASSERT_TRUE(res);
  5074. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5076. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5077. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5078. "7890123456789012345678901234567890",
  5079. body);
  5080. EXPECT_EQ(StatusCode::OK_200, res->status);
  5081. }
  5082. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5083. Headers headers;
  5084. headers.emplace("Accept-Encoding", "zstd");
  5085. cli_.set_decompress(false);
  5086. auto res = cli_.Get("/compress", headers);
  5087. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5088. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5089. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5090. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5091. ASSERT_TRUE(res);
  5092. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5094. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5095. EXPECT_EQ(StatusCode::OK_200, res->status);
  5096. ASSERT_EQ(26U, res->body.size());
  5097. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5098. 0);
  5099. }
  5100. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5101. Headers headers;
  5102. headers.emplace("Accept-Encoding", "");
  5103. std::string body;
  5104. auto res = cli_.Get("/compress", headers,
  5105. [&](const char *data, uint64_t data_length) {
  5106. EXPECT_EQ(100U, data_length);
  5107. body.append(data, data_length);
  5108. return true;
  5109. });
  5110. ASSERT_TRUE(res);
  5111. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5114. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5115. "7890123456789012345678901234567890",
  5116. body);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST_F(ServerTest, NoZstd) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "zstd");
  5122. auto res = cli_.Get("/nocompress", headers);
  5123. ASSERT_TRUE(res);
  5124. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5125. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5127. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5128. "7890123456789012345678901234567890",
  5129. res->body);
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. }
  5132. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5133. Headers headers;
  5134. headers.emplace("Accept-Encoding", "zstd");
  5135. std::string body;
  5136. auto res = cli_.Get("/nocompress", headers,
  5137. [&](const char *data, uint64_t data_length) {
  5138. EXPECT_EQ(100U, data_length);
  5139. body.append(data, data_length);
  5140. return true;
  5141. });
  5142. ASSERT_TRUE(res);
  5143. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5144. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5145. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5146. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5147. "7890123456789012345678901234567890",
  5148. body);
  5149. EXPECT_EQ(StatusCode::OK_200, res->status);
  5150. }
  5151. // TODO: How to enable zstd ??
  5152. TEST_F(ServerTest, MultipartFormDataZstd) {
  5153. UploadFormDataItems items = {
  5154. {"key1", "test", "", ""},
  5155. {"key2", "--abcdefg123", "", ""},
  5156. };
  5157. Headers headers;
  5158. headers.emplace("Accept-Encoding", "zstd");
  5159. cli_.set_compress(true);
  5160. auto res = cli_.Post("/compress-multipart", headers, items);
  5161. ASSERT_TRUE(res);
  5162. EXPECT_EQ(StatusCode::OK_200, res->status);
  5163. }
  5164. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5165. Headers headers;
  5166. headers.emplace("Accept-Encoding", "zstd");
  5167. cli_.set_compress(true);
  5168. auto res = cli_.Put(
  5169. "/put", headers, 3,
  5170. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5171. sink.os << "PUT";
  5172. return true;
  5173. },
  5174. "text/plain");
  5175. ASSERT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. EXPECT_EQ("PUT", res->body);
  5178. }
  5179. // Pre-compression logging tests
  5180. TEST_F(ServerTest, PreCompressionLogging) {
  5181. // Test data for compression (matches the actual /compress endpoint content)
  5182. const std::string test_content =
  5183. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5184. "3456789012345678901234567890";
  5185. // Variables to capture logging data
  5186. std::string pre_compression_body;
  5187. std::string pre_compression_content_type;
  5188. std::string pre_compression_content_encoding;
  5189. std::string post_compression_body;
  5190. std::string post_compression_content_type;
  5191. std::string post_compression_content_encoding;
  5192. // Set up pre-compression logger
  5193. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5194. const Response &res) {
  5195. pre_compression_body = res.body;
  5196. pre_compression_content_type = res.get_header_value("Content-Type");
  5197. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5198. });
  5199. // Set up post-compression logger
  5200. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5201. post_compression_body = res.body;
  5202. post_compression_content_type = res.get_header_value("Content-Type");
  5203. post_compression_content_encoding =
  5204. res.get_header_value("Content-Encoding");
  5205. });
  5206. // Test with gzip compression
  5207. Headers headers;
  5208. headers.emplace("Accept-Encoding", "gzip");
  5209. auto res = cli_.Get("/compress", headers);
  5210. // Verify response was compressed
  5211. ASSERT_TRUE(res);
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5214. // Verify pre-compression logger captured uncompressed content
  5215. EXPECT_EQ(test_content, pre_compression_body);
  5216. EXPECT_EQ("text/plain", pre_compression_content_type);
  5217. EXPECT_TRUE(pre_compression_content_encoding
  5218. .empty()); // No encoding header before compression
  5219. // Verify post-compression logger captured compressed content
  5220. EXPECT_NE(test_content,
  5221. post_compression_body); // Should be different after compression
  5222. EXPECT_EQ("text/plain", post_compression_content_type);
  5223. EXPECT_EQ("gzip", post_compression_content_encoding);
  5224. // Verify compressed content is smaller
  5225. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5226. }
  5227. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5228. const std::string test_content =
  5229. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5230. "3456789012345678901234567890";
  5231. std::string pre_compression_body;
  5232. std::string post_compression_body;
  5233. svr_.set_pre_compression_logger(
  5234. [&](const Request & /*req*/, const Response &res) {
  5235. pre_compression_body = res.body;
  5236. });
  5237. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5238. post_compression_body = res.body;
  5239. });
  5240. Headers headers;
  5241. headers.emplace("Accept-Encoding", "br");
  5242. auto res = cli_.Get("/compress", headers);
  5243. ASSERT_TRUE(res);
  5244. EXPECT_EQ(StatusCode::OK_200, res->status);
  5245. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5246. // Verify pre-compression content is uncompressed
  5247. EXPECT_EQ(test_content, pre_compression_body);
  5248. // Verify post-compression content is compressed
  5249. EXPECT_NE(test_content, post_compression_body);
  5250. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5251. }
  5252. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5253. const std::string test_content =
  5254. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5255. "3456789012345678901234567890";
  5256. std::string pre_compression_body;
  5257. std::string post_compression_body;
  5258. svr_.set_pre_compression_logger(
  5259. [&](const Request & /*req*/, const Response &res) {
  5260. pre_compression_body = res.body;
  5261. });
  5262. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5263. post_compression_body = res.body;
  5264. });
  5265. // Request without compression (use /nocompress endpoint)
  5266. Headers headers;
  5267. auto res = cli_.Get("/nocompress", headers);
  5268. ASSERT_TRUE(res);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5271. // Pre-compression logger should not be called when no compression is applied
  5272. EXPECT_TRUE(
  5273. pre_compression_body.empty()); // Pre-compression logger not called
  5274. EXPECT_EQ(
  5275. test_content,
  5276. post_compression_body); // Post-compression logger captures final content
  5277. }
  5278. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5279. const std::string test_content =
  5280. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5281. "3456789012345678901234567890";
  5282. std::string pre_compression_body;
  5283. bool pre_logger_called = false;
  5284. // Set only pre-compression logger
  5285. svr_.set_pre_compression_logger(
  5286. [&](const Request & /*req*/, const Response &res) {
  5287. pre_compression_body = res.body;
  5288. pre_logger_called = true;
  5289. });
  5290. Headers headers;
  5291. headers.emplace("Accept-Encoding", "gzip");
  5292. auto res = cli_.Get("/compress", headers);
  5293. ASSERT_TRUE(res);
  5294. EXPECT_EQ(StatusCode::OK_200, res->status);
  5295. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5296. // Verify pre-compression logger was called
  5297. EXPECT_TRUE(pre_logger_called);
  5298. EXPECT_EQ(test_content, pre_compression_body);
  5299. }
  5300. TEST(ZstdDecompressor, ChunkedDecompression) {
  5301. std::string data;
  5302. for (size_t i = 0; i < 32 * 1024; ++i) {
  5303. data.push_back(static_cast<char>('a' + i % 26));
  5304. }
  5305. std::string compressed_data;
  5306. {
  5307. httplib::detail::zstd_compressor compressor;
  5308. bool result = compressor.compress(
  5309. data.data(), data.size(),
  5310. /*last=*/true,
  5311. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5312. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5313. compressed_data_size);
  5314. return true;
  5315. });
  5316. ASSERT_TRUE(result);
  5317. }
  5318. std::string decompressed_data;
  5319. {
  5320. httplib::detail::zstd_decompressor decompressor;
  5321. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5322. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5323. size_t chunk_size = 130;
  5324. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5325. chunk_begin += chunk_size) {
  5326. size_t current_chunk_size =
  5327. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5328. bool result = decompressor.decompress(
  5329. compressed_data.data() + chunk_begin, current_chunk_size,
  5330. [&](const char *decompressed_data_chunk,
  5331. size_t decompressed_data_chunk_size) {
  5332. decompressed_data.insert(decompressed_data.size(),
  5333. decompressed_data_chunk,
  5334. decompressed_data_chunk_size);
  5335. return true;
  5336. });
  5337. ASSERT_TRUE(result);
  5338. }
  5339. }
  5340. ASSERT_EQ(data, decompressed_data);
  5341. }
  5342. TEST(ZstdDecompressor, Decompress) {
  5343. std::string original_text = "Compressed with ZSTD";
  5344. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5345. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5346. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5347. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5348. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5349. std::string decompressed_data;
  5350. {
  5351. httplib::detail::zstd_decompressor decompressor;
  5352. bool result = decompressor.decompress(
  5353. compressed_data.data(), compressed_data.size(),
  5354. [&](const char *decompressed_data_chunk,
  5355. size_t decompressed_data_chunk_size) {
  5356. decompressed_data.insert(decompressed_data.size(),
  5357. decompressed_data_chunk,
  5358. decompressed_data_chunk_size);
  5359. return true;
  5360. });
  5361. ASSERT_TRUE(result);
  5362. }
  5363. ASSERT_EQ(original_text, decompressed_data);
  5364. }
  5365. #endif
  5366. // Sends a raw request to a server listening at HOST:PORT.
  5367. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5368. std::string *resp = nullptr) {
  5369. auto error = Error::Success;
  5370. auto client_sock = detail::create_client_socket(
  5371. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5372. /*connection_timeout_sec=*/5, 0,
  5373. /*read_timeout_sec=*/5, 0,
  5374. /*write_timeout_sec=*/5, 0, std::string(), error);
  5375. if (client_sock == INVALID_SOCKET) { return false; }
  5376. auto ret = detail::process_client_socket(
  5377. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5378. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5379. if (req.size() !=
  5380. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5381. return false;
  5382. }
  5383. char buf[512];
  5384. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5385. while (line_reader.getline()) {
  5386. if (resp) { *resp += line_reader.ptr(); }
  5387. }
  5388. return true;
  5389. });
  5390. detail::close_socket(client_sock);
  5391. return ret;
  5392. }
  5393. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5394. Server svr;
  5395. std::string header_value;
  5396. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5397. header_value = req.get_header_value("foo");
  5398. res.set_content("ok", "text/plain");
  5399. });
  5400. thread t = thread([&] { svr.listen(HOST, PORT); });
  5401. auto se = detail::scope_exit([&] {
  5402. svr.stop();
  5403. t.join();
  5404. ASSERT_FALSE(svr.is_running());
  5405. });
  5406. svr.wait_until_ready();
  5407. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5408. // like characters are not treated the same - use vertical tab and escape.
  5409. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5410. "foo: \t \v bar \x1B\t \r\n"
  5411. "Connection: close\r\n"
  5412. "\r\n";
  5413. std::string res;
  5414. ASSERT_TRUE(send_request(5, req, &res));
  5415. EXPECT_EQ(header_value, "");
  5416. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5417. }
  5418. // Sends a raw request and verifies that there isn't a crash or exception.
  5419. static void test_raw_request(const std::string &req,
  5420. std::string *out = nullptr) {
  5421. Server svr;
  5422. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5423. res.set_content("ok", "text/plain");
  5424. });
  5425. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5426. res.set_content("ok", "text/plain");
  5427. });
  5428. svr.Get("/header_field_value_check",
  5429. [&](const Request & /*req*/, Response &res) {
  5430. res.set_content("ok", "text/plain");
  5431. });
  5432. // Server read timeout must be longer than the client read timeout for the
  5433. // bug to reproduce, probably to force the server to process a request
  5434. // without a trailing blank line.
  5435. const time_t client_read_timeout_sec = 1;
  5436. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5437. bool listen_thread_ok = false;
  5438. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5439. auto se = detail::scope_exit([&] {
  5440. svr.stop();
  5441. t.join();
  5442. ASSERT_FALSE(svr.is_running());
  5443. EXPECT_TRUE(listen_thread_ok);
  5444. });
  5445. svr.wait_until_ready();
  5446. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5447. }
  5448. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5449. // A certain header line causes an exception if the header property is parsed
  5450. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5451. test_raw_request(
  5452. "GET /hi HTTP/1.1\r\n"
  5453. " : "
  5454. " "
  5455. " ");
  5456. }
  5457. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5458. // A certain header line causes an exception if the header property *name* is
  5459. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5460. // greedy matcher and requires backtracking when there are a lot of ":"
  5461. // characters.
  5462. // This occurs with libc++ but not libstdc++.
  5463. test_raw_request(
  5464. "GET /hi HTTP/1.1\r\n"
  5465. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5466. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5467. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5468. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5469. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5470. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5471. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5472. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5473. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5474. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5475. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5476. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5477. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5478. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5479. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5480. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5481. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5482. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5483. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5484. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5485. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5486. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5487. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5488. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5489. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5490. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5491. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5492. "&&&%%%");
  5493. }
  5494. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5495. // Make sure this doesn't crash the server.
  5496. // In a previous version of the header line regex, the "\r" rendered the line
  5497. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5498. // a new position where the leading white space ended and the field value
  5499. // began.
  5500. // The crash occurs with libc++ but not libstdc++.
  5501. test_raw_request("GET /hi HTTP/1.1\r\n"
  5502. "a:" +
  5503. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5504. "\r\n"
  5505. "\r\n");
  5506. }
  5507. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5508. std::string out;
  5509. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5510. "Content-Type: text/plain\r\n"
  5511. "Transfer-Encoding: chunked\r\n"
  5512. "\r\n"
  5513. "nothex\r\n",
  5514. &out);
  5515. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5516. }
  5517. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5518. std::string out;
  5519. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5520. "Content-Type: text/plain\r\n"
  5521. "Transfer-Encoding: chunked\r\n"
  5522. "\r\n"
  5523. "3\r\n"
  5524. "xyz\r\n"
  5525. "NaN\r\n",
  5526. &out);
  5527. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5528. }
  5529. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5530. std::string out;
  5531. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5532. "Content-Type: text/plain\r\n"
  5533. "Transfer-Encoding: chunked\r\n"
  5534. "\r\n"
  5535. // Length is too large for 64 bits.
  5536. "1ffffffffffffffff\r\n"
  5537. "xyz\r\n",
  5538. &out);
  5539. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5540. }
  5541. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5542. test_raw_request("GET /hi HTTP/1.1\r\n"
  5543. "Content-Type: text/plain\r\n\r");
  5544. }
  5545. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5546. std::string out;
  5547. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5548. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5549. }
  5550. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5551. std::string out;
  5552. std::string request(
  5553. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5554. test_raw_request(request, &out);
  5555. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5556. }
  5557. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5558. std::string out;
  5559. std::string request(
  5560. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5561. test_raw_request(request, &out);
  5562. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5563. }
  5564. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5565. std::string out;
  5566. std::string request(
  5567. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5568. test_raw_request(request, &out);
  5569. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5570. }
  5571. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5572. std::string out;
  5573. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5574. "Test: \r\n\r\n",
  5575. &out);
  5576. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5577. }
  5578. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5579. Server svr;
  5580. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5581. res.set_header("Cache-Control", "no-cache");
  5582. res.set_chunked_content_provider(
  5583. "text/event-stream", [](size_t offset, DataSink &sink) {
  5584. std::string s = "data:";
  5585. s += std::to_string(offset);
  5586. s += "\n\n";
  5587. auto ret = sink.write(s.data(), s.size());
  5588. EXPECT_TRUE(ret);
  5589. std::this_thread::sleep_for(std::chrono::seconds(1));
  5590. return true;
  5591. });
  5592. });
  5593. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5594. svr.wait_until_ready();
  5595. Client client(HOST, PORT);
  5596. const Headers headers = {{"Accept", "text/event-stream"}};
  5597. auto get_thread = std::thread([&client, &headers]() {
  5598. auto res = client.Get(
  5599. "/events", headers,
  5600. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5601. });
  5602. auto se = detail::scope_exit([&] {
  5603. svr.stop();
  5604. get_thread.join();
  5605. listen_thread.join();
  5606. ASSERT_FALSE(svr.is_running());
  5607. });
  5608. // Give GET time to get a few messages.
  5609. std::this_thread::sleep_for(std::chrono::seconds(2));
  5610. }
  5611. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5612. httplib::Server svr;
  5613. svr.Post("/hi",
  5614. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5615. res.status = StatusCode::OK_200;
  5616. });
  5617. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5618. svr.wait_until_ready();
  5619. Client cli(HOST, PORT);
  5620. auto res = cli.Post("/hi", "data", "text/plain");
  5621. ASSERT_TRUE(res);
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. svr.stop();
  5624. thread.join();
  5625. ASSERT_FALSE(svr.is_running());
  5626. res = cli.Post("/hi", "data", "text/plain");
  5627. ASSERT_FALSE(res);
  5628. }
  5629. TEST(ServerStopTest, ListenFailure) {
  5630. Server svr;
  5631. auto t = thread([&]() {
  5632. auto ret = svr.listen("????", PORT);
  5633. EXPECT_FALSE(ret);
  5634. });
  5635. svr.wait_until_ready();
  5636. svr.stop();
  5637. t.join();
  5638. }
  5639. TEST(ServerStopTest, Decommision) {
  5640. Server svr;
  5641. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5642. for (int i = 0; i < 4; i++) {
  5643. auto is_even = !(i % 2);
  5644. std::thread t{[&] {
  5645. try {
  5646. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5647. if (is_even) {
  5648. throw std::runtime_error("Some thing that happens to go wrong.");
  5649. }
  5650. svr.listen(HOST, PORT);
  5651. } catch (...) { svr.decommission(); }
  5652. }};
  5653. svr.wait_until_ready();
  5654. // Server is up
  5655. {
  5656. Client cli(HOST, PORT);
  5657. auto res = cli.Get("/hi");
  5658. if (is_even) {
  5659. EXPECT_FALSE(res);
  5660. } else {
  5661. EXPECT_TRUE(res);
  5662. EXPECT_EQ("hi...", res->body);
  5663. }
  5664. }
  5665. svr.stop();
  5666. t.join();
  5667. // Server is down...
  5668. {
  5669. Client cli(HOST, PORT);
  5670. auto res = cli.Get("/hi");
  5671. EXPECT_FALSE(res);
  5672. }
  5673. }
  5674. }
  5675. // Helper function for string body upload progress tests
  5676. template <typename SetupHandler, typename ClientCall>
  5677. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5678. ClientCall &&client_call,
  5679. const string &body) {
  5680. Server svr;
  5681. setup_handler(svr);
  5682. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5683. auto se = detail::scope_exit([&] {
  5684. svr.stop();
  5685. t.join();
  5686. });
  5687. svr.wait_until_ready();
  5688. Client cli(HOST, PORT);
  5689. vector<uint64_t> progress_values;
  5690. bool progress_called = false;
  5691. auto res =
  5692. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5693. progress_values.push_back(current);
  5694. progress_called = true;
  5695. return true;
  5696. });
  5697. ASSERT_TRUE(res);
  5698. EXPECT_EQ(200, res->status);
  5699. EXPECT_TRUE(progress_called);
  5700. }
  5701. TEST(UploadProgressTest, PostStringBodyBasic) {
  5702. TestStringBodyUploadProgress(
  5703. [](Server &svr) {
  5704. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5705. res.set_content("received", "text/plain");
  5706. });
  5707. },
  5708. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5709. return cli.Post("/test", body, "text/plain", progress_callback);
  5710. },
  5711. "test data for upload progress");
  5712. }
  5713. TEST(UploadProgressTest, PutStringBodyBasic) {
  5714. TestStringBodyUploadProgress(
  5715. [](Server &svr) {
  5716. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5717. res.set_content("put received", "text/plain");
  5718. });
  5719. },
  5720. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5721. return cli.Put("/test", body, "text/plain", progress_callback);
  5722. },
  5723. "put test data for upload progress");
  5724. }
  5725. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5726. TestStringBodyUploadProgress(
  5727. [](Server &svr) {
  5728. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5729. res.set_content("patch received", "text/plain");
  5730. });
  5731. },
  5732. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5733. return cli.Patch("/test", body, "text/plain", progress_callback);
  5734. },
  5735. "patch test data for upload progress");
  5736. }
  5737. // Helper function for content provider upload progress tests
  5738. template <typename SetupHandler, typename ClientCall>
  5739. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5740. ClientCall &&client_call) {
  5741. Server svr;
  5742. setup_handler(svr);
  5743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5744. auto se = detail::scope_exit([&] {
  5745. svr.stop();
  5746. t.join();
  5747. });
  5748. svr.wait_until_ready();
  5749. Client cli(HOST, PORT);
  5750. vector<uint64_t> progress_values;
  5751. auto res =
  5752. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5753. progress_values.push_back(current);
  5754. return true;
  5755. });
  5756. ASSERT_TRUE(res);
  5757. EXPECT_EQ(200, res->status);
  5758. EXPECT_FALSE(progress_values.empty());
  5759. }
  5760. TEST(UploadProgressTest, PostContentProviderProgress) {
  5761. TestContentProviderUploadProgress(
  5762. [](Server &svr) {
  5763. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5764. res.set_content("provider received", "text/plain");
  5765. });
  5766. },
  5767. [](Client &cli, UploadProgress progress_callback) {
  5768. return cli.Post(
  5769. "/test", 10,
  5770. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5771. sink.os << "test data";
  5772. return true;
  5773. },
  5774. "text/plain", progress_callback);
  5775. });
  5776. }
  5777. // Helper function for multipart upload progress tests
  5778. template <typename SetupHandler, typename ClientCall>
  5779. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5780. ClientCall &&client_call,
  5781. const string &endpoint) {
  5782. Server svr;
  5783. setup_handler(svr);
  5784. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5785. auto se = detail::scope_exit([&] {
  5786. svr.stop();
  5787. t.join();
  5788. });
  5789. svr.wait_until_ready();
  5790. Client cli(HOST, PORT);
  5791. vector<uint64_t> progress_values;
  5792. UploadFormDataItems items = {
  5793. {"field1", "value1", "", ""},
  5794. {"field2", "longer value for progress tracking test", "", ""},
  5795. {"file1", "file content data for upload progress", "test.txt",
  5796. "text/plain"}};
  5797. auto res = client_call(cli, endpoint, items,
  5798. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5799. progress_values.push_back(current);
  5800. return true;
  5801. });
  5802. ASSERT_TRUE(res);
  5803. EXPECT_EQ(200, res->status);
  5804. EXPECT_FALSE(progress_values.empty());
  5805. }
  5806. TEST(UploadProgressTest, PostMultipartProgress) {
  5807. TestMultipartUploadProgress(
  5808. [](Server &svr) {
  5809. svr.Post("/multipart", [](const Request &req, Response &res) {
  5810. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5811. res.set_content("multipart received", "text/plain");
  5812. });
  5813. },
  5814. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5815. UploadProgress progress_callback) {
  5816. return cli.Post(endpoint, items, progress_callback);
  5817. },
  5818. "/multipart");
  5819. }
  5820. // Helper function for basic download progress tests
  5821. template <typename SetupHandler, typename ClientCall>
  5822. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5823. ClientCall &&client_call, const string &endpoint,
  5824. size_t expected_content_size) {
  5825. Server svr;
  5826. setup_handler(svr);
  5827. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5828. auto se = detail::scope_exit([&] {
  5829. svr.stop();
  5830. t.join();
  5831. });
  5832. svr.wait_until_ready();
  5833. Client cli(HOST, PORT);
  5834. vector<uint64_t> progress_values;
  5835. auto res = client_call(cli, endpoint,
  5836. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5837. progress_values.push_back(current);
  5838. return true;
  5839. });
  5840. ASSERT_TRUE(res);
  5841. EXPECT_EQ(200, res->status);
  5842. EXPECT_FALSE(progress_values.empty());
  5843. EXPECT_EQ(expected_content_size, res->body.size());
  5844. }
  5845. TEST(DownloadProgressTest, GetBasic) {
  5846. TestBasicDownloadProgress(
  5847. [](Server &svr) {
  5848. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5849. string content(1000, 'D');
  5850. res.set_content(content, "text/plain");
  5851. });
  5852. },
  5853. [](Client &cli, const string &endpoint,
  5854. DownloadProgress progress_callback) {
  5855. return cli.Get(endpoint, progress_callback);
  5856. },
  5857. "/download", 1000u);
  5858. }
  5859. // Helper function for content receiver download progress tests
  5860. template <typename SetupHandler, typename ClientCall>
  5861. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5862. ClientCall &&client_call,
  5863. const string &endpoint,
  5864. size_t expected_content_size) {
  5865. Server svr;
  5866. setup_handler(svr);
  5867. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5868. auto se = detail::scope_exit([&] {
  5869. svr.stop();
  5870. t.join();
  5871. });
  5872. svr.wait_until_ready();
  5873. Client cli(HOST, PORT);
  5874. vector<uint64_t> progress_values;
  5875. string received_body;
  5876. auto res = client_call(
  5877. cli, endpoint,
  5878. [&](const char *data, size_t data_length) -> bool {
  5879. received_body.append(data, data_length);
  5880. return true;
  5881. },
  5882. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5883. progress_values.push_back(current);
  5884. return true;
  5885. });
  5886. ASSERT_TRUE(res);
  5887. EXPECT_EQ(200, res->status);
  5888. EXPECT_FALSE(progress_values.empty());
  5889. EXPECT_EQ(expected_content_size, received_body.size());
  5890. EXPECT_TRUE(res->body.empty());
  5891. }
  5892. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5893. TestContentReceiverDownloadProgress(
  5894. [](Server &svr) {
  5895. svr.Get("/download-receiver",
  5896. [](const Request & /*req*/, Response &res) {
  5897. string content(2000, 'R');
  5898. res.set_content(content, "text/plain");
  5899. });
  5900. },
  5901. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5902. DownloadProgress progress_callback) {
  5903. return cli.Get(endpoint, content_receiver, progress_callback);
  5904. },
  5905. "/download-receiver", 2000u);
  5906. }
  5907. TEST(StreamingTest, NoContentLengthStreaming) {
  5908. Server svr;
  5909. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5910. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5911. if (offset < 6) {
  5912. sink.os << (offset < 3 ? "a" : "b");
  5913. } else {
  5914. sink.done();
  5915. }
  5916. return true;
  5917. });
  5918. });
  5919. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5920. auto listen_se = detail::scope_exit([&] {
  5921. svr.stop();
  5922. listen_thread.join();
  5923. ASSERT_FALSE(svr.is_running());
  5924. });
  5925. svr.wait_until_ready();
  5926. Client client(HOST, PORT);
  5927. auto get_thread = std::thread([&client]() {
  5928. std::string s;
  5929. auto res =
  5930. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5931. s += std::string(data, len);
  5932. return true;
  5933. });
  5934. ASSERT_TRUE(res);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ("aaabbb", s);
  5937. });
  5938. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5939. // Give GET time to get a few messages.
  5940. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5941. }
  5942. TEST(MountTest, Unmount) {
  5943. Server svr;
  5944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5945. auto se = detail::scope_exit([&] {
  5946. svr.stop();
  5947. listen_thread.join();
  5948. ASSERT_FALSE(svr.is_running());
  5949. });
  5950. svr.wait_until_ready();
  5951. Client cli("localhost", PORT);
  5952. svr.set_mount_point("/mount2", "./www2");
  5953. auto res = cli.Get("/");
  5954. ASSERT_TRUE(res);
  5955. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5956. res = cli.Get("/mount2/dir/test.html");
  5957. ASSERT_TRUE(res);
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. svr.set_mount_point("/", "./www");
  5960. res = cli.Get("/dir/");
  5961. ASSERT_TRUE(res);
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. svr.remove_mount_point("/");
  5964. res = cli.Get("/dir/");
  5965. ASSERT_TRUE(res);
  5966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5967. svr.remove_mount_point("/mount2");
  5968. res = cli.Get("/mount2/dir/test.html");
  5969. ASSERT_TRUE(res);
  5970. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5971. }
  5972. TEST(MountTest, Redicect) {
  5973. Server svr;
  5974. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5975. auto se = detail::scope_exit([&] {
  5976. svr.stop();
  5977. listen_thread.join();
  5978. ASSERT_FALSE(svr.is_running());
  5979. });
  5980. svr.set_mount_point("/", "./www");
  5981. svr.wait_until_ready();
  5982. Client cli("localhost", PORT);
  5983. auto res = cli.Get("/dir/");
  5984. ASSERT_TRUE(res);
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. res = cli.Get("/dir");
  5987. ASSERT_TRUE(res);
  5988. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5989. res = cli.Get("/file");
  5990. ASSERT_TRUE(res);
  5991. EXPECT_EQ(StatusCode::OK_200, res->status);
  5992. res = cli.Get("/file/");
  5993. ASSERT_TRUE(res);
  5994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5995. cli.set_follow_location(true);
  5996. res = cli.Get("/dir");
  5997. ASSERT_TRUE(res);
  5998. EXPECT_EQ(StatusCode::OK_200, res->status);
  5999. }
  6000. TEST(MountTest, MultibytesPathName) {
  6001. Server svr;
  6002. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6003. auto se = detail::scope_exit([&] {
  6004. svr.stop();
  6005. listen_thread.join();
  6006. ASSERT_FALSE(svr.is_running());
  6007. });
  6008. svr.set_mount_point("/", "./www");
  6009. svr.wait_until_ready();
  6010. Client cli("localhost", PORT);
  6011. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6015. }
  6016. TEST(KeepAliveTest, ReadTimeout) {
  6017. Server svr;
  6018. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6019. std::this_thread::sleep_for(std::chrono::seconds(2));
  6020. res.set_content("a", "text/plain");
  6021. });
  6022. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6023. res.set_content("b", "text/plain");
  6024. });
  6025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6026. auto se = detail::scope_exit([&] {
  6027. svr.stop();
  6028. listen_thread.join();
  6029. ASSERT_FALSE(svr.is_running());
  6030. });
  6031. svr.wait_until_ready();
  6032. Client cli("localhost", PORT);
  6033. cli.set_keep_alive(true);
  6034. cli.set_read_timeout(std::chrono::seconds(1));
  6035. auto resa = cli.Get("/a");
  6036. ASSERT_FALSE(resa);
  6037. EXPECT_EQ(Error::Read, resa.error());
  6038. auto resb = cli.Get("/b");
  6039. ASSERT_TRUE(resb);
  6040. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6041. EXPECT_EQ("b", resb->body);
  6042. }
  6043. TEST(KeepAliveTest, MaxCount) {
  6044. size_t keep_alive_max_count = 3;
  6045. Server svr;
  6046. svr.set_keep_alive_max_count(keep_alive_max_count);
  6047. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6048. res.set_content("Hello World!", "text/plain");
  6049. });
  6050. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6051. auto se = detail::scope_exit([&] {
  6052. svr.stop();
  6053. listen_thread.join();
  6054. ASSERT_FALSE(svr.is_running());
  6055. });
  6056. svr.wait_until_ready();
  6057. Client cli(HOST, PORT);
  6058. cli.set_keep_alive(true);
  6059. for (size_t i = 0; i < 5; i++) {
  6060. auto result = cli.Get("/hi");
  6061. ASSERT_TRUE(result);
  6062. EXPECT_EQ(StatusCode::OK_200, result->status);
  6063. if (i == keep_alive_max_count - 1) {
  6064. EXPECT_EQ("close", result->get_header_value("Connection"));
  6065. } else {
  6066. EXPECT_FALSE(result->has_header("Connection"));
  6067. }
  6068. }
  6069. }
  6070. TEST(KeepAliveTest, Issue1041) {
  6071. Server svr;
  6072. svr.set_keep_alive_timeout(3);
  6073. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6074. res.set_content("Hello World!", "text/plain");
  6075. });
  6076. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6077. auto se = detail::scope_exit([&] {
  6078. svr.stop();
  6079. listen_thread.join();
  6080. ASSERT_FALSE(svr.is_running());
  6081. });
  6082. svr.wait_until_ready();
  6083. Client cli(HOST, PORT);
  6084. cli.set_keep_alive(true);
  6085. auto result = cli.Get("/hi");
  6086. ASSERT_TRUE(result);
  6087. EXPECT_EQ(StatusCode::OK_200, result->status);
  6088. std::this_thread::sleep_for(std::chrono::seconds(5));
  6089. result = cli.Get("/hi");
  6090. ASSERT_TRUE(result);
  6091. EXPECT_EQ(StatusCode::OK_200, result->status);
  6092. }
  6093. TEST(KeepAliveTest, Issue1959) {
  6094. Server svr;
  6095. svr.set_keep_alive_timeout(5);
  6096. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6097. res.set_content("a", "text/plain");
  6098. });
  6099. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6100. auto se = detail::scope_exit([&] {
  6101. if (!svr.is_running()) return;
  6102. svr.stop();
  6103. listen_thread.join();
  6104. ASSERT_FALSE(svr.is_running());
  6105. });
  6106. svr.wait_until_ready();
  6107. Client cli("localhost", PORT);
  6108. cli.set_keep_alive(true);
  6109. using namespace std::chrono;
  6110. auto start = steady_clock::now();
  6111. cli.Get("/a");
  6112. svr.stop();
  6113. listen_thread.join();
  6114. auto end = steady_clock::now();
  6115. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6116. EXPECT_LT(elapsed, 5000);
  6117. }
  6118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6119. TEST(KeepAliveTest, SSLClientReconnection) {
  6120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6121. ASSERT_TRUE(svr.is_valid());
  6122. svr.set_keep_alive_timeout(1);
  6123. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6124. res.set_content("Hello World!", "text/plain");
  6125. });
  6126. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6127. auto se = detail::scope_exit([&] {
  6128. svr.stop();
  6129. listen_thread.join();
  6130. ASSERT_FALSE(svr.is_running());
  6131. });
  6132. svr.wait_until_ready();
  6133. SSLClient cli(HOST, PORT);
  6134. cli.enable_server_certificate_verification(false);
  6135. cli.set_keep_alive(true);
  6136. auto result = cli.Get("/hi");
  6137. ASSERT_TRUE(result);
  6138. EXPECT_EQ(StatusCode::OK_200, result->status);
  6139. result = cli.Get("/hi");
  6140. ASSERT_TRUE(result);
  6141. EXPECT_EQ(StatusCode::OK_200, result->status);
  6142. std::this_thread::sleep_for(std::chrono::seconds(2));
  6143. // Recoonect
  6144. result = cli.Get("/hi");
  6145. ASSERT_TRUE(result);
  6146. EXPECT_EQ(StatusCode::OK_200, result->status);
  6147. result = cli.Get("/hi");
  6148. ASSERT_TRUE(result);
  6149. EXPECT_EQ(StatusCode::OK_200, result->status);
  6150. }
  6151. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6153. ASSERT_TRUE(svr.is_valid());
  6154. svr.set_keep_alive_timeout(1);
  6155. std::string content = "reconnect";
  6156. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6157. res.set_content("Hello World!", "text/plain");
  6158. });
  6159. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6160. auto se = detail::scope_exit([&] {
  6161. svr.stop();
  6162. listen_thread.join();
  6163. ASSERT_FALSE(svr.is_running());
  6164. });
  6165. svr.wait_until_ready();
  6166. SSLClient cli(HOST, PORT);
  6167. cli.enable_server_certificate_verification(false);
  6168. cli.set_keep_alive(true);
  6169. auto result = cli.Post(
  6170. "/hi", content.size(),
  6171. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6172. sink.write(content.c_str(), content.size());
  6173. return true;
  6174. },
  6175. "text/plain");
  6176. ASSERT_TRUE(result);
  6177. EXPECT_EQ(200, result->status);
  6178. std::this_thread::sleep_for(std::chrono::seconds(2));
  6179. // Recoonect
  6180. result = cli.Post(
  6181. "/hi", content.size(),
  6182. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6183. sink.write(content.c_str(), content.size());
  6184. return true;
  6185. },
  6186. "text/plain");
  6187. ASSERT_TRUE(result);
  6188. EXPECT_EQ(200, result->status);
  6189. result = cli.Post(
  6190. "/hi", content.size(),
  6191. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6192. sink.write(content.c_str(), content.size());
  6193. return true;
  6194. },
  6195. "text/plain");
  6196. ASSERT_TRUE(result);
  6197. EXPECT_EQ(200, result->status);
  6198. }
  6199. #endif
  6200. TEST(ClientProblemDetectionTest, ContentProvider) {
  6201. Server svr;
  6202. size_t content_length = 1024 * 1024;
  6203. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6204. res.set_content_provider(
  6205. content_length, "text/plain",
  6206. [&](size_t offset, size_t length, DataSink &sink) {
  6207. auto out_len = std::min(length, static_cast<size_t>(1024));
  6208. std::string out(out_len, '@');
  6209. sink.write(out.data(), out_len);
  6210. return offset < 4096;
  6211. },
  6212. [](bool success) { ASSERT_FALSE(success); });
  6213. });
  6214. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6215. res.set_content_provider(
  6216. 0, "text/plain",
  6217. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6218. EXPECT_TRUE(false);
  6219. return true;
  6220. },
  6221. [](bool success) { ASSERT_FALSE(success); });
  6222. });
  6223. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6224. auto se = detail::scope_exit([&] {
  6225. svr.stop();
  6226. listen_thread.join();
  6227. ASSERT_FALSE(svr.is_running());
  6228. });
  6229. svr.wait_until_ready();
  6230. Client cli("localhost", PORT);
  6231. {
  6232. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6233. size_t /*data_length*/) { return false; });
  6234. ASSERT_FALSE(res);
  6235. }
  6236. {
  6237. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6238. size_t /*data_length*/) { return false; });
  6239. ASSERT_TRUE(res);
  6240. }
  6241. }
  6242. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6243. Server svr;
  6244. svr.set_error_handler([](Request const &, Response &res) -> void {
  6245. res.set_chunked_content_provider(
  6246. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6247. sink.os << "hello";
  6248. sink.os << "world";
  6249. sink.done();
  6250. return true;
  6251. });
  6252. });
  6253. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6254. auto se = detail::scope_exit([&] {
  6255. svr.stop();
  6256. listen_thread.join();
  6257. ASSERT_FALSE(svr.is_running());
  6258. });
  6259. svr.wait_until_ready();
  6260. Client cli("localhost", PORT);
  6261. auto res = cli.Get("/");
  6262. ASSERT_TRUE(res);
  6263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6264. EXPECT_EQ("helloworld", res->body);
  6265. }
  6266. TEST(LongPollingTest, ClientCloseDetection) {
  6267. Server svr;
  6268. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6269. res.set_chunked_content_provider(
  6270. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6271. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6272. sink.os << "hello";
  6273. auto count = 10;
  6274. while (count > 0 && sink.is_writable()) {
  6275. this_thread::sleep_for(chrono::milliseconds(10));
  6276. count--;
  6277. }
  6278. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6279. return true;
  6280. });
  6281. });
  6282. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6283. auto se = detail::scope_exit([&] {
  6284. svr.stop();
  6285. listen_thread.join();
  6286. ASSERT_FALSE(svr.is_running());
  6287. });
  6288. svr.wait_until_ready();
  6289. Client cli("localhost", PORT);
  6290. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6291. EXPECT_EQ("hello", string(data, data_length));
  6292. return false; // close the socket immediately.
  6293. });
  6294. ASSERT_FALSE(res);
  6295. }
  6296. TEST(GetWithParametersTest, GetWithParameters) {
  6297. Server svr;
  6298. svr.Get("/", [&](const Request &req, Response &) {
  6299. EXPECT_EQ("world", req.get_param_value("hello"));
  6300. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6301. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6302. });
  6303. svr.Get("/params", [&](const Request &req, Response &) {
  6304. EXPECT_EQ("world", req.get_param_value("hello"));
  6305. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6306. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6307. });
  6308. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6309. EXPECT_EQ("resource-id", req.matches[1]);
  6310. EXPECT_EQ("foo", req.get_param_value("param1"));
  6311. EXPECT_EQ("bar", req.get_param_value("param2"));
  6312. });
  6313. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6314. EXPECT_EQ("user-id", req.path_params.at("id"));
  6315. EXPECT_EQ("foo", req.get_param_value("param1"));
  6316. EXPECT_EQ("bar", req.get_param_value("param2"));
  6317. });
  6318. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6319. auto se = detail::scope_exit([&] {
  6320. svr.stop();
  6321. listen_thread.join();
  6322. ASSERT_FALSE(svr.is_running());
  6323. });
  6324. svr.wait_until_ready();
  6325. {
  6326. Client cli(HOST, PORT);
  6327. Params params;
  6328. params.emplace("hello", "world");
  6329. params.emplace("hello2", "world2");
  6330. params.emplace("hello3", "world3");
  6331. auto res = cli.Get("/", params, Headers{});
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. }
  6335. {
  6336. Client cli(HOST, PORT);
  6337. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. }
  6341. {
  6342. Client cli(HOST, PORT);
  6343. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6344. ASSERT_TRUE(res);
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. }
  6347. {
  6348. Client cli(HOST, PORT);
  6349. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6350. ASSERT_TRUE(res);
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. }
  6354. TEST(GetWithParametersTest, GetWithParameters2) {
  6355. Server svr;
  6356. svr.Get("/", [&](const Request &req, Response &res) {
  6357. auto text = req.get_param_value("hello");
  6358. res.set_content(text, "text/plain");
  6359. });
  6360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6361. auto se = detail::scope_exit([&] {
  6362. svr.stop();
  6363. listen_thread.join();
  6364. ASSERT_FALSE(svr.is_running());
  6365. });
  6366. svr.wait_until_ready();
  6367. Client cli("localhost", PORT);
  6368. Params params;
  6369. params.emplace("hello", "world");
  6370. std::string body;
  6371. auto res = cli.Get("/", params, Headers{},
  6372. [&](const char *data, size_t data_length) {
  6373. body.append(data, data_length);
  6374. return true;
  6375. });
  6376. ASSERT_TRUE(res);
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("world", body);
  6379. }
  6380. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6381. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6382. auto host = "httpbin.org";
  6383. auto path = std::string{"/range/32"};
  6384. #else
  6385. auto host = "nghttp2.org";
  6386. auto path = std::string{"/httpbin/range/32"};
  6387. #endif
  6388. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6389. SSLClient cli(host);
  6390. #else
  6391. Client cli(host);
  6392. #endif
  6393. cli.set_default_headers({make_range_header({{1, 10}})});
  6394. cli.set_connection_timeout(5);
  6395. {
  6396. auto res = cli.Get(path);
  6397. ASSERT_TRUE(res);
  6398. EXPECT_EQ("bcdefghijk", res->body);
  6399. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6400. }
  6401. {
  6402. auto res = cli.Get(path);
  6403. ASSERT_TRUE(res);
  6404. EXPECT_EQ("bcdefghijk", res->body);
  6405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6406. }
  6407. }
  6408. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6409. Server svr;
  6410. svr.set_default_headers({{"Hello", "World"}});
  6411. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6412. res.set_content("ok", "text/plain");
  6413. });
  6414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6415. auto se = detail::scope_exit([&] {
  6416. svr.stop();
  6417. listen_thread.join();
  6418. ASSERT_FALSE(svr.is_running());
  6419. });
  6420. svr.wait_until_ready();
  6421. Client cli("localhost", PORT);
  6422. auto res = cli.Get("/");
  6423. ASSERT_TRUE(res);
  6424. EXPECT_EQ(StatusCode::OK_200, res->status);
  6425. EXPECT_EQ("ok", res->body);
  6426. EXPECT_EQ("World", res->get_header_value("Hello"));
  6427. }
  6428. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6429. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6431. ASSERT_TRUE(svr.is_valid());
  6432. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6433. std::this_thread::sleep_for(std::chrono::seconds(2));
  6434. res.set_content("a", "text/plain");
  6435. });
  6436. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6437. res.set_content("b", "text/plain");
  6438. });
  6439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6440. auto se = detail::scope_exit([&] {
  6441. svr.stop();
  6442. listen_thread.join();
  6443. ASSERT_FALSE(svr.is_running());
  6444. });
  6445. svr.wait_until_ready();
  6446. SSLClient cli("localhost", PORT);
  6447. cli.enable_server_certificate_verification(false);
  6448. cli.set_keep_alive(true);
  6449. cli.set_read_timeout(std::chrono::seconds(1));
  6450. auto resa = cli.Get("/a");
  6451. ASSERT_TRUE(!resa);
  6452. EXPECT_EQ(Error::Read, resa.error());
  6453. auto resb = cli.Get("/b");
  6454. ASSERT_TRUE(resb);
  6455. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6456. EXPECT_EQ("b", resb->body);
  6457. }
  6458. #endif
  6459. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6460. protected:
  6461. ServerTestWithAI_PASSIVE()
  6462. : cli_(HOST, PORT)
  6463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6464. ,
  6465. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6466. #endif
  6467. {
  6468. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6469. cli_.enable_server_certificate_verification(false);
  6470. #endif
  6471. }
  6472. virtual void SetUp() {
  6473. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6474. res.set_content("Hello World!", "text/plain");
  6475. });
  6476. t_ = thread(
  6477. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6478. svr_.wait_until_ready();
  6479. }
  6480. virtual void TearDown() {
  6481. svr_.stop();
  6482. t_.join();
  6483. }
  6484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6485. SSLClient cli_;
  6486. SSLServer svr_;
  6487. #else
  6488. Client cli_;
  6489. Server svr_;
  6490. #endif
  6491. thread t_;
  6492. };
  6493. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6494. auto res = cli_.Get("/hi");
  6495. ASSERT_TRUE(res);
  6496. EXPECT_EQ(StatusCode::OK_200, res->status);
  6497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6498. EXPECT_EQ("Hello World!", res->body);
  6499. }
  6500. class ServerUpDownTest : public ::testing::Test {
  6501. protected:
  6502. ServerUpDownTest() : cli_(HOST, PORT) {}
  6503. virtual void SetUp() {
  6504. t_ = thread([&]() {
  6505. svr_.bind_to_any_port(HOST);
  6506. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6507. ASSERT_TRUE(svr_.listen_after_bind());
  6508. });
  6509. svr_.wait_until_ready();
  6510. }
  6511. virtual void TearDown() {
  6512. svr_.stop();
  6513. t_.join();
  6514. }
  6515. Client cli_;
  6516. Server svr_;
  6517. thread t_;
  6518. };
  6519. TEST_F(ServerUpDownTest, QuickStartStop) {
  6520. // Should not crash, especially when run with
  6521. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6522. }
  6523. class PayloadMaxLengthTest : public ::testing::Test {
  6524. protected:
  6525. PayloadMaxLengthTest()
  6526. : cli_(HOST, PORT)
  6527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6528. ,
  6529. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6530. #endif
  6531. {
  6532. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6533. cli_.enable_server_certificate_verification(false);
  6534. #endif
  6535. }
  6536. virtual void SetUp() {
  6537. svr_.set_payload_max_length(8);
  6538. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6539. res.set_content("test", "text/plain");
  6540. });
  6541. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6542. svr_.wait_until_ready();
  6543. }
  6544. virtual void TearDown() {
  6545. svr_.stop();
  6546. t_.join();
  6547. }
  6548. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6549. SSLClient cli_;
  6550. SSLServer svr_;
  6551. #else
  6552. Client cli_;
  6553. Server svr_;
  6554. #endif
  6555. thread t_;
  6556. };
  6557. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6558. auto res = cli_.Post("/test", "123456789", "text/plain");
  6559. ASSERT_TRUE(res);
  6560. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6561. res = cli_.Post("/test", "12345678", "text/plain");
  6562. ASSERT_TRUE(res);
  6563. EXPECT_EQ(StatusCode::OK_200, res->status);
  6564. }
  6565. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6566. // Test chunked encoding with payload exceeding the 8-byte limit
  6567. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6568. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6569. ASSERT_TRUE(res);
  6570. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6571. }
  6572. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6573. // Test chunked encoding with payload within the 8-byte limit
  6574. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6575. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6576. ASSERT_TRUE(res);
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. }
  6579. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6580. // Test using send_request to send chunked data exceeding payload limit
  6581. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6582. "Host: " +
  6583. std::string(HOST) + ":" + std::to_string(PORT) +
  6584. "\r\n"
  6585. "Transfer-Encoding: chunked\r\n"
  6586. "Connection: close\r\n"
  6587. "\r\n"
  6588. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6589. "0123456789\r\n"
  6590. "0\r\n" // End chunk
  6591. "\r\n";
  6592. std::string response;
  6593. bool result = send_request(1, chunked_request, &response);
  6594. if (!result) {
  6595. // If send_request fails, it might be because the server closed the
  6596. // connection due to payload limit enforcement, which is acceptable
  6597. SUCCEED()
  6598. << "Server rejected oversized chunked request (connection closed)";
  6599. } else {
  6600. // If we got a response, check if it's an error response or connection was
  6601. // closed early Short response length indicates connection was closed due to
  6602. // payload limit
  6603. if (response.length() <= 10) {
  6604. SUCCEED() << "Server closed connection for oversized chunked request";
  6605. } else {
  6606. // Check for error status codes
  6607. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6608. response.find("Payload Too Large") != std::string::npos ||
  6609. response.find("400") != std::string::npos);
  6610. }
  6611. }
  6612. }
  6613. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6614. // Test request without Content-Length header exceeding payload limit
  6615. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6616. "Host: " +
  6617. std::string(HOST) + ":" +
  6618. std::to_string(PORT) +
  6619. "\r\n"
  6620. "Connection: close\r\n"
  6621. "\r\n";
  6622. // Add payload exceeding the 8-byte limit
  6623. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6624. request_without_content_length += large_payload;
  6625. std::string response;
  6626. bool result = send_request(1, request_without_content_length, &response);
  6627. if (!result) {
  6628. // If send_request fails, server likely closed connection due to payload
  6629. // limit
  6630. SUCCEED() << "Server rejected oversized request without Content-Length "
  6631. "(connection closed)";
  6632. } else {
  6633. // Check if server responded with error or closed connection early
  6634. if (response.length() <= 10) {
  6635. SUCCEED() << "Server closed connection for oversized request without "
  6636. "Content-Length";
  6637. } else {
  6638. // Check for error status codes
  6639. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6640. response.find("Payload Too Large") != std::string::npos ||
  6641. response.find("400") != std::string::npos);
  6642. }
  6643. }
  6644. }
  6645. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6646. // Test request without Content-Length header within payload limit
  6647. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6648. "Host: " +
  6649. std::string(HOST) + ":" +
  6650. std::to_string(PORT) +
  6651. "\r\n"
  6652. "Connection: close\r\n"
  6653. "\r\n";
  6654. // Add payload within the 8-byte limit
  6655. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6656. request_without_content_length += small_payload;
  6657. std::string response;
  6658. bool result = send_request(1, request_without_content_length, &response);
  6659. // For requests without Content-Length, the server may have different behavior
  6660. // The key is that it should not reject due to payload limit for small
  6661. // payloads
  6662. if (result) {
  6663. // Check for any HTTP response (success or error, but not connection closed)
  6664. if (response.length() > 10) {
  6665. SUCCEED()
  6666. << "Server processed request without Content-Length within limit";
  6667. } else {
  6668. // Short response might indicate connection closed, which is acceptable
  6669. SUCCEED() << "Server closed connection for request without "
  6670. "Content-Length (acceptable behavior)";
  6671. }
  6672. } else {
  6673. // Connection failure might be due to protocol requirements
  6674. SUCCEED() << "Connection issue with request without Content-Length "
  6675. "(environment-specific)";
  6676. }
  6677. }
  6678. class LargePayloadMaxLengthTest : public ::testing::Test {
  6679. protected:
  6680. LargePayloadMaxLengthTest()
  6681. : cli_(HOST, PORT)
  6682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6683. ,
  6684. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6685. #endif
  6686. {
  6687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6688. cli_.enable_server_certificate_verification(false);
  6689. #endif
  6690. }
  6691. virtual void SetUp() {
  6692. // Set 10MB payload limit
  6693. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6694. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6695. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6696. res.set_content("Large payload test", "text/plain");
  6697. });
  6698. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6699. svr_.wait_until_ready();
  6700. }
  6701. virtual void TearDown() {
  6702. svr_.stop();
  6703. t_.join();
  6704. }
  6705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6706. SSLClient cli_;
  6707. SSLServer svr_;
  6708. #else
  6709. Client cli_;
  6710. Server svr_;
  6711. #endif
  6712. thread t_;
  6713. };
  6714. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6715. // Test chunked encoding with payload within 10MB limit
  6716. std::string medium_payload(5 * 1024 * 1024,
  6717. 'A'); // 5MB payload, within 10MB limit
  6718. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6719. ASSERT_TRUE(res);
  6720. EXPECT_EQ(StatusCode::OK_200, res->status);
  6721. }
  6722. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6723. // Test chunked encoding with payload exceeding 10MB limit
  6724. std::string large_payload(12 * 1024 * 1024,
  6725. 'B'); // 12MB payload, exceeds 10MB limit
  6726. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6727. ASSERT_TRUE(res);
  6728. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6729. }
  6730. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6731. // Test request without Content-Length header within 10MB limit
  6732. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6733. "Host: " +
  6734. std::string(HOST) + ":" +
  6735. std::to_string(PORT) +
  6736. "\r\n"
  6737. "Connection: close\r\n"
  6738. "\r\n";
  6739. // Add 1MB payload (within 10MB limit)
  6740. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6741. request_without_content_length += medium_payload;
  6742. std::string response;
  6743. bool result = send_request(5, request_without_content_length, &response);
  6744. if (result) {
  6745. // Should get a proper HTTP response for payloads within limit
  6746. if (response.length() > 10) {
  6747. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6748. "10MB limit";
  6749. } else {
  6750. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6751. "Content-Length)";
  6752. }
  6753. } else {
  6754. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6755. }
  6756. }
  6757. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6758. // Test request without Content-Length header exceeding 10MB limit
  6759. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6760. "Host: " +
  6761. std::string(HOST) + ":" +
  6762. std::to_string(PORT) +
  6763. "\r\n"
  6764. "Connection: close\r\n"
  6765. "\r\n";
  6766. // Add 12MB payload (exceeds 10MB limit)
  6767. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6768. request_without_content_length += large_payload;
  6769. std::string response;
  6770. bool result = send_request(10, request_without_content_length, &response);
  6771. if (!result) {
  6772. // Server should close connection due to payload limit
  6773. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6774. "(connection closed)";
  6775. } else {
  6776. // Check for error response
  6777. if (response.length() <= 10) {
  6778. SUCCEED()
  6779. << "Server closed connection for 12MB request exceeding 10MB limit";
  6780. } else {
  6781. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6782. response.find("Payload Too Large") != std::string::npos ||
  6783. response.find("400") != std::string::npos);
  6784. }
  6785. }
  6786. }
  6787. TEST(HostAndPortPropertiesTest, NoSSL) {
  6788. httplib::Client cli("www.google.com", 1234);
  6789. ASSERT_EQ("www.google.com", cli.host());
  6790. ASSERT_EQ(1234, cli.port());
  6791. }
  6792. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6793. httplib::Client cli("www.google.com:1234");
  6794. ASSERT_EQ("www.google.com", cli.host());
  6795. ASSERT_EQ(1234, cli.port());
  6796. }
  6797. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6798. TEST(HostAndPortPropertiesTest, SSL) {
  6799. httplib::SSLClient cli("www.google.com");
  6800. ASSERT_EQ("www.google.com", cli.host());
  6801. ASSERT_EQ(443, cli.port());
  6802. }
  6803. #endif
  6804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6805. TEST(SSLClientTest, UpdateCAStore) {
  6806. httplib::SSLClient httplib_client("www.google.com");
  6807. auto ca_store_1 = X509_STORE_new();
  6808. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6809. nullptr);
  6810. httplib_client.set_ca_cert_store(ca_store_1);
  6811. auto ca_store_2 = X509_STORE_new();
  6812. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6813. nullptr);
  6814. httplib_client.set_ca_cert_store(ca_store_2);
  6815. }
  6816. TEST(SSLClientTest, ServerNameIndication_Online) {
  6817. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6818. auto host = "httpbin.org";
  6819. auto path = std::string{"/get"};
  6820. #else
  6821. auto host = "nghttp2.org";
  6822. auto path = std::string{"/httpbin/get"};
  6823. #endif
  6824. SSLClient cli(host, 443);
  6825. auto res = cli.Get(path);
  6826. ASSERT_TRUE(res);
  6827. ASSERT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6830. // Use a site that will cause SSL verification failure due to self-signed cert
  6831. SSLClient cli("self-signed.badssl.com", 443);
  6832. cli.enable_server_certificate_verification(true);
  6833. auto res = cli.Get("/");
  6834. ASSERT_TRUE(!res);
  6835. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6836. // For SSL server verification errors, ssl_error should be 0, only
  6837. // ssl_openssl_error should be set
  6838. EXPECT_EQ(0, res.ssl_error());
  6839. // Verify OpenSSL error is captured for SSLServerVerification
  6840. // This occurs when SSL_get_verify_result() returns a verification failure
  6841. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6842. res.ssl_openssl_error());
  6843. }
  6844. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6845. // Use a site where hostname doesn't match the certificate
  6846. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6847. SSLClient cli("wrong.host.badssl.com", 443);
  6848. cli.enable_server_certificate_verification(true);
  6849. cli.enable_server_hostname_verification(true);
  6850. auto res = cli.Get("/");
  6851. ASSERT_TRUE(!res);
  6852. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6853. // For SSL hostname verification errors, ssl_error should be 0, only
  6854. // ssl_openssl_error should be set
  6855. EXPECT_EQ(0, res.ssl_error());
  6856. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6857. // This occurs when verify_host() fails due to hostname mismatch
  6858. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6859. res.ssl_openssl_error());
  6860. }
  6861. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6862. Client cli("https://google.com");
  6863. auto res = cli.Get("/");
  6864. ASSERT_TRUE(res);
  6865. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6866. }
  6867. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6868. SSLClient cli("google.com");
  6869. cli.set_ca_cert_path(CA_CERT_FILE);
  6870. auto res = cli.Get("/");
  6871. ASSERT_TRUE(res);
  6872. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6873. }
  6874. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6875. SSLClient cli("google.com");
  6876. cli.enable_server_certificate_verification(true);
  6877. cli.set_ca_cert_path("hello");
  6878. auto res = cli.Get("/");
  6879. ASSERT_TRUE(!res);
  6880. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6881. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6882. // should be set
  6883. EXPECT_EQ(0, res.ssl_error());
  6884. // Verify OpenSSL error is captured for SSLLoadingCerts
  6885. // This error occurs when SSL_CTX_load_verify_locations() fails
  6886. // > openssl errstr 0x80000002
  6887. // error:80000002:system library::No such file or directory
  6888. // > openssl errstr 0xA000126
  6889. // error:0A000126:SSL routines::unexpected eof while reading
  6890. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6891. res.ssl_openssl_error() == 0xA000126);
  6892. }
  6893. TEST(SSLClientTest, ServerCertificateVerification4) {
  6894. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6895. ASSERT_TRUE(svr.is_valid());
  6896. svr.Get("/test", [&](const Request &, Response &res) {
  6897. res.set_content("test", "text/plain");
  6898. svr.stop();
  6899. ASSERT_TRUE(true);
  6900. });
  6901. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6902. auto se = detail::scope_exit([&] {
  6903. t.join();
  6904. ASSERT_FALSE(svr.is_running());
  6905. });
  6906. svr.wait_until_ready();
  6907. SSLClient cli("127.0.0.1", PORT);
  6908. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6909. cli.enable_server_certificate_verification(true);
  6910. cli.set_connection_timeout(30);
  6911. auto res = cli.Get("/test");
  6912. ASSERT_TRUE(res);
  6913. ASSERT_EQ(StatusCode::OK_200, res->status);
  6914. }
  6915. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6916. std::string cert;
  6917. read_file(CA_CERT_FILE, cert);
  6918. SSLClient cli("google.com");
  6919. cli.load_ca_cert_store(cert.data(), cert.size());
  6920. const auto res = cli.Get("/");
  6921. ASSERT_TRUE(res);
  6922. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6923. }
  6924. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6925. // clang-format off
  6926. static constexpr char cert[] =
  6927. "GlobalSign Root CA\n"
  6928. "==================\n"
  6929. "-----BEGIN CERTIFICATE-----\n"
  6930. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6931. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6932. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6933. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6934. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6935. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6936. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6937. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6938. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6939. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6940. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6941. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6942. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6943. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6944. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6945. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6946. "-----END CERTIFICATE-----\n";
  6947. // clang-format on
  6948. SSLClient cli("google.com");
  6949. cli.load_ca_cert_store(cert, sizeof(cert));
  6950. const auto res = cli.Get("/");
  6951. ASSERT_TRUE(res);
  6952. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6953. }
  6954. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6955. SSLClient cli("www.youtube.com");
  6956. cli.set_ca_cert_path(CA_CERT_FILE);
  6957. cli.enable_server_certificate_verification(true);
  6958. cli.set_follow_location(true);
  6959. auto res = cli.Get("/");
  6960. ASSERT_TRUE(res);
  6961. ASSERT_EQ(StatusCode::OK_200, res->status);
  6962. }
  6963. TEST(SSLClientTest, Issue2004_Online) {
  6964. Client client("https://google.com");
  6965. client.set_follow_location(true);
  6966. auto res = client.Get("/");
  6967. ASSERT_TRUE(res);
  6968. ASSERT_EQ(StatusCode::OK_200, res->status);
  6969. auto body = res->body;
  6970. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6971. }
  6972. #if 0
  6973. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6974. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6975. ASSERT_TRUE(cli != nullptr);
  6976. cli->set_address_family(AF_INET6);
  6977. cli->set_interface("en0");
  6978. auto res = cli->Get("/get");
  6979. ASSERT_TRUE(res);
  6980. ASSERT_EQ(StatusCode::OK_200, res->status);
  6981. }
  6982. #endif
  6983. void ClientCertPresent(
  6984. const std::string &client_cert_file,
  6985. const std::string &client_private_key_file,
  6986. const std::string &client_encrypted_private_key_pass = std::string()) {
  6987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6988. CLIENT_CA_CERT_DIR);
  6989. ASSERT_TRUE(svr.is_valid());
  6990. svr.Get("/test", [&](const Request &req, Response &res) {
  6991. res.set_content("test", "text/plain");
  6992. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6993. ASSERT_TRUE(peer_cert != nullptr);
  6994. auto subject_name = X509_get_subject_name(peer_cert);
  6995. ASSERT_TRUE(subject_name != nullptr);
  6996. std::string common_name;
  6997. {
  6998. char name[BUFSIZ];
  6999. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7000. name, sizeof(name));
  7001. common_name.assign(name, static_cast<size_t>(name_len));
  7002. }
  7003. EXPECT_EQ("Common Name", common_name);
  7004. X509_free(peer_cert);
  7005. });
  7006. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7007. auto se = detail::scope_exit([&] {
  7008. svr.stop();
  7009. t.join();
  7010. ASSERT_FALSE(svr.is_running());
  7011. });
  7012. svr.wait_until_ready();
  7013. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7014. client_encrypted_private_key_pass);
  7015. cli.enable_server_certificate_verification(false);
  7016. cli.set_connection_timeout(30);
  7017. auto res = cli.Get("/test");
  7018. ASSERT_TRUE(res);
  7019. ASSERT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. TEST(SSLClientServerTest, ClientCertPresent) {
  7022. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7023. }
  7024. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7025. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7026. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7027. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7028. }
  7029. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7030. void MemoryClientCertPresent(
  7031. const std::string &client_cert_file,
  7032. const std::string &client_private_key_file,
  7033. const std::string &client_encrypted_private_key_pass = std::string()) {
  7034. auto f = fopen(SERVER_CERT_FILE, "r+");
  7035. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7036. fclose(f);
  7037. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7038. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7039. fclose(f);
  7040. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7041. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7042. auto client_ca_cert_store = X509_STORE_new();
  7043. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7044. X509_free(client_cert);
  7045. fclose(f);
  7046. f = fopen(client_cert_file.c_str(), "r+");
  7047. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7048. fclose(f);
  7049. f = fopen(client_private_key_file.c_str(), "r+");
  7050. auto client_private_key = PEM_read_PrivateKey(
  7051. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7052. fclose(f);
  7053. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7054. ASSERT_TRUE(svr.is_valid());
  7055. svr.Get("/test", [&](const Request &req, Response &res) {
  7056. res.set_content("test", "text/plain");
  7057. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7058. ASSERT_TRUE(peer_cert != nullptr);
  7059. auto subject_name = X509_get_subject_name(peer_cert);
  7060. ASSERT_TRUE(subject_name != nullptr);
  7061. std::string common_name;
  7062. {
  7063. char name[BUFSIZ];
  7064. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7065. name, sizeof(name));
  7066. common_name.assign(name, static_cast<size_t>(name_len));
  7067. }
  7068. EXPECT_EQ("Common Name", common_name);
  7069. X509_free(peer_cert);
  7070. });
  7071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7072. auto se = detail::scope_exit([&] {
  7073. svr.stop();
  7074. t.join();
  7075. ASSERT_FALSE(svr.is_running());
  7076. });
  7077. svr.wait_until_ready();
  7078. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7079. client_encrypted_private_key_pass);
  7080. cli.enable_server_certificate_verification(false);
  7081. cli.set_connection_timeout(30);
  7082. auto res = cli.Get("/test");
  7083. ASSERT_TRUE(res);
  7084. ASSERT_EQ(StatusCode::OK_200, res->status);
  7085. X509_free(server_cert);
  7086. EVP_PKEY_free(server_private_key);
  7087. X509_free(client_cert);
  7088. EVP_PKEY_free(client_private_key);
  7089. }
  7090. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7091. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7092. }
  7093. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7094. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7095. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7096. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7097. }
  7098. #endif
  7099. TEST(SSLClientServerTest, ClientCertMissing) {
  7100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7101. CLIENT_CA_CERT_DIR);
  7102. ASSERT_TRUE(svr.is_valid());
  7103. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7104. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7105. auto se = detail::scope_exit([&] {
  7106. svr.stop();
  7107. t.join();
  7108. ASSERT_FALSE(svr.is_running());
  7109. });
  7110. svr.wait_until_ready();
  7111. SSLClient cli(HOST, PORT);
  7112. cli.set_connection_timeout(30);
  7113. auto res = cli.Get("/test");
  7114. ASSERT_TRUE(!res);
  7115. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7116. // For SSL server verification errors, ssl_error should be 0, only
  7117. // ssl_openssl_error should be set
  7118. EXPECT_EQ(0, res.ssl_error());
  7119. // Verify OpenSSL error is captured for SSLServerVerification
  7120. // Note: This test may have different error codes depending on the exact
  7121. // verification failure
  7122. EXPECT_NE(0UL, res.ssl_openssl_error());
  7123. }
  7124. TEST(SSLClientServerTest, TrustDirOptional) {
  7125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7126. ASSERT_TRUE(svr.is_valid());
  7127. svr.Get("/test", [&](const Request &, Response &res) {
  7128. res.set_content("test", "text/plain");
  7129. });
  7130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7131. auto se = detail::scope_exit([&] {
  7132. svr.stop();
  7133. t.join();
  7134. ASSERT_FALSE(svr.is_running());
  7135. });
  7136. svr.wait_until_ready();
  7137. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7138. cli.enable_server_certificate_verification(false);
  7139. cli.set_connection_timeout(30);
  7140. auto res = cli.Get("/test");
  7141. ASSERT_TRUE(res);
  7142. ASSERT_EQ(StatusCode::OK_200, res->status);
  7143. }
  7144. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7145. class NoListenSSLServer : public SSLServer {
  7146. public:
  7147. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7148. const char *client_ca_cert_file_path,
  7149. const char *client_ca_cert_dir_path = nullptr)
  7150. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7151. client_ca_cert_dir_path),
  7152. stop_(false) {}
  7153. std::atomic_bool stop_;
  7154. private:
  7155. bool process_and_close_socket(socket_t /*sock*/) override {
  7156. // Don't create SSL context
  7157. while (!stop_.load()) {
  7158. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7159. }
  7160. return true;
  7161. }
  7162. };
  7163. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7164. CLIENT_CA_CERT_FILE);
  7165. ASSERT_TRUE(svr.is_valid());
  7166. svr.Get("/test", [&](const Request &, Response &res) {
  7167. res.set_content("test", "text/plain");
  7168. });
  7169. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7170. auto se = detail::scope_exit([&] {
  7171. svr.stop_ = true;
  7172. svr.stop();
  7173. t.join();
  7174. ASSERT_FALSE(svr.is_running());
  7175. });
  7176. svr.wait_until_ready();
  7177. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7178. cli.enable_server_certificate_verification(false);
  7179. cli.set_connection_timeout(1);
  7180. auto res = cli.Get("/test");
  7181. ASSERT_TRUE(!res);
  7182. EXPECT_EQ(Error::SSLConnection, res.error());
  7183. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7184. }
  7185. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7186. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7187. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7188. SSL_CTX_set_options(&ssl_ctx,
  7189. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7190. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7191. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7192. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7193. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7194. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7195. "ECDHE-DSS-AES128-SHA256:"
  7196. "ECDHE-RSA-AES256-SHA256:"
  7197. "ECDHE-DSS-AES256-SHA256:";
  7198. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7199. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7200. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7201. SSL_FILETYPE_PEM) != 1) {
  7202. return false;
  7203. }
  7204. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7205. CLIENT_CA_CERT_DIR);
  7206. SSL_CTX_set_verify(
  7207. &ssl_ctx,
  7208. SSL_VERIFY_PEER |
  7209. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7210. nullptr);
  7211. return true;
  7212. };
  7213. SSLServer svr(setup_ssl_ctx_callback);
  7214. ASSERT_TRUE(svr.is_valid());
  7215. svr.Get("/test", [&](const Request &req, Response &res) {
  7216. res.set_content("test", "text/plain");
  7217. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7218. ASSERT_TRUE(peer_cert != nullptr);
  7219. auto subject_name = X509_get_subject_name(peer_cert);
  7220. ASSERT_TRUE(subject_name != nullptr);
  7221. std::string common_name;
  7222. {
  7223. char name[BUFSIZ];
  7224. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7225. name, sizeof(name));
  7226. common_name.assign(name, static_cast<size_t>(name_len));
  7227. }
  7228. EXPECT_EQ("Common Name", common_name);
  7229. X509_free(peer_cert);
  7230. });
  7231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7232. auto se = detail::scope_exit([&] {
  7233. svr.stop();
  7234. t.join();
  7235. ASSERT_FALSE(svr.is_running());
  7236. });
  7237. svr.wait_until_ready();
  7238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7239. cli.enable_server_certificate_verification(false);
  7240. cli.set_connection_timeout(30);
  7241. auto res = cli.Get("/test");
  7242. ASSERT_TRUE(res);
  7243. ASSERT_EQ(StatusCode::OK_200, res->status);
  7244. }
  7245. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7246. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7247. // prepare large data
  7248. std::random_device seed_gen;
  7249. std::mt19937 random(seed_gen());
  7250. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7251. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7252. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7253. // server
  7254. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7255. ASSERT_TRUE(svr.is_valid());
  7256. svr.Post("/binary", [&](const Request &req, Response &res) {
  7257. EXPECT_EQ(large_size_byte, req.body.size());
  7258. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7259. res.set_content(req.body, "application/octet-stream");
  7260. });
  7261. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7262. auto se = detail::scope_exit([&] {
  7263. svr.stop();
  7264. listen_thread.join();
  7265. ASSERT_FALSE(svr.is_running());
  7266. });
  7267. svr.wait_until_ready();
  7268. // client POST
  7269. SSLClient cli("localhost", PORT);
  7270. cli.enable_server_certificate_verification(false);
  7271. cli.set_read_timeout(std::chrono::seconds(100));
  7272. cli.set_write_timeout(std::chrono::seconds(100));
  7273. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7274. large_size_byte, "application/octet-stream");
  7275. // compare
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. EXPECT_EQ(large_size_byte, res->body.size());
  7278. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7279. }
  7280. #endif
  7281. #ifdef _WIN32
  7282. TEST(CleanupTest, WSACleanup) {
  7283. int ret = WSACleanup();
  7284. ASSERT_EQ(0, ret);
  7285. }
  7286. #endif
  7287. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7288. TEST(NoSSLSupport, SimpleInterface) {
  7289. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7290. }
  7291. #endif
  7292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7293. TEST(InvalidScheme, SimpleInterface) {
  7294. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7295. }
  7296. #endif
  7297. TEST(NoScheme, SimpleInterface) {
  7298. Client cli("yahoo.com:80");
  7299. ASSERT_TRUE(cli.is_valid());
  7300. }
  7301. TEST(SendAPI, SimpleInterface_Online) {
  7302. Client cli("http://yahoo.com");
  7303. Request req;
  7304. req.method = "GET";
  7305. req.path = "/";
  7306. auto res = cli.send(req);
  7307. ASSERT_TRUE(res);
  7308. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7309. }
  7310. TEST(SendAPI, WithParamsInRequest) {
  7311. Server svr;
  7312. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7313. EXPECT_TRUE(req.has_param("test"));
  7314. EXPECT_EQ("test_value", req.get_param_value("test"));
  7315. });
  7316. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7317. auto se = detail::scope_exit([&] {
  7318. svr.stop();
  7319. t.join();
  7320. ASSERT_FALSE(svr.is_running());
  7321. });
  7322. svr.wait_until_ready();
  7323. Client cli(HOST, PORT);
  7324. {
  7325. Request req;
  7326. req.method = "GET";
  7327. req.path = "/";
  7328. req.params.emplace("test", "test_value");
  7329. auto res = cli.send(req);
  7330. ASSERT_TRUE(res);
  7331. }
  7332. {
  7333. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7334. ASSERT_TRUE(res);
  7335. }
  7336. }
  7337. TEST(ClientImplMethods, GetSocketTest) {
  7338. httplib::Server svr;
  7339. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7340. res.status = StatusCode::OK_200;
  7341. });
  7342. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7343. auto se = detail::scope_exit([&] {
  7344. svr.stop();
  7345. thread.join();
  7346. ASSERT_FALSE(svr.is_running());
  7347. });
  7348. svr.wait_until_ready();
  7349. {
  7350. httplib::Client cli("http://127.0.0.1:3333");
  7351. cli.set_keep_alive(true);
  7352. // Use the behavior of cpp-httplib of opening the connection
  7353. // only when the first request happens. If that changes,
  7354. // this test would be obsolete.
  7355. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7356. // This also implicitly tests the server. But other tests would fail much
  7357. // earlier than this one to be considered.
  7358. auto res = cli.Get("/");
  7359. ASSERT_TRUE(res);
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7362. }
  7363. }
  7364. // Disabled due to out-of-memory problem on GitHub Actions
  7365. #ifdef _WIN64
  7366. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7367. // allocate content size larger than 2GB in memory
  7368. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7369. char *content = (char *)malloc(content_size);
  7370. ASSERT_TRUE(content);
  7371. Server svr;
  7372. svr.Get("/foo",
  7373. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7374. res.set_content(content, content_size, "application/octet-stream");
  7375. });
  7376. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7377. auto se = detail::scope_exit([&] {
  7378. svr.stop();
  7379. listen_thread.join();
  7380. if (content) free(content);
  7381. ASSERT_FALSE(svr.is_running());
  7382. });
  7383. svr.wait_until_ready();
  7384. Client cli(HOST, PORT);
  7385. auto res = cli.Get("/foo");
  7386. ASSERT_TRUE(res);
  7387. EXPECT_EQ(StatusCode::OK_200, res->status);
  7388. EXPECT_EQ(content_size, res->body.length());
  7389. }
  7390. #endif
  7391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7392. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7393. Client cli("http://yahoo.com");
  7394. auto res = cli.Get("/");
  7395. ASSERT_TRUE(res);
  7396. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7397. cli.set_follow_location(true);
  7398. res = cli.Get("/");
  7399. ASSERT_TRUE(res);
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7402. }
  7403. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7404. Client cli("https://yahoo.com");
  7405. auto res = cli.Get("/");
  7406. ASSERT_TRUE(res);
  7407. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7408. cli.set_follow_location(true);
  7409. res = cli.Get("/");
  7410. ASSERT_TRUE(res);
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7413. }
  7414. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7415. Client cli("https://yahoo.com");
  7416. auto res = cli.Get("/");
  7417. ASSERT_TRUE(res);
  7418. ASSERT_FALSE(!res);
  7419. ASSERT_TRUE(res);
  7420. ASSERT_FALSE(res == nullptr);
  7421. ASSERT_TRUE(res != nullptr);
  7422. EXPECT_EQ(Error::Success, res.error());
  7423. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7424. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7425. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7426. cli.set_follow_location(true);
  7427. res = cli.Get("/");
  7428. ASSERT_TRUE(res);
  7429. EXPECT_EQ(Error::Success, res.error());
  7430. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7431. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7434. }
  7435. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7436. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7437. Client cli("https://cdnjs.cloudflare.com");
  7438. auto res =
  7439. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7440. ASSERT_TRUE(res);
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. EXPECT_EQ(287630U, res->body.size());
  7443. EXPECT_EQ("application/javascript; charset=utf-8",
  7444. res->get_header_value("Content-Type"));
  7445. }
  7446. #endif
  7447. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7448. #undef REDIR_HOST // Silence compiler warning
  7449. #define REDIR_HOST "https://httpbingo.org"
  7450. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7451. Client cli(REDIR_HOST);
  7452. cli.set_follow_location(true);
  7453. auto res =
  7454. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7455. ASSERT_TRUE(res);
  7456. EXPECT_EQ(StatusCode::OK_200, res->status);
  7457. }
  7458. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7459. Client cli(REDIR_HOST);
  7460. cli.set_follow_location(true);
  7461. Params params;
  7462. params.emplace("url", "http://example.com");
  7463. params.emplace("status_code", "302");
  7464. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7465. ASSERT_TRUE(res);
  7466. EXPECT_EQ(StatusCode::OK_200, res->status);
  7467. }
  7468. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7469. Client cli(REDIR_HOST);
  7470. cli.set_follow_location(true);
  7471. Params params;
  7472. params.emplace("url", "http://example.com");
  7473. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::OK_200, res->status);
  7476. }
  7477. TEST(HttpToHttpsRedirectTest, CertFile) {
  7478. Server svr;
  7479. ASSERT_TRUE(svr.is_valid());
  7480. svr.Get("/index", [&](const Request &, Response &res) {
  7481. res.set_redirect("https://127.0.0.1:1235/index");
  7482. svr.stop();
  7483. });
  7484. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7485. ASSERT_TRUE(ssl_svr.is_valid());
  7486. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7487. res.set_content("test", "text/plain");
  7488. ssl_svr.stop();
  7489. });
  7490. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7491. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7492. auto se = detail::scope_exit([&] {
  7493. t2.join();
  7494. t.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. ssl_svr.wait_until_ready();
  7499. Client cli("127.0.0.1", PORT);
  7500. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7501. cli.enable_server_certificate_verification(true);
  7502. cli.set_follow_location(true);
  7503. cli.set_connection_timeout(30);
  7504. auto res = cli.Get("/index");
  7505. ASSERT_TRUE(res);
  7506. ASSERT_EQ(StatusCode::OK_200, res->status);
  7507. }
  7508. TEST(MultipartFormDataTest, LargeData) {
  7509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7510. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7511. const ContentReader &content_reader) {
  7512. if (req.is_multipart_form_data()) {
  7513. std::vector<FormData> items;
  7514. content_reader(
  7515. [&](const FormData &file) {
  7516. items.push_back(file);
  7517. return true;
  7518. },
  7519. [&](const char *data, size_t data_length) {
  7520. items.back().content.append(data, data_length);
  7521. return true;
  7522. });
  7523. EXPECT_TRUE(std::string(items[0].name) == "document");
  7524. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7525. EXPECT_TRUE(items[0].filename == "2MB_data");
  7526. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7527. EXPECT_TRUE(items[1].name == "hello");
  7528. EXPECT_TRUE(items[1].content == "world");
  7529. EXPECT_TRUE(items[1].filename == "");
  7530. EXPECT_TRUE(items[1].content_type == "");
  7531. } else {
  7532. std::string body;
  7533. content_reader([&](const char *data, size_t data_length) {
  7534. body.append(data, data_length);
  7535. return true;
  7536. });
  7537. }
  7538. });
  7539. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7540. auto se = detail::scope_exit([&] {
  7541. svr.stop();
  7542. t.join();
  7543. ASSERT_FALSE(svr.is_running());
  7544. });
  7545. svr.wait_until_ready();
  7546. {
  7547. std::string data(1024 * 1024 * 2, '.');
  7548. std::stringstream buffer;
  7549. buffer << data;
  7550. Client cli("https://localhost:8080");
  7551. cli.enable_server_certificate_verification(false);
  7552. UploadFormDataItems items{
  7553. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7554. {"hello", "world", "", ""},
  7555. };
  7556. auto res = cli.Post("/post", items);
  7557. ASSERT_TRUE(res);
  7558. ASSERT_EQ(StatusCode::OK_200, res->status);
  7559. }
  7560. }
  7561. TEST(MultipartFormDataTest, DataProviderItems) {
  7562. std::random_device seed_gen;
  7563. std::mt19937 random(seed_gen());
  7564. std::string rand1;
  7565. rand1.resize(1000);
  7566. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7567. std::string rand2;
  7568. rand2.resize(3000);
  7569. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7571. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7572. const ContentReader &content_reader) {
  7573. ASSERT_FALSE(req.is_multipart_form_data());
  7574. std::string body;
  7575. content_reader([&](const char *data, size_t data_length) {
  7576. body.append(data, data_length);
  7577. return true;
  7578. });
  7579. EXPECT_EQ(body, "");
  7580. });
  7581. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7582. const ContentReader &content_reader) {
  7583. ASSERT_TRUE(req.is_multipart_form_data());
  7584. std::vector<FormData> items;
  7585. content_reader(
  7586. [&](const FormData &file) {
  7587. items.push_back(file);
  7588. return true;
  7589. },
  7590. [&](const char *data, size_t data_length) {
  7591. items.back().content.append(data, data_length);
  7592. return true;
  7593. });
  7594. ASSERT_TRUE(items.size() == 2);
  7595. EXPECT_EQ(std::string(items[0].name), "name1");
  7596. EXPECT_EQ(items[0].content, "Testing123");
  7597. EXPECT_EQ(items[0].filename, "filename1");
  7598. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7599. EXPECT_EQ(items[1].name, "name2");
  7600. EXPECT_EQ(items[1].content, "Testing456");
  7601. EXPECT_EQ(items[1].filename, "");
  7602. EXPECT_EQ(items[1].content_type, "");
  7603. });
  7604. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7605. const ContentReader &content_reader) {
  7606. ASSERT_TRUE(req.is_multipart_form_data());
  7607. std::vector<FormData> items;
  7608. content_reader(
  7609. [&](const FormData &file) {
  7610. items.push_back(file);
  7611. return true;
  7612. },
  7613. [&](const char *data, size_t data_length) {
  7614. items.back().content.append(data, data_length);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(items.size() == 2);
  7618. EXPECT_EQ(items[0].name, "name3");
  7619. EXPECT_EQ(items[0].content, rand1);
  7620. EXPECT_EQ(items[0].filename, "filename3");
  7621. EXPECT_EQ(items[0].content_type, "");
  7622. EXPECT_EQ(items[1].name, "name4");
  7623. EXPECT_EQ(items[1].content, rand2);
  7624. EXPECT_EQ(items[1].filename, "filename4");
  7625. EXPECT_EQ(items[1].content_type, "");
  7626. });
  7627. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7628. const ContentReader &content_reader) {
  7629. ASSERT_TRUE(req.is_multipart_form_data());
  7630. std::vector<FormData> items;
  7631. content_reader(
  7632. [&](const FormData &file) {
  7633. items.push_back(file);
  7634. return true;
  7635. },
  7636. [&](const char *data, size_t data_length) {
  7637. items.back().content.append(data, data_length);
  7638. return true;
  7639. });
  7640. ASSERT_TRUE(items.size() == 4);
  7641. EXPECT_EQ(std::string(items[0].name), "name1");
  7642. EXPECT_EQ(items[0].content, "Testing123");
  7643. EXPECT_EQ(items[0].filename, "filename1");
  7644. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7645. EXPECT_EQ(items[1].name, "name2");
  7646. EXPECT_EQ(items[1].content, "Testing456");
  7647. EXPECT_EQ(items[1].filename, "");
  7648. EXPECT_EQ(items[1].content_type, "");
  7649. EXPECT_EQ(items[2].name, "name3");
  7650. EXPECT_EQ(items[2].content, rand1);
  7651. EXPECT_EQ(items[2].filename, "filename3");
  7652. EXPECT_EQ(items[2].content_type, "");
  7653. EXPECT_EQ(items[3].name, "name4");
  7654. EXPECT_EQ(items[3].content, rand2);
  7655. EXPECT_EQ(items[3].filename, "filename4");
  7656. EXPECT_EQ(items[3].content_type, "");
  7657. });
  7658. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7659. auto se = detail::scope_exit([&] {
  7660. svr.stop();
  7661. t.join();
  7662. ASSERT_FALSE(svr.is_running());
  7663. });
  7664. svr.wait_until_ready();
  7665. {
  7666. Client cli("https://localhost:8080");
  7667. cli.enable_server_certificate_verification(false);
  7668. UploadFormDataItems items{
  7669. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7670. {"name2", "Testing456", "", ""}, // not a file
  7671. };
  7672. {
  7673. auto res = cli.Post("/post-none", {}, {}, {});
  7674. ASSERT_TRUE(res);
  7675. ASSERT_EQ(StatusCode::OK_200, res->status);
  7676. }
  7677. FormDataProviderItems providers;
  7678. {
  7679. auto res =
  7680. cli.Post("/post-items", {}, items, providers); // empty providers
  7681. ASSERT_TRUE(res);
  7682. ASSERT_EQ(StatusCode::OK_200, res->status);
  7683. }
  7684. providers.push_back({"name3",
  7685. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7686. // test the offset is given correctly at each step
  7687. if (!offset)
  7688. sink.os.write(rand1.data(), 30);
  7689. else if (offset == 30)
  7690. sink.os.write(rand1.data() + 30, 300);
  7691. else if (offset == 330)
  7692. sink.os.write(rand1.data() + 330, 670);
  7693. else if (offset == rand1.size())
  7694. sink.done();
  7695. return true;
  7696. },
  7697. "filename3",
  7698. {}});
  7699. providers.push_back({"name4",
  7700. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7701. // test the offset is given correctly at each step
  7702. if (!offset)
  7703. sink.os.write(rand2.data(), 2000);
  7704. else if (offset == 2000)
  7705. sink.os.write(rand2.data() + 2000, 1);
  7706. else if (offset == 2001)
  7707. sink.os.write(rand2.data() + 2001, 999);
  7708. else if (offset == rand2.size())
  7709. sink.done();
  7710. return true;
  7711. },
  7712. "filename4",
  7713. {}});
  7714. {
  7715. auto res = cli.Post("/post-providers", {}, {}, providers);
  7716. ASSERT_TRUE(res);
  7717. ASSERT_EQ(StatusCode::OK_200, res->status);
  7718. }
  7719. {
  7720. auto res = cli.Post("/post-both", {}, items, providers);
  7721. ASSERT_TRUE(res);
  7722. ASSERT_EQ(StatusCode::OK_200, res->status);
  7723. }
  7724. }
  7725. }
  7726. TEST(MultipartFormDataTest, BadHeader) {
  7727. Server svr;
  7728. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7729. res.set_content("ok", "text/plain");
  7730. });
  7731. thread t = thread([&] { svr.listen(HOST, PORT); });
  7732. auto se = detail::scope_exit([&] {
  7733. svr.stop();
  7734. t.join();
  7735. ASSERT_FALSE(svr.is_running());
  7736. });
  7737. svr.wait_until_ready();
  7738. const std::string body =
  7739. "This is the preamble. It is to be ignored, though it\r\n"
  7740. "is a handy place for composition agents to include an\r\n"
  7741. "explanatory note to non-MIME conformant readers.\r\n"
  7742. "\r\n"
  7743. "\r\n"
  7744. "--simple boundary\r\n"
  7745. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7746. ": BAD...\r\n"
  7747. "\r\n"
  7748. "value1\r\n"
  7749. "--simple boundary\r\n"
  7750. "Content-Disposition: form-data; name=\"field2\"; "
  7751. "filename=\"example.txt\"\r\n"
  7752. "\r\n"
  7753. "value2\r\n"
  7754. "--simple boundary--\r\n"
  7755. "This is the epilogue. It is also to be ignored.\r\n";
  7756. std::string content_type =
  7757. R"(multipart/form-data; boundary="simple boundary")";
  7758. Client cli(HOST, PORT);
  7759. auto res = cli.Post("/post", body, content_type.c_str());
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7762. }
  7763. TEST(MultipartFormDataTest, WithPreamble) {
  7764. Server svr;
  7765. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7766. res.set_content("ok", "text/plain");
  7767. });
  7768. thread t = thread([&] { svr.listen(HOST, PORT); });
  7769. auto se = detail::scope_exit([&] {
  7770. svr.stop();
  7771. t.join();
  7772. ASSERT_FALSE(svr.is_running());
  7773. });
  7774. svr.wait_until_ready();
  7775. const std::string body =
  7776. "This is the preamble. It is to be ignored, though it\r\n"
  7777. "is a handy place for composition agents to include an\r\n"
  7778. "explanatory note to non-MIME conformant readers.\r\n"
  7779. "\r\n"
  7780. "\r\n"
  7781. "--simple boundary\r\n"
  7782. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7783. "\r\n"
  7784. "value1\r\n"
  7785. "--simple boundary\r\n"
  7786. "Content-Disposition: form-data; name=\"field2\"; "
  7787. "filename=\"example.txt\"\r\n"
  7788. "\r\n"
  7789. "value2\r\n"
  7790. "--simple boundary--\r\n"
  7791. "This is the epilogue. It is also to be ignored.\r\n";
  7792. std::string content_type =
  7793. R"(multipart/form-data; boundary="simple boundary")";
  7794. Client cli(HOST, PORT);
  7795. auto res = cli.Post("/post", body, content_type.c_str());
  7796. ASSERT_TRUE(res);
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. }
  7799. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7801. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7802. const ContentReader &content_reader) {
  7803. if (req.is_multipart_form_data()) {
  7804. std::vector<FormData> items;
  7805. content_reader(
  7806. [&](const FormData &file) {
  7807. items.push_back(file);
  7808. return true;
  7809. },
  7810. [&](const char *data, size_t data_length) {
  7811. items.back().content.append(data, data_length);
  7812. return true;
  7813. });
  7814. EXPECT_TRUE(std::string(items[0].name) == "document");
  7815. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7816. EXPECT_TRUE(items[0].filename == "2MB_data");
  7817. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7818. EXPECT_TRUE(items[1].name == "hello");
  7819. EXPECT_TRUE(items[1].content == "world");
  7820. EXPECT_TRUE(items[1].filename == "");
  7821. EXPECT_TRUE(items[1].content_type == "");
  7822. } else {
  7823. std::string body;
  7824. content_reader([&](const char *data, size_t data_length) {
  7825. body.append(data, data_length);
  7826. return true;
  7827. });
  7828. }
  7829. });
  7830. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7831. auto se = detail::scope_exit([&] {
  7832. svr.stop();
  7833. t.join();
  7834. ASSERT_FALSE(svr.is_running());
  7835. });
  7836. svr.wait_until_ready();
  7837. {
  7838. std::string data(1024 * 1024 * 2, '.');
  7839. std::stringstream buffer;
  7840. buffer << data;
  7841. Client cli("https://localhost:8080");
  7842. cli.enable_server_certificate_verification(false);
  7843. UploadFormDataItems items{
  7844. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7845. {"hello", "world", "", ""},
  7846. };
  7847. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7848. ASSERT_TRUE(res);
  7849. ASSERT_EQ(StatusCode::OK_200, res->status);
  7850. }
  7851. }
  7852. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7853. std::string data(1024 * 1024 * 2, '&');
  7854. std::stringstream buffer;
  7855. buffer << data;
  7856. Client cli("https://localhost:8080");
  7857. UploadFormDataItems items{
  7858. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7859. {"hello", "world", "", ""},
  7860. };
  7861. for (const char &c : " \t\r\n") {
  7862. auto res =
  7863. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7864. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7865. ASSERT_FALSE(res);
  7866. }
  7867. }
  7868. TEST(MultipartFormDataTest, PutFormData) {
  7869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7870. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7871. const ContentReader &content_reader) {
  7872. if (req.is_multipart_form_data()) {
  7873. std::vector<FormData> items;
  7874. content_reader(
  7875. [&](const FormData &file) {
  7876. items.push_back(file);
  7877. return true;
  7878. },
  7879. [&](const char *data, size_t data_length) {
  7880. items.back().content.append(data, data_length);
  7881. return true;
  7882. });
  7883. EXPECT_TRUE(std::string(items[0].name) == "document");
  7884. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7885. EXPECT_TRUE(items[0].filename == "2MB_data");
  7886. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7887. EXPECT_TRUE(items[1].name == "hello");
  7888. EXPECT_TRUE(items[1].content == "world");
  7889. EXPECT_TRUE(items[1].filename == "");
  7890. EXPECT_TRUE(items[1].content_type == "");
  7891. } else {
  7892. std::string body;
  7893. content_reader([&](const char *data, size_t data_length) {
  7894. body.append(data, data_length);
  7895. return true;
  7896. });
  7897. }
  7898. });
  7899. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7900. auto se = detail::scope_exit([&] {
  7901. svr.stop();
  7902. t.join();
  7903. ASSERT_FALSE(svr.is_running());
  7904. });
  7905. svr.wait_until_ready();
  7906. {
  7907. std::string data(1024 * 1024 * 2, '&');
  7908. std::stringstream buffer;
  7909. buffer << data;
  7910. Client cli("https://localhost:8080");
  7911. cli.enable_server_certificate_verification(false);
  7912. UploadFormDataItems items{
  7913. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7914. {"hello", "world", "", ""},
  7915. };
  7916. auto res = cli.Put("/put", items);
  7917. ASSERT_TRUE(res);
  7918. ASSERT_EQ(StatusCode::OK_200, res->status);
  7919. }
  7920. }
  7921. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7923. svr.Put("/put_customboundary",
  7924. [&](const Request &req, const Response & /*res*/,
  7925. const ContentReader &content_reader) {
  7926. if (req.is_multipart_form_data()) {
  7927. std::vector<FormData> items;
  7928. content_reader(
  7929. [&](const FormData &file) {
  7930. items.push_back(file);
  7931. return true;
  7932. },
  7933. [&](const char *data, size_t data_length) {
  7934. items.back().content.append(data, data_length);
  7935. return true;
  7936. });
  7937. EXPECT_TRUE(std::string(items[0].name) == "document");
  7938. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7939. EXPECT_TRUE(items[0].filename == "2MB_data");
  7940. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7941. EXPECT_TRUE(items[1].name == "hello");
  7942. EXPECT_TRUE(items[1].content == "world");
  7943. EXPECT_TRUE(items[1].filename == "");
  7944. EXPECT_TRUE(items[1].content_type == "");
  7945. } else {
  7946. std::string body;
  7947. content_reader([&](const char *data, size_t data_length) {
  7948. body.append(data, data_length);
  7949. return true;
  7950. });
  7951. }
  7952. });
  7953. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7954. auto se = detail::scope_exit([&] {
  7955. svr.stop();
  7956. t.join();
  7957. ASSERT_FALSE(svr.is_running());
  7958. });
  7959. svr.wait_until_ready();
  7960. {
  7961. std::string data(1024 * 1024 * 2, '&');
  7962. std::stringstream buffer;
  7963. buffer << data;
  7964. Client cli("https://localhost:8080");
  7965. cli.enable_server_certificate_verification(false);
  7966. UploadFormDataItems items{
  7967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7968. {"hello", "world", "", ""},
  7969. };
  7970. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7971. ASSERT_TRUE(res);
  7972. ASSERT_EQ(StatusCode::OK_200, res->status);
  7973. }
  7974. }
  7975. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7976. std::string data(1024 * 1024 * 2, '&');
  7977. std::stringstream buffer;
  7978. buffer << data;
  7979. Client cli("https://localhost:8080");
  7980. cli.enable_server_certificate_verification(false);
  7981. UploadFormDataItems items{
  7982. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7983. {"hello", "world", "", ""},
  7984. };
  7985. for (const char &c : " \t\r\n") {
  7986. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7988. ASSERT_FALSE(res);
  7989. }
  7990. }
  7991. TEST(MultipartFormDataTest, AlternateFilename) {
  7992. auto handled = false;
  7993. Server svr;
  7994. svr.Post("/test", [&](const Request &req, Response &res) {
  7995. ASSERT_EQ(2u, req.form.files.size());
  7996. ASSERT_EQ(1u, req.form.fields.size());
  7997. // Test files
  7998. const auto &file1 = req.form.get_file("file1");
  7999. ASSERT_EQ("file1", file1.name);
  8000. ASSERT_EQ("A.txt", file1.filename);
  8001. ASSERT_EQ("text/plain", file1.content_type);
  8002. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8003. const auto &file2 = req.form.get_file("file2");
  8004. ASSERT_EQ("file2", file2.name);
  8005. ASSERT_EQ("a.html", file2.filename);
  8006. ASSERT_EQ("text/html", file2.content_type);
  8007. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8008. file2.content);
  8009. // Test text field
  8010. const auto &text = req.form.get_field("text");
  8011. ASSERT_EQ("text default", text);
  8012. res.set_content("ok", "text/plain");
  8013. handled = true;
  8014. });
  8015. thread t = thread([&] { svr.listen(HOST, PORT); });
  8016. auto se = detail::scope_exit([&] {
  8017. svr.stop();
  8018. t.join();
  8019. ASSERT_FALSE(svr.is_running());
  8020. ASSERT_TRUE(handled);
  8021. });
  8022. svr.wait_until_ready();
  8023. auto req = "POST /test HTTP/1.1\r\n"
  8024. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8025. "Content-Length: 399\r\n"
  8026. "\r\n"
  8027. "----------\r\n"
  8028. "Content-Disposition: form-data; name=\"text\"\r\n"
  8029. "\r\n"
  8030. "text default\r\n"
  8031. "----------\r\n"
  8032. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8033. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8034. "Content-Type: text/plain\r\n"
  8035. "\r\n"
  8036. "Content of a.txt.\r\n"
  8037. "\r\n"
  8038. "----------\r\n"
  8039. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8040. "\"a.html\"\r\n"
  8041. "Content-Type: text/html\r\n"
  8042. "\r\n"
  8043. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8044. "\r\n"
  8045. "------------\r\n";
  8046. ASSERT_TRUE(send_request(1, req));
  8047. }
  8048. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8049. auto handled = false;
  8050. Server svr;
  8051. svr.Post("/test", [&](const Request &req, Response &) {
  8052. ASSERT_EQ(2u, req.form.fields.size());
  8053. const auto &text1 = req.form.get_field("text1");
  8054. ASSERT_EQ("text1", text1);
  8055. const auto &text2 = req.form.get_field("text2");
  8056. ASSERT_EQ("text2", text2);
  8057. handled = true;
  8058. });
  8059. thread t = thread([&] { svr.listen(HOST, PORT); });
  8060. auto se = detail::scope_exit([&] {
  8061. svr.stop();
  8062. t.join();
  8063. ASSERT_FALSE(svr.is_running());
  8064. ASSERT_TRUE(handled);
  8065. });
  8066. svr.wait_until_ready();
  8067. auto req = "POST /test HTTP/1.1\r\n"
  8068. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8069. "Content-Length: 146\r\n"
  8070. "\r\n----------\r\n"
  8071. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8072. "\r\n"
  8073. "text1"
  8074. "\r\n----------\r\n"
  8075. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8076. "\r\n"
  8077. "text2"
  8078. "\r\n------------";
  8079. std::string response;
  8080. ASSERT_TRUE(send_request(1, req, &response));
  8081. ASSERT_EQ("200", response.substr(9, 3));
  8082. }
  8083. TEST(MultipartFormDataTest, ContentLength) {
  8084. auto handled = false;
  8085. Server svr;
  8086. svr.Post("/test", [&](const Request &req, Response &) {
  8087. ASSERT_EQ(2u, req.form.fields.size());
  8088. const auto &text1 = req.form.get_field("text1");
  8089. ASSERT_EQ("text1", text1);
  8090. const auto &text2 = req.form.get_field("text2");
  8091. ASSERT_EQ("text2", text2);
  8092. handled = true;
  8093. });
  8094. thread t = thread([&] { svr.listen(HOST, PORT); });
  8095. auto se = detail::scope_exit([&] {
  8096. svr.stop();
  8097. t.join();
  8098. ASSERT_FALSE(svr.is_running());
  8099. ASSERT_TRUE(handled);
  8100. });
  8101. svr.wait_until_ready();
  8102. auto req = "POST /test HTTP/1.1\r\n"
  8103. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8104. "Content-Length: 167\r\n"
  8105. "\r\n----------\r\n"
  8106. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8107. "Content-Length: 5\r\n"
  8108. "\r\n"
  8109. "text1"
  8110. "\r\n----------\r\n"
  8111. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8112. "\r\n"
  8113. "text2"
  8114. "\r\n------------\r\n";
  8115. std::string response;
  8116. ASSERT_TRUE(send_request(1, req, &response));
  8117. ASSERT_EQ("200", response.substr(9, 3));
  8118. }
  8119. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8120. auto handled = false;
  8121. Server svr;
  8122. svr.Post("/test", [&](const Request &req, Response &) {
  8123. ASSERT_EQ(2u, req.form.fields.size());
  8124. const auto &text1 = req.form.get_field("text1");
  8125. ASSERT_EQ("text1", text1);
  8126. // TODO: Add header access for text fields if needed
  8127. const auto &text2 = req.form.get_field("text2");
  8128. ASSERT_EQ("text2", text2);
  8129. // TODO: Header access for text fields needs to be implemented
  8130. // auto &headers = it->second.headers;
  8131. // ASSERT_EQ(3U, headers.size());
  8132. // auto custom_header = headers.find("x-whatever");
  8133. // ASSERT_TRUE(custom_header != headers.end());
  8134. // ASSERT_NE("customvalue", custom_header->second);
  8135. // ASSERT_EQ("CustomValue", custom_header->second);
  8136. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8137. handled = true;
  8138. });
  8139. thread t = thread([&] { svr.listen(HOST, PORT); });
  8140. auto se = detail::scope_exit([&] {
  8141. svr.stop();
  8142. t.join();
  8143. ASSERT_FALSE(svr.is_running());
  8144. ASSERT_TRUE(handled);
  8145. });
  8146. svr.wait_until_ready();
  8147. auto req = "POST /test HTTP/1.1\r\n"
  8148. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8149. "Content-Length: 232\r\n"
  8150. "\r\n----------\r\n"
  8151. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8152. "Content-Length: 5\r\n"
  8153. "X-Test: 1\r\n"
  8154. "\r\n"
  8155. "text1"
  8156. "\r\n----------\r\n"
  8157. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8158. "Content-Type: text/plain\r\n"
  8159. "X-Whatever: CustomValue\r\n"
  8160. "\r\n"
  8161. "text2"
  8162. "\r\n------------\r\n"
  8163. "That should be disregarded. Not even read";
  8164. std::string response;
  8165. ASSERT_TRUE(send_request(1, req, &response));
  8166. ASSERT_EQ("200", response.substr(9, 3));
  8167. }
  8168. #endif
  8169. TEST(MultipartFormDataTest, LargeHeader) {
  8170. auto handled = false;
  8171. Server svr;
  8172. svr.Post("/test", [&](const Request &req, Response &) {
  8173. ASSERT_EQ(1u, req.form.fields.size());
  8174. const auto &text = req.form.get_field("name1");
  8175. ASSERT_EQ("text1", text);
  8176. handled = true;
  8177. });
  8178. thread t = thread([&] { svr.listen(HOST, PORT); });
  8179. auto se = detail::scope_exit([&] {
  8180. svr.stop();
  8181. t.join();
  8182. ASSERT_FALSE(svr.is_running());
  8183. ASSERT_TRUE(handled);
  8184. });
  8185. svr.wait_until_ready();
  8186. auto boundary = std::string("cpp-httplib-multipart-data");
  8187. std::string content = "--" + boundary +
  8188. "\r\n"
  8189. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8190. "\r\n"
  8191. "text1\r\n"
  8192. "--" +
  8193. boundary + "--\r\n";
  8194. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8195. "Content-Type: multipart/form-data;boundary=" +
  8196. boundary +
  8197. "\r\n"
  8198. "Content-Length: " +
  8199. std::to_string(content.size()) +
  8200. "\r\n"
  8201. "Dummy-Header: ";
  8202. std::string header_suffix = "\r\n"
  8203. "\r\n";
  8204. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8205. size_t header_dummy_size =
  8206. read_buff_size -
  8207. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8208. auto header_dummy = std::string(header_dummy_size, '@');
  8209. auto req = header_prefix + header_dummy + header_suffix + content;
  8210. std::string response;
  8211. ASSERT_TRUE(send_request(1, req, &response));
  8212. ASSERT_EQ("200", response.substr(9, 3));
  8213. }
  8214. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8215. static constexpr unsigned int number_of_tasks{1000000};
  8216. std::atomic_uint count{0};
  8217. std::unique_ptr<TaskQueue> task_queue{
  8218. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8219. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8220. auto queued = task_queue->enqueue(
  8221. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8222. EXPECT_TRUE(queued);
  8223. }
  8224. EXPECT_NO_THROW(task_queue->shutdown());
  8225. EXPECT_EQ(number_of_tasks, count.load());
  8226. }
  8227. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8228. static constexpr unsigned int number_of_tasks{1000000};
  8229. static constexpr unsigned int qlimit{2};
  8230. unsigned int queued_count{0};
  8231. std::atomic_uint count{0};
  8232. std::unique_ptr<TaskQueue> task_queue{
  8233. new ThreadPool{/*num_threads=*/1, qlimit}};
  8234. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8235. if (task_queue->enqueue(
  8236. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8237. queued_count++;
  8238. }
  8239. }
  8240. EXPECT_NO_THROW(task_queue->shutdown());
  8241. EXPECT_EQ(queued_count, count.load());
  8242. EXPECT_TRUE(queued_count <= number_of_tasks);
  8243. EXPECT_TRUE(queued_count >= qlimit);
  8244. }
  8245. TEST(TaskQueueTest, MaxQueuedRequests) {
  8246. static constexpr unsigned int qlimit{3};
  8247. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8248. std::condition_variable sem_cv;
  8249. std::mutex sem_mtx;
  8250. int credits = 0;
  8251. bool queued;
  8252. /* Fill up the queue with tasks that will block until we give them credits to
  8253. * complete. */
  8254. for (unsigned int n = 0; n <= qlimit;) {
  8255. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8256. std::unique_lock<std::mutex> lock(sem_mtx);
  8257. while (credits <= 0) {
  8258. sem_cv.wait(lock);
  8259. }
  8260. /* Consume the credit and signal the test code if they are all gone. */
  8261. if (--credits == 0) { sem_cv.notify_one(); }
  8262. });
  8263. if (n < qlimit) {
  8264. /* The first qlimit enqueues must succeed. */
  8265. EXPECT_TRUE(queued);
  8266. } else {
  8267. /* The last one will succeed only when the worker thread
  8268. * starts and dequeues the first blocking task. Although
  8269. * not necessary for the correctness of this test, we sleep for
  8270. * a short while to avoid busy waiting. */
  8271. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8272. }
  8273. if (queued) { n++; }
  8274. }
  8275. /* Further enqueues must fail since the queue is full. */
  8276. for (auto i = 0; i < 4; i++) {
  8277. queued = task_queue->enqueue([] {});
  8278. EXPECT_FALSE(queued);
  8279. }
  8280. /* Give the credits to allow the previous tasks to complete. */
  8281. {
  8282. std::unique_lock<std::mutex> lock(sem_mtx);
  8283. credits += qlimit + 1;
  8284. }
  8285. sem_cv.notify_all();
  8286. /* Wait for all the credits to be consumed. */
  8287. {
  8288. std::unique_lock<std::mutex> lock(sem_mtx);
  8289. while (credits > 0) {
  8290. sem_cv.wait(lock);
  8291. }
  8292. }
  8293. /* Check that we are able again to enqueue at least qlimit tasks. */
  8294. for (unsigned int i = 0; i < qlimit; i++) {
  8295. queued = task_queue->enqueue([] {});
  8296. EXPECT_TRUE(queued);
  8297. }
  8298. EXPECT_NO_THROW(task_queue->shutdown());
  8299. }
  8300. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8301. Server svr;
  8302. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8303. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8304. });
  8305. svr.Get("/hello", [](const Request &req, Response &res) {
  8306. res.set_content(req.get_param_value("key"), "text/plain");
  8307. });
  8308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8309. auto se = detail::scope_exit([&] {
  8310. svr.stop();
  8311. thread.join();
  8312. ASSERT_FALSE(svr.is_running());
  8313. });
  8314. svr.wait_until_ready();
  8315. {
  8316. Client cli(HOST, PORT);
  8317. cli.set_follow_location(true);
  8318. auto res = cli.Get("/");
  8319. ASSERT_TRUE(res);
  8320. EXPECT_EQ(StatusCode::OK_200, res->status);
  8321. EXPECT_EQ("val&key2=val2", res->body);
  8322. }
  8323. }
  8324. TEST(VulnerabilityTest, CRLFInjection) {
  8325. Server svr;
  8326. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8327. res.set_content("Hello 1", "text/plain");
  8328. });
  8329. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8330. res.set_content("Hello 2", "text/plain");
  8331. });
  8332. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8333. res.set_content("Hello 3", "text/plain");
  8334. });
  8335. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8336. res.set_content("Hello 4", "text/plain");
  8337. });
  8338. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8339. for (const auto &x : req.headers) {
  8340. auto key = x.first;
  8341. EXPECT_STRNE("evil", key.c_str());
  8342. }
  8343. });
  8344. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8345. auto se = detail::scope_exit([&] {
  8346. svr.stop();
  8347. thread.join();
  8348. ASSERT_FALSE(svr.is_running());
  8349. });
  8350. svr.wait_until_ready();
  8351. {
  8352. Client cli(HOST, PORT);
  8353. cli.Post("/test1", "A=B",
  8354. "application/x-www-form-urlencoded\r\nevil: hello1");
  8355. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8356. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8357. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8358. }
  8359. }
  8360. TEST(PathParamsTest, StaticMatch) {
  8361. const auto pattern = "/users/all";
  8362. detail::PathParamsMatcher matcher(pattern);
  8363. Request request;
  8364. request.path = "/users/all";
  8365. ASSERT_TRUE(matcher.match(request));
  8366. std::unordered_map<std::string, std::string> expected_params = {};
  8367. EXPECT_EQ(request.path_params, expected_params);
  8368. }
  8369. TEST(PathParamsTest, StaticMismatch) {
  8370. const auto pattern = "/users/all";
  8371. detail::PathParamsMatcher matcher(pattern);
  8372. Request request;
  8373. request.path = "/users/1";
  8374. ASSERT_FALSE(matcher.match(request));
  8375. }
  8376. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8377. const auto pattern = "/users/:id/subscriptions";
  8378. detail::PathParamsMatcher matcher(pattern);
  8379. Request request;
  8380. request.path = "/users/42/subscriptions";
  8381. ASSERT_TRUE(matcher.match(request));
  8382. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8383. EXPECT_EQ(request.path_params, expected_params);
  8384. }
  8385. TEST(PathParamsTest, SingleParamInTheEnd) {
  8386. const auto pattern = "/users/:id";
  8387. detail::PathParamsMatcher matcher(pattern);
  8388. Request request;
  8389. request.path = "/users/24";
  8390. ASSERT_TRUE(matcher.match(request));
  8391. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8392. EXPECT_EQ(request.path_params, expected_params);
  8393. }
  8394. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8395. const auto pattern = "/users/:id/";
  8396. detail::PathParamsMatcher matcher(pattern);
  8397. Request request;
  8398. request.path = "/users/42/";
  8399. ASSERT_TRUE(matcher.match(request));
  8400. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8401. EXPECT_EQ(request.path_params, expected_params);
  8402. }
  8403. TEST(PathParamsTest, EmptyParam) {
  8404. const auto pattern = "/users/:id/";
  8405. detail::PathParamsMatcher matcher(pattern);
  8406. Request request;
  8407. request.path = "/users//";
  8408. ASSERT_TRUE(matcher.match(request));
  8409. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8410. EXPECT_EQ(request.path_params, expected_params);
  8411. }
  8412. TEST(PathParamsTest, FragmentMismatch) {
  8413. const auto pattern = "/users/:id/";
  8414. detail::PathParamsMatcher matcher(pattern);
  8415. Request request;
  8416. request.path = "/admins/24/";
  8417. ASSERT_FALSE(matcher.match(request));
  8418. }
  8419. TEST(PathParamsTest, ExtraFragments) {
  8420. const auto pattern = "/users/:id";
  8421. detail::PathParamsMatcher matcher(pattern);
  8422. Request request;
  8423. request.path = "/users/42/subscriptions";
  8424. ASSERT_FALSE(matcher.match(request));
  8425. }
  8426. TEST(PathParamsTest, MissingTrailingParam) {
  8427. const auto pattern = "/users/:id";
  8428. detail::PathParamsMatcher matcher(pattern);
  8429. Request request;
  8430. request.path = "/users";
  8431. ASSERT_FALSE(matcher.match(request));
  8432. }
  8433. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8434. const auto pattern = "/users/:id/subscriptions";
  8435. detail::PathParamsMatcher matcher(pattern);
  8436. Request request;
  8437. request.path = "/users/subscriptions";
  8438. ASSERT_FALSE(matcher.match(request));
  8439. }
  8440. TEST(PathParamsTest, MultipleParams) {
  8441. const auto pattern = "/users/:userid/subscriptions/:subid";
  8442. detail::PathParamsMatcher matcher(pattern);
  8443. Request request;
  8444. request.path = "/users/42/subscriptions/2";
  8445. ASSERT_TRUE(matcher.match(request));
  8446. std::unordered_map<std::string, std::string> expected_params = {
  8447. {"userid", "42"}, {"subid", "2"}};
  8448. EXPECT_EQ(request.path_params, expected_params);
  8449. }
  8450. TEST(PathParamsTest, SequenceOfParams) {
  8451. const auto pattern = "/values/:x/:y/:z";
  8452. detail::PathParamsMatcher matcher(pattern);
  8453. Request request;
  8454. request.path = "/values/1/2/3";
  8455. ASSERT_TRUE(matcher.match(request));
  8456. std::unordered_map<std::string, std::string> expected_params = {
  8457. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8458. EXPECT_EQ(request.path_params, expected_params);
  8459. }
  8460. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8461. const auto pattern = "/prefix:suffix";
  8462. detail::PathParamsMatcher matcher(pattern);
  8463. Request request;
  8464. request.path = "/prefix:suffix";
  8465. ASSERT_TRUE(matcher.match(request));
  8466. const std::unordered_map<std::string, std::string> expected_params = {};
  8467. EXPECT_EQ(request.path_params, expected_params);
  8468. }
  8469. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8470. // If ipv6 regex working, regex match codepath is taken.
  8471. // else port will default to 80 in Client impl
  8472. int clientImplMagicPort = 80;
  8473. int port = 4321;
  8474. // above ports must be different to avoid false negative
  8475. EXPECT_NE(clientImplMagicPort, port);
  8476. std::string ipV6TestURL = "http://[ff06::c3]";
  8477. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8478. CLIENT_PRIVATE_KEY_FILE);
  8479. EXPECT_EQ(cli.port(), port);
  8480. }
  8481. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8482. auto file_path = "./www/dir/index.html";
  8483. auto dir_path = "./www/dir";
  8484. detail::FileStat stat_file(file_path);
  8485. EXPECT_TRUE(stat_file.is_file());
  8486. EXPECT_FALSE(stat_file.is_dir());
  8487. detail::FileStat stat_dir(dir_path);
  8488. EXPECT_FALSE(stat_dir.is_file());
  8489. EXPECT_TRUE(stat_dir.is_dir());
  8490. }
  8491. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8492. Server svr;
  8493. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8494. EXPECT_EQ(res.status, 400);
  8495. });
  8496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8497. auto se = detail::scope_exit([&] {
  8498. svr.stop();
  8499. thread.join();
  8500. ASSERT_FALSE(svr.is_running());
  8501. });
  8502. svr.wait_until_ready();
  8503. Client cli(HOST, PORT);
  8504. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8505. }
  8506. TEST(InvalidHeaderCharsTest, is_field_name) {
  8507. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8508. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8509. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8510. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8511. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8512. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8513. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8514. EXPECT_FALSE(detail::fields::is_field_name(""));
  8515. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8516. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8517. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8518. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8519. }
  8520. TEST(InvalidHeaderCharsTest, is_field_value) {
  8521. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8522. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8523. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8524. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8525. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8526. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8527. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8528. EXPECT_TRUE(detail::fields::is_field_value(""));
  8529. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8530. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8531. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8532. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8533. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8534. }
  8535. TEST(InvalidHeaderCharsTest, OnServer) {
  8536. Server svr;
  8537. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8538. std::string header = "Not Set";
  8539. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8540. res.set_header(header, "value");
  8541. res.set_content("Page Content Page Content", "text/plain");
  8542. });
  8543. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8544. std::string header = "Not Set";
  8545. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8546. res.set_header("X-Test", header);
  8547. res.set_content("Page Content Page Content", "text/plain");
  8548. });
  8549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. thread.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. Client cli(HOST, PORT);
  8557. {
  8558. auto res = cli.Get(
  8559. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8560. ASSERT_TRUE(res);
  8561. EXPECT_EQ("Page Content Page Content", res->body);
  8562. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8563. }
  8564. {
  8565. auto res = cli.Get(
  8566. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8567. ASSERT_TRUE(res);
  8568. EXPECT_EQ("Page Content Page Content", res->body);
  8569. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8570. }
  8571. }
  8572. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8573. auto handled = false;
  8574. Server svr;
  8575. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8576. thread t = thread([&] { svr.listen(HOST, PORT); });
  8577. auto se = detail::scope_exit([&] {
  8578. svr.stop();
  8579. t.join();
  8580. ASSERT_FALSE(svr.is_running());
  8581. ASSERT_FALSE(handled);
  8582. });
  8583. svr.wait_until_ready();
  8584. auto req = "POST /test HTTP/1.1\r\n"
  8585. "Content-Length: x\r\n"
  8586. "\r\n";
  8587. std::string response;
  8588. ASSERT_TRUE(send_request(1, req, &response));
  8589. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8590. response.substr(0, response.find("\r\n")));
  8591. }
  8592. #ifndef _WIN32
  8593. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8594. static constexpr char reject[] = "Unauthorized";
  8595. static constexpr char accept[] = "Upload accepted";
  8596. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8597. Server svr;
  8598. svr.set_expect_100_continue_handler(
  8599. [](const Request & /*req*/, Response &res) {
  8600. res.status = StatusCode::Unauthorized_401;
  8601. res.set_content(reject, "text/plain");
  8602. return res.status;
  8603. });
  8604. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8605. res.set_content(accept, "text/plain");
  8606. });
  8607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8608. auto se = detail::scope_exit([&] {
  8609. svr.stop();
  8610. thread.join();
  8611. ASSERT_FALSE(svr.is_running());
  8612. });
  8613. svr.wait_until_ready();
  8614. {
  8615. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8616. curl_easy_init(), &curl_easy_cleanup};
  8617. ASSERT_NE(curl, nullptr);
  8618. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8619. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8620. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8621. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8622. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8623. &curl_slist_free_all};
  8624. ASSERT_NE(list, nullptr);
  8625. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8626. struct read_data {
  8627. size_t read_size;
  8628. size_t total_size;
  8629. } data = {0, total_size};
  8630. using read_callback_t =
  8631. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8632. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8633. void *userdata) -> size_t {
  8634. read_data *data = (read_data *)userdata;
  8635. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8636. std::fill_n(ptr, size * nmemb, 'A');
  8637. data->read_size += size * nmemb;
  8638. return size * nmemb;
  8639. };
  8640. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8641. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8642. std::vector<char> buffer;
  8643. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8644. using write_callback_t =
  8645. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8646. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8647. void *userdata) -> size_t {
  8648. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8649. buffer->reserve(buffer->size() + size * nmemb + 1);
  8650. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8651. return size * nmemb;
  8652. };
  8653. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8654. {
  8655. const auto res = curl_easy_perform(curl.get());
  8656. ASSERT_EQ(res, CURLE_OK);
  8657. }
  8658. {
  8659. auto response_code = long{};
  8660. const auto res =
  8661. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8662. ASSERT_EQ(res, CURLE_OK);
  8663. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8664. }
  8665. {
  8666. auto dl = curl_off_t{};
  8667. const auto res =
  8668. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8669. ASSERT_EQ(res, CURLE_OK);
  8670. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8671. }
  8672. {
  8673. buffer.push_back('\0');
  8674. ASSERT_STRCASEEQ(buffer.data(), reject);
  8675. }
  8676. }
  8677. }
  8678. #endif
  8679. template <typename S, typename C>
  8680. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8681. svr.Get("/stream", [&](const Request &, Response &res) {
  8682. auto data = new std::string("01234567890123456789");
  8683. res.set_content_provider(
  8684. data->size(), "text/plain",
  8685. [&, data](size_t offset, size_t length, DataSink &sink) {
  8686. const size_t DATA_CHUNK_SIZE = 4;
  8687. const auto &d = *data;
  8688. std::this_thread::sleep_for(std::chrono::seconds(1));
  8689. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8690. return true;
  8691. },
  8692. [data](bool success) {
  8693. EXPECT_FALSE(success);
  8694. delete data;
  8695. });
  8696. });
  8697. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8698. auto i = new size_t(0);
  8699. res.set_content_provider(
  8700. "text/plain",
  8701. [i](size_t, DataSink &sink) {
  8702. if (*i < 5) {
  8703. std::this_thread::sleep_for(std::chrono::seconds(1));
  8704. sink.write("abcd", 4);
  8705. (*i)++;
  8706. } else {
  8707. sink.done();
  8708. }
  8709. return true;
  8710. },
  8711. [i](bool success) {
  8712. EXPECT_FALSE(success);
  8713. delete i;
  8714. });
  8715. });
  8716. svr.Get("/chunked", [&](const Request &, Response &res) {
  8717. auto i = new size_t(0);
  8718. res.set_chunked_content_provider(
  8719. "text/plain",
  8720. [i](size_t, DataSink &sink) {
  8721. if (*i < 5) {
  8722. std::this_thread::sleep_for(std::chrono::seconds(1));
  8723. sink.os << "abcd";
  8724. (*i)++;
  8725. } else {
  8726. sink.done();
  8727. }
  8728. return true;
  8729. },
  8730. [i](bool success) {
  8731. EXPECT_FALSE(success);
  8732. delete i;
  8733. });
  8734. });
  8735. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8736. auto se = detail::scope_exit([&] {
  8737. svr.stop();
  8738. listen_thread.join();
  8739. ASSERT_FALSE(svr.is_running());
  8740. });
  8741. svr.wait_until_ready();
  8742. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8743. {
  8744. auto start = std::chrono::steady_clock::now();
  8745. auto res = cli.Get("/stream");
  8746. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8747. std::chrono::steady_clock::now() - start)
  8748. .count();
  8749. ASSERT_FALSE(res);
  8750. EXPECT_EQ(Error::Read, res.error());
  8751. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8752. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8753. }
  8754. {
  8755. auto start = std::chrono::steady_clock::now();
  8756. auto res = cli.Get("/stream_without_length");
  8757. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8758. std::chrono::steady_clock::now() - start)
  8759. .count();
  8760. ASSERT_FALSE(res);
  8761. EXPECT_EQ(Error::Read, res.error());
  8762. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8763. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8764. }
  8765. {
  8766. auto start = std::chrono::steady_clock::now();
  8767. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8768. EXPECT_EQ("abcd", string(data, data_length));
  8769. return true;
  8770. });
  8771. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8772. std::chrono::steady_clock::now() - start)
  8773. .count();
  8774. ASSERT_FALSE(res);
  8775. EXPECT_EQ(Error::Read, res.error());
  8776. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8777. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8778. }
  8779. }
  8780. TEST(MaxTimeoutTest, ContentStream) {
  8781. time_t timeout = 2000;
  8782. time_t threshold = 200;
  8783. Server svr;
  8784. Client cli("localhost", PORT);
  8785. max_timeout_test(svr, cli, timeout, threshold);
  8786. }
  8787. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8788. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8789. time_t timeout = 2000;
  8790. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8792. SSLClient cli("localhost", PORT);
  8793. cli.enable_server_certificate_verification(false);
  8794. max_timeout_test(svr, cli, timeout, threshold);
  8795. }
  8796. #endif
  8797. class EventDispatcher {
  8798. public:
  8799. EventDispatcher() {}
  8800. void wait_event(DataSink *sink) {
  8801. unique_lock<mutex> lk(m_);
  8802. int id = id_;
  8803. cv_.wait(lk, [&] { return cid_ == id; });
  8804. sink->write(message_.data(), message_.size());
  8805. }
  8806. void send_event(const string &message) {
  8807. lock_guard<mutex> lk(m_);
  8808. cid_ = id_++;
  8809. message_ = message;
  8810. cv_.notify_all();
  8811. }
  8812. private:
  8813. mutex m_;
  8814. condition_variable cv_;
  8815. atomic_int id_{0};
  8816. atomic_int cid_{-1};
  8817. string message_;
  8818. };
  8819. TEST(ClientInThreadTest, Issue2068) {
  8820. EventDispatcher ed;
  8821. Server svr;
  8822. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8823. res.set_chunked_content_provider("text/event-stream",
  8824. [&](size_t /*offset*/, DataSink &sink) {
  8825. ed.wait_event(&sink);
  8826. return true;
  8827. });
  8828. });
  8829. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8830. svr.wait_until_ready();
  8831. thread event_thread([&] {
  8832. int id = 0;
  8833. while (svr.is_running()) {
  8834. this_thread::sleep_for(chrono::milliseconds(500));
  8835. std::stringstream ss;
  8836. ss << "data: " << id << "\n\n";
  8837. ed.send_event(ss.str());
  8838. id++;
  8839. }
  8840. });
  8841. auto se = detail::scope_exit([&] {
  8842. svr.stop();
  8843. listen_thread.join();
  8844. event_thread.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. {
  8848. auto client = detail::make_unique<Client>(HOST, PORT);
  8849. client->set_read_timeout(std::chrono::minutes(10));
  8850. std::atomic<bool> stop{false};
  8851. std::thread t([&] {
  8852. client->Get("/event1",
  8853. [&](const char *, size_t) -> bool { return !stop; });
  8854. });
  8855. std::this_thread::sleep_for(std::chrono::seconds(2));
  8856. stop = true;
  8857. client->stop();
  8858. client.reset();
  8859. t.join();
  8860. }
  8861. }
  8862. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8863. Server svr;
  8864. svr.Get("/", [](const Request &req, Response &res) {
  8865. EXPECT_EQ(2U, req.trailers.size());
  8866. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8867. // Denied
  8868. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8869. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8870. // Accepted
  8871. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8872. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  8873. EXPECT_TRUE(req.has_trailer("X-World"));
  8874. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  8875. res.set_content("ok", "text/plain");
  8876. });
  8877. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8878. auto se = detail::scope_exit([&] {
  8879. svr.stop();
  8880. t.join();
  8881. ASSERT_FALSE(svr.is_running());
  8882. });
  8883. svr.wait_until_ready();
  8884. const std::string req = "GET / HTTP/1.1\r\n"
  8885. "Transfer-Encoding: chunked\r\n"
  8886. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  8887. "\r\n"
  8888. "0\r\n"
  8889. "Content-Length: 10\r\n"
  8890. "Host: internal.local\r\n"
  8891. "Content-Type: malicious/content\r\n"
  8892. "Cookie: any\r\n"
  8893. "Set-Cookie: any\r\n"
  8894. "X-Forwarded-For: attacker.com\r\n"
  8895. "X-Real-Ip: 1.1.1.1\r\n"
  8896. "X-Hello: hello\r\n"
  8897. "X-World: world\r\n"
  8898. "\r\n";
  8899. std::string res;
  8900. ASSERT_TRUE(send_request(1, req, &res));
  8901. }