test.cc 408 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256
  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 <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. auto port = 1234;
  74. Server svr;
  75. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  76. res.set_content("Benchmark Response", "text/plain");
  77. });
  78. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  79. auto se = detail::scope_exit([&] {
  80. svr.stop();
  81. listen_thread.join();
  82. ASSERT_FALSE(svr.is_running());
  83. });
  84. svr.wait_until_ready();
  85. Client cli(host, port);
  86. // Warm-up request to establish connection and resolve DNS
  87. auto warmup_res = cli.Get("/benchmark");
  88. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  89. // Run multiple trials and collect timings
  90. const int num_trials = 20;
  91. std::vector<int64_t> timings;
  92. timings.reserve(num_trials);
  93. for (int i = 0; i < num_trials; i++) {
  94. auto start = std::chrono::high_resolution_clock::now();
  95. auto res = cli.Get("/benchmark");
  96. auto end = std::chrono::high_resolution_clock::now();
  97. auto elapsed =
  98. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  99. .count();
  100. // Assertions after timing measurement to avoid overhead
  101. ASSERT_TRUE(res);
  102. EXPECT_EQ(StatusCode::OK_200, res->status);
  103. timings.push_back(elapsed);
  104. }
  105. // Calculate 25th percentile (lower quartile)
  106. std::sort(timings.begin(), timings.end());
  107. auto p25 = timings[num_trials / 4];
  108. // Format timings for output
  109. std::ostringstream timings_str;
  110. timings_str << "[";
  111. for (size_t i = 0; i < timings.size(); i++) {
  112. if (i > 0) timings_str << ", ";
  113. timings_str << timings[i];
  114. }
  115. timings_str << "]";
  116. // Localhost HTTP GET should be fast even in CI environments
  117. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  118. << "ms (Issue #1777). Timings: " << timings_str.str();
  119. }
  120. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  121. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. const std::string pathname_{"./httplib-server.sock"};
  136. const std::string pattern_{"/hi"};
  137. const std::string content_{"Hello World!"};
  138. };
  139. TEST_F(UnixSocketTest, pathname) {
  140. httplib::Server svr;
  141. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  142. res.set_content(content_, "text/plain");
  143. });
  144. std::thread t{[&] {
  145. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  146. }};
  147. auto se = detail::scope_exit([&] {
  148. svr.stop();
  149. t.join();
  150. ASSERT_FALSE(svr.is_running());
  151. });
  152. svr.wait_until_ready();
  153. ASSERT_TRUE(svr.is_running());
  154. client_GET(pathname_);
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.wait_writable());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(PORT + 1);
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  263. ASSERT_EQ(0, listen(s, 1));
  264. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  268. std::thread cli{[&] {
  269. const int s = socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_LE(0, s);
  271. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. cli.join();
  275. svr.join();
  276. ASSERT_NE(disconnected_svr_sock, -1);
  277. const auto asSocketStream = [&](socket_t fd,
  278. std::function<bool(Stream &)> func) {
  279. return detail::process_client_socket(
  280. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  281. };
  282. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  283. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  284. EXPECT_FALSE(ss.wait_writable());
  285. return true;
  286. });
  287. ASSERT_EQ(0, close(disconnected_svr_sock));
  288. }
  289. #endif // #ifndef _WIN32
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. u8"descrip=Gastos áéíóúñÑ 6");
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  319. string unescapedCharacters = "-_.!~*'()";
  320. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  321. }
  322. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  323. string reservedCharacters = ";,/?:@&=+$";
  324. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  325. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  326. }
  327. TEST(ClientQueryOrder, PreserveOrder) {
  328. // This test reproduces Issue #2259: client may reorder query parameters
  329. // when sending a GET request. The expected behavior is that the client
  330. // preserves the original query string order when the caller supplied it
  331. // as part of the path.
  332. Server svr;
  333. svr.Get("/", [&](const Request &req, Response &res) {
  334. // Echo back the raw target so the test can assert ordering
  335. res.set_content(req.target, "text/plain");
  336. });
  337. std::thread t{[&] { svr.listen(HOST, PORT); }};
  338. auto se = detail::scope_exit([&] {
  339. svr.stop();
  340. t.join();
  341. ASSERT_FALSE(svr.is_running());
  342. });
  343. svr.wait_until_ready();
  344. Client cli(HOST, PORT);
  345. ASSERT_TRUE(cli.is_valid());
  346. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  347. auto res = cli.Get(original);
  348. ASSERT_TRUE(res);
  349. // Expect the echoed target to exactly match the original path (order
  350. // preserved)
  351. EXPECT_EQ(res->body, original);
  352. }
  353. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  354. string chineseCharacters = u8"中国語";
  355. string russianCharacters = u8"дом";
  356. string brazilianCharacters = u8"óculos";
  357. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  358. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  359. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  360. "%D0%B4%D0%BE%D0%BC");
  361. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  362. }
  363. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  364. string unescapedCharacters = "-_.!~*'()";
  365. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  366. }
  367. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  368. string reservedCharacters = ";,/?:@&=+$";
  369. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  370. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  371. }
  372. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  373. string chineseCharacters = u8"中国語";
  374. string russianCharacters = u8"дом";
  375. string brazilianCharacters = u8"óculos";
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  383. // Issue #2082 use case: encoding path component with ampersand
  384. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  385. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  386. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  387. }
  388. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$#";
  394. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  395. }
  396. TEST(EncodeUriTest, TestUTF8Characters) {
  397. string chineseCharacters = u8"中国語";
  398. string russianCharacters = u8"дом";
  399. string brazilianCharacters = u8"óculos";
  400. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  401. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  402. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  403. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  404. }
  405. TEST(EncodeUriTest, TestCompleteUri) {
  406. string uri =
  407. "https://example.com/path/to/resource?query=value&param=test#fragment";
  408. EXPECT_EQ(
  409. httplib::encode_uri(uri),
  410. "https://example.com/path/to/resource?query=value&param=test#fragment");
  411. }
  412. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  413. string uri =
  414. "https://example.com/path with spaces/file name.html?q=hello world";
  415. EXPECT_EQ(httplib::encode_uri(uri),
  416. "https://example.com/path%20with%20spaces/"
  417. "file%20name.html?q=hello%20world");
  418. }
  419. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  420. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  421. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  422. }
  423. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  424. string unescapedCharacters = "-_.!~*'()";
  425. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  426. }
  427. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  428. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  429. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  430. string encodedBrazilian = "%C3%B3culos";
  431. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  433. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  434. }
  435. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  436. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  437. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  438. "Piri Tommy Villiers - on & on");
  439. }
  440. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  441. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  442. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  443. }
  444. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  445. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  446. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  447. }
  448. TEST(DecodeUriTest, TestUTF8Characters) {
  449. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  450. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  451. string encodedBrazilian = "%C3%B3culos";
  452. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  453. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  454. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  455. }
  456. TEST(DecodeUriTest, TestCompleteUri) {
  457. string encodedUri = "https://example.com/path%20with%20spaces/"
  458. "file%20name.html?q=hello%20world";
  459. EXPECT_EQ(
  460. httplib::decode_uri(encodedUri),
  461. "https://example.com/path with spaces/file name.html?q=hello world");
  462. }
  463. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  464. string original =
  465. "https://example.com/path with spaces/file name.html?q=hello world";
  466. string encoded = httplib::encode_uri(original);
  467. string decoded = httplib::decode_uri(encoded);
  468. EXPECT_EQ(decoded, original);
  469. }
  470. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  471. string original = "Piri Tommy Villiers - on & on";
  472. string encoded = httplib::encode_uri_component(original);
  473. string decoded = httplib::decode_uri_component(encoded);
  474. EXPECT_EQ(decoded, original);
  475. }
  476. TEST(TrimTests, TrimStringTests) {
  477. EXPECT_EQ("abc", detail::trim_copy("abc"));
  478. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  479. EXPECT_TRUE(detail::trim_copy("").empty());
  480. }
  481. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  482. // Simple case without quality values
  483. std::vector<std::string> result1;
  484. EXPECT_TRUE(detail::parse_accept_header(
  485. "text/html,application/json,text/plain", result1));
  486. EXPECT_EQ(result1.size(), 3U);
  487. EXPECT_EQ(result1[0], "text/html");
  488. EXPECT_EQ(result1[1], "application/json");
  489. EXPECT_EQ(result1[2], "text/plain");
  490. // With quality values
  491. std::vector<std::string> result2;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  494. EXPECT_EQ(result2.size(), 3U);
  495. EXPECT_EQ(result2[0], "application/json"); // highest q value
  496. EXPECT_EQ(result2[1], "text/html");
  497. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  498. }
  499. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  500. // Mixed with and without quality values
  501. std::vector<std::string> result;
  502. EXPECT_TRUE(detail::parse_accept_header(
  503. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  504. EXPECT_EQ(result.size(), 3U);
  505. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  506. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  507. EXPECT_EQ(result[2], "application/json"); // q=0.5
  508. }
  509. TEST(ParseAcceptHeaderTest, EdgeCases) {
  510. // Empty header
  511. std::vector<std::string> empty_result;
  512. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  513. EXPECT_TRUE(empty_result.empty());
  514. // Single type
  515. std::vector<std::string> single_result;
  516. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  517. EXPECT_EQ(single_result.size(), 1U);
  518. EXPECT_EQ(single_result[0], "application/json");
  519. // Wildcard types
  520. std::vector<std::string> wildcard_result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  523. EXPECT_EQ(wildcard_result.size(), 3U);
  524. EXPECT_EQ(wildcard_result[0], "application/json");
  525. EXPECT_EQ(wildcard_result[1], "text/*");
  526. EXPECT_EQ(wildcard_result[2], "*/*");
  527. }
  528. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  529. // Common browser Accept header
  530. std::vector<std::string> browser_result;
  531. EXPECT_TRUE(
  532. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  533. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  534. browser_result));
  535. EXPECT_EQ(browser_result.size(), 6U);
  536. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  540. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  541. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  542. // API client header
  543. std::vector<std::string> api_result;
  544. EXPECT_TRUE(detail::parse_accept_header(
  545. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  546. api_result));
  547. EXPECT_EQ(api_result.size(), 3U);
  548. EXPECT_EQ(api_result[0], "application/json");
  549. EXPECT_EQ(api_result[1], "application/xml");
  550. EXPECT_EQ(api_result[2], "text/plain");
  551. }
  552. TEST(ParseAcceptHeaderTest, SpecialCases) {
  553. // Quality value with 3 decimal places
  554. std::vector<std::string> decimal_result;
  555. EXPECT_TRUE(detail::parse_accept_header(
  556. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  557. EXPECT_EQ(decimal_result.size(), 2U);
  558. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  559. EXPECT_EQ(decimal_result[1], "text/html");
  560. // Zero quality (should still be included but with lowest priority)
  561. std::vector<std::string> zero_q_result;
  562. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  563. zero_q_result));
  564. EXPECT_EQ(zero_q_result.size(), 2U);
  565. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  566. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  567. // No spaces around commas
  568. std::vector<std::string> no_space_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  571. no_space_result));
  572. EXPECT_EQ(no_space_result.size(), 3U);
  573. EXPECT_EQ(no_space_result[0], "text/html");
  574. EXPECT_EQ(no_space_result[1], "application/json");
  575. EXPECT_EQ(no_space_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, InvalidCases) {
  578. std::vector<std::string> result;
  579. // Invalid quality value (> 1.0)
  580. EXPECT_FALSE(
  581. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  582. // Invalid quality value (< 0.0)
  583. EXPECT_FALSE(
  584. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  585. // Invalid quality value (not a number)
  586. EXPECT_FALSE(detail::parse_accept_header(
  587. "text/html;q=invalid,application/json", result));
  588. // Empty quality value
  589. EXPECT_FALSE(
  590. detail::parse_accept_header("text/html;q=,application/json", result));
  591. // Invalid media type format (no slash and not wildcard)
  592. EXPECT_FALSE(
  593. detail::parse_accept_header("invalidtype,application/json", result));
  594. // Empty media type
  595. result.clear();
  596. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  597. // Only commas
  598. result.clear();
  599. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  600. // Valid cases should still work
  601. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  602. EXPECT_EQ(result.size(), 1U);
  603. EXPECT_EQ(result[0], "*/*");
  604. EXPECT_TRUE(detail::parse_accept_header("*", result));
  605. EXPECT_EQ(result.size(), 1U);
  606. EXPECT_EQ(result[0], "*");
  607. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  608. EXPECT_EQ(result.size(), 1U);
  609. EXPECT_EQ(result[0], "text/*");
  610. }
  611. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  612. Server svr;
  613. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  614. EXPECT_EQ(req.accept_content_types.size(), 3U);
  615. EXPECT_EQ(req.accept_content_types[0], "application/json");
  616. EXPECT_EQ(req.accept_content_types[1], "text/html");
  617. EXPECT_EQ(req.accept_content_types[2], "*/*");
  618. res.set_content("ok", "text/plain");
  619. });
  620. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  621. EXPECT_TRUE(false);
  622. res.set_content("bad request", "text/plain");
  623. });
  624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  625. auto se = detail::scope_exit([&] {
  626. svr.stop();
  627. listen_thread.join();
  628. ASSERT_FALSE(svr.is_running());
  629. });
  630. svr.wait_until_ready();
  631. Client cli("localhost", PORT);
  632. {
  633. auto res =
  634. cli.Get("/accept_ok",
  635. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  636. ASSERT_TRUE(res);
  637. EXPECT_EQ(StatusCode::OK_200, res->status);
  638. }
  639. {
  640. auto res = cli.Get("/accept_bad_request",
  641. {{"Accept", "text/html;q=abc,application/json"}});
  642. ASSERT_TRUE(res);
  643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  644. }
  645. }
  646. TEST(DivideTest, DivideStringTests) {
  647. auto divide = [](const std::string &str, char d) {
  648. std::string lhs;
  649. std::string rhs;
  650. detail::divide(str, d,
  651. [&](const char *lhs_data, std::size_t lhs_size,
  652. const char *rhs_data, std::size_t rhs_size) {
  653. lhs.assign(lhs_data, lhs_size);
  654. rhs.assign(rhs_data, rhs_size);
  655. });
  656. return std::make_pair(std::move(lhs), std::move(rhs));
  657. };
  658. {
  659. const auto res = divide("", '=');
  660. EXPECT_EQ(res.first, "");
  661. EXPECT_EQ(res.second, "");
  662. }
  663. {
  664. const auto res = divide("=", '=');
  665. EXPECT_EQ(res.first, "");
  666. EXPECT_EQ(res.second, "");
  667. }
  668. {
  669. const auto res = divide(" ", '=');
  670. EXPECT_EQ(res.first, " ");
  671. EXPECT_EQ(res.second, "");
  672. }
  673. {
  674. const auto res = divide("a", '=');
  675. EXPECT_EQ(res.first, "a");
  676. EXPECT_EQ(res.second, "");
  677. }
  678. {
  679. const auto res = divide("a=", '=');
  680. EXPECT_EQ(res.first, "a");
  681. EXPECT_EQ(res.second, "");
  682. }
  683. {
  684. const auto res = divide("=b", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "b");
  687. }
  688. {
  689. const auto res = divide("a=b", '=');
  690. EXPECT_EQ(res.first, "a");
  691. EXPECT_EQ(res.second, "b");
  692. }
  693. {
  694. const auto res = divide("a=b=", '=');
  695. EXPECT_EQ(res.first, "a");
  696. EXPECT_EQ(res.second, "b=");
  697. }
  698. {
  699. const auto res = divide("a=b=c", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "b=c");
  702. }
  703. }
  704. TEST(SplitTest, ParseQueryString) {
  705. string s = "key1=val1&key2=val2&key3=val3";
  706. Params dic;
  707. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  708. [&](const char *b, const char *e) {
  709. string key, val;
  710. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  711. if (key.empty()) {
  712. key.assign(b2, e2);
  713. } else {
  714. val.assign(b2, e2);
  715. }
  716. });
  717. dic.emplace(key, val);
  718. });
  719. EXPECT_EQ("val1", dic.find("key1")->second);
  720. EXPECT_EQ("val2", dic.find("key2")->second);
  721. EXPECT_EQ("val3", dic.find("key3")->second);
  722. }
  723. TEST(SplitTest, ParseInvalidQueryTests) {
  724. {
  725. string s = " ";
  726. Params dict;
  727. detail::parse_query_text(s, dict);
  728. EXPECT_TRUE(dict.empty());
  729. }
  730. {
  731. string s = " = =";
  732. Params dict;
  733. detail::parse_query_text(s, dict);
  734. EXPECT_TRUE(dict.empty());
  735. }
  736. }
  737. TEST(ParseQueryTest, ParseQueryString) {
  738. {
  739. std::string s = "key1=val1&key2=val2&key3=val3";
  740. Params dic;
  741. detail::parse_query_text(s, dic);
  742. EXPECT_EQ("val1", dic.find("key1")->second);
  743. EXPECT_EQ("val2", dic.find("key2")->second);
  744. EXPECT_EQ("val3", dic.find("key3")->second);
  745. }
  746. {
  747. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("", dic.find("key1")->second);
  751. EXPECT_EQ("val1", dic.find("key2")->second);
  752. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  753. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  754. }
  755. }
  756. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  757. Params dic;
  758. EXPECT_EQ(detail::params_to_query_str(dic), "");
  759. dic.emplace("key1", "val1");
  760. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  761. dic.emplace("key2", "val2");
  762. dic.emplace("key3", "val3");
  763. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  764. }
  765. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  766. string content_type = "multipart/form-data; boundary=something";
  767. string boundary;
  768. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  769. EXPECT_TRUE(ret);
  770. EXPECT_EQ(boundary, "something");
  771. }
  772. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  773. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  780. string content_type =
  781. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  794. }
  795. TEST(GetHeaderValueTest, DefaultValue) {
  796. Headers headers = {{"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  798. EXPECT_STREQ("text/plain", val);
  799. }
  800. TEST(GetHeaderValueTest, DefaultValueInt) {
  801. Headers headers = {{"Dummy", "Dummy"}};
  802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  803. EXPECT_EQ(100ull, val);
  804. }
  805. TEST(GetHeaderValueTest, RegularValue) {
  806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  808. EXPECT_STREQ("text/html", val);
  809. }
  810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  813. EXPECT_STREQ("text/html", val);
  814. }
  815. TEST(GetHeaderValueTest, SetContent) {
  816. Response res;
  817. res.set_content("html", "text/html");
  818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  819. res.set_content("text", "text/plain");
  820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  822. }
  823. TEST(GetHeaderValueTest, RegularValueInt) {
  824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  826. EXPECT_EQ(100ull, val);
  827. }
  828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  829. Headers headers = {{"Content-Length", "x"}};
  830. auto is_invalid_value = false;
  831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  832. is_invalid_value);
  833. EXPECT_EQ(0ull, val);
  834. EXPECT_TRUE(is_invalid_value);
  835. }
  836. TEST(GetHeaderValueTest, Range) {
  837. {
  838. Headers headers = {make_range_header({{1, -1}})};
  839. auto val = detail::get_header_value(headers, "Range", 0, 0);
  840. EXPECT_STREQ("bytes=1-", val);
  841. }
  842. {
  843. Headers headers = {make_range_header({{-1, 1}})};
  844. auto val = detail::get_header_value(headers, "Range", 0, 0);
  845. EXPECT_STREQ("bytes=-1", val);
  846. }
  847. {
  848. Headers headers = {make_range_header({{1, 10}})};
  849. auto val = detail::get_header_value(headers, "Range", 0, 0);
  850. EXPECT_STREQ("bytes=1-10", val);
  851. }
  852. {
  853. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  854. auto val = detail::get_header_value(headers, "Range", 0, 0);
  855. EXPECT_STREQ("bytes=1-10, 100-", val);
  856. }
  857. {
  858. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  859. auto val = detail::get_header_value(headers, "Range", 0, 0);
  860. EXPECT_STREQ("bytes=1-10, 100-200", val);
  861. }
  862. {
  863. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=0-0, -1", val);
  866. }
  867. }
  868. TEST(ParseHeaderValueTest, Range) {
  869. {
  870. Ranges ranges;
  871. auto ret = detail::parse_range_header("bytes=1-", ranges);
  872. EXPECT_TRUE(ret);
  873. EXPECT_EQ(1u, ranges.size());
  874. EXPECT_EQ(1u, ranges[0].first);
  875. EXPECT_EQ(-1, ranges[0].second);
  876. }
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=-1", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(-1, ranges[0].first);
  883. EXPECT_EQ(1u, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(1u, ranges[0].first);
  891. EXPECT_EQ(10u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  896. EXPECT_FALSE(ret);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(2u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. EXPECT_EQ(100u, ranges[1].first);
  906. EXPECT_EQ(-1, ranges[1].second);
  907. }
  908. {
  909. Ranges ranges;
  910. auto ret =
  911. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  912. EXPECT_TRUE(ret);
  913. EXPECT_EQ(3u, ranges.size());
  914. EXPECT_EQ(1u, ranges[0].first);
  915. EXPECT_EQ(10u, ranges[0].second);
  916. EXPECT_EQ(100u, ranges[1].first);
  917. EXPECT_EQ(200u, ranges[1].second);
  918. EXPECT_EQ(300u, ranges[2].first);
  919. EXPECT_EQ(400u, ranges[2].second);
  920. }
  921. {
  922. Ranges ranges;
  923. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  926. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  927. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  928. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  929. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  936. EXPECT_TRUE(ranges.empty());
  937. }
  938. }
  939. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding", "gzip");
  942. Response res;
  943. res.set_header("Content-Type", "text/plain");
  944. auto ret = detail::encoding_type(req, res);
  945. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  947. #else
  948. EXPECT_TRUE(ret == detail::EncodingType::None);
  949. #endif
  950. }
  951. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  952. Request req;
  953. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  954. Response res;
  955. res.set_header("Content-Type", "text/plain");
  956. auto ret = detail::encoding_type(req, res);
  957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  963. #else
  964. EXPECT_TRUE(ret == detail::EncodingType::None);
  965. #endif
  966. }
  967. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  968. Request req;
  969. req.set_header("Accept-Encoding",
  970. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  971. Response res;
  972. res.set_header("Content-Type", "text/plain");
  973. auto ret = detail::encoding_type(req, res);
  974. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  976. #elif CPPHTTPLIB_ZLIB_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  980. #else
  981. EXPECT_TRUE(ret == detail::EncodingType::None);
  982. #endif
  983. }
  984. TEST(BufferStreamTest, read) {
  985. detail::BufferStream strm1;
  986. Stream &strm = strm1;
  987. EXPECT_EQ(5, strm.write("hello"));
  988. char buf[512];
  989. EXPECT_EQ(2, strm.read(buf, 2));
  990. EXPECT_EQ('h', buf[0]);
  991. EXPECT_EQ('e', buf[1]);
  992. EXPECT_EQ(2, strm.read(buf, 2));
  993. EXPECT_EQ('l', buf[0]);
  994. EXPECT_EQ('l', buf[1]);
  995. EXPECT_EQ(1, strm.read(buf, 1));
  996. EXPECT_EQ('o', buf[0]);
  997. EXPECT_EQ(0, strm.read(buf, 1));
  998. }
  999. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1000. auto host = "www.httpwatch.com";
  1001. auto ip = hosted_at(host);
  1002. EXPECT_EQ("23.96.13.243", ip);
  1003. std::vector<std::string> addrs;
  1004. hosted_at(host, addrs);
  1005. EXPECT_EQ(1u, addrs.size());
  1006. }
  1007. #if 0 // It depends on each test environment...
  1008. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1009. auto host = "www.youtube.com";
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(20u, addrs.size());
  1013. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1014. EXPECT_TRUE(it != addrs.end());
  1015. }
  1016. #endif
  1017. class ChunkedEncodingTest : public ::testing::Test {
  1018. protected:
  1019. ChunkedEncodingTest()
  1020. : cli_(HOST, PORT)
  1021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1022. ,
  1023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1024. #endif
  1025. {
  1026. cli_.set_connection_timeout(2);
  1027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1028. cli_.enable_server_certificate_verification(false);
  1029. #endif
  1030. }
  1031. virtual void SetUp() {
  1032. read_file("./image.jpg", image_data_);
  1033. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1034. res.set_content("Hello World!", "text/plain");
  1035. });
  1036. svr_.Get(
  1037. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1038. res.set_chunked_content_provider(
  1039. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1040. size_t remaining = image_data_.size() - offset;
  1041. if (remaining == 0) {
  1042. sink.done();
  1043. } else {
  1044. constexpr size_t CHUNK_SIZE = 1024;
  1045. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1046. sink.write(&image_data_[offset], send_size);
  1047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1048. }
  1049. return true;
  1050. });
  1051. });
  1052. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1053. svr_.wait_until_ready();
  1054. }
  1055. virtual void TearDown() {
  1056. svr_.stop();
  1057. if (!request_threads_.empty()) {
  1058. std::this_thread::sleep_for(std::chrono::seconds(1));
  1059. for (auto &t : request_threads_) {
  1060. t.join();
  1061. }
  1062. }
  1063. t_.join();
  1064. }
  1065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1066. SSLClient cli_;
  1067. SSLServer svr_;
  1068. #else
  1069. Client cli_;
  1070. Server svr_;
  1071. #endif
  1072. thread t_;
  1073. std::vector<thread> request_threads_;
  1074. std::string image_data_;
  1075. };
  1076. TEST_F(ChunkedEncodingTest, NormalGet) {
  1077. auto res = cli_.Get("/chunked");
  1078. ASSERT_TRUE(res);
  1079. std::string out;
  1080. read_file("./image.jpg", out);
  1081. EXPECT_EQ(StatusCode::OK_200, res->status);
  1082. EXPECT_EQ(out, res->body);
  1083. }
  1084. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1085. std::string body;
  1086. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1087. body.append(data, data_length);
  1088. return true;
  1089. });
  1090. ASSERT_TRUE(res);
  1091. std::string out;
  1092. read_file("./image.jpg", out);
  1093. EXPECT_EQ(StatusCode::OK_200, res->status);
  1094. EXPECT_EQ(out, body);
  1095. }
  1096. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1097. std::string body;
  1098. auto res = cli_.Get(
  1099. "/chunked",
  1100. [&](const Response &response) {
  1101. EXPECT_EQ(StatusCode::OK_200, response.status);
  1102. return true;
  1103. },
  1104. [&](const char *data, size_t data_length) {
  1105. body.append(data, data_length);
  1106. return true;
  1107. });
  1108. ASSERT_TRUE(res);
  1109. std::string out;
  1110. read_file("./image.jpg", out);
  1111. EXPECT_EQ(StatusCode::OK_200, res->status);
  1112. EXPECT_EQ(out, body);
  1113. }
  1114. TEST(RangeTest, FromHTTPBin_Online) {
  1115. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1116. auto host = "httpbin.org";
  1117. auto path = std::string{"/range/32"};
  1118. #else
  1119. auto host = "nghttp2.org";
  1120. auto path = std::string{"/httpbin/range/32"};
  1121. #endif
  1122. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1123. auto port = 443;
  1124. SSLClient cli(host, port);
  1125. #else
  1126. auto port = 80;
  1127. Client cli(host, port);
  1128. #endif
  1129. cli.set_connection_timeout(5);
  1130. {
  1131. auto res = cli.Get(path);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{1, -1}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, 10}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijk", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{0, 31}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, -1}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, 32}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1169. }
  1170. }
  1171. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1172. auto host = "unresolvableaddress.local";
  1173. auto path = std::string{"/"};
  1174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1175. auto port = 443;
  1176. SSLClient cli(host, port);
  1177. #else
  1178. auto port = 80;
  1179. Client cli(host, port);
  1180. #endif
  1181. cli.set_connection_timeout(1);
  1182. {
  1183. auto res = cli.Get(path);
  1184. ASSERT_FALSE(res);
  1185. }
  1186. std::this_thread::sleep_for(std::chrono::seconds(8));
  1187. }
  1188. TEST(ConnectionErrorTest, InvalidHost) {
  1189. auto host = "-abcde.com";
  1190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1191. auto port = 443;
  1192. SSLClient cli(host, port);
  1193. #else
  1194. auto port = 80;
  1195. Client cli(host, port);
  1196. #endif
  1197. cli.set_connection_timeout(std::chrono::seconds(2));
  1198. auto res = cli.Get("/");
  1199. ASSERT_TRUE(!res);
  1200. EXPECT_EQ(Error::Connection, res.error());
  1201. }
  1202. TEST(ConnectionErrorTest, InvalidHost2) {
  1203. auto host = "httpbin.org/";
  1204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1205. SSLClient cli(host);
  1206. #else
  1207. Client cli(host);
  1208. #endif
  1209. cli.set_connection_timeout(std::chrono::seconds(2));
  1210. auto res = cli.Get("/");
  1211. ASSERT_TRUE(!res);
  1212. EXPECT_EQ(Error::Connection, res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1215. auto host = "httpbin.org/";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. SSLClient cli(host);
  1218. #else
  1219. Client cli(host);
  1220. #endif
  1221. cli.set_connection_timeout(std::chrono::seconds(2));
  1222. auto res = cli.Get("/");
  1223. ASSERT_TRUE(!res);
  1224. stringstream s;
  1225. s << "error code: " << res.error();
  1226. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1227. }
  1228. TEST(ConnectionErrorTest, InvalidPort) {
  1229. auto host = "localhost";
  1230. auto port = 44380;
  1231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1232. SSLClient cli(host, port);
  1233. #else
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(2));
  1237. auto res = cli.Get("/");
  1238. ASSERT_TRUE(!res);
  1239. EXPECT_TRUE(Error::Connection == res.error() ||
  1240. Error::ConnectionTimeout == res.error());
  1241. }
  1242. TEST(ConnectionErrorTest, Timeout_Online) {
  1243. auto host = "google.com";
  1244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1245. auto port = 44380;
  1246. SSLClient cli(host, port);
  1247. #else
  1248. auto port = 8080;
  1249. Client cli(host, port);
  1250. #endif
  1251. cli.set_connection_timeout(std::chrono::seconds(2));
  1252. // only probe one address type so that the error reason
  1253. // correlates to the timed-out IPv4, not the unsupported
  1254. // IPv6 connection attempt
  1255. cli.set_address_family(AF_INET);
  1256. auto res = cli.Get("/");
  1257. ASSERT_TRUE(!res);
  1258. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1259. }
  1260. TEST(CancelTest, NoCancel_Online) {
  1261. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1262. auto host = "httpbin.org";
  1263. auto path = std::string{"/range/32"};
  1264. #else
  1265. auto host = "nghttp2.org";
  1266. auto path = std::string{"/httpbin/range/32"};
  1267. #endif
  1268. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1269. auto port = 443;
  1270. SSLClient cli(host, port);
  1271. #else
  1272. auto port = 80;
  1273. Client cli(host, port);
  1274. #endif
  1275. cli.set_connection_timeout(std::chrono::seconds(5));
  1276. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1277. ASSERT_TRUE(res);
  1278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1279. EXPECT_EQ(StatusCode::OK_200, res->status);
  1280. }
  1281. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1282. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1283. auto host = "httpbin.org";
  1284. auto path = std::string{"/range/32"};
  1285. #else
  1286. auto host = "nghttp2.org";
  1287. auto path = std::string{"/httpbin/range/32"};
  1288. #endif
  1289. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1290. auto port = 443;
  1291. SSLClient cli(host, port);
  1292. #else
  1293. auto port = 80;
  1294. Client cli(host, port);
  1295. #endif
  1296. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. ASSERT_TRUE(!res);
  1299. EXPECT_EQ(Error::Canceled, res.error());
  1300. }
  1301. TEST(CancelTest, WithCancelLargePayload_Online) {
  1302. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1303. auto host = "httpbin.org";
  1304. auto path = std::string{"/range/65536"};
  1305. #else
  1306. auto host = "nghttp2.org";
  1307. auto path = std::string{"/httpbin/range/65536"};
  1308. #endif
  1309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1310. auto port = 443;
  1311. SSLClient cli(host, port);
  1312. #else
  1313. auto port = 80;
  1314. Client cli(host, port);
  1315. #endif
  1316. cli.set_connection_timeout(std::chrono::seconds(5));
  1317. uint32_t count = 0;
  1318. auto res =
  1319. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, NoCancelPost) {
  1324. Server svr;
  1325. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1326. res.set_content("Hello World!", "text/plain");
  1327. });
  1328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. thread.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. Client cli(HOST, PORT);
  1336. cli.set_connection_timeout(std::chrono::seconds(5));
  1337. auto res =
  1338. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1339. "application/json", [](uint64_t, uint64_t) { return true; });
  1340. ASSERT_TRUE(res);
  1341. EXPECT_EQ("Hello World!", res->body);
  1342. EXPECT_EQ(StatusCode::OK_200, res->status);
  1343. }
  1344. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1345. Server svr;
  1346. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1347. res.set_content("Hello World!", "text/plain");
  1348. });
  1349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1350. auto se = detail::scope_exit([&] {
  1351. svr.stop();
  1352. thread.join();
  1353. ASSERT_FALSE(svr.is_running());
  1354. });
  1355. svr.wait_until_ready();
  1356. Client cli(HOST, PORT);
  1357. cli.set_connection_timeout(std::chrono::seconds(5));
  1358. auto res =
  1359. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1360. "application/json", [](uint64_t, uint64_t) { return false; });
  1361. ASSERT_TRUE(!res);
  1362. EXPECT_EQ(Error::Canceled, res.error());
  1363. }
  1364. TEST(CancelTest, WithCancelLargePayloadPost) {
  1365. Server svr;
  1366. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1367. res.set_content(LARGE_DATA, "text/plain");
  1368. });
  1369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1370. auto se = detail::scope_exit([&] {
  1371. svr.stop();
  1372. thread.join();
  1373. ASSERT_FALSE(svr.is_running());
  1374. });
  1375. svr.wait_until_ready();
  1376. Client cli(HOST, PORT);
  1377. cli.set_connection_timeout(std::chrono::seconds(5));
  1378. auto res =
  1379. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1380. "application/json", [](uint64_t, uint64_t) { return false; });
  1381. ASSERT_TRUE(!res);
  1382. EXPECT_EQ(Error::Canceled, res.error());
  1383. }
  1384. TEST(CancelTest, NoCancelPut) {
  1385. Server svr;
  1386. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1387. res.set_content("Hello World!", "text/plain");
  1388. });
  1389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. thread.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, PORT);
  1397. cli.set_connection_timeout(std::chrono::seconds(5));
  1398. auto res =
  1399. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1400. "application/json", [](uint64_t, uint64_t) { return true; });
  1401. ASSERT_TRUE(res);
  1402. EXPECT_EQ("Hello World!", res->body);
  1403. EXPECT_EQ(StatusCode::OK_200, res->status);
  1404. }
  1405. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1406. Server svr;
  1407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1408. res.set_content("Hello World!", "text/plain");
  1409. });
  1410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1411. auto se = detail::scope_exit([&] {
  1412. svr.stop();
  1413. thread.join();
  1414. ASSERT_FALSE(svr.is_running());
  1415. });
  1416. svr.wait_until_ready();
  1417. Client cli(HOST, PORT);
  1418. cli.set_connection_timeout(std::chrono::seconds(5));
  1419. auto res =
  1420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1421. "application/json", [](uint64_t, uint64_t) { return false; });
  1422. ASSERT_TRUE(!res);
  1423. EXPECT_EQ(Error::Canceled, res.error());
  1424. }
  1425. TEST(CancelTest, WithCancelLargePayloadPut) {
  1426. Server svr;
  1427. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1428. res.set_content(LARGE_DATA, "text/plain");
  1429. });
  1430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. thread.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, PORT);
  1438. cli.set_connection_timeout(std::chrono::seconds(5));
  1439. auto res =
  1440. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1441. "application/json", [](uint64_t, uint64_t) { return false; });
  1442. ASSERT_TRUE(!res);
  1443. EXPECT_EQ(Error::Canceled, res.error());
  1444. }
  1445. TEST(CancelTest, NoCancelPatch) {
  1446. Server svr;
  1447. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1448. res.set_content("Hello World!", "text/plain");
  1449. });
  1450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1451. auto se = detail::scope_exit([&] {
  1452. svr.stop();
  1453. thread.join();
  1454. ASSERT_FALSE(svr.is_running());
  1455. });
  1456. svr.wait_until_ready();
  1457. Client cli(HOST, PORT);
  1458. cli.set_connection_timeout(std::chrono::seconds(5));
  1459. auto res =
  1460. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1461. "application/json", [](uint64_t, uint64_t) { return true; });
  1462. ASSERT_TRUE(res);
  1463. EXPECT_EQ("Hello World!", res->body);
  1464. EXPECT_EQ(StatusCode::OK_200, res->status);
  1465. }
  1466. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1467. Server svr;
  1468. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1469. res.set_content("Hello World!", "text/plain");
  1470. });
  1471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1472. auto se = detail::scope_exit([&] {
  1473. svr.stop();
  1474. thread.join();
  1475. ASSERT_FALSE(svr.is_running());
  1476. });
  1477. svr.wait_until_ready();
  1478. Client cli(HOST, PORT);
  1479. cli.set_connection_timeout(std::chrono::seconds(5));
  1480. auto res =
  1481. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1482. "application/json", [](uint64_t, uint64_t) { return false; });
  1483. ASSERT_TRUE(!res);
  1484. EXPECT_EQ(Error::Canceled, res.error());
  1485. }
  1486. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1487. Server svr;
  1488. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1489. res.set_content(LARGE_DATA, "text/plain");
  1490. });
  1491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. thread.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, PORT);
  1499. cli.set_connection_timeout(std::chrono::seconds(5));
  1500. auto res =
  1501. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1502. "application/json", [](uint64_t, uint64_t) { return false; });
  1503. ASSERT_TRUE(!res);
  1504. EXPECT_EQ(Error::Canceled, res.error());
  1505. }
  1506. TEST(CancelTest, NoCancelDelete) {
  1507. Server svr;
  1508. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1509. res.set_content("Hello World!", "text/plain");
  1510. });
  1511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1512. auto se = detail::scope_exit([&] {
  1513. svr.stop();
  1514. thread.join();
  1515. ASSERT_FALSE(svr.is_running());
  1516. });
  1517. svr.wait_until_ready();
  1518. Client cli(HOST, PORT);
  1519. cli.set_connection_timeout(std::chrono::seconds(5));
  1520. auto res =
  1521. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1522. "application/json", [](uint64_t, uint64_t) { return true; });
  1523. ASSERT_TRUE(res);
  1524. EXPECT_EQ("Hello World!", res->body);
  1525. EXPECT_EQ(StatusCode::OK_200, res->status);
  1526. }
  1527. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1528. Server svr;
  1529. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1530. res.set_content("Hello World!", "text/plain");
  1531. });
  1532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1533. auto se = detail::scope_exit([&] {
  1534. svr.stop();
  1535. thread.join();
  1536. ASSERT_FALSE(svr.is_running());
  1537. });
  1538. svr.wait_until_ready();
  1539. Client cli(HOST, PORT);
  1540. cli.set_connection_timeout(std::chrono::seconds(5));
  1541. auto res =
  1542. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1543. "application/json", [](uint64_t, uint64_t) { return false; });
  1544. ASSERT_TRUE(!res);
  1545. EXPECT_EQ(Error::Canceled, res.error());
  1546. }
  1547. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1548. Server svr;
  1549. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1550. res.set_content(LARGE_DATA, "text/plain");
  1551. });
  1552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. Client cli(HOST, PORT);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. static std::string remove_whitespace(const std::string &input) {
  1568. std::string output;
  1569. output.reserve(input.size());
  1570. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1571. [](unsigned char c) { return !std::isspace(c); });
  1572. return output;
  1573. }
  1574. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1575. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1576. auto host = "httpbin.org";
  1577. auto path = std::string{"/basic-auth/hello/world"};
  1578. #else
  1579. auto host = "nghttp2.org";
  1580. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1581. #endif
  1582. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1583. auto port = 443;
  1584. SSLClient cli(host, port);
  1585. #else
  1586. auto port = 80;
  1587. Client cli(host, port);
  1588. #endif
  1589. {
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. {
  1595. auto res =
  1596. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1599. remove_whitespace(res->body));
  1600. EXPECT_EQ(StatusCode::OK_200, res->status);
  1601. }
  1602. {
  1603. cli.set_basic_auth("hello", "world");
  1604. auto res = cli.Get(path);
  1605. ASSERT_TRUE(res);
  1606. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1607. remove_whitespace(res->body));
  1608. EXPECT_EQ(StatusCode::OK_200, res->status);
  1609. }
  1610. {
  1611. cli.set_basic_auth("hello", "bad");
  1612. auto res = cli.Get(path);
  1613. ASSERT_TRUE(res);
  1614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1615. }
  1616. {
  1617. cli.set_basic_auth("bad", "world");
  1618. auto res = cli.Get(path);
  1619. ASSERT_TRUE(res);
  1620. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1621. }
  1622. }
  1623. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1624. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1625. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1626. auto host = "httpbin.org";
  1627. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1628. auto paths = std::vector<std::string>{
  1629. "/digest-auth/auth/hello/world/MD5",
  1630. "/digest-auth/auth/hello/world/SHA-256",
  1631. "/digest-auth/auth/hello/world/SHA-512",
  1632. "/digest-auth/auth-int/hello/world/MD5",
  1633. };
  1634. #else
  1635. auto host = "nghttp2.org";
  1636. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1637. auto paths = std::vector<std::string>{
  1638. "/httpbin/digest-auth/auth/hello/world/MD5",
  1639. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1640. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1641. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1642. };
  1643. #endif
  1644. auto port = 443;
  1645. SSLClient cli(host, port);
  1646. {
  1647. auto res = cli.Get(unauth_path);
  1648. ASSERT_TRUE(res);
  1649. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1650. }
  1651. {
  1652. cli.set_digest_auth("hello", "world");
  1653. for (const auto &path : paths) {
  1654. auto res = cli.Get(path.c_str());
  1655. ASSERT_TRUE(res);
  1656. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1657. remove_whitespace(res->body));
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. cli.set_digest_auth("hello", "bad");
  1661. for (const auto &path : paths) {
  1662. auto res = cli.Get(path.c_str());
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1665. }
  1666. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1667. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1668. // cli.set_digest_auth("bad", "world");
  1669. // for (const auto& path : paths) {
  1670. // auto res = cli.Get(path.c_str());
  1671. // ASSERT_TRUE(res);
  1672. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1673. // }
  1674. }
  1675. }
  1676. #endif
  1677. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1678. auto host = "google.com";
  1679. auto another_host = "example.com";
  1680. auto wrong_ip = "0.0.0.0";
  1681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1682. SSLClient cli(host);
  1683. #else
  1684. Client cli(host);
  1685. #endif
  1686. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1687. auto res = cli.Get("/");
  1688. ASSERT_TRUE(res);
  1689. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1690. }
  1691. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1692. auto host = "google.com";
  1693. auto wrong_ip = "0.0.0.0";
  1694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1695. SSLClient cli(host);
  1696. #else
  1697. Client cli(host);
  1698. #endif
  1699. cli.set_hostname_addr_map({{host, wrong_ip}});
  1700. auto res = cli.Get("/");
  1701. ASSERT_TRUE(!res);
  1702. EXPECT_EQ(Error::Connection, res.error());
  1703. }
  1704. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1705. auto host = "nghttp2.org";
  1706. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1707. SSLClient cli(host);
  1708. #else
  1709. Client cli(host);
  1710. #endif
  1711. cli.set_follow_location(true);
  1712. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(StatusCode::OK_200, res->status);
  1715. }
  1716. TEST(RedirectTest, Redirect_Online) {
  1717. auto host = "nghttp2.org";
  1718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1719. SSLClient cli(host);
  1720. #else
  1721. Client cli(host);
  1722. #endif
  1723. cli.set_follow_location(true);
  1724. auto res = cli.Get("/httpbin/redirect/3");
  1725. ASSERT_TRUE(res);
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. TEST(RelativeRedirectTest, Redirect_Online) {
  1729. auto host = "nghttp2.org";
  1730. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1731. SSLClient cli(host);
  1732. #else
  1733. Client cli(host);
  1734. #endif
  1735. cli.set_follow_location(true);
  1736. auto res = cli.Get("/httpbin/relative-redirect/3");
  1737. ASSERT_TRUE(res);
  1738. EXPECT_EQ(StatusCode::OK_200, res->status);
  1739. }
  1740. TEST(TooManyRedirectTest, Redirect_Online) {
  1741. auto host = "nghttp2.org";
  1742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1743. SSLClient cli(host);
  1744. #else
  1745. Client cli(host);
  1746. #endif
  1747. cli.set_follow_location(true);
  1748. auto res = cli.Get("/httpbin/redirect/21");
  1749. ASSERT_TRUE(!res);
  1750. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1751. }
  1752. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1753. TEST(YahooRedirectTest, Redirect_Online) {
  1754. Client cli("yahoo.com");
  1755. auto res = cli.Get("/");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1758. cli.set_follow_location(true);
  1759. res = cli.Get("/");
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1763. }
  1764. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1765. #define REDIR_HOST "httpbingo.org"
  1766. #define REDIR_PATH "/redirect-to"
  1767. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1768. SSLClient cli(REDIR_HOST);
  1769. cli.set_follow_location(true);
  1770. auto res =
  1771. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. Params params;
  1779. params.emplace("url", "http://example.com");
  1780. params.emplace("status_code", "302");
  1781. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. }
  1794. TEST(UrlWithSpace, Redirect_Online) {
  1795. SSLClient cli("edge.forgecdn.net");
  1796. cli.set_follow_location(true);
  1797. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1798. ASSERT_TRUE(res);
  1799. EXPECT_EQ(StatusCode::OK_200, res->status);
  1800. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1801. }
  1802. #endif
  1803. #if !defined(_WIN32) && !defined(_WIN64)
  1804. TEST(ReceiveSignals, Signal) {
  1805. auto setupSignalHandlers = []() {
  1806. struct sigaction act;
  1807. sigemptyset(&act.sa_mask);
  1808. act.sa_flags = SA_SIGINFO;
  1809. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1810. switch (sig) {
  1811. case SIGINT:
  1812. default: break;
  1813. }
  1814. };
  1815. ::sigaction(SIGINT, &act, nullptr);
  1816. };
  1817. Server svr;
  1818. int port = 0;
  1819. auto thread = std::thread([&]() {
  1820. setupSignalHandlers();
  1821. port = svr.bind_to_any_port("localhost");
  1822. svr.listen_after_bind();
  1823. });
  1824. auto se = detail::scope_exit([&] {
  1825. svr.stop();
  1826. thread.join();
  1827. ASSERT_FALSE(svr.is_running());
  1828. });
  1829. svr.wait_until_ready();
  1830. ASSERT_TRUE(svr.is_running());
  1831. pthread_kill(thread.native_handle(), SIGINT);
  1832. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1833. ASSERT_TRUE(svr.is_running());
  1834. }
  1835. #endif
  1836. TEST(RedirectToDifferentPort, Redirect) {
  1837. Server svr1;
  1838. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1839. res.set_content("Hello World!", "text/plain");
  1840. });
  1841. int svr1_port = 0;
  1842. auto thread1 = std::thread([&]() {
  1843. svr1_port = svr1.bind_to_any_port("localhost");
  1844. svr1.listen_after_bind();
  1845. });
  1846. Server svr2;
  1847. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1848. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1849. });
  1850. int svr2_port = 0;
  1851. auto thread2 = std::thread([&]() {
  1852. svr2_port = svr2.bind_to_any_port("localhost");
  1853. svr2.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr2.stop();
  1857. thread2.join();
  1858. svr1.stop();
  1859. thread1.join();
  1860. ASSERT_FALSE(svr2.is_running());
  1861. ASSERT_FALSE(svr1.is_running());
  1862. });
  1863. svr1.wait_until_ready();
  1864. svr2.wait_until_ready();
  1865. Client cli("localhost", svr2_port);
  1866. cli.set_follow_location(true);
  1867. auto res = cli.Get("/2");
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", res->body);
  1871. }
  1872. TEST(RedirectFromPageWithContent, Redirect) {
  1873. Server svr;
  1874. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("___", "text/plain");
  1876. res.set_redirect("/2");
  1877. });
  1878. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!", "text/plain");
  1880. });
  1881. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. th.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. {
  1889. Client cli("localhost", PORT);
  1890. cli.set_follow_location(true);
  1891. std::string body;
  1892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1893. body.append(data, data_length);
  1894. return true;
  1895. });
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::OK_200, res->status);
  1898. EXPECT_EQ("Hello World!", body);
  1899. }
  1900. {
  1901. Client cli("localhost", PORT);
  1902. std::string body;
  1903. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1904. body.append(data, data_length);
  1905. return true;
  1906. });
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::Found_302, res->status);
  1909. EXPECT_EQ("___", body);
  1910. }
  1911. }
  1912. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1913. Server svr;
  1914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1915. res.set_content("___", "text/plain");
  1916. // res.set_redirect("/2");
  1917. res.set_redirect("http://[::1]:1234/2");
  1918. });
  1919. svr.Get("/2", [&](const Request &req, Response &res) {
  1920. auto host_header = req.headers.find("Host");
  1921. ASSERT_TRUE(host_header != req.headers.end());
  1922. EXPECT_EQ("[::1]:1234", host_header->second);
  1923. res.set_content("Hello World!", "text/plain");
  1924. });
  1925. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. th.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1932. // actually starts anything, so the condition !svr.is_running() will
  1933. // always remain true, and the loop never stops.
  1934. // This basically counts how many milliseconds have passed since the
  1935. // call to svr.listen(), and if after 5 seconds nothing started yet
  1936. // aborts the test.
  1937. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1938. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1939. ASSERT_LT(milliseconds, 5000U);
  1940. }
  1941. {
  1942. Client cli("http://[::1]:1234");
  1943. cli.set_follow_location(true);
  1944. std::string body;
  1945. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(StatusCode::OK_200, res->status);
  1951. EXPECT_EQ("Hello World!", body);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. std::string body;
  1956. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::Found_302, res->status);
  1962. EXPECT_EQ("___", body);
  1963. }
  1964. }
  1965. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1966. Server svr;
  1967. svr.Get("/foo", [](const Request &req, Response &res) {
  1968. auto a = req.params.find("a");
  1969. if (a != req.params.end()) {
  1970. res.set_content((*a).second, "text/plain");
  1971. res.status = StatusCode::OK_200;
  1972. } else {
  1973. res.status = StatusCode::BadRequest_400;
  1974. }
  1975. });
  1976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1977. auto se = detail::scope_exit([&] {
  1978. svr.stop();
  1979. thread.join();
  1980. ASSERT_FALSE(svr.is_running());
  1981. });
  1982. svr.wait_until_ready();
  1983. {
  1984. Client cli(HOST, PORT);
  1985. cli.set_path_encode(false);
  1986. auto res = cli.Get("/foo?a=explicitly+encoded");
  1987. ASSERT_TRUE(res);
  1988. EXPECT_EQ(StatusCode::OK_200, res->status);
  1989. // This expects it back with a space, as the `+` won't have been
  1990. // url-encoded, and server-side the params get decoded turning `+`
  1991. // into spaces.
  1992. EXPECT_EQ("explicitly encoded", res->body);
  1993. }
  1994. }
  1995. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1996. Server svr;
  1997. svr.Get("/", [](const Request &req, Response &) {
  1998. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1999. });
  2000. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2001. auto se = detail::scope_exit([&] {
  2002. svr.stop();
  2003. thread.join();
  2004. ASSERT_FALSE(svr.is_running());
  2005. });
  2006. svr.wait_until_ready();
  2007. {
  2008. Client cli(HOST, PORT);
  2009. cli.set_path_encode(false);
  2010. auto res = cli.Get("/?something=%0A");
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. }
  2014. }
  2015. TEST(BindServerTest, DISABLED_BindDualStack) {
  2016. Server svr;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. {
  2028. Client cli("127.0.0.1", PORT);
  2029. auto res = cli.Get("/1");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::OK_200, res->status);
  2032. EXPECT_EQ("Hello World!", res->body);
  2033. }
  2034. {
  2035. Client cli("::1", PORT);
  2036. auto res = cli.Get("/1");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("Hello World!", res->body);
  2040. }
  2041. }
  2042. TEST(BindServerTest, BindAndListenSeparately) {
  2043. Server svr;
  2044. int port = svr.bind_to_any_port("0.0.0.0");
  2045. ASSERT_TRUE(svr.is_valid());
  2046. ASSERT_TRUE(port > 0);
  2047. svr.stop();
  2048. }
  2049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2050. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2052. CLIENT_CA_CERT_DIR);
  2053. int port = svr.bind_to_any_port("0.0.0.0");
  2054. ASSERT_TRUE(svr.is_valid());
  2055. ASSERT_TRUE(port > 0);
  2056. svr.stop();
  2057. }
  2058. #endif
  2059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2060. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2061. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2062. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2063. int port = svr.bind_to_any_port("0.0.0.0");
  2064. ASSERT_TRUE(svr.is_valid());
  2065. ASSERT_TRUE(port > 0);
  2066. svr.stop();
  2067. }
  2068. #endif
  2069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2070. X509 *readCertificate(const std::string &strFileName) {
  2071. std::ifstream inStream(strFileName);
  2072. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2073. std::istreambuf_iterator<char>());
  2074. if (strCertPEM.empty()) return (nullptr);
  2075. BIO *pbCert = BIO_new(BIO_s_mem());
  2076. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2077. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2078. BIO_free(pbCert);
  2079. return (pCert);
  2080. }
  2081. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2082. std::ifstream inStream(strFileName);
  2083. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2084. std::istreambuf_iterator<char>());
  2085. if (strPrivateKeyPEM.empty()) return (nullptr);
  2086. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2087. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2088. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2089. BIO_free(pbPrivKey);
  2090. return (pPrivateKey);
  2091. }
  2092. TEST(BindServerTest, UpdateCerts) {
  2093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2094. int port = svr.bind_to_any_port("0.0.0.0");
  2095. ASSERT_TRUE(svr.is_valid());
  2096. ASSERT_TRUE(port > 0);
  2097. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2098. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2099. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2100. ASSERT_TRUE(cert != nullptr);
  2101. ASSERT_TRUE(ca_cert != nullptr);
  2102. ASSERT_TRUE(key != nullptr);
  2103. X509_STORE *cert_store = X509_STORE_new();
  2104. X509_STORE_add_cert(cert_store, ca_cert);
  2105. svr.update_certs(cert, key, cert_store);
  2106. ASSERT_TRUE(svr.is_valid());
  2107. svr.stop();
  2108. X509_free(cert);
  2109. X509_free(ca_cert);
  2110. EVP_PKEY_free(key);
  2111. }
  2112. #endif
  2113. TEST(ErrorHandlerTest, ContentLength) {
  2114. Server svr;
  2115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2116. res.status = StatusCode::OK_200;
  2117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2118. "text/html"); // <= Content-Length still 13
  2119. });
  2120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!\n", "text/plain");
  2122. res.status = 524;
  2123. });
  2124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2125. auto se = detail::scope_exit([&] {
  2126. svr.stop();
  2127. thread.join();
  2128. ASSERT_FALSE(svr.is_running());
  2129. });
  2130. svr.wait_until_ready();
  2131. {
  2132. Client cli(HOST, PORT);
  2133. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2139. }
  2140. }
  2141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2142. TEST(ExceptionTest, WithoutExceptionHandler) {
  2143. Server svr;
  2144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2145. throw std::runtime_error("exception...");
  2146. });
  2147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2148. throw std::runtime_error("exception\r\n...");
  2149. });
  2150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. listen_thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. Client cli("localhost", PORT);
  2158. {
  2159. auto res = cli.Get("/exception");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2163. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2164. }
  2165. {
  2166. auto res = cli.Get("/unknown");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2169. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2170. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2171. }
  2172. }
  2173. TEST(ExceptionTest, WithExceptionHandler) {
  2174. Server svr;
  2175. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2176. std::exception_ptr ep) {
  2177. EXPECT_FALSE(ep == nullptr);
  2178. try {
  2179. std::rethrow_exception(ep);
  2180. } catch (std::exception &e) {
  2181. EXPECT_EQ("abc", std::string(e.what()));
  2182. } catch (...) {}
  2183. res.status = StatusCode::InternalServerError_500;
  2184. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2185. "text/html"); // <= Content-Length still 13 at this point
  2186. });
  2187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2188. res.set_content("Hello World!\n", "text/plain");
  2189. throw std::runtime_error("abc");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. for (size_t i = 0; i < 10; i++) {
  2199. Client cli(HOST, PORT);
  2200. for (size_t j = 0; j < 100; j++) {
  2201. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2205. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2206. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2207. }
  2208. cli.set_keep_alive(true);
  2209. for (size_t j = 0; j < 100; j++) {
  2210. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2216. }
  2217. }
  2218. }
  2219. TEST(ExceptionTest, AndErrorHandler) {
  2220. Server svr;
  2221. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2222. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2223. });
  2224. svr.set_exception_handler(
  2225. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2226. EXPECT_FALSE(ep == nullptr);
  2227. try {
  2228. std::rethrow_exception(ep);
  2229. } catch (std::exception &e) {
  2230. res.set_content(e.what(), "text/html");
  2231. } catch (...) {}
  2232. res.status = StatusCode::InternalServerError_500;
  2233. });
  2234. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2235. throw std::runtime_error("EXCEPTION");
  2236. });
  2237. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2238. res.set_content("ERROR", "text/html");
  2239. res.status = StatusCode::InternalServerError_500;
  2240. });
  2241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2242. auto se = detail::scope_exit([&] {
  2243. svr.stop();
  2244. thread.join();
  2245. ASSERT_FALSE(svr.is_running());
  2246. });
  2247. svr.wait_until_ready();
  2248. Client cli(HOST, PORT);
  2249. {
  2250. auto res = cli.Get("/exception");
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2253. EXPECT_EQ("EXCEPTION", res->body);
  2254. }
  2255. {
  2256. auto res = cli.Get("/error");
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2259. EXPECT_EQ("ERROR", res->body);
  2260. }
  2261. {
  2262. auto res = cli.Get("/invalid");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("NOT_FOUND", res->body);
  2266. }
  2267. }
  2268. #endif
  2269. TEST(NoContentTest, ContentLength) {
  2270. Server svr;
  2271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2272. res.status = StatusCode::NoContent_204;
  2273. });
  2274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. {
  2282. Client cli(HOST, PORT);
  2283. auto res = cli.Get("/hi");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2287. }
  2288. }
  2289. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2292. ASSERT_TRUE(svr.is_valid());
  2293. #else
  2294. Server svr;
  2295. #endif
  2296. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2297. if (req.path == "/routing_handler") {
  2298. res.set_header("PRE_ROUTING", "on");
  2299. res.set_content("Routing Handler", "text/plain");
  2300. return httplib::Server::HandlerResponse::Handled;
  2301. }
  2302. return httplib::Server::HandlerResponse::Unhandled;
  2303. });
  2304. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2305. res.set_content("Error", "text/html");
  2306. });
  2307. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2308. if (req.path == "/routing_handler") {
  2309. res.set_header("POST_ROUTING", "on");
  2310. }
  2311. });
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.set_content("Hello World!\n", "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2324. SSLClient cli(HOST, PORT);
  2325. cli.enable_server_certificate_verification(false);
  2326. #else
  2327. Client cli(HOST, PORT);
  2328. #endif
  2329. auto res = cli.Get("/routing_handler");
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::OK_200, res->status);
  2332. EXPECT_EQ("Routing Handler", res->body);
  2333. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2334. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2335. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2336. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2337. }
  2338. {
  2339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2340. SSLClient cli(HOST, PORT);
  2341. cli.enable_server_certificate_verification(false);
  2342. #else
  2343. Client cli(HOST, PORT);
  2344. #endif
  2345. auto res = cli.Get("/hi");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(StatusCode::OK_200, res->status);
  2348. EXPECT_EQ("Hello World!\n", res->body);
  2349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2351. }
  2352. {
  2353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2354. SSLClient cli(HOST, PORT);
  2355. cli.enable_server_certificate_verification(false);
  2356. #else
  2357. Client cli(HOST, PORT);
  2358. #endif
  2359. auto res = cli.Get("/aaa");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2362. EXPECT_EQ("Error", res->body);
  2363. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2364. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2365. }
  2366. }
  2367. TEST(RequestHandlerTest, PreRequestHandler) {
  2368. auto route_path = "/user/:user";
  2369. Server svr;
  2370. svr.Get("/hi", [](const Request &, Response &res) {
  2371. res.set_content("hi", "text/plain");
  2372. });
  2373. svr.Get(route_path, [](const Request &req, Response &res) {
  2374. res.set_content(req.path_params.at("user"), "text/plain");
  2375. });
  2376. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2377. if (req.matched_route == route_path) {
  2378. auto user = req.path_params.at("user");
  2379. if (user != "john") {
  2380. res.status = StatusCode::Forbidden_403;
  2381. res.set_content("error", "text/html");
  2382. return Server::HandlerResponse::Handled;
  2383. }
  2384. }
  2385. return Server::HandlerResponse::Unhandled;
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. Client cli(HOST, PORT);
  2395. {
  2396. auto res = cli.Get("/hi");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ("hi", res->body);
  2400. }
  2401. {
  2402. auto res = cli.Get("/user/john");
  2403. ASSERT_TRUE(res);
  2404. EXPECT_EQ(StatusCode::OK_200, res->status);
  2405. EXPECT_EQ("john", res->body);
  2406. }
  2407. {
  2408. auto res = cli.Get("/user/invalid-user");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2411. EXPECT_EQ("error", res->body);
  2412. }
  2413. }
  2414. TEST(InvalidFormatTest, StatusCode) {
  2415. Server svr;
  2416. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2417. res.set_content("Hello World!\n", "text/plain");
  2418. res.status = 9999; // Status should be a three-digit code...
  2419. });
  2420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2421. auto se = detail::scope_exit([&] {
  2422. svr.stop();
  2423. thread.join();
  2424. ASSERT_FALSE(svr.is_running());
  2425. });
  2426. svr.wait_until_ready();
  2427. {
  2428. Client cli(HOST, PORT);
  2429. auto res = cli.Get("/hi");
  2430. ASSERT_FALSE(res);
  2431. }
  2432. }
  2433. TEST(URLFragmentTest, WithFragment) {
  2434. Server svr;
  2435. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2436. EXPECT_TRUE(req.target == "/hi");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. {
  2446. Client cli(HOST, PORT);
  2447. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2448. EXPECT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::OK_200, res->status);
  2450. res = cli.Get("/hi%23key1=val1=key2=val2");
  2451. EXPECT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2453. }
  2454. }
  2455. TEST(HeaderWriter, SetHeaderWriter) {
  2456. Server svr;
  2457. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2458. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2459. return detail::write_headers(strm, hdrs);
  2460. });
  2461. svr.Get("/hi", [](const Request &req, Response &res) {
  2462. auto it = req.headers.find("CustomClientHeader");
  2463. EXPECT_TRUE(it != req.headers.end());
  2464. EXPECT_EQ(it->second, "CustomClientValue");
  2465. res.set_content("Hello World!\n", "text/plain");
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. {
  2475. Client cli(HOST, PORT);
  2476. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2477. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2478. return detail::write_headers(strm, hdrs);
  2479. });
  2480. auto res = cli.Get("/hi");
  2481. EXPECT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::OK_200, res->status);
  2483. auto it = res->headers.find("CustomServerHeader");
  2484. EXPECT_TRUE(it != res->headers.end());
  2485. EXPECT_EQ(it->second, "CustomServerValue");
  2486. }
  2487. }
  2488. class ServerTest : public ::testing::Test {
  2489. protected:
  2490. ServerTest()
  2491. : cli_(HOST, PORT)
  2492. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2493. ,
  2494. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2495. #endif
  2496. {
  2497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2498. cli_.enable_server_certificate_verification(false);
  2499. #endif
  2500. }
  2501. virtual void SetUp() {
  2502. svr_.set_mount_point("/", "./www");
  2503. svr_.set_mount_point("/mount", "./www2");
  2504. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2505. svr_.Get("/hi",
  2506. [&](const Request & /*req*/, Response &res) {
  2507. res.set_content("Hello World!", "text/plain");
  2508. })
  2509. .Get("/file_content",
  2510. [&](const Request & /*req*/, Response &res) {
  2511. res.set_file_content("./www/dir/test.html");
  2512. })
  2513. .Get("/file_content_with_content_type",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_file_content("./www/file", "text/plain");
  2516. })
  2517. .Get("/invalid_file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/invalid_file_path");
  2520. })
  2521. .Get("/http_response_splitting",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2524. EXPECT_EQ(0U, res.headers.size());
  2525. EXPECT_FALSE(res.has_header("a"));
  2526. res.set_header("a", "1\nSet-Cookie: a=1");
  2527. EXPECT_EQ(0U, res.headers.size());
  2528. EXPECT_FALSE(res.has_header("a"));
  2529. res.set_header("a", "1\rSet-Cookie: a=1");
  2530. EXPECT_EQ(0U, res.headers.size());
  2531. EXPECT_FALSE(res.has_header("a"));
  2532. res.set_header("a\r\nb", "0");
  2533. EXPECT_EQ(0U, res.headers.size());
  2534. EXPECT_FALSE(res.has_header("a"));
  2535. res.set_header("a\rb", "0");
  2536. EXPECT_EQ(0U, res.headers.size());
  2537. EXPECT_FALSE(res.has_header("a"));
  2538. res.set_header("a\nb", "0");
  2539. EXPECT_EQ(0U, res.headers.size());
  2540. EXPECT_FALSE(res.has_header("a"));
  2541. res.set_redirect("1\r\nSet-Cookie: a=1");
  2542. EXPECT_EQ(0U, res.headers.size());
  2543. EXPECT_FALSE(res.has_header("Location"));
  2544. })
  2545. .Get("/slow",
  2546. [&](const Request & /*req*/, Response &res) {
  2547. std::this_thread::sleep_for(std::chrono::seconds(2));
  2548. res.set_content("slow", "text/plain");
  2549. })
  2550. #if 0
  2551. .Post("/slowpost",
  2552. [&](const Request & /*req*/, Response &res) {
  2553. std::this_thread::sleep_for(std::chrono::seconds(2));
  2554. res.set_content("slow", "text/plain");
  2555. })
  2556. #endif
  2557. .Get("/remote_addr",
  2558. [&](const Request &req, Response &res) {
  2559. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2560. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2561. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2562. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2563. res.set_content(req.remote_addr, "text/plain");
  2564. })
  2565. .Get("/local_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2568. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2571. auto local_addr = req.local_addr;
  2572. auto local_port = std::to_string(req.local_port);
  2573. res.set_content(local_addr.append(":").append(local_port),
  2574. "text/plain");
  2575. })
  2576. .Get("/endwith%",
  2577. [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. })
  2580. .Get("/a\\+\\+b",
  2581. [&](const Request &req, Response &res) {
  2582. ASSERT_TRUE(req.has_param("a +b"));
  2583. auto val = req.get_param_value("a +b");
  2584. res.set_content(val, "text/plain");
  2585. })
  2586. .Get("/", [&](const Request & /*req*/,
  2587. Response &res) { res.set_redirect("/hi"); })
  2588. .Post("/1",
  2589. [](const Request & /*req*/, Response &res) {
  2590. res.set_redirect("/2", StatusCode::SeeOther_303);
  2591. })
  2592. .Get("/2",
  2593. [](const Request & /*req*/, Response &res) {
  2594. res.set_content("redirected.", "text/plain");
  2595. res.status = StatusCode::OK_200;
  2596. })
  2597. .Post("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name") && req.has_param("note")) {
  2600. persons_[req.get_param_value("name")] =
  2601. req.get_param_value("note");
  2602. } else {
  2603. res.status = StatusCode::BadRequest_400;
  2604. }
  2605. })
  2606. .Put("/person",
  2607. [&](const Request &req, Response &res) {
  2608. if (req.has_param("name") && req.has_param("note")) {
  2609. persons_[req.get_param_value("name")] =
  2610. req.get_param_value("note");
  2611. } else {
  2612. res.status = StatusCode::BadRequest_400;
  2613. }
  2614. })
  2615. .Get("/person/(.*)",
  2616. [&](const Request &req, Response &res) {
  2617. string name = req.matches[1];
  2618. if (persons_.find(name) != persons_.end()) {
  2619. auto note = persons_[name];
  2620. res.set_content(note, "text/plain");
  2621. } else {
  2622. res.status = StatusCode::NotFound_404;
  2623. }
  2624. })
  2625. .Delete("/person",
  2626. [&](const Request &req, Response &res) {
  2627. if (req.has_param("name")) {
  2628. string name = req.get_param_value("name");
  2629. if (persons_.find(name) != persons_.end()) {
  2630. persons_.erase(name);
  2631. res.set_content("DELETED", "text/plain");
  2632. } else {
  2633. res.status = StatusCode::NotFound_404;
  2634. }
  2635. } else {
  2636. res.status = StatusCode::BadRequest_400;
  2637. }
  2638. })
  2639. .Post("/x-www-form-urlencoded-json",
  2640. [&](const Request &req, Response &res) {
  2641. auto json = req.get_param_value("json");
  2642. ASSERT_EQ(JSON_DATA, json);
  2643. res.set_content(json, "appliation/json");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Get("/streamed-chunked",
  2647. [&](const Request & /*req*/, Response &res) {
  2648. res.set_chunked_content_provider(
  2649. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2650. sink.os << "123";
  2651. sink.os << "456";
  2652. sink.os << "789";
  2653. sink.done();
  2654. return true;
  2655. });
  2656. })
  2657. .Get("/streamed-chunked-with-prohibited-trailer",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. auto i = new int(0);
  2660. // Declare both a prohibited trailer (Content-Length) and an
  2661. // allowed one
  2662. res.set_header("Trailer", "Content-Length, X-Allowed");
  2663. res.set_chunked_content_provider(
  2664. "text/plain",
  2665. [i](size_t /*offset*/, DataSink &sink) {
  2666. switch (*i) {
  2667. case 0: sink.os << "123"; break;
  2668. case 1: sink.os << "456"; break;
  2669. case 2: sink.os << "789"; break;
  2670. case 3: {
  2671. sink.done_with_trailer(
  2672. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2673. } break;
  2674. }
  2675. (*i)++;
  2676. return true;
  2677. },
  2678. [i](bool success) {
  2679. EXPECT_TRUE(success);
  2680. delete i;
  2681. });
  2682. })
  2683. .Get("/streamed-chunked2",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. auto i = new int(0);
  2686. res.set_chunked_content_provider(
  2687. "text/plain",
  2688. [i](size_t /*offset*/, DataSink &sink) {
  2689. switch (*i) {
  2690. case 0: sink.os << "123"; break;
  2691. case 1: sink.os << "456"; break;
  2692. case 2: sink.os << "789"; break;
  2693. case 3: sink.done(); break;
  2694. }
  2695. (*i)++;
  2696. return true;
  2697. },
  2698. [i](bool success) {
  2699. EXPECT_TRUE(success);
  2700. delete i;
  2701. });
  2702. })
  2703. .Get("/streamed-chunked-with-trailer",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. auto i = new int(0);
  2706. res.set_header("Trailer", "Dummy1, Dummy2");
  2707. res.set_chunked_content_provider(
  2708. "text/plain",
  2709. [i](size_t /*offset*/, DataSink &sink) {
  2710. switch (*i) {
  2711. case 0: sink.os << "123"; break;
  2712. case 1: sink.os << "456"; break;
  2713. case 2: sink.os << "789"; break;
  2714. case 3: {
  2715. sink.done_with_trailer(
  2716. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2717. } break;
  2718. }
  2719. (*i)++;
  2720. return true;
  2721. },
  2722. [i](bool success) {
  2723. EXPECT_TRUE(success);
  2724. delete i;
  2725. });
  2726. })
  2727. .Get("/streamed",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_content_provider(
  2730. 6, "text/plain",
  2731. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2732. sink.os << (offset < 3 ? "a" : "b");
  2733. return true;
  2734. });
  2735. })
  2736. .Get("/streamed-with-range",
  2737. [&](const Request &req, Response &res) {
  2738. auto data = new std::string("abcdefg");
  2739. res.set_content_provider(
  2740. data->size(), "text/plain",
  2741. [data](size_t offset, size_t length, DataSink &sink) {
  2742. size_t DATA_CHUNK_SIZE = 4;
  2743. const auto &d = *data;
  2744. auto out_len =
  2745. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2746. auto ret =
  2747. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2748. EXPECT_TRUE(ret);
  2749. return true;
  2750. },
  2751. [data, &req](bool success) {
  2752. EXPECT_EQ(success, !req.has_param("error"));
  2753. delete data;
  2754. });
  2755. })
  2756. .Get("/streamed-cancel",
  2757. [&](const Request & /*req*/, Response &res) {
  2758. res.set_content_provider(
  2759. size_t(-1), "text/plain",
  2760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2761. sink.os << "data_chunk";
  2762. return true;
  2763. });
  2764. })
  2765. .Get("/regex-with-delimiter",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. ASSERT_TRUE(req.has_param("key"));
  2768. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2769. })
  2770. .Get("/with-range",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_content("abcdefg", "text/plain");
  2773. })
  2774. .Get("/test-start-time",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_NE(req.start_time_,
  2777. std::chrono::steady_clock::time_point::min());
  2778. })
  2779. .Get("/with-range-customized-response",
  2780. [&](const Request & /*req*/, Response &res) {
  2781. res.status = StatusCode::BadRequest_400;
  2782. res.set_content(JSON_DATA, "application/json");
  2783. })
  2784. .Post("/chunked",
  2785. [&](const Request &req, Response & /*res*/) {
  2786. EXPECT_EQ(req.body, "dechunked post body");
  2787. })
  2788. .Post("/large-chunked",
  2789. [&](const Request &req, Response & /*res*/) {
  2790. std::string expected(6 * 30 * 1024u, 'a');
  2791. EXPECT_EQ(req.body, expected);
  2792. })
  2793. .Post("/multipart",
  2794. [&](const Request &req, Response & /*res*/) {
  2795. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2796. req.form.get_field_count("text2") +
  2797. req.form.get_field_count("file3") +
  2798. req.form.get_field_count("file4"));
  2799. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2800. req.form.get_file_count("file2"));
  2801. ASSERT_TRUE(!req.form.has_file("???"));
  2802. ASSERT_TRUE(!req.form.has_field("???"));
  2803. ASSERT_TRUE(req.body.empty());
  2804. {
  2805. const auto &text = req.form.get_field("text1");
  2806. EXPECT_EQ("text default", text);
  2807. }
  2808. {
  2809. const auto &text = req.form.get_field("text2");
  2810. EXPECT_EQ("aωb", text);
  2811. }
  2812. {
  2813. const auto &file = req.form.get_file("file1");
  2814. EXPECT_EQ("hello.txt", file.filename);
  2815. EXPECT_EQ("text/plain", file.content_type);
  2816. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2817. }
  2818. {
  2819. const auto &file = req.form.get_file("file2");
  2820. EXPECT_EQ("world.json", file.filename);
  2821. EXPECT_EQ("application/json", file.content_type);
  2822. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2823. }
  2824. {
  2825. const auto &text = req.form.get_field("file3");
  2826. EXPECT_EQ(0u, text.size());
  2827. }
  2828. {
  2829. const auto &text = req.form.get_field("file4");
  2830. EXPECT_EQ(0u, text.size());
  2831. }
  2832. })
  2833. .Post("/multipart/multi_file_values",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2836. req.form.get_field_count("multi_text1"));
  2837. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2838. ASSERT_TRUE(!req.form.has_file("???"));
  2839. ASSERT_TRUE(!req.form.has_field("???"));
  2840. ASSERT_TRUE(req.body.empty());
  2841. {
  2842. const auto &text = req.form.get_field("text");
  2843. EXPECT_EQ("default text", text);
  2844. }
  2845. {
  2846. const auto &text1_values = req.form.get_fields("multi_text1");
  2847. EXPECT_EQ(2u, text1_values.size());
  2848. EXPECT_EQ("aaaaa", text1_values[0]);
  2849. EXPECT_EQ("bbbbb", text1_values[1]);
  2850. }
  2851. {
  2852. const auto &file1_values = req.form.get_files("multi_file1");
  2853. EXPECT_EQ(2u, file1_values.size());
  2854. auto file1 = file1_values[0];
  2855. EXPECT_EQ(file1.filename, "hello.txt");
  2856. EXPECT_EQ(file1.content_type, "text/plain");
  2857. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2858. auto file2 = file1_values[1];
  2859. EXPECT_EQ(file2.filename, "world.json");
  2860. EXPECT_EQ(file2.content_type, "application/json");
  2861. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2862. }
  2863. })
  2864. .Post("/empty",
  2865. [&](const Request &req, Response &res) {
  2866. EXPECT_EQ(req.body, "");
  2867. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2869. res.set_content("empty", "text/plain");
  2870. })
  2871. .Post("/empty-no-content-type",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "");
  2874. EXPECT_FALSE(req.has_header("Content-Type"));
  2875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2876. res.set_content("empty-no-content-type", "text/plain");
  2877. })
  2878. .Post("/path-only",
  2879. [&](const Request &req, Response &res) {
  2880. EXPECT_EQ(req.body, "");
  2881. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2882. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2883. res.set_content("path-only", "text/plain");
  2884. })
  2885. .Post("/path-headers-only",
  2886. [&](const Request &req, Response &res) {
  2887. EXPECT_EQ(req.body, "");
  2888. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2889. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2890. EXPECT_EQ("world", req.get_header_value("hello"));
  2891. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2892. res.set_content("path-headers-only", "text/plain");
  2893. })
  2894. .Post("/post-large",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(req.body, LARGE_DATA);
  2897. res.set_content(req.body, "text/plain");
  2898. })
  2899. .Post("/post-loopback",
  2900. [&](const Request &, Response &res,
  2901. ContentReader const &content_reader) {
  2902. std::string body;
  2903. content_reader([&](const char *data, size_t data_length) {
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. res.set_content(body, "text/plain");
  2908. })
  2909. .Put("/put-loopback",
  2910. [&](const Request &, Response &res,
  2911. ContentReader const &content_reader) {
  2912. std::string body;
  2913. content_reader([&](const char *data, size_t data_length) {
  2914. body.append(data, data_length);
  2915. return true;
  2916. });
  2917. res.set_content(body, "text/plain");
  2918. })
  2919. .Patch("/patch-loopback",
  2920. [&](const Request &, Response &res,
  2921. ContentReader const &content_reader) {
  2922. std::string body;
  2923. content_reader([&](const char *data, size_t data_length) {
  2924. body.append(data, data_length);
  2925. return true;
  2926. });
  2927. res.set_content(body, "text/plain");
  2928. })
  2929. .Put("/empty-no-content-type",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "");
  2932. EXPECT_FALSE(req.has_header("Content-Type"));
  2933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2934. res.set_content("empty-no-content-type", "text/plain");
  2935. })
  2936. .Put("/put",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "PUT");
  2939. res.set_content(req.body, "text/plain");
  2940. })
  2941. .Put("/put-large",
  2942. [&](const Request &req, Response &res) {
  2943. EXPECT_EQ(req.body, LARGE_DATA);
  2944. res.set_content(req.body, "text/plain");
  2945. })
  2946. .Patch("/patch",
  2947. [&](const Request &req, Response &res) {
  2948. EXPECT_EQ(req.body, "PATCH");
  2949. res.set_content(req.body, "text/plain");
  2950. })
  2951. .Delete("/delete",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_content("DELETE", "text/plain");
  2954. })
  2955. .Delete("/delete-body",
  2956. [&](const Request &req, Response &res) {
  2957. EXPECT_EQ(req.body, "content");
  2958. res.set_content(req.body, "text/plain");
  2959. })
  2960. .Options(R"(\*)",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2963. })
  2964. .Get("/request-target",
  2965. [&](const Request &req, Response & /*res*/) {
  2966. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2967. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2968. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2969. })
  2970. .Get("/long-query-value",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2973. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2974. })
  2975. .Get("/too-long-query-value",
  2976. [&](const Request &req, Response & /*res*/) {
  2977. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2978. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2979. })
  2980. .Get("/array-param",
  2981. [&](const Request &req, Response & /*res*/) {
  2982. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2983. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2984. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2985. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2986. })
  2987. .Post("/validate-no-multiple-headers",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2990. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2991. })
  2992. .Post("/content_receiver",
  2993. [&](const Request &req, Response &res,
  2994. const ContentReader &content_reader) {
  2995. if (req.is_multipart_form_data()) {
  2996. std::vector<FormData> items;
  2997. content_reader(
  2998. [&](const FormData &file) {
  2999. items.push_back(file);
  3000. return true;
  3001. },
  3002. [&](const char *data, size_t data_length) {
  3003. items.back().content.append(data, data_length);
  3004. return true;
  3005. });
  3006. EXPECT_EQ(5u, items.size());
  3007. {
  3008. const auto &file = get_file_value(items, "text1");
  3009. EXPECT_TRUE(file.filename.empty());
  3010. EXPECT_EQ("text default", file.content);
  3011. }
  3012. {
  3013. const auto &file = get_file_value(items, "text2");
  3014. EXPECT_TRUE(file.filename.empty());
  3015. EXPECT_EQ("aωb", file.content);
  3016. }
  3017. {
  3018. const auto &file = get_file_value(items, "file1");
  3019. EXPECT_EQ("hello.txt", file.filename);
  3020. EXPECT_EQ("text/plain", file.content_type);
  3021. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3022. }
  3023. {
  3024. const auto &file = get_file_value(items, "file2");
  3025. EXPECT_EQ("world.json", file.filename);
  3026. EXPECT_EQ("application/json", file.content_type);
  3027. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3028. }
  3029. {
  3030. const auto &file = get_file_value(items, "file3");
  3031. EXPECT_TRUE(file.filename.empty());
  3032. EXPECT_EQ("application/octet-stream", file.content_type);
  3033. EXPECT_EQ(0u, file.content.size());
  3034. }
  3035. } else {
  3036. std::string body;
  3037. content_reader([&](const char *data, size_t data_length) {
  3038. EXPECT_EQ(7U, data_length);
  3039. body.append(data, data_length);
  3040. return true;
  3041. });
  3042. EXPECT_EQ(body, "content");
  3043. res.set_content(body, "text/plain");
  3044. }
  3045. })
  3046. .Put("/content_receiver",
  3047. [&](const Request & /*req*/, Response &res,
  3048. const ContentReader &content_reader) {
  3049. std::string body;
  3050. content_reader([&](const char *data, size_t data_length) {
  3051. body.append(data, data_length);
  3052. return true;
  3053. });
  3054. EXPECT_EQ(body, "content");
  3055. res.set_content(body, "text/plain");
  3056. })
  3057. .Patch("/content_receiver",
  3058. [&](const Request & /*req*/, Response &res,
  3059. const ContentReader &content_reader) {
  3060. std::string body;
  3061. content_reader([&](const char *data, size_t data_length) {
  3062. body.append(data, data_length);
  3063. return true;
  3064. });
  3065. EXPECT_EQ(body, "content");
  3066. res.set_content(body, "text/plain");
  3067. })
  3068. .Post("/query-string-and-body",
  3069. [&](const Request &req, Response & /*res*/) {
  3070. ASSERT_TRUE(req.has_param("key"));
  3071. EXPECT_EQ(req.get_param_value("key"), "value");
  3072. EXPECT_EQ(req.body, "content");
  3073. })
  3074. .Get("/last-request",
  3075. [&](const Request &req, Response & /*res*/) {
  3076. EXPECT_EQ("close", req.get_header_value("Connection"));
  3077. })
  3078. .Get(R"(/redirect/(\d+))",
  3079. [&](const Request &req, Response &res) {
  3080. auto num = std::stoi(req.matches[1]) + 1;
  3081. std::string url = "/redirect/" + std::to_string(num);
  3082. res.set_redirect(url);
  3083. })
  3084. .Post("/binary",
  3085. [&](const Request &req, Response &res) {
  3086. EXPECT_EQ(4U, req.body.size());
  3087. EXPECT_EQ("application/octet-stream",
  3088. req.get_header_value("Content-Type"));
  3089. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3090. res.set_content(req.body, "application/octet-stream");
  3091. })
  3092. .Put("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Patch("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Delete("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Get("/issue1772",
  3117. [&](const Request & /*req*/, Response &res) {
  3118. res.status = 401;
  3119. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3120. })
  3121. .Delete("/issue609",
  3122. [](const httplib::Request &, httplib::Response &res,
  3123. const httplib::ContentReader &) {
  3124. res.set_content("ok", "text/plain");
  3125. })
  3126. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3127. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3128. .Get("/compress",
  3129. [&](const Request & /*req*/, Response &res) {
  3130. res.set_content(
  3131. "12345678901234567890123456789012345678901234567890123456789"
  3132. "01234567890123456789012345678901234567890",
  3133. "text/plain");
  3134. })
  3135. .Get("/nocompress",
  3136. [&](const Request & /*req*/, Response &res) {
  3137. res.set_content(
  3138. "12345678901234567890123456789012345678901234567890123456789"
  3139. "01234567890123456789012345678901234567890",
  3140. "application/octet-stream");
  3141. })
  3142. .Post("/compress-multipart",
  3143. [&](const Request &req, Response & /*res*/) {
  3144. EXPECT_EQ(2u, req.form.fields.size());
  3145. ASSERT_TRUE(!req.form.has_field("???"));
  3146. {
  3147. const auto &text = req.form.get_field("key1");
  3148. EXPECT_EQ("test", text);
  3149. }
  3150. {
  3151. const auto &text = req.form.get_field("key2");
  3152. EXPECT_EQ("--abcdefg123", text);
  3153. }
  3154. })
  3155. #endif
  3156. ;
  3157. persons_["john"] = "programmer";
  3158. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3159. svr_.wait_until_ready();
  3160. }
  3161. virtual void TearDown() {
  3162. svr_.stop();
  3163. if (!request_threads_.empty()) {
  3164. std::this_thread::sleep_for(std::chrono::seconds(1));
  3165. for (auto &t : request_threads_) {
  3166. t.join();
  3167. }
  3168. }
  3169. t_.join();
  3170. }
  3171. map<string, string> persons_;
  3172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3173. SSLClient cli_;
  3174. SSLServer svr_;
  3175. #else
  3176. Client cli_;
  3177. Server svr_;
  3178. #endif
  3179. thread t_;
  3180. std::vector<thread> request_threads_;
  3181. };
  3182. TEST_F(ServerTest, GetMethod200) {
  3183. auto res = cli_.Get("/hi");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ("HTTP/1.1", res->version);
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. EXPECT_EQ("OK", res->reason);
  3188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3190. EXPECT_EQ("Hello World!", res->body);
  3191. }
  3192. TEST_F(ServerTest, GetEmptyFile) {
  3193. auto res = cli_.Get("/empty_file");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3198. EXPECT_EQ("", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetFileContent) {
  3201. auto res = cli_.Get("/file_content");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("test.html", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContentWithRange) {
  3209. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3214. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3215. EXPECT_EQ("est", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetFileContentWithContentType) {
  3218. auto res = cli_.Get("/file_content_with_content_type");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("file\n", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetInvalidFileContent) {
  3226. auto res = cli_.Get("/invalid_file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3231. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ("HTTP/1.1", res->version);
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3236. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. TEST_F(ServerTest, GetMethod302) {
  3240. auto res = cli_.Get("/");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::Found_302, res->status);
  3243. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3244. }
  3245. TEST_F(ServerTest, GetMethod302Redirect) {
  3246. cli_.set_follow_location(true);
  3247. auto res = cli_.Get("/");
  3248. ASSERT_TRUE(res);
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. EXPECT_EQ("Hello World!", res->body);
  3251. EXPECT_EQ("/hi", res->location);
  3252. }
  3253. TEST_F(ServerTest, GetMethod404) {
  3254. auto res = cli_.Get("/invalid");
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3257. }
  3258. TEST_F(ServerTest, HeadMethod200) {
  3259. auto res = cli_.Head("/hi");
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. EXPECT_TRUE(res->body.empty());
  3264. }
  3265. TEST_F(ServerTest, HeadMethod200Static) {
  3266. auto res = cli_.Head("/mount/dir/index.html");
  3267. ASSERT_TRUE(res);
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3270. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod404) {
  3274. auto res = cli_.Head("/invalid");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3277. EXPECT_TRUE(res->body.empty());
  3278. }
  3279. TEST_F(ServerTest, GetMethodPersonJohn) {
  3280. auto res = cli_.Get("/person/john");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("programmer", res->body);
  3285. }
  3286. TEST_F(ServerTest, PostMethod1) {
  3287. auto res = cli_.Get("/person/john1");
  3288. ASSERT_TRUE(res);
  3289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3290. res = cli_.Post("/person", "name=john1&note=coder",
  3291. "application/x-www-form-urlencoded");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::OK_200, res->status);
  3294. res = cli_.Get("/person/john1");
  3295. ASSERT_TRUE(res);
  3296. ASSERT_EQ(StatusCode::OK_200, res->status);
  3297. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3298. ASSERT_EQ("coder", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostMethod2) {
  3301. auto res = cli_.Get("/person/john2");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john2");
  3306. params.emplace("note", "coder");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john2");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("coder", res->body);
  3315. }
  3316. TEST_F(ServerTest, PutMethod3) {
  3317. auto res = cli_.Get("/person/john3");
  3318. ASSERT_TRUE(res);
  3319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3320. Params params;
  3321. params.emplace("name", "john3");
  3322. params.emplace("note", "coder");
  3323. res = cli_.Put("/person", params);
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::OK_200, res->status);
  3326. res = cli_.Get("/person/john3");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3330. ASSERT_EQ("coder", res->body);
  3331. }
  3332. TEST_F(ServerTest, DeleteMethod1) {
  3333. auto res = cli_.Get("/person/john4");
  3334. ASSERT_TRUE(res);
  3335. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3336. Params params;
  3337. params.emplace("name", "john4");
  3338. params.emplace("note", "coder");
  3339. res = cli_.Post("/person", params);
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. res = cli_.Get("/person/john4");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3346. ASSERT_EQ("coder", res->body);
  3347. Params delete_params;
  3348. delete_params.emplace("name", "john4");
  3349. res = cli_.Delete("/person", delete_params);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john4");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod2) {
  3358. auto res = cli_.Get("/person/john5");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john5");
  3363. params.emplace("note", "developer");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john5");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("developer", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john5");
  3374. Headers headers;
  3375. headers.emplace("Custom-Header", "test-value");
  3376. res = cli_.Delete("/person", headers, delete_params);
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::OK_200, res->status);
  3379. ASSERT_EQ("DELETED", res->body);
  3380. res = cli_.Get("/person/john5");
  3381. ASSERT_TRUE(res);
  3382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3383. }
  3384. TEST_F(ServerTest, DeleteMethod3) {
  3385. auto res = cli_.Get("/person/john6");
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3388. Params params;
  3389. params.emplace("name", "john6");
  3390. params.emplace("note", "tester");
  3391. res = cli_.Post("/person", params);
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. res = cli_.Get("/person/john6");
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. ASSERT_EQ("tester", res->body);
  3399. Params delete_params;
  3400. delete_params.emplace("name", "john6");
  3401. Headers headers;
  3402. headers.emplace("Custom-Header", "test-value");
  3403. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3404. ASSERT_TRUE(res);
  3405. ASSERT_EQ(StatusCode::OK_200, res->status);
  3406. ASSERT_EQ("DELETED", res->body);
  3407. res = cli_.Get("/person/john6");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3412. Params params;
  3413. params.emplace("json", JSON_DATA);
  3414. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ(JSON_DATA, res->body);
  3418. }
  3419. TEST_F(ServerTest, PostEmptyContent) {
  3420. auto res = cli_.Post("/empty", "", "text/plain");
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::OK_200, res->status);
  3423. ASSERT_EQ("empty", res->body);
  3424. }
  3425. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3426. auto res = cli_.Post("/empty-no-content-type");
  3427. ASSERT_TRUE(res);
  3428. ASSERT_EQ(StatusCode::OK_200, res->status);
  3429. ASSERT_EQ("empty-no-content-type", res->body);
  3430. }
  3431. TEST_F(ServerTest, PostPathOnly) {
  3432. auto res = cli_.Post("/path-only");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::OK_200, res->status);
  3435. ASSERT_EQ("path-only", res->body);
  3436. }
  3437. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3438. auto res = cli_.Post("/path-headers-only",
  3439. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("path-headers-only", res->body);
  3443. }
  3444. TEST_F(ServerTest, PostLarge) {
  3445. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ(LARGE_DATA, res->body);
  3449. }
  3450. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3451. auto res = cli_.Put("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetMethodDir) {
  3457. auto res = cli_.Get("/dir/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. auto body = R"(<html>
  3462. <head>
  3463. </head>
  3464. <body>
  3465. <a href="/dir/test.html">Test</a>
  3466. <a href="/hi">hi</a>
  3467. </body>
  3468. </html>
  3469. )";
  3470. EXPECT_EQ(body, res->body);
  3471. }
  3472. TEST_F(ServerTest, GetMethodDirTest) {
  3473. auto res = cli_.Get("/dir/test.html");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("test.html", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3480. auto res = cli_.Get("/dir/../dir/test.html");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3484. EXPECT_EQ("test.html", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethodInvalidPath) {
  3487. auto res = cli_.Get("/dir/../test.html");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3490. }
  3491. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3492. auto res = cli_.Get("/../www/dir/test.html");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3495. }
  3496. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3497. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3500. }
  3501. TEST_F(ServerTest, GetMethodDirMountTest) {
  3502. auto res = cli_.Get("/mount/dir/test.html");
  3503. ASSERT_TRUE(res);
  3504. EXPECT_EQ(StatusCode::OK_200, res->status);
  3505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3506. EXPECT_EQ("test.html", res->body);
  3507. }
  3508. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3509. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("test.html", res->body);
  3514. }
  3515. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3516. auto res = cli_.Get("/mount/dir/../test.html");
  3517. ASSERT_TRUE(res);
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3521. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. }
  3525. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3526. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3527. ASSERT_TRUE(res);
  3528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3529. }
  3530. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3531. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3534. }
  3535. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3536. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, PostMethod303) {
  3541. auto res = cli_.Post("/1", "body", "text/plain");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3544. EXPECT_EQ("/2", res->get_header_value("Location"));
  3545. }
  3546. TEST_F(ServerTest, PostMethod303Redirect) {
  3547. cli_.set_follow_location(true);
  3548. auto res = cli_.Post("/1", "body", "text/plain");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ(StatusCode::OK_200, res->status);
  3551. EXPECT_EQ("redirected.", res->body);
  3552. EXPECT_EQ("/2", res->location);
  3553. }
  3554. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3555. auto res = cli_.Get("/dir/test.abcde");
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3559. EXPECT_EQ("abcde", res->body);
  3560. }
  3561. TEST_F(ServerTest, StaticFileRange) {
  3562. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3565. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3566. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3567. EXPECT_EQ(true, res->has_header("Content-Range"));
  3568. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3569. EXPECT_EQ(std::string("cd"), res->body);
  3570. }
  3571. TEST_F(ServerTest, StaticFileRanges) {
  3572. auto res =
  3573. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3576. EXPECT_TRUE(
  3577. res->get_header_value("Content-Type")
  3578. .find(
  3579. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3580. 0);
  3581. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3582. }
  3583. TEST_F(ServerTest, StaticFileRangeHead) {
  3584. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3585. ASSERT_TRUE(res);
  3586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3587. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3589. EXPECT_EQ(true, res->has_header("Content-Range"));
  3590. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3591. }
  3592. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3593. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3597. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3598. EXPECT_EQ(true, res->has_header("Content-Range"));
  3599. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3600. res->get_header_value("Content-Range"));
  3601. EXPECT_EQ("LAST\n", res->body);
  3602. }
  3603. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3604. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3609. EXPECT_EQ(true, res->has_header("Content-Range"));
  3610. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3611. }
  3612. TEST_F(ServerTest, StaticFileBigFile) {
  3613. auto res = cli_.Get("/dir/1MB.txt");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3617. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3618. }
  3619. TEST_F(ServerTest, InvalidBaseDirMount) {
  3620. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3621. }
  3622. TEST_F(ServerTest, Binary) {
  3623. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3624. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3625. "application/octet-stream");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ(4U, res->body.size());
  3629. res = cli_.Put("/binary", binary.data(), binary.size(),
  3630. "application/octet-stream");
  3631. ASSERT_TRUE(res);
  3632. ASSERT_EQ(StatusCode::OK_200, res->status);
  3633. ASSERT_EQ(4U, res->body.size());
  3634. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3635. "application/octet-stream");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ(4U, res->body.size());
  3639. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3640. "application/octet-stream");
  3641. ASSERT_TRUE(res);
  3642. ASSERT_EQ(StatusCode::OK_200, res->status);
  3643. ASSERT_EQ(4U, res->body.size());
  3644. }
  3645. TEST_F(ServerTest, BinaryString) {
  3646. auto binary = std::string("\x00\x01\x02\x03", 4);
  3647. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. ASSERT_EQ(4U, res->body.size());
  3651. res = cli_.Put("/binary", binary, "application/octet-stream");
  3652. ASSERT_TRUE(res);
  3653. ASSERT_EQ(StatusCode::OK_200, res->status);
  3654. ASSERT_EQ(4U, res->body.size());
  3655. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. }
  3664. TEST_F(ServerTest, EmptyRequest) {
  3665. auto res = cli_.Get("");
  3666. ASSERT_TRUE(!res);
  3667. EXPECT_EQ(Error::Connection, res.error());
  3668. }
  3669. TEST_F(ServerTest, LongRequest) {
  3670. std::string request;
  3671. for (size_t i = 0; i < 545; i++) {
  3672. request += "/TooLongRequest";
  3673. }
  3674. request += "OK";
  3675. auto res = cli_.Get(request.c_str());
  3676. ASSERT_TRUE(res);
  3677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3678. }
  3679. TEST_F(ServerTest, TooLongRequest) {
  3680. std::string request;
  3681. for (size_t i = 0; i < 546; i++) {
  3682. request += "/TooLongRequest";
  3683. }
  3684. request += "_NG";
  3685. auto start = std::chrono::high_resolution_clock::now();
  3686. cli_.set_keep_alive(true);
  3687. auto res = cli_.Get(request.c_str());
  3688. auto end = std::chrono::high_resolution_clock::now();
  3689. auto elapsed =
  3690. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3691. .count();
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3694. EXPECT_LE(elapsed, 100);
  3695. EXPECT_EQ("close", res->get_header_value("Connection"));
  3696. EXPECT_FALSE(cli_.is_socket_open());
  3697. }
  3698. TEST_F(ServerTest, AlmostTooLongRequest) {
  3699. // test for #2046 - URI length check shouldn't include other content on req
  3700. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3701. // leading /, space, HTTP/1.1)
  3702. std::string request =
  3703. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3704. auto res = cli_.Get(request.c_str());
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3707. }
  3708. TEST_F(ServerTest, LongHeader) {
  3709. Request req;
  3710. req.method = "GET";
  3711. req.path = "/hi";
  3712. std::string host_and_port;
  3713. host_and_port += HOST;
  3714. host_and_port += ":";
  3715. host_and_port += std::to_string(PORT);
  3716. req.headers.emplace("Host", host_and_port.c_str());
  3717. req.headers.emplace("Accept", "*/*");
  3718. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3719. req.headers.emplace(
  3720. "Header-Name",
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@");
  3750. auto res = std::make_shared<Response>();
  3751. auto error = Error::Success;
  3752. auto ret = cli_.send(req, *res, error);
  3753. ASSERT_TRUE(ret);
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST_F(ServerTest, LongQueryValue) {
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3760. auto end = std::chrono::high_resolution_clock::now();
  3761. auto elapsed =
  3762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3763. .count();
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3766. EXPECT_LE(elapsed, 100);
  3767. EXPECT_EQ("close", res->get_header_value("Connection"));
  3768. EXPECT_FALSE(cli_.is_socket_open());
  3769. }
  3770. TEST_F(ServerTest, TooLongQueryValue) {
  3771. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3772. ASSERT_FALSE(res);
  3773. EXPECT_EQ(Error::Read, res.error());
  3774. }
  3775. TEST_F(ServerTest, TooLongHeader) {
  3776. Request req;
  3777. req.method = "GET";
  3778. req.path = "/hi";
  3779. std::string host_and_port;
  3780. host_and_port += HOST;
  3781. host_and_port += ":";
  3782. host_and_port += std::to_string(PORT);
  3783. req.headers.emplace("Host", host_and_port.c_str());
  3784. req.headers.emplace("Accept", "*/*");
  3785. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3786. req.headers.emplace(
  3787. "Header-Name",
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@");
  3817. auto res = std::make_shared<Response>();
  3818. auto error = Error::Success;
  3819. auto ret = cli_.send(req, *res, error);
  3820. ASSERT_TRUE(ret);
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. TEST_F(ServerTest, HeaderCountAtLimit) {
  3824. // Test with headers just under the 100 limit
  3825. httplib::Headers headers;
  3826. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3827. // This should keep us just under the 100 header limit
  3828. for (int i = 0; i < 95; i++) {
  3829. std::string name = "X-Test-Header-" + std::to_string(i);
  3830. std::string value = "value" + std::to_string(i);
  3831. headers.emplace(name, value);
  3832. }
  3833. // This should work fine as we're under the limit
  3834. auto res = cli_.Get("/hi", headers);
  3835. EXPECT_TRUE(res);
  3836. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3837. }
  3838. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3839. // Test with many headers to exceed the 100 limit
  3840. httplib::Headers headers;
  3841. // Add 150 headers to definitely exceed the 100 limit
  3842. for (int i = 0; i < 150; i++) {
  3843. std::string name = "X-Test-Header-" + std::to_string(i);
  3844. std::string value = "value" + std::to_string(i);
  3845. headers.emplace(name, value);
  3846. }
  3847. // This should fail due to exceeding header count limit
  3848. cli_.set_keep_alive(true);
  3849. auto res = cli_.Get("/hi", headers);
  3850. // The request should either fail or return 400 Bad Request
  3851. if (res) {
  3852. // If we get a response, it should be 400 Bad Request
  3853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3854. } else {
  3855. // Or the request should fail entirely
  3856. EXPECT_FALSE(res);
  3857. }
  3858. EXPECT_EQ("close", res->get_header_value("Connection"));
  3859. EXPECT_FALSE(cli_.is_socket_open());
  3860. }
  3861. TEST_F(ServerTest, PercentEncoding) {
  3862. auto res = cli_.Get("/e%6edwith%");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, PercentEncodingUnicode) {
  3867. auto res = cli_.Get("/e%u006edwith%");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, InvalidPercentEncoding) {
  3872. auto res = cli_.Get("/%endwith%");
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3875. }
  3876. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3877. auto res = cli_.Get("/%uendwith%");
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3880. }
  3881. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3882. auto res = cli_.Get("/hello?aaa=bbb%");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3885. }
  3886. TEST_F(ServerTest, PlusSignEncoding) {
  3887. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. EXPECT_EQ("a +b", res->body);
  3891. }
  3892. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3893. // This test simulates a potential DoS attack using many headers
  3894. // to verify our security fix prevents memory exhaustion
  3895. httplib::Headers attack_headers;
  3896. // Attempt to add many headers like an attacker would (200 headers to far
  3897. // exceed limit)
  3898. for (int i = 0; i < 200; i++) {
  3899. std::string name = "X-Attack-Header-" + std::to_string(i);
  3900. std::string value = "attack_payload_" + std::to_string(i);
  3901. attack_headers.emplace(name, value);
  3902. }
  3903. // Try to POST with excessive headers
  3904. cli_.set_keep_alive(true);
  3905. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3906. // Should either fail or return 400 Bad Request due to security limit
  3907. if (res) {
  3908. // If we get a response, it should be 400 Bad Request
  3909. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3910. } else {
  3911. // Request failed, which is the expected behavior for DoS protection
  3912. EXPECT_FALSE(res);
  3913. }
  3914. EXPECT_EQ("close", res->get_header_value("Connection"));
  3915. EXPECT_FALSE(cli_.is_socket_open());
  3916. }
  3917. TEST_F(ServerTest, MultipartFormData) {
  3918. UploadFormDataItems items = {
  3919. {"text1", "text default", "", ""},
  3920. {"text2", "aωb", "", ""},
  3921. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3922. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3923. {"file3", "", "", "application/octet-stream"},
  3924. {"file4", "", "", " application/json tmp-string "}};
  3925. auto res = cli_.Post("/multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3930. UploadFormDataItems items = {
  3931. {"text", "default text", "", ""},
  3932. {"multi_text1", "aaaaa", "", ""},
  3933. {"multi_text1", "bbbbb", "", ""},
  3934. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3935. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3936. "application/json"},
  3937. };
  3938. auto res = cli_.Post("/multipart/multi_file_values", items);
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::OK_200, res->status);
  3941. }
  3942. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3943. auto res = cli_.Get("/hi");
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3947. EXPECT_EQ("Hello World!", res->body);
  3948. }
  3949. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3950. Request req;
  3951. req.method = "POST";
  3952. req.path = "/chunked";
  3953. std::string host_and_port;
  3954. host_and_port += HOST;
  3955. host_and_port += ":";
  3956. host_and_port += std::to_string(PORT);
  3957. req.headers.emplace("Host", host_and_port.c_str());
  3958. req.headers.emplace("Accept", "*/*");
  3959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3960. req.headers.emplace("Content-Type", "text/plain");
  3961. req.headers.emplace("Content-Length", "0");
  3962. req.headers.emplace(
  3963. "Transfer-Encoding",
  3964. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3965. // Client does not chunk, so make a chunked body manually.
  3966. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3967. auto res = std::make_shared<Response>();
  3968. auto error = Error::Success;
  3969. auto ret = cli_.send(req, *res, error);
  3970. ASSERT_TRUE(ret);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, GetStreamed2) {
  3974. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(true, res->has_header("Content-Range"));
  3979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3980. EXPECT_EQ(std::string("ab"), res->body);
  3981. }
  3982. TEST_F(ServerTest, GetStreamed) {
  3983. auto res = cli_.Get("/streamed");
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::OK_200, res->status);
  3986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3987. EXPECT_EQ(std::string("aaabbb"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedWithRange1) {
  3990. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3994. EXPECT_EQ(true, res->has_header("Content-Range"));
  3995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3996. EXPECT_EQ(std::string("def"), res->body);
  3997. }
  3998. TEST_F(ServerTest, GetStreamedWithRange2) {
  3999. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("bcdefg"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4008. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4011. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(true, res->has_header("Content-Range"));
  4013. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4014. EXPECT_EQ(std::string("efg"), res->body);
  4015. }
  4016. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4017. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4020. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4021. EXPECT_EQ(false, res->has_header("Content-Range"));
  4022. EXPECT_EQ(0U, res->body.size());
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4025. auto res = cli_.Get("/streamed-with-range",
  4026. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4027. "92233720368547758079223372036854775807"}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4035. auto res = cli_.Get(
  4036. "/with-range",
  4037. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4038. {"Accept-Encoding", ""}});
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4042. EXPECT_EQ(true, res->has_header("Content-Range"));
  4043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4044. EXPECT_EQ(std::string("abcdefg"), res->body);
  4045. }
  4046. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4047. auto res = cli_.Get("/with-range", {
  4048. {"Range", "bytes=0-"},
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("abcdefg"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4059. auto res =
  4060. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4063. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4064. EXPECT_EQ(false, res->has_header("Content-Range"));
  4065. EXPECT_EQ(267U, res->body.size());
  4066. // Check that both range contents are present
  4067. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4068. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4069. // Check that Content-Range headers are present for both ranges
  4070. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4071. std::string::npos);
  4072. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4073. std::string::npos);
  4074. }
  4075. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4076. Ranges ranges;
  4077. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4078. ranges.emplace_back(0, -1);
  4079. }
  4080. auto res =
  4081. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4084. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(0U, res->body.size());
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(5U, res->body.size());
  4094. // Check that overlapping ranges are coalesced into a single range
  4095. EXPECT_EQ("bcdef", res->body);
  4096. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4097. // Should be single range, not multipart
  4098. EXPECT_TRUE(res->has_header("Content-Range"));
  4099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. }
  4101. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4102. auto res =
  4103. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4106. EXPECT_EQ(268U, res->body.size());
  4107. // Check that both range contents are present
  4108. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4109. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4110. // Check that Content-Range headers are present for both ranges
  4111. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4112. std::string::npos);
  4113. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4114. std::string::npos);
  4115. }
  4116. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4117. auto res =
  4118. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ(269U, res->body.size());
  4122. // Check that both duplicate range contents are present
  4123. size_t first_abc = res->body.find("abc\r\n");
  4124. EXPECT_TRUE(first_abc != std::string::npos);
  4125. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4126. EXPECT_TRUE(second_abc != std::string::npos);
  4127. // Check that Content-Range headers are present for both ranges
  4128. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4129. EXPECT_TRUE(first_range != std::string::npos);
  4130. size_t second_range =
  4131. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4132. EXPECT_TRUE(second_range != std::string::npos);
  4133. }
  4134. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4135. auto res = cli_.Get("/streamed-with-range?error",
  4136. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(0U, res->body.size());
  4142. }
  4143. TEST_F(ServerTest, GetStreamedEndless) {
  4144. uint64_t offset = 0;
  4145. auto res = cli_.Get("/streamed-cancel",
  4146. [&](const char * /*data*/, uint64_t data_length) {
  4147. if (offset < 100) {
  4148. offset += data_length;
  4149. return true;
  4150. }
  4151. return false;
  4152. });
  4153. ASSERT_TRUE(!res);
  4154. EXPECT_EQ(Error::Canceled, res.error());
  4155. }
  4156. TEST_F(ServerTest, ClientStop) {
  4157. std::atomic_size_t count{4};
  4158. std::vector<std::thread> threads;
  4159. for (auto i = count.load(); i != 0; --i) {
  4160. threads.emplace_back([&]() {
  4161. auto res = cli_.Get("/streamed-cancel",
  4162. [&](const char *, uint64_t) { return true; });
  4163. --count;
  4164. ASSERT_TRUE(!res);
  4165. EXPECT_TRUE(res.error() == Error::Canceled ||
  4166. res.error() == Error::Read || res.error() == Error::Write);
  4167. });
  4168. }
  4169. std::this_thread::sleep_for(std::chrono::seconds(2));
  4170. while (count != 0) {
  4171. cli_.stop();
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4173. }
  4174. for (auto &t : threads) {
  4175. t.join();
  4176. }
  4177. }
  4178. TEST_F(ServerTest, GetWithRange1) {
  4179. auto res = cli_.Get("/with-range", {
  4180. make_range_header({{3, 5}}),
  4181. {"Accept-Encoding", ""},
  4182. });
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4185. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(true, res->has_header("Content-Range"));
  4187. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4188. EXPECT_EQ(std::string("def"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetWithRange2) {
  4191. auto res = cli_.Get("/with-range", {
  4192. make_range_header({{1, -1}}),
  4193. {"Accept-Encoding", ""},
  4194. });
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4197. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4198. EXPECT_EQ(true, res->has_header("Content-Range"));
  4199. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4200. EXPECT_EQ(std::string("bcdefg"), res->body);
  4201. }
  4202. TEST_F(ServerTest, GetWithRange3) {
  4203. auto res = cli_.Get("/with-range", {
  4204. make_range_header({{0, 0}}),
  4205. {"Accept-Encoding", ""},
  4206. });
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("a"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetWithRange4) {
  4215. auto res = cli_.Get("/with-range", {
  4216. make_range_header({{-1, 2}}),
  4217. {"Accept-Encoding", ""},
  4218. });
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(true, res->has_header("Content-Range"));
  4223. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4224. EXPECT_EQ(std::string("fg"), res->body);
  4225. }
  4226. TEST_F(ServerTest, GetWithRange5) {
  4227. auto res = cli_.Get("/with-range", {
  4228. make_range_header({{0, 5}}),
  4229. {"Accept-Encoding", ""},
  4230. });
  4231. ASSERT_TRUE(res);
  4232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4233. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4236. EXPECT_EQ(std::string("abcdef"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4239. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4242. }
  4243. TEST_F(ServerTest, GetWithRangeMultipart) {
  4244. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4247. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4248. EXPECT_EQ(false, res->has_header("Content-Range"));
  4249. EXPECT_EQ(267U, res->body.size());
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4252. auto res =
  4253. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4256. }
  4257. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4258. auto res = cli_.Get("/with-range-customized-response",
  4259. {{make_range_header({{1, 2}})}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4262. EXPECT_EQ(true, res->has_header("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(JSON_DATA, res->body);
  4265. }
  4266. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4267. auto res = cli_.Get("/with-range-customized-response",
  4268. {{make_range_header({{1, 2}, {4, 5}})}});
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4271. EXPECT_EQ(true, res->has_header("Content-Length"));
  4272. EXPECT_EQ(false, res->has_header("Content-Range"));
  4273. EXPECT_EQ(JSON_DATA, res->body);
  4274. }
  4275. TEST_F(ServerTest, Issue1772) {
  4276. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4279. }
  4280. TEST_F(ServerTest, Issue609) {
  4281. auto res = cli_.Delete("/issue609");
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ(std::string("ok"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetStreamedChunked) {
  4287. auto res = cli_.Get("/streamed-chunked");
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. EXPECT_EQ(std::string("123456789"), res->body);
  4291. }
  4292. TEST_F(ServerTest, GetStreamedChunked2) {
  4293. auto res = cli_.Get("/streamed-chunked2");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ(std::string("123456789"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4299. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ(std::string("123456789"), res->body);
  4303. EXPECT_TRUE(res->has_header("Trailer"));
  4304. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4305. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4306. // Trailers are now stored separately from headers (security fix)
  4307. EXPECT_EQ(2U, res->trailers.size());
  4308. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4309. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4310. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4311. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4312. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4313. // Verify trailers are NOT in headers (security verification)
  4314. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4315. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4316. }
  4317. TEST_F(ServerTest, LargeChunkedPost) {
  4318. Request req;
  4319. req.method = "POST";
  4320. req.path = "/large-chunked";
  4321. std::string host_and_port;
  4322. host_and_port += HOST;
  4323. host_and_port += ":";
  4324. host_and_port += std::to_string(PORT);
  4325. req.headers.emplace("Host", host_and_port.c_str());
  4326. req.headers.emplace("Accept", "*/*");
  4327. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4328. req.headers.emplace("Content-Type", "text/plain");
  4329. req.headers.emplace("Content-Length", "0");
  4330. req.headers.emplace("Transfer-Encoding", "chunked");
  4331. std::string long_string(30 * 1024u, 'a');
  4332. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4333. // Attempt to make a large enough post to exceed OS buffers, to test that
  4334. // the server handles short reads if the full chunk data isn't available.
  4335. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4336. auto res = std::make_shared<Response>();
  4337. auto error = Error::Success;
  4338. auto ret = cli_.send(req, *res, error);
  4339. ASSERT_TRUE(ret);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. }
  4342. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4343. auto res = cli_.Get("/remote_addr");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4347. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4348. }
  4349. TEST_F(ServerTest, GetMethodLocalAddr) {
  4350. auto res = cli_.Get("/local_addr");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4354. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4355. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4356. }
  4357. TEST_F(ServerTest, HTTPResponseSplitting) {
  4358. auto res = cli_.Get("/http_response_splitting");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. }
  4362. TEST_F(ServerTest, SlowRequest) {
  4363. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4364. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4366. }
  4367. #if 0
  4368. TEST_F(ServerTest, SlowPost) {
  4369. char buffer[64 * 1024];
  4370. memset(buffer, 0x42, sizeof(buffer));
  4371. auto res = cli_.Post(
  4372. "/slowpost", 64 * 1024 * 1024,
  4373. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4374. auto ret = sink.write(buffer, sizeof(buffer));
  4375. EXPECT_TRUE(ret);
  4376. return true;
  4377. },
  4378. "text/plain");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. TEST_F(ServerTest, SlowPostFail) {
  4383. char buffer[64 * 1024];
  4384. memset(buffer, 0x42, sizeof(buffer));
  4385. cli_.set_write_timeout(std::chrono::seconds(0));
  4386. auto res = cli_.Post(
  4387. "/slowpost", 64 * 1024 * 1024,
  4388. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4389. sink.write(buffer, sizeof(buffer));
  4390. return true;
  4391. },
  4392. "text/plain");
  4393. ASSERT_TRUE(!res);
  4394. EXPECT_EQ(Error::Write, res.error());
  4395. }
  4396. #endif
  4397. TEST_F(ServerTest, Put) {
  4398. auto res = cli_.Put("/put", "PUT", "text/plain");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("PUT", res->body);
  4402. }
  4403. TEST_F(ServerTest, PutWithContentProvider) {
  4404. auto res = cli_.Put(
  4405. "/put", 3,
  4406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4407. sink.os << "PUT";
  4408. return true;
  4409. },
  4410. "text/plain");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("PUT", res->body);
  4414. }
  4415. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4416. auto res = cli_.Post(
  4417. "/post", 42,
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4419. return false;
  4420. },
  4421. "text/plain");
  4422. ASSERT_TRUE(!res);
  4423. EXPECT_EQ(Error::Canceled, res.error());
  4424. }
  4425. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4426. auto res = cli_.Put(
  4427. "/put",
  4428. [](size_t /*offset*/, DataSink &sink) {
  4429. sink.os << "PUT";
  4430. sink.done();
  4431. return true;
  4432. },
  4433. "text/plain");
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ("PUT", res->body);
  4437. }
  4438. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4439. auto res = cli_.Post(
  4440. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4441. "text/plain");
  4442. ASSERT_TRUE(!res);
  4443. EXPECT_EQ(Error::Canceled, res.error());
  4444. }
  4445. TEST_F(ServerTest, PostLoopBack) {
  4446. std::string body;
  4447. auto res = cli_.Post(
  4448. "/post-loopback", 9,
  4449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4450. EXPECT_EQ(9u, length);
  4451. sink.write("123", 3);
  4452. sink.write("456", 3);
  4453. sink.write("789", 3);
  4454. return true;
  4455. },
  4456. "text/plain",
  4457. [&body](const char *data, size_t data_length) {
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::OK_200, res->status);
  4463. EXPECT_EQ("123456789", body);
  4464. }
  4465. TEST_F(ServerTest, PutLoopBack) {
  4466. std::string body;
  4467. auto res = cli_.Put(
  4468. "/put-loopback", 9,
  4469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4470. EXPECT_EQ(9u, length);
  4471. sink.write("123", 3);
  4472. sink.write("456", 3);
  4473. sink.write("789", 3);
  4474. return true;
  4475. },
  4476. "text/plain",
  4477. [&body](const char *data, size_t data_length) {
  4478. body.append(data, data_length);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("123456789", body);
  4484. }
  4485. TEST_F(ServerTest, PatchLoopBack) {
  4486. std::string body;
  4487. auto res = cli_.Patch(
  4488. "/patch-loopback", 9,
  4489. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4490. EXPECT_EQ(9u, length);
  4491. sink.write("123", 3);
  4492. sink.write("456", 3);
  4493. sink.write("789", 3);
  4494. return true;
  4495. },
  4496. "text/plain",
  4497. [&body](const char *data, size_t data_length) {
  4498. body.append(data, data_length);
  4499. return true;
  4500. });
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ("123456789", body);
  4504. }
  4505. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4506. std::string body;
  4507. auto res = cli_.Post(
  4508. "/post-loopback",
  4509. [](size_t /*offset*/, DataSink &sink) {
  4510. sink.write("123", 3);
  4511. sink.write("456", 3);
  4512. sink.write("789", 3);
  4513. sink.done();
  4514. return true;
  4515. },
  4516. "text/plain",
  4517. [&body](const char *data, size_t data_length) {
  4518. body.append(data, data_length);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("123456789", body);
  4524. }
  4525. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4526. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4527. cli_.set_compress(true);
  4528. auto res = cli_.Put(
  4529. "/put", 3,
  4530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4531. sink.os << "PUT";
  4532. return true;
  4533. },
  4534. "text/plain");
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("PUT", res->body);
  4538. }
  4539. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4540. cli_.set_compress(true);
  4541. auto res = cli_.Post(
  4542. "/post", 42,
  4543. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4544. return false;
  4545. },
  4546. "text/plain");
  4547. ASSERT_TRUE(!res);
  4548. EXPECT_EQ(Error::Canceled, res.error());
  4549. }
  4550. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4551. cli_.set_compress(true);
  4552. auto res = cli_.Put(
  4553. "/put",
  4554. [](size_t /*offset*/, DataSink &sink) {
  4555. sink.os << "PUT";
  4556. sink.done();
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4568. "text/plain");
  4569. ASSERT_TRUE(!res);
  4570. EXPECT_EQ(Error::Canceled, res.error());
  4571. }
  4572. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ(LARGE_DATA, res->body);
  4578. }
  4579. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4581. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4582. Client cli(s.c_str());
  4583. cli.enable_server_certificate_verification(false);
  4584. #else
  4585. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4586. Client cli(s.c_str());
  4587. #endif
  4588. cli.set_compress(true);
  4589. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ(LARGE_DATA, res->body);
  4593. // The compressed size should be less than a 10th of the original. May vary
  4594. // depending on the zlib library.
  4595. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4596. static_cast<uint64_t>(10 * 1024 * 1024));
  4597. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4598. }
  4599. TEST_F(ServerTest, PutContentWithDeflate) {
  4600. cli_.set_compress(false);
  4601. Headers headers;
  4602. headers.emplace("Content-Encoding", "deflate");
  4603. // PUT in deflate format:
  4604. auto res = cli_.Put("/put", headers,
  4605. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("PUT", res->body);
  4609. }
  4610. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4611. Headers headers;
  4612. headers.emplace("Accept-Encoding", "gzip, deflate");
  4613. auto res = cli_.Get("/streamed-chunked", headers);
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ(std::string("123456789"), res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked2", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4627. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. }
  4631. TEST(GzipDecompressor, ChunkedDecompression) {
  4632. std::string data;
  4633. for (size_t i = 0; i < 32 * 1024; ++i) {
  4634. data.push_back(static_cast<char>('a' + i % 26));
  4635. }
  4636. std::string compressed_data;
  4637. {
  4638. httplib::detail::gzip_compressor compressor;
  4639. bool result = compressor.compress(
  4640. data.data(), data.size(),
  4641. /*last=*/true,
  4642. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4643. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4644. compressed_data_size);
  4645. return true;
  4646. });
  4647. ASSERT_TRUE(result);
  4648. }
  4649. std::string decompressed_data;
  4650. {
  4651. httplib::detail::gzip_decompressor decompressor;
  4652. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4653. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4654. size_t chunk_size = 130;
  4655. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4656. chunk_begin += chunk_size) {
  4657. size_t current_chunk_size =
  4658. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4659. bool result = decompressor.decompress(
  4660. compressed_data.data() + chunk_begin, current_chunk_size,
  4661. [&](const char *decompressed_data_chunk,
  4662. size_t decompressed_data_chunk_size) {
  4663. decompressed_data.insert(decompressed_data.size(),
  4664. decompressed_data_chunk,
  4665. decompressed_data_chunk_size);
  4666. return true;
  4667. });
  4668. ASSERT_TRUE(result);
  4669. }
  4670. }
  4671. ASSERT_EQ(data, decompressed_data);
  4672. }
  4673. TEST(GzipDecompressor, DeflateDecompression) {
  4674. std::string original_text = "Raw deflate without gzip";
  4675. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4676. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4677. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4678. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4679. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4680. std::string decompressed_data;
  4681. {
  4682. httplib::detail::gzip_decompressor decompressor;
  4683. bool result = decompressor.decompress(
  4684. compressed_data.data(), compressed_data.size(),
  4685. [&](const char *decompressed_data_chunk,
  4686. size_t decompressed_data_chunk_size) {
  4687. decompressed_data.insert(decompressed_data.size(),
  4688. decompressed_data_chunk,
  4689. decompressed_data_chunk_size);
  4690. return true;
  4691. });
  4692. ASSERT_TRUE(result);
  4693. }
  4694. ASSERT_EQ(original_text, decompressed_data);
  4695. }
  4696. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4697. std::string original_text = "Raw deflate without gzip";
  4698. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4699. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4700. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4701. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4702. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4703. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4704. std::string decompressed_data;
  4705. {
  4706. httplib::detail::gzip_decompressor decompressor;
  4707. bool result = decompressor.decompress(
  4708. compressed_data.data(), compressed_data.size(),
  4709. [&](const char *decompressed_data_chunk,
  4710. size_t decompressed_data_chunk_size) {
  4711. decompressed_data.insert(decompressed_data.size(),
  4712. decompressed_data_chunk,
  4713. decompressed_data_chunk_size);
  4714. return true;
  4715. });
  4716. ASSERT_TRUE(result);
  4717. }
  4718. ASSERT_EQ(original_text, decompressed_data);
  4719. }
  4720. #ifdef _WIN32
  4721. TEST(GzipDecompressor, LargeRandomData) {
  4722. // prepare large random data that is difficult to be compressed and is
  4723. // expected to have large size even when compressed
  4724. std::random_device seed_gen;
  4725. std::mt19937 random(seed_gen());
  4726. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4727. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4728. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4729. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4730. // compress data over 4GiB
  4731. std::string compressed_data;
  4732. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4733. httplib::detail::gzip_compressor compressor;
  4734. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4735. data.size() * sizeof(std::uint32_t), true,
  4736. [&](const char *data, size_t size) {
  4737. compressed_data.insert(
  4738. compressed_data.size(), data, size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. // FIXME: compressed data size is expected to be greater than 4GiB,
  4743. // but there is no guarantee
  4744. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4745. // decompress data over 4GiB
  4746. std::string decompressed_data;
  4747. decompressed_data.reserve(data_size);
  4748. httplib::detail::gzip_decompressor decompressor;
  4749. result = decompressor.decompress(
  4750. compressed_data.data(), compressed_data.size(),
  4751. [&](const char *data, size_t size) {
  4752. decompressed_data.insert(decompressed_data.size(), data, size);
  4753. return true;
  4754. });
  4755. ASSERT_TRUE(result);
  4756. // compare
  4757. ASSERT_EQ(data_size, decompressed_data.size());
  4758. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4759. 0);
  4760. }
  4761. #endif
  4762. #endif
  4763. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4764. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4765. Headers headers;
  4766. headers.emplace("Accept-Encoding", "br");
  4767. auto res = cli_.Get("/streamed-chunked", headers);
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ(std::string("123456789"), res->body);
  4771. }
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked2", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Patch) {
  4782. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PATCH", res->body);
  4786. }
  4787. TEST_F(ServerTest, Delete) {
  4788. auto res = cli_.Delete("/delete");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("DELETE", res->body);
  4792. }
  4793. TEST_F(ServerTest, DeleteContentReceiver) {
  4794. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("content", res->body);
  4798. }
  4799. TEST_F(ServerTest, Options) {
  4800. auto res = cli_.Options("*");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4804. EXPECT_TRUE(res->body.empty());
  4805. }
  4806. TEST_F(ServerTest, URL) {
  4807. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, ArrayParam) {
  4812. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, NoMultipleHeaders) {
  4817. Headers headers = {{"Content-Length", "5"}};
  4818. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4819. "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. }
  4823. TEST_F(ServerTest, PostContentReceiver) {
  4824. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4830. UploadFormDataItems items = {
  4831. {"text1", "text default", "", ""},
  4832. {"text2", "aωb", "", ""},
  4833. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4834. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4835. {"file3", "", "", "application/octet-stream"},
  4836. };
  4837. auto res = cli_.Post("/content_receiver", items);
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4842. UploadFormDataItems items = {
  4843. {"text1", "text default", "", ""},
  4844. {"text2", "aωb", "", ""},
  4845. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4846. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4847. {"file3", "", "", "application/octet-stream"},
  4848. };
  4849. auto boundary = std::string("+++++");
  4850. std::string body;
  4851. for (const auto &item : items) {
  4852. body += "--" + boundary + "\r\n";
  4853. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4854. if (!item.filename.empty()) {
  4855. body += "; filename=\"" + item.filename + "\"";
  4856. }
  4857. body += "\r\n";
  4858. if (!item.content_type.empty()) {
  4859. body += "Content-Type: " + item.content_type + "\r\n";
  4860. }
  4861. body += "\r\n";
  4862. body += item.content + "\r\n";
  4863. }
  4864. body += "--" + boundary + "--\r\n";
  4865. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4866. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, PostContentReceiverGzip) {
  4871. cli_.set_compress(true);
  4872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4873. ASSERT_TRUE(res);
  4874. ASSERT_EQ(StatusCode::OK_200, res->status);
  4875. ASSERT_EQ("content", res->body);
  4876. }
  4877. TEST_F(ServerTest, PutContentReceiver) {
  4878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4879. ASSERT_TRUE(res);
  4880. ASSERT_EQ(StatusCode::OK_200, res->status);
  4881. ASSERT_EQ("content", res->body);
  4882. }
  4883. TEST_F(ServerTest, PatchContentReceiver) {
  4884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4885. ASSERT_TRUE(res);
  4886. ASSERT_EQ(StatusCode::OK_200, res->status);
  4887. ASSERT_EQ("content", res->body);
  4888. }
  4889. template <typename ClientType>
  4890. void TestWithHeadersAndContentReceiver(
  4891. ClientType &cli,
  4892. std::function<Result(ClientType &, const std::string &, const Headers &,
  4893. const std::string &, const std::string &,
  4894. ContentReceiver, DownloadProgress)>
  4895. request_func) {
  4896. Headers headers;
  4897. headers.emplace("X-Custom-Header", "test-value");
  4898. std::string received_body;
  4899. auto res = request_func(
  4900. cli, "/content_receiver", headers, "content", "application/json",
  4901. [&](const char *data, size_t data_length) {
  4902. received_body.append(data, data_length);
  4903. return true;
  4904. },
  4905. nullptr);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("content", received_body);
  4909. }
  4910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4912. using ClientT = SSLClient;
  4913. #else
  4914. using ClientT = Client;
  4915. #endif
  4916. TestWithHeadersAndContentReceiver<ClientT>(
  4917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4918. const std::string &body, const std::string &content_type,
  4919. ContentReceiver receiver, DownloadProgress progress) {
  4920. return cli.Post(path, headers, body, content_type, receiver, progress);
  4921. });
  4922. }
  4923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4925. using ClientT = SSLClient;
  4926. #else
  4927. using ClientT = Client;
  4928. #endif
  4929. TestWithHeadersAndContentReceiver<ClientT>(
  4930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4931. const std::string &body, const std::string &content_type,
  4932. ContentReceiver receiver, DownloadProgress progress) {
  4933. return cli.Put(path, headers, body, content_type, receiver, progress);
  4934. });
  4935. }
  4936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4937. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4938. using ClientT = SSLClient;
  4939. #else
  4940. using ClientT = Client;
  4941. #endif
  4942. TestWithHeadersAndContentReceiver<ClientT>(
  4943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4944. const std::string &body, const std::string &content_type,
  4945. ContentReceiver receiver, DownloadProgress progress) {
  4946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4947. });
  4948. }
  4949. template <typename ClientType>
  4950. void TestWithHeadersAndContentReceiverWithProgress(
  4951. ClientType &cli,
  4952. std::function<Result(ClientType &, const std::string &, const Headers &,
  4953. const std::string &, const std::string &,
  4954. ContentReceiver, DownloadProgress)>
  4955. request_func) {
  4956. Headers headers;
  4957. headers.emplace("X-Test-Header", "progress-test");
  4958. std::string received_body;
  4959. auto progress_called = false;
  4960. auto res = request_func(
  4961. cli, "/content_receiver", headers, "content", "text/plain",
  4962. [&](const char *data, size_t data_length) {
  4963. received_body.append(data, data_length);
  4964. return true;
  4965. },
  4966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4967. progress_called = true;
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ("content", received_body);
  4973. EXPECT_TRUE(progress_called);
  4974. }
  4975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4977. using ClientT = SSLClient;
  4978. #else
  4979. using ClientT = Client;
  4980. #endif
  4981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4983. const std::string &body, const std::string &content_type,
  4984. ContentReceiver receiver, DownloadProgress progress) {
  4985. return cli.Post(path, headers, body, content_type, receiver, progress);
  4986. });
  4987. }
  4988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4990. using ClientT = SSLClient;
  4991. #else
  4992. using ClientT = Client;
  4993. #endif
  4994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4996. const std::string &body, const std::string &content_type,
  4997. ContentReceiver receiver, DownloadProgress progress) {
  4998. return cli.Put(path, headers, body, content_type, receiver, progress);
  4999. });
  5000. }
  5001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5003. using ClientT = SSLClient;
  5004. #else
  5005. using ClientT = Client;
  5006. #endif
  5007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5009. const std::string &body, const std::string &content_type,
  5010. ContentReceiver receiver, DownloadProgress progress) {
  5011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5012. });
  5013. }
  5014. template <typename ClientType>
  5015. void TestWithHeadersAndContentReceiverError(
  5016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5017. const Headers &, const std::string &,
  5018. const std::string &, ContentReceiver)>
  5019. request_func) {
  5020. Headers headers;
  5021. headers.emplace("X-Error-Test", "true");
  5022. std::string received_body;
  5023. auto receiver_failed = false;
  5024. auto res =
  5025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5026. [&](const char *data, size_t data_length) {
  5027. received_body.append(data, data_length);
  5028. receiver_failed = true;
  5029. return false;
  5030. });
  5031. ASSERT_FALSE(res);
  5032. EXPECT_TRUE(receiver_failed);
  5033. }
  5034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5036. using ClientT = SSLClient;
  5037. #else
  5038. using ClientT = Client;
  5039. #endif
  5040. TestWithHeadersAndContentReceiverError<ClientT>(
  5041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5042. const std::string &body, const std::string &content_type,
  5043. ContentReceiver receiver) {
  5044. return cli.Post(path, headers, body, content_type, receiver);
  5045. });
  5046. }
  5047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverError<ClientT>(
  5054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5055. const std::string &body, const std::string &content_type,
  5056. ContentReceiver receiver) {
  5057. return cli.Put(path, headers, body, content_type, receiver);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverError<ClientT>(
  5067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5068. const std::string &body, const std::string &content_type,
  5069. ContentReceiver receiver) {
  5070. return cli.Patch(path, headers, body, content_type, receiver);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PostQueryStringAndBody) {
  5074. auto res =
  5075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5076. ASSERT_TRUE(res);
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, HTTP2Magic) {
  5080. Request req;
  5081. req.method = "PRI";
  5082. req.path = "*";
  5083. req.body = "SM";
  5084. auto res = std::make_shared<Response>();
  5085. auto error = Error::Success;
  5086. auto ret = cli_.send(req, *res, error);
  5087. ASSERT_TRUE(ret);
  5088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5089. }
  5090. TEST_F(ServerTest, KeepAlive) {
  5091. auto res = cli_.Get("/hi");
  5092. ASSERT_TRUE(res);
  5093. EXPECT_EQ(StatusCode::OK_200, res->status);
  5094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5095. EXPECT_EQ("Hello World!", res->body);
  5096. res = cli_.Get("/hi");
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("Hello World!", res->body);
  5101. res = cli_.Get("/hi");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5105. EXPECT_EQ("Hello World!", res->body);
  5106. res = cli_.Get("/not-exist");
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5109. res = cli_.Post("/empty", "", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("empty", res->body);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. res = cli_.Post(
  5116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5117. "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. cli_.set_keep_alive(false);
  5123. res = cli_.Get("/last-request");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("close", res->get_header_value("Connection"));
  5127. }
  5128. TEST_F(ServerTest, TooManyRedirect) {
  5129. cli_.set_follow_location(true);
  5130. auto res = cli_.Get("/redirect/0");
  5131. ASSERT_TRUE(!res);
  5132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5133. }
  5134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5135. Request req;
  5136. req.method = "FOOBAR";
  5137. req.path = "/hi";
  5138. cli_.set_keep_alive(true);
  5139. auto res = cli_.send(req);
  5140. ASSERT_TRUE(res);
  5141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5142. EXPECT_EQ("close", res->get_header_value("Connection"));
  5143. EXPECT_FALSE(cli_.is_socket_open());
  5144. }
  5145. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5146. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5147. TEST_F(ServerTest, Gzip) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "gzip, deflate");
  5150. auto res = cli_.Get("/compress", headers);
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5156. "7890123456789012345678901234567890",
  5157. res->body);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. }
  5160. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5161. Headers headers;
  5162. headers.emplace("Accept-Encoding", "");
  5163. auto res = cli_.Get("/compress", headers);
  5164. ASSERT_TRUE(res);
  5165. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. res->body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. TEST_F(ServerTest, GzipWithContentReceiver) {
  5174. Headers headers;
  5175. headers.emplace("Accept-Encoding", "gzip, deflate");
  5176. std::string body;
  5177. auto res = cli_.Get("/compress", headers,
  5178. [&](const char *data, uint64_t data_length) {
  5179. EXPECT_EQ(100U, data_length);
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5186. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5188. "7890123456789012345678901234567890",
  5189. body);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. }
  5192. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5193. Headers headers;
  5194. headers.emplace("Accept-Encoding", "gzip, deflate");
  5195. cli_.set_decompress(false);
  5196. auto res = cli_.Get("/compress", headers);
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5200. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5201. EXPECT_EQ(33U, res->body.size());
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. std::string body;
  5208. auto res = cli_.Get("/compress", headers,
  5209. [&](const char *data, uint64_t data_length) {
  5210. EXPECT_EQ(100U, data_length);
  5211. body.append(data, data_length);
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5217. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5218. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5219. "7890123456789012345678901234567890",
  5220. body);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. }
  5223. TEST_F(ServerTest, NoGzip) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "gzip, deflate");
  5226. auto res = cli_.Get("/nocompress", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5229. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. res->body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. std::string body;
  5240. auto res = cli_.Get("/nocompress", headers,
  5241. [&](const char *data, uint64_t data_length) {
  5242. EXPECT_EQ(100U, data_length);
  5243. body.append(data, data_length);
  5244. return true;
  5245. });
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5248. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5250. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5251. "7890123456789012345678901234567890",
  5252. body);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. }
  5255. TEST_F(ServerTest, MultipartFormDataGzip) {
  5256. UploadFormDataItems items = {
  5257. {"key1", "test", "", ""},
  5258. {"key2", "--abcdefg123", "", ""},
  5259. };
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/compress-multipart", items);
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. }
  5265. #endif
  5266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5267. TEST_F(ServerTest, Brotli) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "br");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. #endif
  5281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5282. TEST_F(ServerTest, Zstd) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "zstd");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "");
  5298. auto res = cli_.Get("/compress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "zstd");
  5311. std::string body;
  5312. auto res = cli_.Get("/compress", headers,
  5313. [&](const char *data, uint64_t data_length) {
  5314. EXPECT_EQ(100U, data_length);
  5315. body.append(data, data_length);
  5316. return true;
  5317. });
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5323. "7890123456789012345678901234567890",
  5324. body);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "zstd");
  5330. cli_.set_decompress(false);
  5331. auto res = cli_.Get("/compress", headers);
  5332. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5333. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5334. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5335. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ(26U, res->body.size());
  5342. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5343. 0);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "");
  5348. std::string body;
  5349. auto res = cli_.Get("/compress", headers,
  5350. [&](const char *data, uint64_t data_length) {
  5351. EXPECT_EQ(100U, data_length);
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. ASSERT_TRUE(res);
  5356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoZstd) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "zstd");
  5367. auto res = cli_.Get("/nocompress", headers);
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5370. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5373. "7890123456789012345678901234567890",
  5374. res->body);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. }
  5377. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5378. Headers headers;
  5379. headers.emplace("Accept-Encoding", "zstd");
  5380. std::string body;
  5381. auto res = cli_.Get("/nocompress", headers,
  5382. [&](const char *data, uint64_t data_length) {
  5383. EXPECT_EQ(100U, data_length);
  5384. body.append(data, data_length);
  5385. return true;
  5386. });
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5390. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5391. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5392. "7890123456789012345678901234567890",
  5393. body);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. }
  5396. // TODO: How to enable zstd ??
  5397. TEST_F(ServerTest, MultipartFormDataZstd) {
  5398. UploadFormDataItems items = {
  5399. {"key1", "test", "", ""},
  5400. {"key2", "--abcdefg123", "", ""},
  5401. };
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "zstd");
  5404. cli_.set_compress(true);
  5405. auto res = cli_.Post("/compress-multipart", headers, items);
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Put(
  5414. "/put", headers, 3,
  5415. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5416. sink.os << "PUT";
  5417. return true;
  5418. },
  5419. "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. // Pre-compression logging tests
  5425. TEST_F(ServerTest, PreCompressionLogging) {
  5426. // Test data for compression (matches the actual /compress endpoint content)
  5427. const std::string test_content =
  5428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5429. "3456789012345678901234567890";
  5430. // Variables to capture logging data
  5431. std::string pre_compression_body;
  5432. std::string pre_compression_content_type;
  5433. std::string pre_compression_content_encoding;
  5434. std::string post_compression_body;
  5435. std::string post_compression_content_type;
  5436. std::string post_compression_content_encoding;
  5437. // Set up pre-compression logger
  5438. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5439. const Response &res) {
  5440. pre_compression_body = res.body;
  5441. pre_compression_content_type = res.get_header_value("Content-Type");
  5442. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5443. });
  5444. // Set up post-compression logger
  5445. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5446. post_compression_body = res.body;
  5447. post_compression_content_type = res.get_header_value("Content-Type");
  5448. post_compression_content_encoding =
  5449. res.get_header_value("Content-Encoding");
  5450. });
  5451. // Test with gzip compression
  5452. Headers headers;
  5453. headers.emplace("Accept-Encoding", "gzip");
  5454. auto res = cli_.Get("/compress", headers);
  5455. // Verify response was compressed
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5459. // Verify pre-compression logger captured uncompressed content
  5460. EXPECT_EQ(test_content, pre_compression_body);
  5461. EXPECT_EQ("text/plain", pre_compression_content_type);
  5462. EXPECT_TRUE(pre_compression_content_encoding
  5463. .empty()); // No encoding header before compression
  5464. // Verify post-compression logger captured compressed content
  5465. EXPECT_NE(test_content,
  5466. post_compression_body); // Should be different after compression
  5467. EXPECT_EQ("text/plain", post_compression_content_type);
  5468. EXPECT_EQ("gzip", post_compression_content_encoding);
  5469. // Verify compressed content is smaller
  5470. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5471. }
  5472. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5473. const std::string test_content =
  5474. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5475. "3456789012345678901234567890";
  5476. std::string pre_compression_body;
  5477. std::string post_compression_body;
  5478. svr_.set_pre_compression_logger(
  5479. [&](const Request & /*req*/, const Response &res) {
  5480. pre_compression_body = res.body;
  5481. });
  5482. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5483. post_compression_body = res.body;
  5484. });
  5485. Headers headers;
  5486. headers.emplace("Accept-Encoding", "br");
  5487. auto res = cli_.Get("/compress", headers);
  5488. ASSERT_TRUE(res);
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5491. // Verify pre-compression content is uncompressed
  5492. EXPECT_EQ(test_content, pre_compression_body);
  5493. // Verify post-compression content is compressed
  5494. EXPECT_NE(test_content, post_compression_body);
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. // Request without compression (use /nocompress endpoint)
  5511. Headers headers;
  5512. auto res = cli_.Get("/nocompress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5516. // Pre-compression logger should not be called when no compression is applied
  5517. EXPECT_TRUE(
  5518. pre_compression_body.empty()); // Pre-compression logger not called
  5519. EXPECT_EQ(
  5520. test_content,
  5521. post_compression_body); // Post-compression logger captures final content
  5522. }
  5523. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5524. const std::string test_content =
  5525. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5526. "3456789012345678901234567890";
  5527. std::string pre_compression_body;
  5528. bool pre_logger_called = false;
  5529. // Set only pre-compression logger
  5530. svr_.set_pre_compression_logger(
  5531. [&](const Request & /*req*/, const Response &res) {
  5532. pre_compression_body = res.body;
  5533. pre_logger_called = true;
  5534. });
  5535. Headers headers;
  5536. headers.emplace("Accept-Encoding", "gzip");
  5537. auto res = cli_.Get("/compress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5541. // Verify pre-compression logger was called
  5542. EXPECT_TRUE(pre_logger_called);
  5543. EXPECT_EQ(test_content, pre_compression_body);
  5544. }
  5545. TEST(ZstdDecompressor, ChunkedDecompression) {
  5546. std::string data;
  5547. for (size_t i = 0; i < 32 * 1024; ++i) {
  5548. data.push_back(static_cast<char>('a' + i % 26));
  5549. }
  5550. std::string compressed_data;
  5551. {
  5552. httplib::detail::zstd_compressor compressor;
  5553. bool result = compressor.compress(
  5554. data.data(), data.size(),
  5555. /*last=*/true,
  5556. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5557. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5558. compressed_data_size);
  5559. return true;
  5560. });
  5561. ASSERT_TRUE(result);
  5562. }
  5563. std::string decompressed_data;
  5564. {
  5565. httplib::detail::zstd_decompressor decompressor;
  5566. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5567. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5568. size_t chunk_size = 130;
  5569. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5570. chunk_begin += chunk_size) {
  5571. size_t current_chunk_size =
  5572. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5573. bool result = decompressor.decompress(
  5574. compressed_data.data() + chunk_begin, current_chunk_size,
  5575. [&](const char *decompressed_data_chunk,
  5576. size_t decompressed_data_chunk_size) {
  5577. decompressed_data.insert(decompressed_data.size(),
  5578. decompressed_data_chunk,
  5579. decompressed_data_chunk_size);
  5580. return true;
  5581. });
  5582. ASSERT_TRUE(result);
  5583. }
  5584. }
  5585. ASSERT_EQ(data, decompressed_data);
  5586. }
  5587. TEST(ZstdDecompressor, Decompress) {
  5588. std::string original_text = "Compressed with ZSTD";
  5589. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5590. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5591. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5592. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5593. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5594. std::string decompressed_data;
  5595. {
  5596. httplib::detail::zstd_decompressor decompressor;
  5597. bool result = decompressor.decompress(
  5598. compressed_data.data(), compressed_data.size(),
  5599. [&](const char *decompressed_data_chunk,
  5600. size_t decompressed_data_chunk_size) {
  5601. decompressed_data.insert(decompressed_data.size(),
  5602. decompressed_data_chunk,
  5603. decompressed_data_chunk_size);
  5604. return true;
  5605. });
  5606. ASSERT_TRUE(result);
  5607. }
  5608. ASSERT_EQ(original_text, decompressed_data);
  5609. }
  5610. #endif
  5611. // Sends a raw request to a server listening at HOST:PORT.
  5612. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5613. std::string *resp = nullptr) {
  5614. auto error = Error::Success;
  5615. auto client_sock = detail::create_client_socket(
  5616. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5617. /*connection_timeout_sec=*/5, 0,
  5618. /*read_timeout_sec=*/5, 0,
  5619. /*write_timeout_sec=*/5, 0, std::string(), error);
  5620. if (client_sock == INVALID_SOCKET) { return false; }
  5621. auto ret = detail::process_client_socket(
  5622. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5623. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5624. if (req.size() !=
  5625. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5626. return false;
  5627. }
  5628. char buf[512];
  5629. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5630. while (line_reader.getline()) {
  5631. if (resp) { *resp += line_reader.ptr(); }
  5632. }
  5633. return true;
  5634. });
  5635. detail::close_socket(client_sock);
  5636. return ret;
  5637. }
  5638. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5639. Server svr;
  5640. std::string header_value;
  5641. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5642. header_value = req.get_header_value("foo");
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. thread t = thread([&] { svr.listen(HOST, PORT); });
  5646. auto se = detail::scope_exit([&] {
  5647. svr.stop();
  5648. t.join();
  5649. ASSERT_FALSE(svr.is_running());
  5650. });
  5651. svr.wait_until_ready();
  5652. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5653. // like characters are not treated the same - use vertical tab and escape.
  5654. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5655. "foo: \t \v bar \x1B\t \r\n"
  5656. "Connection: close\r\n"
  5657. "\r\n";
  5658. std::string res;
  5659. ASSERT_TRUE(send_request(5, req, &res));
  5660. EXPECT_EQ(header_value, "");
  5661. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5662. }
  5663. // Sends a raw request and verifies that there isn't a crash or exception.
  5664. static void test_raw_request(const std::string &req,
  5665. std::string *out = nullptr) {
  5666. Server svr;
  5667. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5668. res.set_content("ok", "text/plain");
  5669. });
  5670. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5671. res.set_content("ok", "text/plain");
  5672. });
  5673. svr.Get("/header_field_value_check",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_content("ok", "text/plain");
  5676. });
  5677. // Server read timeout must be longer than the client read timeout for the
  5678. // bug to reproduce, probably to force the server to process a request
  5679. // without a trailing blank line.
  5680. const time_t client_read_timeout_sec = 1;
  5681. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5682. bool listen_thread_ok = false;
  5683. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5684. auto se = detail::scope_exit([&] {
  5685. svr.stop();
  5686. t.join();
  5687. ASSERT_FALSE(svr.is_running());
  5688. EXPECT_TRUE(listen_thread_ok);
  5689. });
  5690. svr.wait_until_ready();
  5691. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5692. }
  5693. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5694. // A certain header line causes an exception if the header property is parsed
  5695. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5696. test_raw_request(
  5697. "GET /hi HTTP/1.1\r\n"
  5698. " : "
  5699. " "
  5700. " ");
  5701. }
  5702. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5703. // A certain header line causes an exception if the header property *name* is
  5704. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5705. // greedy matcher and requires backtracking when there are a lot of ":"
  5706. // characters.
  5707. // This occurs with libc++ but not libstdc++.
  5708. test_raw_request(
  5709. "GET /hi HTTP/1.1\r\n"
  5710. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5711. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5712. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5713. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5714. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5715. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5716. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5717. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5718. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5719. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5720. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5722. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5723. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5724. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5725. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5726. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5727. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5728. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5729. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5730. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5731. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5732. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5733. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5734. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5735. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5736. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5737. "&&&%%%");
  5738. }
  5739. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5740. // Make sure this doesn't crash the server.
  5741. // In a previous version of the header line regex, the "\r" rendered the line
  5742. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5743. // a new position where the leading white space ended and the field value
  5744. // began.
  5745. // The crash occurs with libc++ but not libstdc++.
  5746. test_raw_request("GET /hi HTTP/1.1\r\n"
  5747. "a:" +
  5748. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5749. "\r\n"
  5750. "\r\n");
  5751. }
  5752. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5753. std::string out;
  5754. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5755. "Content-Type: text/plain\r\n"
  5756. "Transfer-Encoding: chunked\r\n"
  5757. "\r\n"
  5758. "nothex\r\n",
  5759. &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5763. std::string out;
  5764. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5765. "Content-Type: text/plain\r\n"
  5766. "Transfer-Encoding: chunked\r\n"
  5767. "\r\n"
  5768. "3\r\n"
  5769. "xyz\r\n"
  5770. "NaN\r\n",
  5771. &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5775. std::string out;
  5776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5777. "Content-Type: text/plain\r\n"
  5778. "Transfer-Encoding: chunked\r\n"
  5779. "\r\n"
  5780. // Length is too large for 64 bits.
  5781. "1ffffffffffffffff\r\n"
  5782. "xyz\r\n",
  5783. &out);
  5784. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5785. }
  5786. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5787. test_raw_request("GET /hi HTTP/1.1\r\n"
  5788. "Content-Type: text/plain\r\n\r");
  5789. }
  5790. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5791. std::string out;
  5792. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5793. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5794. }
  5795. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5796. std::string out;
  5797. std::string request(
  5798. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5799. test_raw_request(request, &out);
  5800. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5801. }
  5802. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5803. std::string out;
  5804. std::string request(
  5805. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5806. test_raw_request(request, &out);
  5807. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5808. }
  5809. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5810. std::string out;
  5811. std::string request(
  5812. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5813. test_raw_request(request, &out);
  5814. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5815. }
  5816. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5817. std::string out;
  5818. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5819. "Test: \r\n\r\n",
  5820. &out);
  5821. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5822. }
  5823. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5824. Server svr;
  5825. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5826. res.set_header("Cache-Control", "no-cache");
  5827. res.set_chunked_content_provider(
  5828. "text/event-stream", [](size_t offset, DataSink &sink) {
  5829. std::string s = "data:";
  5830. s += std::to_string(offset);
  5831. s += "\n\n";
  5832. auto ret = sink.write(s.data(), s.size());
  5833. EXPECT_TRUE(ret);
  5834. std::this_thread::sleep_for(std::chrono::seconds(1));
  5835. return true;
  5836. });
  5837. });
  5838. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5839. svr.wait_until_ready();
  5840. Client client(HOST, PORT);
  5841. const Headers headers = {{"Accept", "text/event-stream"}};
  5842. auto get_thread = std::thread([&client, &headers]() {
  5843. auto res = client.Get(
  5844. "/events", headers,
  5845. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5846. });
  5847. auto se = detail::scope_exit([&] {
  5848. svr.stop();
  5849. get_thread.join();
  5850. listen_thread.join();
  5851. ASSERT_FALSE(svr.is_running());
  5852. });
  5853. // Give GET time to get a few messages.
  5854. std::this_thread::sleep_for(std::chrono::seconds(2));
  5855. }
  5856. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5857. httplib::Server svr;
  5858. svr.Post("/hi",
  5859. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5860. res.status = StatusCode::OK_200;
  5861. });
  5862. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5863. svr.wait_until_ready();
  5864. Client cli(HOST, PORT);
  5865. auto res = cli.Post("/hi", "data", "text/plain");
  5866. ASSERT_TRUE(res);
  5867. EXPECT_EQ(StatusCode::OK_200, res->status);
  5868. svr.stop();
  5869. thread.join();
  5870. ASSERT_FALSE(svr.is_running());
  5871. res = cli.Post("/hi", "data", "text/plain");
  5872. ASSERT_FALSE(res);
  5873. }
  5874. TEST(ServerStopTest, ListenFailure) {
  5875. Server svr;
  5876. auto t = thread([&]() {
  5877. auto ret = svr.listen("????", PORT);
  5878. EXPECT_FALSE(ret);
  5879. });
  5880. svr.wait_until_ready();
  5881. svr.stop();
  5882. t.join();
  5883. }
  5884. TEST(ServerStopTest, Decommision) {
  5885. Server svr;
  5886. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5887. for (int i = 0; i < 4; i++) {
  5888. auto is_even = !(i % 2);
  5889. std::thread t{[&] {
  5890. try {
  5891. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5892. if (is_even) {
  5893. throw std::runtime_error("Some thing that happens to go wrong.");
  5894. }
  5895. svr.listen(HOST, PORT);
  5896. } catch (...) { svr.decommission(); }
  5897. }};
  5898. svr.wait_until_ready();
  5899. // Server is up
  5900. {
  5901. Client cli(HOST, PORT);
  5902. auto res = cli.Get("/hi");
  5903. if (is_even) {
  5904. EXPECT_FALSE(res);
  5905. } else {
  5906. EXPECT_TRUE(res);
  5907. EXPECT_EQ("hi...", res->body);
  5908. }
  5909. }
  5910. svr.stop();
  5911. t.join();
  5912. // Server is down...
  5913. {
  5914. Client cli(HOST, PORT);
  5915. auto res = cli.Get("/hi");
  5916. EXPECT_FALSE(res);
  5917. }
  5918. }
  5919. }
  5920. // Helper function for string body upload progress tests
  5921. template <typename SetupHandler, typename ClientCall>
  5922. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5923. ClientCall &&client_call,
  5924. const string &body) {
  5925. Server svr;
  5926. setup_handler(svr);
  5927. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5928. auto se = detail::scope_exit([&] {
  5929. svr.stop();
  5930. t.join();
  5931. });
  5932. svr.wait_until_ready();
  5933. Client cli(HOST, PORT);
  5934. vector<uint64_t> progress_values;
  5935. bool progress_called = false;
  5936. auto res =
  5937. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5938. progress_values.push_back(current);
  5939. progress_called = true;
  5940. return true;
  5941. });
  5942. ASSERT_TRUE(res);
  5943. EXPECT_EQ(200, res->status);
  5944. EXPECT_TRUE(progress_called);
  5945. }
  5946. TEST(UploadProgressTest, PostStringBodyBasic) {
  5947. TestStringBodyUploadProgress(
  5948. [](Server &svr) {
  5949. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5950. res.set_content("received", "text/plain");
  5951. });
  5952. },
  5953. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5954. return cli.Post("/test", body, "text/plain", progress_callback);
  5955. },
  5956. "test data for upload progress");
  5957. }
  5958. TEST(UploadProgressTest, PutStringBodyBasic) {
  5959. TestStringBodyUploadProgress(
  5960. [](Server &svr) {
  5961. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5962. res.set_content("put received", "text/plain");
  5963. });
  5964. },
  5965. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5966. return cli.Put("/test", body, "text/plain", progress_callback);
  5967. },
  5968. "put test data for upload progress");
  5969. }
  5970. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5971. TestStringBodyUploadProgress(
  5972. [](Server &svr) {
  5973. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5974. res.set_content("patch received", "text/plain");
  5975. });
  5976. },
  5977. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5978. return cli.Patch("/test", body, "text/plain", progress_callback);
  5979. },
  5980. "patch test data for upload progress");
  5981. }
  5982. // Helper function for content provider upload progress tests
  5983. template <typename SetupHandler, typename ClientCall>
  5984. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5985. ClientCall &&client_call) {
  5986. Server svr;
  5987. setup_handler(svr);
  5988. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5989. auto se = detail::scope_exit([&] {
  5990. svr.stop();
  5991. t.join();
  5992. });
  5993. svr.wait_until_ready();
  5994. Client cli(HOST, PORT);
  5995. vector<uint64_t> progress_values;
  5996. auto res =
  5997. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5998. progress_values.push_back(current);
  5999. return true;
  6000. });
  6001. ASSERT_TRUE(res);
  6002. EXPECT_EQ(200, res->status);
  6003. EXPECT_FALSE(progress_values.empty());
  6004. }
  6005. TEST(UploadProgressTest, PostContentProviderProgress) {
  6006. TestContentProviderUploadProgress(
  6007. [](Server &svr) {
  6008. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6009. res.set_content("provider received", "text/plain");
  6010. });
  6011. },
  6012. [](Client &cli, UploadProgress progress_callback) {
  6013. return cli.Post(
  6014. "/test", 10,
  6015. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6016. sink.os << "test data";
  6017. return true;
  6018. },
  6019. "text/plain", progress_callback);
  6020. });
  6021. }
  6022. // Helper function for multipart upload progress tests
  6023. template <typename SetupHandler, typename ClientCall>
  6024. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6025. ClientCall &&client_call,
  6026. const string &endpoint) {
  6027. Server svr;
  6028. setup_handler(svr);
  6029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6030. auto se = detail::scope_exit([&] {
  6031. svr.stop();
  6032. t.join();
  6033. });
  6034. svr.wait_until_ready();
  6035. Client cli(HOST, PORT);
  6036. vector<uint64_t> progress_values;
  6037. UploadFormDataItems items = {
  6038. {"field1", "value1", "", ""},
  6039. {"field2", "longer value for progress tracking test", "", ""},
  6040. {"file1", "file content data for upload progress", "test.txt",
  6041. "text/plain"}};
  6042. auto res = client_call(cli, endpoint, items,
  6043. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6044. progress_values.push_back(current);
  6045. return true;
  6046. });
  6047. ASSERT_TRUE(res);
  6048. EXPECT_EQ(200, res->status);
  6049. EXPECT_FALSE(progress_values.empty());
  6050. }
  6051. TEST(UploadProgressTest, PostMultipartProgress) {
  6052. TestMultipartUploadProgress(
  6053. [](Server &svr) {
  6054. svr.Post("/multipart", [](const Request &req, Response &res) {
  6055. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6056. res.set_content("multipart received", "text/plain");
  6057. });
  6058. },
  6059. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6060. UploadProgress progress_callback) {
  6061. return cli.Post(endpoint, items, progress_callback);
  6062. },
  6063. "/multipart");
  6064. }
  6065. // Helper function for basic download progress tests
  6066. template <typename SetupHandler, typename ClientCall>
  6067. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6068. ClientCall &&client_call, const string &endpoint,
  6069. size_t expected_content_size) {
  6070. Server svr;
  6071. setup_handler(svr);
  6072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. t.join();
  6076. });
  6077. svr.wait_until_ready();
  6078. Client cli(HOST, PORT);
  6079. vector<uint64_t> progress_values;
  6080. auto res = client_call(cli, endpoint,
  6081. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6082. progress_values.push_back(current);
  6083. return true;
  6084. });
  6085. ASSERT_TRUE(res);
  6086. EXPECT_EQ(200, res->status);
  6087. EXPECT_FALSE(progress_values.empty());
  6088. EXPECT_EQ(expected_content_size, res->body.size());
  6089. }
  6090. TEST(DownloadProgressTest, GetBasic) {
  6091. TestBasicDownloadProgress(
  6092. [](Server &svr) {
  6093. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6094. string content(1000, 'D');
  6095. res.set_content(content, "text/plain");
  6096. });
  6097. },
  6098. [](Client &cli, const string &endpoint,
  6099. DownloadProgress progress_callback) {
  6100. return cli.Get(endpoint, progress_callback);
  6101. },
  6102. "/download", 1000u);
  6103. }
  6104. // Helper function for content receiver download progress tests
  6105. template <typename SetupHandler, typename ClientCall>
  6106. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6107. ClientCall &&client_call,
  6108. const string &endpoint,
  6109. size_t expected_content_size) {
  6110. Server svr;
  6111. setup_handler(svr);
  6112. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6113. auto se = detail::scope_exit([&] {
  6114. svr.stop();
  6115. t.join();
  6116. });
  6117. svr.wait_until_ready();
  6118. Client cli(HOST, PORT);
  6119. vector<uint64_t> progress_values;
  6120. string received_body;
  6121. auto res = client_call(
  6122. cli, endpoint,
  6123. [&](const char *data, size_t data_length) -> bool {
  6124. received_body.append(data, data_length);
  6125. return true;
  6126. },
  6127. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6128. progress_values.push_back(current);
  6129. return true;
  6130. });
  6131. ASSERT_TRUE(res);
  6132. EXPECT_EQ(200, res->status);
  6133. EXPECT_FALSE(progress_values.empty());
  6134. EXPECT_EQ(expected_content_size, received_body.size());
  6135. EXPECT_TRUE(res->body.empty());
  6136. }
  6137. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6138. TestContentReceiverDownloadProgress(
  6139. [](Server &svr) {
  6140. svr.Get("/download-receiver",
  6141. [](const Request & /*req*/, Response &res) {
  6142. string content(2000, 'R');
  6143. res.set_content(content, "text/plain");
  6144. });
  6145. },
  6146. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6147. DownloadProgress progress_callback) {
  6148. return cli.Get(endpoint, content_receiver, progress_callback);
  6149. },
  6150. "/download-receiver", 2000u);
  6151. }
  6152. TEST(StreamingTest, NoContentLengthStreaming) {
  6153. Server svr;
  6154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6155. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6156. if (offset < 6) {
  6157. sink.os << (offset < 3 ? "a" : "b");
  6158. } else {
  6159. sink.done();
  6160. }
  6161. return true;
  6162. });
  6163. });
  6164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6165. auto listen_se = detail::scope_exit([&] {
  6166. svr.stop();
  6167. listen_thread.join();
  6168. ASSERT_FALSE(svr.is_running());
  6169. });
  6170. svr.wait_until_ready();
  6171. Client client(HOST, PORT);
  6172. auto get_thread = std::thread([&client]() {
  6173. std::string s;
  6174. auto res =
  6175. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6176. s += std::string(data, len);
  6177. return true;
  6178. });
  6179. ASSERT_TRUE(res);
  6180. EXPECT_EQ(StatusCode::OK_200, res->status);
  6181. EXPECT_EQ("aaabbb", s);
  6182. });
  6183. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6184. // Give GET time to get a few messages.
  6185. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6186. }
  6187. TEST(MountTest, Unmount) {
  6188. Server svr;
  6189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6190. auto se = detail::scope_exit([&] {
  6191. svr.stop();
  6192. listen_thread.join();
  6193. ASSERT_FALSE(svr.is_running());
  6194. });
  6195. svr.wait_until_ready();
  6196. Client cli("localhost", PORT);
  6197. svr.set_mount_point("/mount2", "./www2");
  6198. auto res = cli.Get("/");
  6199. ASSERT_TRUE(res);
  6200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6201. res = cli.Get("/mount2/dir/test.html");
  6202. ASSERT_TRUE(res);
  6203. EXPECT_EQ(StatusCode::OK_200, res->status);
  6204. svr.set_mount_point("/", "./www");
  6205. res = cli.Get("/dir/");
  6206. ASSERT_TRUE(res);
  6207. EXPECT_EQ(StatusCode::OK_200, res->status);
  6208. svr.remove_mount_point("/");
  6209. res = cli.Get("/dir/");
  6210. ASSERT_TRUE(res);
  6211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6212. svr.remove_mount_point("/mount2");
  6213. res = cli.Get("/mount2/dir/test.html");
  6214. ASSERT_TRUE(res);
  6215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6216. }
  6217. TEST(MountTest, Redicect) {
  6218. Server svr;
  6219. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.set_mount_point("/", "./www");
  6226. svr.wait_until_ready();
  6227. Client cli("localhost", PORT);
  6228. auto res = cli.Get("/dir/");
  6229. ASSERT_TRUE(res);
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. res = cli.Get("/dir");
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6234. res = cli.Get("/file");
  6235. ASSERT_TRUE(res);
  6236. EXPECT_EQ(StatusCode::OK_200, res->status);
  6237. res = cli.Get("/file/");
  6238. ASSERT_TRUE(res);
  6239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6240. cli.set_follow_location(true);
  6241. res = cli.Get("/dir");
  6242. ASSERT_TRUE(res);
  6243. EXPECT_EQ(StatusCode::OK_200, res->status);
  6244. }
  6245. TEST(MountTest, MultibytesPathName) {
  6246. Server svr;
  6247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6248. auto se = detail::scope_exit([&] {
  6249. svr.stop();
  6250. listen_thread.join();
  6251. ASSERT_FALSE(svr.is_running());
  6252. });
  6253. svr.set_mount_point("/", "./www");
  6254. svr.wait_until_ready();
  6255. Client cli("localhost", PORT);
  6256. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6257. ASSERT_TRUE(res);
  6258. EXPECT_EQ(StatusCode::OK_200, res->status);
  6259. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6260. }
  6261. TEST(KeepAliveTest, ReadTimeout) {
  6262. Server svr;
  6263. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6264. std::this_thread::sleep_for(std::chrono::seconds(2));
  6265. res.set_content("a", "text/plain");
  6266. });
  6267. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6268. res.set_content("b", "text/plain");
  6269. });
  6270. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6271. auto se = detail::scope_exit([&] {
  6272. svr.stop();
  6273. listen_thread.join();
  6274. ASSERT_FALSE(svr.is_running());
  6275. });
  6276. svr.wait_until_ready();
  6277. Client cli("localhost", PORT);
  6278. cli.set_keep_alive(true);
  6279. cli.set_read_timeout(std::chrono::seconds(1));
  6280. auto resa = cli.Get("/a");
  6281. ASSERT_FALSE(resa);
  6282. EXPECT_EQ(Error::Read, resa.error());
  6283. auto resb = cli.Get("/b");
  6284. ASSERT_TRUE(resb);
  6285. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6286. EXPECT_EQ("b", resb->body);
  6287. }
  6288. TEST(KeepAliveTest, MaxCount) {
  6289. size_t keep_alive_max_count = 3;
  6290. Server svr;
  6291. svr.set_keep_alive_max_count(keep_alive_max_count);
  6292. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6293. res.set_content("Hello World!", "text/plain");
  6294. });
  6295. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6296. auto se = detail::scope_exit([&] {
  6297. svr.stop();
  6298. listen_thread.join();
  6299. ASSERT_FALSE(svr.is_running());
  6300. });
  6301. svr.wait_until_ready();
  6302. Client cli(HOST, PORT);
  6303. cli.set_keep_alive(true);
  6304. for (size_t i = 0; i < 5; i++) {
  6305. auto result = cli.Get("/hi");
  6306. ASSERT_TRUE(result);
  6307. EXPECT_EQ(StatusCode::OK_200, result->status);
  6308. if (i == keep_alive_max_count - 1) {
  6309. EXPECT_EQ("close", result->get_header_value("Connection"));
  6310. } else {
  6311. EXPECT_FALSE(result->has_header("Connection"));
  6312. }
  6313. }
  6314. }
  6315. TEST(KeepAliveTest, Issue1041) {
  6316. Server svr;
  6317. svr.set_keep_alive_timeout(3);
  6318. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6319. res.set_content("Hello World!", "text/plain");
  6320. });
  6321. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6322. auto se = detail::scope_exit([&] {
  6323. svr.stop();
  6324. listen_thread.join();
  6325. ASSERT_FALSE(svr.is_running());
  6326. });
  6327. svr.wait_until_ready();
  6328. Client cli(HOST, PORT);
  6329. cli.set_keep_alive(true);
  6330. auto result = cli.Get("/hi");
  6331. ASSERT_TRUE(result);
  6332. EXPECT_EQ(StatusCode::OK_200, result->status);
  6333. std::this_thread::sleep_for(std::chrono::seconds(5));
  6334. result = cli.Get("/hi");
  6335. ASSERT_TRUE(result);
  6336. EXPECT_EQ(StatusCode::OK_200, result->status);
  6337. }
  6338. TEST(KeepAliveTest, Issue1959) {
  6339. Server svr;
  6340. svr.set_keep_alive_timeout(5);
  6341. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6342. res.set_content("a", "text/plain");
  6343. });
  6344. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6345. auto se = detail::scope_exit([&] {
  6346. if (!svr.is_running()) return;
  6347. svr.stop();
  6348. listen_thread.join();
  6349. ASSERT_FALSE(svr.is_running());
  6350. });
  6351. svr.wait_until_ready();
  6352. Client cli("localhost", PORT);
  6353. cli.set_keep_alive(true);
  6354. using namespace std::chrono;
  6355. auto start = steady_clock::now();
  6356. cli.Get("/a");
  6357. svr.stop();
  6358. listen_thread.join();
  6359. auto end = steady_clock::now();
  6360. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6361. EXPECT_LT(elapsed, 5000);
  6362. }
  6363. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6364. TEST(KeepAliveTest, SSLClientReconnection) {
  6365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6366. ASSERT_TRUE(svr.is_valid());
  6367. svr.set_keep_alive_timeout(1);
  6368. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6369. res.set_content("Hello World!", "text/plain");
  6370. });
  6371. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6372. auto se = detail::scope_exit([&] {
  6373. svr.stop();
  6374. listen_thread.join();
  6375. ASSERT_FALSE(svr.is_running());
  6376. });
  6377. svr.wait_until_ready();
  6378. SSLClient cli(HOST, PORT);
  6379. cli.enable_server_certificate_verification(false);
  6380. cli.set_keep_alive(true);
  6381. auto result = cli.Get("/hi");
  6382. ASSERT_TRUE(result);
  6383. EXPECT_EQ(StatusCode::OK_200, result->status);
  6384. result = cli.Get("/hi");
  6385. ASSERT_TRUE(result);
  6386. EXPECT_EQ(StatusCode::OK_200, result->status);
  6387. std::this_thread::sleep_for(std::chrono::seconds(2));
  6388. // Recoonect
  6389. result = cli.Get("/hi");
  6390. ASSERT_TRUE(result);
  6391. EXPECT_EQ(StatusCode::OK_200, result->status);
  6392. result = cli.Get("/hi");
  6393. ASSERT_TRUE(result);
  6394. EXPECT_EQ(StatusCode::OK_200, result->status);
  6395. }
  6396. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6398. ASSERT_TRUE(svr.is_valid());
  6399. svr.set_keep_alive_timeout(1);
  6400. std::string content = "reconnect";
  6401. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6402. res.set_content("Hello World!", "text/plain");
  6403. });
  6404. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6405. auto se = detail::scope_exit([&] {
  6406. svr.stop();
  6407. listen_thread.join();
  6408. ASSERT_FALSE(svr.is_running());
  6409. });
  6410. svr.wait_until_ready();
  6411. SSLClient cli(HOST, PORT);
  6412. cli.enable_server_certificate_verification(false);
  6413. cli.set_keep_alive(true);
  6414. auto result = cli.Post(
  6415. "/hi", content.size(),
  6416. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6417. sink.write(content.c_str(), content.size());
  6418. return true;
  6419. },
  6420. "text/plain");
  6421. ASSERT_TRUE(result);
  6422. EXPECT_EQ(200, result->status);
  6423. std::this_thread::sleep_for(std::chrono::seconds(2));
  6424. // Recoonect
  6425. result = cli.Post(
  6426. "/hi", content.size(),
  6427. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6428. sink.write(content.c_str(), content.size());
  6429. return true;
  6430. },
  6431. "text/plain");
  6432. ASSERT_TRUE(result);
  6433. EXPECT_EQ(200, result->status);
  6434. result = cli.Post(
  6435. "/hi", content.size(),
  6436. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6437. sink.write(content.c_str(), content.size());
  6438. return true;
  6439. },
  6440. "text/plain");
  6441. ASSERT_TRUE(result);
  6442. EXPECT_EQ(200, result->status);
  6443. }
  6444. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6445. {
  6446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6447. ASSERT_TRUE(svr.is_valid());
  6448. svr.Get("/sni", [&](const Request &req, Response &res) {
  6449. std::string expected;
  6450. if (req.ssl) {
  6451. if (const char *sni =
  6452. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6453. expected = sni;
  6454. }
  6455. }
  6456. EXPECT_EQ(expected, req.get_param_value("expected"));
  6457. res.set_content("ok", "text/plain");
  6458. });
  6459. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6460. auto se = detail::scope_exit([&] {
  6461. svr.stop();
  6462. listen_thread.join();
  6463. ASSERT_FALSE(svr.is_running());
  6464. });
  6465. svr.wait_until_ready();
  6466. {
  6467. SSLClient cli("localhost", PORT);
  6468. cli.enable_server_certificate_verification(false);
  6469. auto res = cli.Get("/sni?expected=localhost");
  6470. ASSERT_TRUE(res);
  6471. }
  6472. {
  6473. SSLClient cli("::1", PORT);
  6474. cli.enable_server_certificate_verification(false);
  6475. auto res = cli.Get("/sni?expected=");
  6476. // NOTE: This may fail if the server is listening on IPv4 only
  6477. // (e.g., when localhost resolves to 127.0.0.1 only)
  6478. if (res) {
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. } else {
  6481. EXPECT_EQ(Error::Connection, res.error());
  6482. }
  6483. }
  6484. }
  6485. }
  6486. #endif
  6487. TEST(ClientProblemDetectionTest, ContentProvider) {
  6488. Server svr;
  6489. size_t content_length = 1024 * 1024;
  6490. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6491. res.set_content_provider(
  6492. content_length, "text/plain",
  6493. [&](size_t offset, size_t length, DataSink &sink) {
  6494. auto out_len = std::min(length, static_cast<size_t>(1024));
  6495. std::string out(out_len, '@');
  6496. sink.write(out.data(), out_len);
  6497. return offset < 4096;
  6498. },
  6499. [](bool success) { ASSERT_FALSE(success); });
  6500. });
  6501. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6502. res.set_content_provider(
  6503. 0, "text/plain",
  6504. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6505. EXPECT_TRUE(false);
  6506. return true;
  6507. },
  6508. [](bool success) { ASSERT_FALSE(success); });
  6509. });
  6510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6511. auto se = detail::scope_exit([&] {
  6512. svr.stop();
  6513. listen_thread.join();
  6514. ASSERT_FALSE(svr.is_running());
  6515. });
  6516. svr.wait_until_ready();
  6517. Client cli("localhost", PORT);
  6518. {
  6519. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6520. size_t /*data_length*/) { return false; });
  6521. ASSERT_FALSE(res);
  6522. }
  6523. {
  6524. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6525. size_t /*data_length*/) { return false; });
  6526. ASSERT_TRUE(res);
  6527. }
  6528. }
  6529. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6530. Server svr;
  6531. svr.set_error_handler([](Request const &, Response &res) -> void {
  6532. res.set_chunked_content_provider(
  6533. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6534. sink.os << "hello";
  6535. sink.os << "world";
  6536. sink.done();
  6537. return true;
  6538. });
  6539. });
  6540. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6541. auto se = detail::scope_exit([&] {
  6542. svr.stop();
  6543. listen_thread.join();
  6544. ASSERT_FALSE(svr.is_running());
  6545. });
  6546. svr.wait_until_ready();
  6547. Client cli("localhost", PORT);
  6548. auto res = cli.Get("/");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. EXPECT_EQ("helloworld", res->body);
  6552. }
  6553. TEST(LongPollingTest, ClientCloseDetection) {
  6554. Server svr;
  6555. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6556. res.set_chunked_content_provider(
  6557. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6558. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6559. sink.os << "hello";
  6560. auto count = 10;
  6561. while (count > 0 && sink.is_writable()) {
  6562. this_thread::sleep_for(chrono::milliseconds(10));
  6563. count--;
  6564. }
  6565. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6566. return true;
  6567. });
  6568. });
  6569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. listen_thread.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.wait_until_ready();
  6576. Client cli("localhost", PORT);
  6577. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6578. EXPECT_EQ("hello", string(data, data_length));
  6579. return false; // close the socket immediately.
  6580. });
  6581. ASSERT_FALSE(res);
  6582. }
  6583. TEST(GetWithParametersTest, GetWithParameters) {
  6584. Server svr;
  6585. svr.Get("/", [&](const Request &req, Response &) {
  6586. EXPECT_EQ("world", req.get_param_value("hello"));
  6587. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6588. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6589. });
  6590. svr.Get("/params", [&](const Request &req, Response &) {
  6591. EXPECT_EQ("world", req.get_param_value("hello"));
  6592. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6593. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6594. });
  6595. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6596. EXPECT_EQ("resource-id", req.matches[1]);
  6597. EXPECT_EQ("foo", req.get_param_value("param1"));
  6598. EXPECT_EQ("bar", req.get_param_value("param2"));
  6599. });
  6600. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6601. EXPECT_EQ("user-id", req.path_params.at("id"));
  6602. EXPECT_EQ("foo", req.get_param_value("param1"));
  6603. EXPECT_EQ("bar", req.get_param_value("param2"));
  6604. });
  6605. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6606. auto se = detail::scope_exit([&] {
  6607. svr.stop();
  6608. listen_thread.join();
  6609. ASSERT_FALSE(svr.is_running());
  6610. });
  6611. svr.wait_until_ready();
  6612. {
  6613. Client cli(HOST, PORT);
  6614. Params params;
  6615. params.emplace("hello", "world");
  6616. params.emplace("hello2", "world2");
  6617. params.emplace("hello3", "world3");
  6618. auto res = cli.Get("/", params, Headers{});
  6619. ASSERT_TRUE(res);
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. }
  6622. {
  6623. Client cli(HOST, PORT);
  6624. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6625. ASSERT_TRUE(res);
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. }
  6628. {
  6629. Client cli(HOST, PORT);
  6630. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6631. ASSERT_TRUE(res);
  6632. EXPECT_EQ(StatusCode::OK_200, res->status);
  6633. }
  6634. {
  6635. Client cli(HOST, PORT);
  6636. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. }
  6641. TEST(GetWithParametersTest, GetWithParameters2) {
  6642. Server svr;
  6643. svr.Get("/", [&](const Request &req, Response &res) {
  6644. auto text = req.get_param_value("hello");
  6645. res.set_content(text, "text/plain");
  6646. });
  6647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6648. auto se = detail::scope_exit([&] {
  6649. svr.stop();
  6650. listen_thread.join();
  6651. ASSERT_FALSE(svr.is_running());
  6652. });
  6653. svr.wait_until_ready();
  6654. Client cli("localhost", PORT);
  6655. Params params;
  6656. params.emplace("hello", "world");
  6657. std::string body;
  6658. auto res = cli.Get("/", params, Headers{},
  6659. [&](const char *data, size_t data_length) {
  6660. body.append(data, data_length);
  6661. return true;
  6662. });
  6663. ASSERT_TRUE(res);
  6664. EXPECT_EQ(StatusCode::OK_200, res->status);
  6665. EXPECT_EQ("world", body);
  6666. }
  6667. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6669. auto host = "httpbin.org";
  6670. auto path = std::string{"/range/32"};
  6671. #else
  6672. auto host = "nghttp2.org";
  6673. auto path = std::string{"/httpbin/range/32"};
  6674. #endif
  6675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6676. SSLClient cli(host);
  6677. #else
  6678. Client cli(host);
  6679. #endif
  6680. cli.set_default_headers({make_range_header({{1, 10}})});
  6681. cli.set_connection_timeout(5);
  6682. {
  6683. auto res = cli.Get(path);
  6684. ASSERT_TRUE(res);
  6685. EXPECT_EQ("bcdefghijk", res->body);
  6686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6687. }
  6688. {
  6689. auto res = cli.Get(path);
  6690. ASSERT_TRUE(res);
  6691. EXPECT_EQ("bcdefghijk", res->body);
  6692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6693. }
  6694. }
  6695. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6696. Server svr;
  6697. svr.set_default_headers({{"Hello", "World"}});
  6698. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6699. res.set_content("ok", "text/plain");
  6700. });
  6701. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6702. auto se = detail::scope_exit([&] {
  6703. svr.stop();
  6704. listen_thread.join();
  6705. ASSERT_FALSE(svr.is_running());
  6706. });
  6707. svr.wait_until_ready();
  6708. Client cli("localhost", PORT);
  6709. auto res = cli.Get("/");
  6710. ASSERT_TRUE(res);
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. EXPECT_EQ("ok", res->body);
  6713. EXPECT_EQ("World", res->get_header_value("Hello"));
  6714. }
  6715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6716. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6718. ASSERT_TRUE(svr.is_valid());
  6719. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6720. std::this_thread::sleep_for(std::chrono::seconds(2));
  6721. res.set_content("a", "text/plain");
  6722. });
  6723. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6724. res.set_content("b", "text/plain");
  6725. });
  6726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6727. auto se = detail::scope_exit([&] {
  6728. svr.stop();
  6729. listen_thread.join();
  6730. ASSERT_FALSE(svr.is_running());
  6731. });
  6732. svr.wait_until_ready();
  6733. SSLClient cli("localhost", PORT);
  6734. cli.enable_server_certificate_verification(false);
  6735. cli.set_keep_alive(true);
  6736. cli.set_read_timeout(std::chrono::seconds(1));
  6737. auto resa = cli.Get("/a");
  6738. ASSERT_TRUE(!resa);
  6739. EXPECT_EQ(Error::Read, resa.error());
  6740. auto resb = cli.Get("/b");
  6741. ASSERT_TRUE(resb);
  6742. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6743. EXPECT_EQ("b", resb->body);
  6744. }
  6745. #endif
  6746. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6747. protected:
  6748. ServerTestWithAI_PASSIVE()
  6749. : cli_(HOST, PORT)
  6750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6751. ,
  6752. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6753. #endif
  6754. {
  6755. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6756. cli_.enable_server_certificate_verification(false);
  6757. #endif
  6758. }
  6759. virtual void SetUp() {
  6760. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6761. res.set_content("Hello World!", "text/plain");
  6762. });
  6763. t_ = thread(
  6764. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6765. svr_.wait_until_ready();
  6766. }
  6767. virtual void TearDown() {
  6768. svr_.stop();
  6769. t_.join();
  6770. }
  6771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6772. SSLClient cli_;
  6773. SSLServer svr_;
  6774. #else
  6775. Client cli_;
  6776. Server svr_;
  6777. #endif
  6778. thread t_;
  6779. };
  6780. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6781. auto res = cli_.Get("/hi");
  6782. ASSERT_TRUE(res);
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6785. EXPECT_EQ("Hello World!", res->body);
  6786. }
  6787. class ServerUpDownTest : public ::testing::Test {
  6788. protected:
  6789. ServerUpDownTest() : cli_(HOST, PORT) {}
  6790. virtual void SetUp() {
  6791. t_ = thread([&]() {
  6792. svr_.bind_to_any_port(HOST);
  6793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6794. ASSERT_TRUE(svr_.listen_after_bind());
  6795. });
  6796. svr_.wait_until_ready();
  6797. }
  6798. virtual void TearDown() {
  6799. svr_.stop();
  6800. t_.join();
  6801. }
  6802. Client cli_;
  6803. Server svr_;
  6804. thread t_;
  6805. };
  6806. TEST_F(ServerUpDownTest, QuickStartStop) {
  6807. // Should not crash, especially when run with
  6808. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6809. }
  6810. class PayloadMaxLengthTest : public ::testing::Test {
  6811. protected:
  6812. PayloadMaxLengthTest()
  6813. : cli_(HOST, PORT)
  6814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6815. ,
  6816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6817. #endif
  6818. {
  6819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6820. cli_.enable_server_certificate_verification(false);
  6821. #endif
  6822. }
  6823. virtual void SetUp() {
  6824. svr_.set_payload_max_length(8);
  6825. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6826. res.set_content("test", "text/plain");
  6827. });
  6828. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6829. svr_.wait_until_ready();
  6830. }
  6831. virtual void TearDown() {
  6832. svr_.stop();
  6833. t_.join();
  6834. }
  6835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6836. SSLClient cli_;
  6837. SSLServer svr_;
  6838. #else
  6839. Client cli_;
  6840. Server svr_;
  6841. #endif
  6842. thread t_;
  6843. };
  6844. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6845. auto res = cli_.Post("/test", "123456789", "text/plain");
  6846. ASSERT_TRUE(res);
  6847. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6848. res = cli_.Post("/test", "12345678", "text/plain");
  6849. ASSERT_TRUE(res);
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. }
  6852. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6853. // Test chunked encoding with payload exceeding the 8-byte limit
  6854. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6855. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6856. ASSERT_TRUE(res);
  6857. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6858. }
  6859. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6860. // Test chunked encoding with payload within the 8-byte limit
  6861. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6862. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6863. ASSERT_TRUE(res);
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6867. // Test using send_request to send chunked data exceeding payload limit
  6868. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6869. "Host: " +
  6870. std::string(HOST) + ":" + std::to_string(PORT) +
  6871. "\r\n"
  6872. "Transfer-Encoding: chunked\r\n"
  6873. "Connection: close\r\n"
  6874. "\r\n"
  6875. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6876. "0123456789\r\n"
  6877. "0\r\n" // End chunk
  6878. "\r\n";
  6879. std::string response;
  6880. bool result = send_request(1, chunked_request, &response);
  6881. if (!result) {
  6882. // If send_request fails, it might be because the server closed the
  6883. // connection due to payload limit enforcement, which is acceptable
  6884. SUCCEED()
  6885. << "Server rejected oversized chunked request (connection closed)";
  6886. } else {
  6887. // If we got a response, check if it's an error response or connection was
  6888. // closed early Short response length indicates connection was closed due to
  6889. // payload limit
  6890. if (response.length() <= 10) {
  6891. SUCCEED() << "Server closed connection for oversized chunked request";
  6892. } else {
  6893. // Check for error status codes
  6894. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6895. response.find("Payload Too Large") != std::string::npos ||
  6896. response.find("400") != std::string::npos);
  6897. }
  6898. }
  6899. }
  6900. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6901. // Test request without Content-Length header exceeding payload limit
  6902. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6903. "Host: " +
  6904. std::string(HOST) + ":" +
  6905. std::to_string(PORT) +
  6906. "\r\n"
  6907. "Connection: close\r\n"
  6908. "\r\n";
  6909. // Add payload exceeding the 8-byte limit
  6910. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6911. request_without_content_length += large_payload;
  6912. std::string response;
  6913. bool result = send_request(1, request_without_content_length, &response);
  6914. if (!result) {
  6915. // If send_request fails, server likely closed connection due to payload
  6916. // limit
  6917. SUCCEED() << "Server rejected oversized request without Content-Length "
  6918. "(connection closed)";
  6919. } else {
  6920. // Check if server responded with error or closed connection early
  6921. if (response.length() <= 10) {
  6922. SUCCEED() << "Server closed connection for oversized request without "
  6923. "Content-Length";
  6924. } else {
  6925. // Check for error status codes
  6926. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6927. response.find("Payload Too Large") != std::string::npos ||
  6928. response.find("400") != std::string::npos);
  6929. }
  6930. }
  6931. }
  6932. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6933. // Test request without Content-Length header within payload limit
  6934. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6935. "Host: " +
  6936. std::string(HOST) + ":" +
  6937. std::to_string(PORT) +
  6938. "\r\n"
  6939. "Connection: close\r\n"
  6940. "\r\n";
  6941. // Add payload within the 8-byte limit
  6942. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6943. request_without_content_length += small_payload;
  6944. std::string response;
  6945. bool result = send_request(1, request_without_content_length, &response);
  6946. // For requests without Content-Length, the server may have different behavior
  6947. // The key is that it should not reject due to payload limit for small
  6948. // payloads
  6949. if (result) {
  6950. // Check for any HTTP response (success or error, but not connection closed)
  6951. if (response.length() > 10) {
  6952. SUCCEED()
  6953. << "Server processed request without Content-Length within limit";
  6954. } else {
  6955. // Short response might indicate connection closed, which is acceptable
  6956. SUCCEED() << "Server closed connection for request without "
  6957. "Content-Length (acceptable behavior)";
  6958. }
  6959. } else {
  6960. // Connection failure might be due to protocol requirements
  6961. SUCCEED() << "Connection issue with request without Content-Length "
  6962. "(environment-specific)";
  6963. }
  6964. }
  6965. class LargePayloadMaxLengthTest : public ::testing::Test {
  6966. protected:
  6967. LargePayloadMaxLengthTest()
  6968. : cli_(HOST, PORT)
  6969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6970. ,
  6971. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6972. #endif
  6973. {
  6974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6975. cli_.enable_server_certificate_verification(false);
  6976. #endif
  6977. }
  6978. virtual void SetUp() {
  6979. // Set 10MB payload limit
  6980. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6981. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6982. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6983. res.set_content("Large payload test", "text/plain");
  6984. });
  6985. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6986. svr_.wait_until_ready();
  6987. }
  6988. virtual void TearDown() {
  6989. svr_.stop();
  6990. t_.join();
  6991. }
  6992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6993. SSLClient cli_;
  6994. SSLServer svr_;
  6995. #else
  6996. Client cli_;
  6997. Server svr_;
  6998. #endif
  6999. thread t_;
  7000. };
  7001. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7002. // Test chunked encoding with payload within 10MB limit
  7003. std::string medium_payload(5 * 1024 * 1024,
  7004. 'A'); // 5MB payload, within 10MB limit
  7005. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7006. ASSERT_TRUE(res);
  7007. EXPECT_EQ(StatusCode::OK_200, res->status);
  7008. }
  7009. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7010. // Test chunked encoding with payload exceeding 10MB limit
  7011. std::string large_payload(12 * 1024 * 1024,
  7012. 'B'); // 12MB payload, exceeds 10MB limit
  7013. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7014. ASSERT_TRUE(res);
  7015. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7016. }
  7017. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7018. // Test request without Content-Length header within 10MB limit
  7019. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7020. "Host: " +
  7021. std::string(HOST) + ":" +
  7022. std::to_string(PORT) +
  7023. "\r\n"
  7024. "Connection: close\r\n"
  7025. "\r\n";
  7026. // Add 1MB payload (within 10MB limit)
  7027. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7028. request_without_content_length += medium_payload;
  7029. std::string response;
  7030. bool result = send_request(5, request_without_content_length, &response);
  7031. if (result) {
  7032. // Should get a proper HTTP response for payloads within limit
  7033. if (response.length() > 10) {
  7034. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7035. "10MB limit";
  7036. } else {
  7037. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7038. "Content-Length)";
  7039. }
  7040. } else {
  7041. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7042. }
  7043. }
  7044. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7045. // Test request without Content-Length header exceeding 10MB limit
  7046. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7047. "Host: " +
  7048. std::string(HOST) + ":" +
  7049. std::to_string(PORT) +
  7050. "\r\n"
  7051. "Connection: close\r\n"
  7052. "\r\n";
  7053. // Add 12MB payload (exceeds 10MB limit)
  7054. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7055. request_without_content_length += large_payload;
  7056. std::string response;
  7057. bool result = send_request(10, request_without_content_length, &response);
  7058. if (!result) {
  7059. // Server should close connection due to payload limit
  7060. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7061. "(connection closed)";
  7062. } else {
  7063. // Check for error response
  7064. if (response.length() <= 10) {
  7065. SUCCEED()
  7066. << "Server closed connection for 12MB request exceeding 10MB limit";
  7067. } else {
  7068. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7069. response.find("Payload Too Large") != std::string::npos ||
  7070. response.find("400") != std::string::npos);
  7071. }
  7072. }
  7073. }
  7074. TEST(HostAndPortPropertiesTest, NoSSL) {
  7075. httplib::Client cli("www.google.com", 1234);
  7076. ASSERT_EQ("www.google.com", cli.host());
  7077. ASSERT_EQ(1234, cli.port());
  7078. }
  7079. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7080. httplib::Client cli("www.google.com:1234");
  7081. ASSERT_EQ("www.google.com", cli.host());
  7082. ASSERT_EQ(1234, cli.port());
  7083. }
  7084. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7085. TEST(HostAndPortPropertiesTest, SSL) {
  7086. httplib::SSLClient cli("www.google.com");
  7087. ASSERT_EQ("www.google.com", cli.host());
  7088. ASSERT_EQ(443, cli.port());
  7089. }
  7090. #endif
  7091. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7092. TEST(SSLClientTest, UpdateCAStore) {
  7093. httplib::SSLClient httplib_client("www.google.com");
  7094. auto ca_store_1 = X509_STORE_new();
  7095. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7096. nullptr);
  7097. httplib_client.set_ca_cert_store(ca_store_1);
  7098. auto ca_store_2 = X509_STORE_new();
  7099. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7100. nullptr);
  7101. httplib_client.set_ca_cert_store(ca_store_2);
  7102. }
  7103. TEST(SSLClientTest, ServerNameIndication_Online) {
  7104. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7105. auto host = "httpbin.org";
  7106. auto path = std::string{"/get"};
  7107. #else
  7108. auto host = "nghttp2.org";
  7109. auto path = std::string{"/httpbin/get"};
  7110. #endif
  7111. SSLClient cli(host, 443);
  7112. auto res = cli.Get(path);
  7113. ASSERT_TRUE(res);
  7114. ASSERT_EQ(StatusCode::OK_200, res->status);
  7115. }
  7116. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7117. // Use a site that will cause SSL verification failure due to self-signed cert
  7118. SSLClient cli("self-signed.badssl.com", 443);
  7119. cli.enable_server_certificate_verification(true);
  7120. auto res = cli.Get("/");
  7121. ASSERT_TRUE(!res);
  7122. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7123. // For SSL server verification errors, ssl_error should be 0, only
  7124. // ssl_openssl_error should be set
  7125. EXPECT_EQ(0, res.ssl_error());
  7126. // Verify OpenSSL error is captured for SSLServerVerification
  7127. // This occurs when SSL_get_verify_result() returns a verification failure
  7128. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7129. res.ssl_openssl_error());
  7130. }
  7131. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7132. // Use a site where hostname doesn't match the certificate
  7133. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7134. SSLClient cli("wrong.host.badssl.com", 443);
  7135. cli.enable_server_certificate_verification(true);
  7136. cli.enable_server_hostname_verification(true);
  7137. auto res = cli.Get("/");
  7138. ASSERT_TRUE(!res);
  7139. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7140. // For SSL hostname verification errors, ssl_error should be 0, only
  7141. // ssl_openssl_error should be set
  7142. EXPECT_EQ(0, res.ssl_error());
  7143. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7144. // This occurs when verify_host() fails due to hostname mismatch
  7145. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7146. res.ssl_openssl_error());
  7147. }
  7148. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7149. Client cli("https://google.com");
  7150. auto res = cli.Get("/");
  7151. ASSERT_TRUE(res);
  7152. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7153. }
  7154. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7155. SSLClient cli("google.com");
  7156. cli.set_ca_cert_path(CA_CERT_FILE);
  7157. auto res = cli.Get("/");
  7158. ASSERT_TRUE(res);
  7159. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7160. }
  7161. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7162. SSLClient cli("google.com");
  7163. cli.enable_server_certificate_verification(true);
  7164. cli.set_ca_cert_path("hello");
  7165. auto res = cli.Get("/");
  7166. ASSERT_TRUE(!res);
  7167. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7168. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7169. // should be set
  7170. EXPECT_EQ(0, res.ssl_error());
  7171. // Verify OpenSSL error is captured for SSLLoadingCerts
  7172. // This error occurs when SSL_CTX_load_verify_locations() fails
  7173. // > openssl errstr 0x80000002
  7174. // error:80000002:system library::No such file or directory
  7175. // > openssl errstr 0xA000126
  7176. // error:0A000126:SSL routines::unexpected eof while reading
  7177. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7178. res.ssl_openssl_error() == 0xA000126);
  7179. }
  7180. TEST(SSLClientTest, ServerCertificateVerification4) {
  7181. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7182. ASSERT_TRUE(svr.is_valid());
  7183. svr.Get("/test", [&](const Request &, Response &res) {
  7184. res.set_content("test", "text/plain");
  7185. svr.stop();
  7186. ASSERT_TRUE(true);
  7187. });
  7188. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7189. auto se = detail::scope_exit([&] {
  7190. t.join();
  7191. ASSERT_FALSE(svr.is_running());
  7192. });
  7193. svr.wait_until_ready();
  7194. SSLClient cli("127.0.0.1", PORT);
  7195. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7196. cli.enable_server_certificate_verification(true);
  7197. cli.set_connection_timeout(30);
  7198. auto res = cli.Get("/test");
  7199. ASSERT_TRUE(res);
  7200. ASSERT_EQ(StatusCode::OK_200, res->status);
  7201. }
  7202. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7203. std::string cert;
  7204. read_file(CA_CERT_FILE, cert);
  7205. SSLClient cli("google.com");
  7206. cli.load_ca_cert_store(cert.data(), cert.size());
  7207. const auto res = cli.Get("/");
  7208. ASSERT_TRUE(res);
  7209. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7210. }
  7211. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7212. // clang-format off
  7213. static constexpr char cert[] =
  7214. "GlobalSign Root CA\n"
  7215. "==================\n"
  7216. "-----BEGIN CERTIFICATE-----\n"
  7217. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7218. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7219. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7220. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7221. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7222. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7223. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7224. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7225. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7226. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7227. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7228. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7229. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7230. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7231. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7232. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7233. "-----END CERTIFICATE-----\n";
  7234. // clang-format on
  7235. SSLClient cli("google.com");
  7236. cli.load_ca_cert_store(cert, sizeof(cert));
  7237. const auto res = cli.Get("/");
  7238. ASSERT_TRUE(res);
  7239. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7240. }
  7241. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7242. SSLClient cli("www.youtube.com");
  7243. cli.set_ca_cert_path(CA_CERT_FILE);
  7244. cli.enable_server_certificate_verification(true);
  7245. cli.set_follow_location(true);
  7246. auto res = cli.Get("/");
  7247. ASSERT_TRUE(res);
  7248. ASSERT_EQ(StatusCode::OK_200, res->status);
  7249. }
  7250. TEST(SSLClientTest, Issue2004_Online) {
  7251. Client client("https://google.com");
  7252. client.set_follow_location(true);
  7253. auto res = client.Get("/");
  7254. ASSERT_TRUE(res);
  7255. ASSERT_EQ(StatusCode::OK_200, res->status);
  7256. auto body = res->body;
  7257. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7258. }
  7259. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7260. // Create SSLClient with invalid cert/key to make is_valid() return false
  7261. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7262. "nonexistent_key.pem");
  7263. // is_valid() should be false due to cert loading failure
  7264. ASSERT_FALSE(cli.is_valid());
  7265. auto res = cli.Get("/");
  7266. ASSERT_FALSE(res);
  7267. EXPECT_EQ(Error::SSLConnection, res.error());
  7268. }
  7269. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7270. // Test for Issue #2251: SSL error not properly reported when client cert
  7271. // and key paths are swapped or mismatched
  7272. // This simulates the scenario where user accidentally swaps the cert and key
  7273. // files
  7274. // Using client cert file as private key and vice versa (completely wrong)
  7275. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7276. // Should fail validation due to cert/key mismatch
  7277. ASSERT_FALSE(cli.is_valid());
  7278. // Attempt to make a request should fail with proper error
  7279. auto res = cli.Get("/");
  7280. ASSERT_FALSE(res);
  7281. EXPECT_EQ(Error::SSLConnection, res.error());
  7282. // SSL error should be recorded in the Result object (this is the key fix for
  7283. // Issue #2251)
  7284. auto openssl_error = res.ssl_openssl_error();
  7285. EXPECT_NE(0u, openssl_error);
  7286. }
  7287. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7288. // Another variant: using valid file paths but with mismatched cert/key pair
  7289. // This tests the case where files exist but contain incompatible key material
  7290. // Using client cert with wrong key (cert2 key)
  7291. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7292. // Should fail validation
  7293. ASSERT_FALSE(cli.is_valid());
  7294. auto res = cli.Get("/");
  7295. ASSERT_FALSE(res);
  7296. // Must report error properly, not appear as success
  7297. EXPECT_EQ(Error::SSLConnection, res.error());
  7298. // OpenSSL error should be captured in Result
  7299. EXPECT_NE(0u, res.ssl_openssl_error());
  7300. }
  7301. #if 0
  7302. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7303. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7304. ASSERT_TRUE(cli != nullptr);
  7305. cli->set_address_family(AF_INET6);
  7306. cli->set_interface("en0");
  7307. auto res = cli->Get("/get");
  7308. ASSERT_TRUE(res);
  7309. ASSERT_EQ(StatusCode::OK_200, res->status);
  7310. }
  7311. #endif
  7312. void ClientCertPresent(
  7313. const std::string &client_cert_file,
  7314. const std::string &client_private_key_file,
  7315. const std::string &client_encrypted_private_key_pass = std::string()) {
  7316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7317. CLIENT_CA_CERT_DIR);
  7318. ASSERT_TRUE(svr.is_valid());
  7319. svr.Get("/test", [&](const Request &req, Response &res) {
  7320. res.set_content("test", "text/plain");
  7321. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7322. ASSERT_TRUE(peer_cert != nullptr);
  7323. auto subject_name = X509_get_subject_name(peer_cert);
  7324. ASSERT_TRUE(subject_name != nullptr);
  7325. std::string common_name;
  7326. {
  7327. char name[BUFSIZ];
  7328. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7329. name, sizeof(name));
  7330. common_name.assign(name, static_cast<size_t>(name_len));
  7331. }
  7332. EXPECT_EQ("Common Name", common_name);
  7333. X509_free(peer_cert);
  7334. });
  7335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7336. auto se = detail::scope_exit([&] {
  7337. svr.stop();
  7338. t.join();
  7339. ASSERT_FALSE(svr.is_running());
  7340. });
  7341. svr.wait_until_ready();
  7342. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7343. client_encrypted_private_key_pass);
  7344. cli.enable_server_certificate_verification(false);
  7345. cli.set_connection_timeout(30);
  7346. auto res = cli.Get("/test");
  7347. ASSERT_TRUE(res);
  7348. ASSERT_EQ(StatusCode::OK_200, res->status);
  7349. }
  7350. TEST(SSLClientServerTest, ClientCertPresent) {
  7351. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7352. }
  7353. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7354. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7355. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7356. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7357. }
  7358. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7359. void MemoryClientCertPresent(
  7360. const std::string &client_cert_file,
  7361. const std::string &client_private_key_file,
  7362. const std::string &client_encrypted_private_key_pass = std::string()) {
  7363. auto f = fopen(SERVER_CERT_FILE, "r+");
  7364. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7365. fclose(f);
  7366. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7367. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7368. fclose(f);
  7369. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7370. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7371. auto client_ca_cert_store = X509_STORE_new();
  7372. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7373. X509_free(client_cert);
  7374. fclose(f);
  7375. f = fopen(client_cert_file.c_str(), "r+");
  7376. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7377. fclose(f);
  7378. f = fopen(client_private_key_file.c_str(), "r+");
  7379. auto client_private_key = PEM_read_PrivateKey(
  7380. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7381. fclose(f);
  7382. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7383. ASSERT_TRUE(svr.is_valid());
  7384. svr.Get("/test", [&](const Request &req, Response &res) {
  7385. res.set_content("test", "text/plain");
  7386. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7387. ASSERT_TRUE(peer_cert != nullptr);
  7388. auto subject_name = X509_get_subject_name(peer_cert);
  7389. ASSERT_TRUE(subject_name != nullptr);
  7390. std::string common_name;
  7391. {
  7392. char name[BUFSIZ];
  7393. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7394. name, sizeof(name));
  7395. common_name.assign(name, static_cast<size_t>(name_len));
  7396. }
  7397. EXPECT_EQ("Common Name", common_name);
  7398. X509_free(peer_cert);
  7399. });
  7400. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7401. auto se = detail::scope_exit([&] {
  7402. svr.stop();
  7403. t.join();
  7404. ASSERT_FALSE(svr.is_running());
  7405. });
  7406. svr.wait_until_ready();
  7407. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7408. client_encrypted_private_key_pass);
  7409. cli.enable_server_certificate_verification(false);
  7410. cli.set_connection_timeout(30);
  7411. auto res = cli.Get("/test");
  7412. ASSERT_TRUE(res);
  7413. ASSERT_EQ(StatusCode::OK_200, res->status);
  7414. X509_free(server_cert);
  7415. EVP_PKEY_free(server_private_key);
  7416. X509_free(client_cert);
  7417. EVP_PKEY_free(client_private_key);
  7418. }
  7419. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7420. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7421. }
  7422. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7423. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7424. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7425. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7426. }
  7427. #endif
  7428. TEST(SSLClientServerTest, ClientCertMissing) {
  7429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7430. CLIENT_CA_CERT_DIR);
  7431. ASSERT_TRUE(svr.is_valid());
  7432. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7433. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7434. auto se = detail::scope_exit([&] {
  7435. svr.stop();
  7436. t.join();
  7437. ASSERT_FALSE(svr.is_running());
  7438. });
  7439. svr.wait_until_ready();
  7440. SSLClient cli(HOST, PORT);
  7441. cli.set_connection_timeout(30);
  7442. auto res = cli.Get("/test");
  7443. ASSERT_TRUE(!res);
  7444. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7445. // For SSL server verification errors, ssl_error should be 0, only
  7446. // ssl_openssl_error should be set
  7447. EXPECT_EQ(0, res.ssl_error());
  7448. // Verify OpenSSL error is captured for SSLServerVerification
  7449. // Note: This test may have different error codes depending on the exact
  7450. // verification failure
  7451. EXPECT_NE(0UL, res.ssl_openssl_error());
  7452. }
  7453. TEST(SSLClientServerTest, TrustDirOptional) {
  7454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7455. ASSERT_TRUE(svr.is_valid());
  7456. svr.Get("/test", [&](const Request &, Response &res) {
  7457. res.set_content("test", "text/plain");
  7458. });
  7459. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7460. auto se = detail::scope_exit([&] {
  7461. svr.stop();
  7462. t.join();
  7463. ASSERT_FALSE(svr.is_running());
  7464. });
  7465. svr.wait_until_ready();
  7466. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7467. cli.enable_server_certificate_verification(false);
  7468. cli.set_connection_timeout(30);
  7469. auto res = cli.Get("/test");
  7470. ASSERT_TRUE(res);
  7471. ASSERT_EQ(StatusCode::OK_200, res->status);
  7472. }
  7473. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7474. class NoListenSSLServer : public SSLServer {
  7475. public:
  7476. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7477. const char *client_ca_cert_file_path,
  7478. const char *client_ca_cert_dir_path = nullptr)
  7479. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7480. client_ca_cert_dir_path),
  7481. stop_(false) {}
  7482. std::atomic_bool stop_;
  7483. private:
  7484. bool process_and_close_socket(socket_t /*sock*/) override {
  7485. // Don't create SSL context
  7486. while (!stop_.load()) {
  7487. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7488. }
  7489. return true;
  7490. }
  7491. };
  7492. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7493. CLIENT_CA_CERT_FILE);
  7494. ASSERT_TRUE(svr.is_valid());
  7495. svr.Get("/test", [&](const Request &, Response &res) {
  7496. res.set_content("test", "text/plain");
  7497. });
  7498. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7499. auto se = detail::scope_exit([&] {
  7500. svr.stop_ = true;
  7501. svr.stop();
  7502. t.join();
  7503. ASSERT_FALSE(svr.is_running());
  7504. });
  7505. svr.wait_until_ready();
  7506. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7507. cli.enable_server_certificate_verification(false);
  7508. cli.set_connection_timeout(1);
  7509. auto res = cli.Get("/test");
  7510. ASSERT_TRUE(!res);
  7511. EXPECT_EQ(Error::SSLConnection, res.error());
  7512. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7513. }
  7514. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7515. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7516. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7517. SSL_CTX_set_options(&ssl_ctx,
  7518. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7519. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7520. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7521. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7522. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7523. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7524. "ECDHE-DSS-AES128-SHA256:"
  7525. "ECDHE-RSA-AES256-SHA256:"
  7526. "ECDHE-DSS-AES256-SHA256:";
  7527. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7528. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7529. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7530. SSL_FILETYPE_PEM) != 1) {
  7531. return false;
  7532. }
  7533. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7534. CLIENT_CA_CERT_DIR);
  7535. SSL_CTX_set_verify(
  7536. &ssl_ctx,
  7537. SSL_VERIFY_PEER |
  7538. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7539. nullptr);
  7540. return true;
  7541. };
  7542. SSLServer svr(setup_ssl_ctx_callback);
  7543. ASSERT_TRUE(svr.is_valid());
  7544. svr.Get("/test", [&](const Request &req, Response &res) {
  7545. res.set_content("test", "text/plain");
  7546. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7547. ASSERT_TRUE(peer_cert != nullptr);
  7548. auto subject_name = X509_get_subject_name(peer_cert);
  7549. ASSERT_TRUE(subject_name != nullptr);
  7550. std::string common_name;
  7551. {
  7552. char name[BUFSIZ];
  7553. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7554. name, sizeof(name));
  7555. common_name.assign(name, static_cast<size_t>(name_len));
  7556. }
  7557. EXPECT_EQ("Common Name", common_name);
  7558. X509_free(peer_cert);
  7559. });
  7560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7561. auto se = detail::scope_exit([&] {
  7562. svr.stop();
  7563. t.join();
  7564. ASSERT_FALSE(svr.is_running());
  7565. });
  7566. svr.wait_until_ready();
  7567. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7568. cli.enable_server_certificate_verification(false);
  7569. cli.set_connection_timeout(30);
  7570. auto res = cli.Get("/test");
  7571. ASSERT_TRUE(res);
  7572. ASSERT_EQ(StatusCode::OK_200, res->status);
  7573. }
  7574. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7576. ASSERT_TRUE(svr.is_valid());
  7577. // Set up a handler to verify client certificate is present
  7578. bool client_cert_verified = false;
  7579. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7580. // Verify that client certificate was provided
  7581. client_cert_verified = true;
  7582. res.set_content("success", "text/plain");
  7583. });
  7584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7585. auto se = detail::scope_exit([&] {
  7586. svr.stop();
  7587. t.join();
  7588. ASSERT_FALSE(svr.is_running());
  7589. });
  7590. svr.wait_until_ready();
  7591. // Client with certificate
  7592. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7593. cli.enable_server_certificate_verification(false);
  7594. cli.set_connection_timeout(30);
  7595. auto res = cli.Get("/test");
  7596. ASSERT_TRUE(res);
  7597. ASSERT_EQ(StatusCode::OK_200, res->status);
  7598. ASSERT_TRUE(client_cert_verified);
  7599. EXPECT_EQ("success", res->body);
  7600. }
  7601. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7602. // Test that when client CA cert file is provided,
  7603. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7604. // Create a server with client authentication
  7605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7606. ASSERT_TRUE(svr.is_valid());
  7607. // We can't directly access the SSL_CTX from SSLServer to verify,
  7608. // but we can test that the server properly requests client certificates
  7609. // and accepts valid ones from the specified CA
  7610. bool handler_called = false;
  7611. svr.Get("/test", [&](const Request &req, Response &res) {
  7612. handler_called = true;
  7613. // Verify that a client certificate was provided
  7614. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7615. ASSERT_TRUE(peer_cert != nullptr);
  7616. // Get the issuer name
  7617. auto issuer_name = X509_get_issuer_name(peer_cert);
  7618. ASSERT_TRUE(issuer_name != nullptr);
  7619. char issuer_buf[256];
  7620. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7621. // The client certificate should be issued by our test CA
  7622. std::string issuer_str(issuer_buf);
  7623. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7624. X509_free(peer_cert);
  7625. res.set_content("authenticated", "text/plain");
  7626. });
  7627. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7628. auto se = detail::scope_exit([&] {
  7629. svr.stop();
  7630. t.join();
  7631. ASSERT_FALSE(svr.is_running());
  7632. });
  7633. svr.wait_until_ready();
  7634. // Connect with a client certificate issued by the CA
  7635. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7636. cli.enable_server_certificate_verification(false);
  7637. cli.set_connection_timeout(30);
  7638. auto res = cli.Get("/test");
  7639. ASSERT_TRUE(res);
  7640. ASSERT_EQ(StatusCode::OK_200, res->status);
  7641. ASSERT_TRUE(handler_called);
  7642. EXPECT_EQ("authenticated", res->body);
  7643. }
  7644. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7645. // Test 1: Valid CA file - no error should be recorded
  7646. {
  7647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7648. CLIENT_CA_CERT_FILE);
  7649. ASSERT_TRUE(svr.is_valid());
  7650. // With valid setup, last_ssl_error should be 0
  7651. EXPECT_EQ(0, svr.ssl_last_error());
  7652. }
  7653. // Test 2: Invalid CA file content
  7654. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7655. {
  7656. // Create a temporary file with completely invalid content
  7657. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7658. {
  7659. std::ofstream ofs(temp_invalid_ca);
  7660. ofs << "This is not a certificate file at all\n";
  7661. ofs << "Just plain text content\n";
  7662. }
  7663. // Create server with invalid CA file
  7664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7665. // Clean up temporary file
  7666. std::remove(temp_invalid_ca);
  7667. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7668. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7669. // Note: SSL_CTX_load_verify_locations typically fails first,
  7670. // but our error handling code path is still exercised
  7671. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7672. }
  7673. }
  7674. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7675. // Test SSL server using X509_STORE constructor with client CA certificates
  7676. // This test verifies that Phase 2 implementation correctly extracts CA names
  7677. // from an X509_STORE and sets them in the SSL context
  7678. // Load the CA certificate into memory
  7679. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7680. ASSERT_NE(nullptr, bio);
  7681. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7682. BIO_free(bio);
  7683. ASSERT_NE(nullptr, ca_cert);
  7684. // Create an X509_STORE and add the CA certificate
  7685. auto store = X509_STORE_new();
  7686. ASSERT_NE(nullptr, store);
  7687. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7688. // Load server certificate and private key
  7689. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7690. ASSERT_NE(nullptr, cert_bio);
  7691. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7692. BIO_free(cert_bio);
  7693. ASSERT_NE(nullptr, server_cert);
  7694. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7695. ASSERT_NE(nullptr, key_bio);
  7696. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7697. BIO_free(key_bio);
  7698. ASSERT_NE(nullptr, server_key);
  7699. // Create SSLServer with X509_STORE constructor
  7700. // Note: X509_STORE ownership is transferred to SSL_CTX
  7701. SSLServer svr(server_cert, server_key, store);
  7702. ASSERT_TRUE(svr.is_valid());
  7703. // No SSL error should be recorded for valid setup
  7704. EXPECT_EQ(0, svr.ssl_last_error());
  7705. // Set up server endpoints
  7706. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7707. res.set_content("ok", "text/plain");
  7708. });
  7709. // Start server in a thread
  7710. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7711. svr.wait_until_ready();
  7712. // Connect with client certificate (using constructor with paths)
  7713. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7714. cli.enable_server_certificate_verification(false);
  7715. auto res = cli.Get("/test-x509store");
  7716. ASSERT_TRUE(res);
  7717. EXPECT_EQ(200, res->status);
  7718. EXPECT_EQ("ok", res->body);
  7719. // Clean up
  7720. X509_free(server_cert);
  7721. EVP_PKEY_free(server_key);
  7722. X509_free(ca_cert);
  7723. svr.stop();
  7724. server_thread.join();
  7725. }
  7726. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7727. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7728. // prepare large data
  7729. std::random_device seed_gen;
  7730. std::mt19937 random(seed_gen());
  7731. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7732. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7733. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7734. // server
  7735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7736. ASSERT_TRUE(svr.is_valid());
  7737. svr.Post("/binary", [&](const Request &req, Response &res) {
  7738. EXPECT_EQ(large_size_byte, req.body.size());
  7739. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7740. res.set_content(req.body, "application/octet-stream");
  7741. });
  7742. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. listen_thread.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. // client POST
  7750. SSLClient cli("localhost", PORT);
  7751. cli.enable_server_certificate_verification(false);
  7752. cli.set_read_timeout(std::chrono::seconds(100));
  7753. cli.set_write_timeout(std::chrono::seconds(100));
  7754. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7755. large_size_byte, "application/octet-stream");
  7756. // compare
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ(large_size_byte, res->body.size());
  7759. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7760. }
  7761. #endif
  7762. #ifdef _WIN32
  7763. TEST(CleanupTest, WSACleanup) {
  7764. int ret = WSACleanup();
  7765. ASSERT_EQ(0, ret);
  7766. }
  7767. #endif
  7768. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7769. TEST(NoSSLSupport, SimpleInterface) {
  7770. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7771. }
  7772. #endif
  7773. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7774. TEST(InvalidScheme, SimpleInterface) {
  7775. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7776. }
  7777. #endif
  7778. TEST(NoScheme, SimpleInterface) {
  7779. Client cli("yahoo.com:80");
  7780. ASSERT_TRUE(cli.is_valid());
  7781. }
  7782. TEST(SendAPI, SimpleInterface_Online) {
  7783. Client cli("http://yahoo.com");
  7784. Request req;
  7785. req.method = "GET";
  7786. req.path = "/";
  7787. auto res = cli.send(req);
  7788. ASSERT_TRUE(res);
  7789. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7790. }
  7791. TEST(SendAPI, WithParamsInRequest) {
  7792. Server svr;
  7793. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7794. EXPECT_TRUE(req.has_param("test"));
  7795. EXPECT_EQ("test_value", req.get_param_value("test"));
  7796. });
  7797. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. t.join();
  7801. ASSERT_FALSE(svr.is_running());
  7802. });
  7803. svr.wait_until_ready();
  7804. Client cli(HOST, PORT);
  7805. {
  7806. Request req;
  7807. req.method = "GET";
  7808. req.path = "/";
  7809. req.params.emplace("test", "test_value");
  7810. auto res = cli.send(req);
  7811. ASSERT_TRUE(res);
  7812. }
  7813. {
  7814. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7815. ASSERT_TRUE(res);
  7816. }
  7817. }
  7818. TEST(ClientImplMethods, GetSocketTest) {
  7819. httplib::Server svr;
  7820. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7821. res.status = StatusCode::OK_200;
  7822. });
  7823. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7824. auto se = detail::scope_exit([&] {
  7825. svr.stop();
  7826. thread.join();
  7827. ASSERT_FALSE(svr.is_running());
  7828. });
  7829. svr.wait_until_ready();
  7830. {
  7831. httplib::Client cli("http://127.0.0.1:3333");
  7832. cli.set_keep_alive(true);
  7833. // Use the behavior of cpp-httplib of opening the connection
  7834. // only when the first request happens. If that changes,
  7835. // this test would be obsolete.
  7836. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7837. // This also implicitly tests the server. But other tests would fail much
  7838. // earlier than this one to be considered.
  7839. auto res = cli.Get("/");
  7840. ASSERT_TRUE(res);
  7841. EXPECT_EQ(StatusCode::OK_200, res->status);
  7842. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7843. }
  7844. }
  7845. // Disabled due to out-of-memory problem on GitHub Actions
  7846. #ifdef _WIN64
  7847. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7848. // allocate content size larger than 2GB in memory
  7849. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7850. char *content = (char *)malloc(content_size);
  7851. ASSERT_TRUE(content);
  7852. Server svr;
  7853. svr.Get("/foo",
  7854. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7855. res.set_content(content, content_size, "application/octet-stream");
  7856. });
  7857. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7858. auto se = detail::scope_exit([&] {
  7859. svr.stop();
  7860. listen_thread.join();
  7861. if (content) free(content);
  7862. ASSERT_FALSE(svr.is_running());
  7863. });
  7864. svr.wait_until_ready();
  7865. Client cli(HOST, PORT);
  7866. auto res = cli.Get("/foo");
  7867. ASSERT_TRUE(res);
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. EXPECT_EQ(content_size, res->body.length());
  7870. }
  7871. #endif
  7872. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7873. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7874. Client cli("http://yahoo.com");
  7875. auto res = cli.Get("/");
  7876. ASSERT_TRUE(res);
  7877. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7878. cli.set_follow_location(true);
  7879. res = cli.Get("/");
  7880. ASSERT_TRUE(res);
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7883. }
  7884. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7885. Client cli("https://yahoo.com");
  7886. auto res = cli.Get("/");
  7887. ASSERT_TRUE(res);
  7888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7889. cli.set_follow_location(true);
  7890. res = cli.Get("/");
  7891. ASSERT_TRUE(res);
  7892. EXPECT_EQ(StatusCode::OK_200, res->status);
  7893. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7894. }
  7895. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7896. Client cli("https://yahoo.com");
  7897. auto res = cli.Get("/");
  7898. ASSERT_TRUE(res);
  7899. ASSERT_FALSE(!res);
  7900. ASSERT_TRUE(res);
  7901. ASSERT_FALSE(res == nullptr);
  7902. ASSERT_TRUE(res != nullptr);
  7903. EXPECT_EQ(Error::Success, res.error());
  7904. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7905. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7906. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7907. cli.set_follow_location(true);
  7908. res = cli.Get("/");
  7909. ASSERT_TRUE(res);
  7910. EXPECT_EQ(Error::Success, res.error());
  7911. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7912. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7915. }
  7916. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7917. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7918. Client cli("https://cdnjs.cloudflare.com");
  7919. auto res =
  7920. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7921. ASSERT_TRUE(res);
  7922. EXPECT_EQ(StatusCode::OK_200, res->status);
  7923. EXPECT_EQ(287630U, res->body.size());
  7924. EXPECT_EQ("application/javascript; charset=utf-8",
  7925. res->get_header_value("Content-Type"));
  7926. }
  7927. #endif
  7928. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7929. #undef REDIR_HOST // Silence compiler warning
  7930. #define REDIR_HOST "https://httpbingo.org"
  7931. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7932. Client cli(REDIR_HOST);
  7933. cli.set_follow_location(true);
  7934. auto res =
  7935. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7936. ASSERT_TRUE(res);
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. }
  7939. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7940. Client cli(REDIR_HOST);
  7941. cli.set_follow_location(true);
  7942. Params params;
  7943. params.emplace("url", "http://example.com");
  7944. params.emplace("status_code", "302");
  7945. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7946. ASSERT_TRUE(res);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7950. Client cli(REDIR_HOST);
  7951. cli.set_follow_location(true);
  7952. Params params;
  7953. params.emplace("url", "http://example.com");
  7954. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7955. ASSERT_TRUE(res);
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. }
  7958. TEST(HttpToHttpsRedirectTest, CertFile) {
  7959. Server svr;
  7960. ASSERT_TRUE(svr.is_valid());
  7961. svr.Get("/index", [&](const Request &, Response &res) {
  7962. res.set_redirect("https://127.0.0.1:1235/index");
  7963. svr.stop();
  7964. });
  7965. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7966. ASSERT_TRUE(ssl_svr.is_valid());
  7967. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7968. res.set_content("test", "text/plain");
  7969. ssl_svr.stop();
  7970. });
  7971. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7972. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7973. auto se = detail::scope_exit([&] {
  7974. t2.join();
  7975. t.join();
  7976. ASSERT_FALSE(svr.is_running());
  7977. });
  7978. svr.wait_until_ready();
  7979. ssl_svr.wait_until_ready();
  7980. Client cli("127.0.0.1", PORT);
  7981. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7982. cli.enable_server_certificate_verification(true);
  7983. cli.set_follow_location(true);
  7984. cli.set_connection_timeout(30);
  7985. auto res = cli.Get("/index");
  7986. ASSERT_TRUE(res);
  7987. ASSERT_EQ(StatusCode::OK_200, res->status);
  7988. }
  7989. TEST(SSLClientRedirectTest, CertFile) {
  7990. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7991. ASSERT_TRUE(ssl_svr1.is_valid());
  7992. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7993. res.set_redirect("https://127.0.0.1:1235/index");
  7994. ssl_svr1.stop();
  7995. });
  7996. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7997. ASSERT_TRUE(ssl_svr2.is_valid());
  7998. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7999. res.set_content("test", "text/plain");
  8000. ssl_svr2.stop();
  8001. });
  8002. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8003. thread t2 =
  8004. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8005. auto se = detail::scope_exit([&] {
  8006. t2.join();
  8007. t.join();
  8008. ASSERT_FALSE(ssl_svr1.is_running());
  8009. });
  8010. ssl_svr1.wait_until_ready();
  8011. ssl_svr2.wait_until_ready();
  8012. SSLClient cli("127.0.0.1", PORT);
  8013. std::string cert;
  8014. read_file(SERVER_CERT2_FILE, cert);
  8015. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8016. cli.enable_server_certificate_verification(true);
  8017. cli.set_follow_location(true);
  8018. cli.set_connection_timeout(30);
  8019. auto res = cli.Get("/index");
  8020. ASSERT_TRUE(res);
  8021. ASSERT_EQ(StatusCode::OK_200, res->status);
  8022. }
  8023. TEST(MultipartFormDataTest, LargeData) {
  8024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8025. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8026. const ContentReader &content_reader) {
  8027. if (req.is_multipart_form_data()) {
  8028. std::vector<FormData> items;
  8029. content_reader(
  8030. [&](const FormData &file) {
  8031. items.push_back(file);
  8032. return true;
  8033. },
  8034. [&](const char *data, size_t data_length) {
  8035. items.back().content.append(data, data_length);
  8036. return true;
  8037. });
  8038. EXPECT_TRUE(std::string(items[0].name) == "document");
  8039. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8040. EXPECT_TRUE(items[0].filename == "2MB_data");
  8041. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8042. EXPECT_TRUE(items[1].name == "hello");
  8043. EXPECT_TRUE(items[1].content == "world");
  8044. EXPECT_TRUE(items[1].filename == "");
  8045. EXPECT_TRUE(items[1].content_type == "");
  8046. } else {
  8047. std::string body;
  8048. content_reader([&](const char *data, size_t data_length) {
  8049. body.append(data, data_length);
  8050. return true;
  8051. });
  8052. }
  8053. });
  8054. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8055. auto se = detail::scope_exit([&] {
  8056. svr.stop();
  8057. t.join();
  8058. ASSERT_FALSE(svr.is_running());
  8059. });
  8060. svr.wait_until_ready();
  8061. {
  8062. std::string data(1024 * 1024 * 2, '.');
  8063. std::stringstream buffer;
  8064. buffer << data;
  8065. Client cli("https://localhost:8080");
  8066. cli.enable_server_certificate_verification(false);
  8067. UploadFormDataItems items{
  8068. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8069. {"hello", "world", "", ""},
  8070. };
  8071. auto res = cli.Post("/post", items);
  8072. ASSERT_TRUE(res);
  8073. ASSERT_EQ(StatusCode::OK_200, res->status);
  8074. }
  8075. }
  8076. TEST(MultipartFormDataTest, DataProviderItems) {
  8077. std::random_device seed_gen;
  8078. std::mt19937 random(seed_gen());
  8079. std::string rand1;
  8080. rand1.resize(1000);
  8081. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8082. std::string rand2;
  8083. rand2.resize(3000);
  8084. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8086. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8087. const ContentReader &content_reader) {
  8088. ASSERT_FALSE(req.is_multipart_form_data());
  8089. std::string body;
  8090. content_reader([&](const char *data, size_t data_length) {
  8091. body.append(data, data_length);
  8092. return true;
  8093. });
  8094. EXPECT_EQ(body, "");
  8095. });
  8096. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8097. const ContentReader &content_reader) {
  8098. ASSERT_TRUE(req.is_multipart_form_data());
  8099. std::vector<FormData> items;
  8100. content_reader(
  8101. [&](const FormData &file) {
  8102. items.push_back(file);
  8103. return true;
  8104. },
  8105. [&](const char *data, size_t data_length) {
  8106. items.back().content.append(data, data_length);
  8107. return true;
  8108. });
  8109. ASSERT_TRUE(items.size() == 2);
  8110. EXPECT_EQ(std::string(items[0].name), "name1");
  8111. EXPECT_EQ(items[0].content, "Testing123");
  8112. EXPECT_EQ(items[0].filename, "filename1");
  8113. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8114. EXPECT_EQ(items[1].name, "name2");
  8115. EXPECT_EQ(items[1].content, "Testing456");
  8116. EXPECT_EQ(items[1].filename, "");
  8117. EXPECT_EQ(items[1].content_type, "");
  8118. });
  8119. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8120. const ContentReader &content_reader) {
  8121. ASSERT_TRUE(req.is_multipart_form_data());
  8122. std::vector<FormData> items;
  8123. content_reader(
  8124. [&](const FormData &file) {
  8125. items.push_back(file);
  8126. return true;
  8127. },
  8128. [&](const char *data, size_t data_length) {
  8129. items.back().content.append(data, data_length);
  8130. return true;
  8131. });
  8132. ASSERT_TRUE(items.size() == 2);
  8133. EXPECT_EQ(items[0].name, "name3");
  8134. EXPECT_EQ(items[0].content, rand1);
  8135. EXPECT_EQ(items[0].filename, "filename3");
  8136. EXPECT_EQ(items[0].content_type, "");
  8137. EXPECT_EQ(items[1].name, "name4");
  8138. EXPECT_EQ(items[1].content, rand2);
  8139. EXPECT_EQ(items[1].filename, "filename4");
  8140. EXPECT_EQ(items[1].content_type, "");
  8141. });
  8142. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8143. const ContentReader &content_reader) {
  8144. ASSERT_TRUE(req.is_multipart_form_data());
  8145. std::vector<FormData> items;
  8146. content_reader(
  8147. [&](const FormData &file) {
  8148. items.push_back(file);
  8149. return true;
  8150. },
  8151. [&](const char *data, size_t data_length) {
  8152. items.back().content.append(data, data_length);
  8153. return true;
  8154. });
  8155. ASSERT_TRUE(items.size() == 4);
  8156. EXPECT_EQ(std::string(items[0].name), "name1");
  8157. EXPECT_EQ(items[0].content, "Testing123");
  8158. EXPECT_EQ(items[0].filename, "filename1");
  8159. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8160. EXPECT_EQ(items[1].name, "name2");
  8161. EXPECT_EQ(items[1].content, "Testing456");
  8162. EXPECT_EQ(items[1].filename, "");
  8163. EXPECT_EQ(items[1].content_type, "");
  8164. EXPECT_EQ(items[2].name, "name3");
  8165. EXPECT_EQ(items[2].content, rand1);
  8166. EXPECT_EQ(items[2].filename, "filename3");
  8167. EXPECT_EQ(items[2].content_type, "");
  8168. EXPECT_EQ(items[3].name, "name4");
  8169. EXPECT_EQ(items[3].content, rand2);
  8170. EXPECT_EQ(items[3].filename, "filename4");
  8171. EXPECT_EQ(items[3].content_type, "");
  8172. });
  8173. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8174. auto se = detail::scope_exit([&] {
  8175. svr.stop();
  8176. t.join();
  8177. ASSERT_FALSE(svr.is_running());
  8178. });
  8179. svr.wait_until_ready();
  8180. {
  8181. Client cli("https://localhost:8080");
  8182. cli.enable_server_certificate_verification(false);
  8183. UploadFormDataItems items{
  8184. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8185. {"name2", "Testing456", "", ""}, // not a file
  8186. };
  8187. {
  8188. auto res = cli.Post("/post-none", {}, {}, {});
  8189. ASSERT_TRUE(res);
  8190. ASSERT_EQ(StatusCode::OK_200, res->status);
  8191. }
  8192. FormDataProviderItems providers;
  8193. {
  8194. auto res =
  8195. cli.Post("/post-items", {}, items, providers); // empty providers
  8196. ASSERT_TRUE(res);
  8197. ASSERT_EQ(StatusCode::OK_200, res->status);
  8198. }
  8199. providers.push_back({"name3",
  8200. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8201. // test the offset is given correctly at each step
  8202. if (!offset)
  8203. sink.os.write(rand1.data(), 30);
  8204. else if (offset == 30)
  8205. sink.os.write(rand1.data() + 30, 300);
  8206. else if (offset == 330)
  8207. sink.os.write(rand1.data() + 330, 670);
  8208. else if (offset == rand1.size())
  8209. sink.done();
  8210. return true;
  8211. },
  8212. "filename3",
  8213. {}});
  8214. providers.push_back({"name4",
  8215. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8216. // test the offset is given correctly at each step
  8217. if (!offset)
  8218. sink.os.write(rand2.data(), 2000);
  8219. else if (offset == 2000)
  8220. sink.os.write(rand2.data() + 2000, 1);
  8221. else if (offset == 2001)
  8222. sink.os.write(rand2.data() + 2001, 999);
  8223. else if (offset == rand2.size())
  8224. sink.done();
  8225. return true;
  8226. },
  8227. "filename4",
  8228. {}});
  8229. {
  8230. auto res = cli.Post("/post-providers", {}, {}, providers);
  8231. ASSERT_TRUE(res);
  8232. ASSERT_EQ(StatusCode::OK_200, res->status);
  8233. }
  8234. {
  8235. auto res = cli.Post("/post-both", {}, items, providers);
  8236. ASSERT_TRUE(res);
  8237. ASSERT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. }
  8240. }
  8241. TEST(MultipartFormDataTest, BadHeader) {
  8242. Server svr;
  8243. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8244. res.set_content("ok", "text/plain");
  8245. });
  8246. thread t = thread([&] { svr.listen(HOST, PORT); });
  8247. auto se = detail::scope_exit([&] {
  8248. svr.stop();
  8249. t.join();
  8250. ASSERT_FALSE(svr.is_running());
  8251. });
  8252. svr.wait_until_ready();
  8253. const std::string body =
  8254. "This is the preamble. It is to be ignored, though it\r\n"
  8255. "is a handy place for composition agents to include an\r\n"
  8256. "explanatory note to non-MIME conformant readers.\r\n"
  8257. "\r\n"
  8258. "\r\n"
  8259. "--simple boundary\r\n"
  8260. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8261. ": BAD...\r\n"
  8262. "\r\n"
  8263. "value1\r\n"
  8264. "--simple boundary\r\n"
  8265. "Content-Disposition: form-data; name=\"field2\"; "
  8266. "filename=\"example.txt\"\r\n"
  8267. "\r\n"
  8268. "value2\r\n"
  8269. "--simple boundary--\r\n"
  8270. "This is the epilogue. It is also to be ignored.\r\n";
  8271. std::string content_type =
  8272. R"(multipart/form-data; boundary="simple boundary")";
  8273. Client cli(HOST, PORT);
  8274. auto res = cli.Post("/post", body, content_type.c_str());
  8275. ASSERT_TRUE(res);
  8276. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8277. }
  8278. TEST(MultipartFormDataTest, WithPreamble) {
  8279. Server svr;
  8280. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8281. res.set_content("ok", "text/plain");
  8282. });
  8283. thread t = thread([&] { svr.listen(HOST, PORT); });
  8284. auto se = detail::scope_exit([&] {
  8285. svr.stop();
  8286. t.join();
  8287. ASSERT_FALSE(svr.is_running());
  8288. });
  8289. svr.wait_until_ready();
  8290. const std::string body =
  8291. "This is the preamble. It is to be ignored, though it\r\n"
  8292. "is a handy place for composition agents to include an\r\n"
  8293. "explanatory note to non-MIME conformant readers.\r\n"
  8294. "\r\n"
  8295. "\r\n"
  8296. "--simple boundary\r\n"
  8297. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8298. "\r\n"
  8299. "value1\r\n"
  8300. "--simple boundary\r\n"
  8301. "Content-Disposition: form-data; name=\"field2\"; "
  8302. "filename=\"example.txt\"\r\n"
  8303. "\r\n"
  8304. "value2\r\n"
  8305. "--simple boundary--\r\n"
  8306. "This is the epilogue. It is also to be ignored.\r\n";
  8307. std::string content_type =
  8308. R"(multipart/form-data; boundary="simple boundary")";
  8309. Client cli(HOST, PORT);
  8310. auto res = cli.Post("/post", body, content_type.c_str());
  8311. ASSERT_TRUE(res);
  8312. EXPECT_EQ(StatusCode::OK_200, res->status);
  8313. }
  8314. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8316. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8317. const ContentReader &content_reader) {
  8318. if (req.is_multipart_form_data()) {
  8319. std::vector<FormData> items;
  8320. content_reader(
  8321. [&](const FormData &file) {
  8322. items.push_back(file);
  8323. return true;
  8324. },
  8325. [&](const char *data, size_t data_length) {
  8326. items.back().content.append(data, data_length);
  8327. return true;
  8328. });
  8329. EXPECT_TRUE(std::string(items[0].name) == "document");
  8330. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8331. EXPECT_TRUE(items[0].filename == "2MB_data");
  8332. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8333. EXPECT_TRUE(items[1].name == "hello");
  8334. EXPECT_TRUE(items[1].content == "world");
  8335. EXPECT_TRUE(items[1].filename == "");
  8336. EXPECT_TRUE(items[1].content_type == "");
  8337. } else {
  8338. std::string body;
  8339. content_reader([&](const char *data, size_t data_length) {
  8340. body.append(data, data_length);
  8341. return true;
  8342. });
  8343. }
  8344. });
  8345. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8346. auto se = detail::scope_exit([&] {
  8347. svr.stop();
  8348. t.join();
  8349. ASSERT_FALSE(svr.is_running());
  8350. });
  8351. svr.wait_until_ready();
  8352. {
  8353. std::string data(1024 * 1024 * 2, '.');
  8354. std::stringstream buffer;
  8355. buffer << data;
  8356. Client cli("https://localhost:8080");
  8357. cli.enable_server_certificate_verification(false);
  8358. UploadFormDataItems items{
  8359. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8360. {"hello", "world", "", ""},
  8361. };
  8362. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8363. ASSERT_TRUE(res);
  8364. ASSERT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. }
  8367. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8368. std::string data(1024 * 1024 * 2, '&');
  8369. std::stringstream buffer;
  8370. buffer << data;
  8371. Client cli("https://localhost:8080");
  8372. UploadFormDataItems items{
  8373. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8374. {"hello", "world", "", ""},
  8375. };
  8376. for (const char &c : " \t\r\n") {
  8377. auto res =
  8378. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8379. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8380. ASSERT_FALSE(res);
  8381. }
  8382. }
  8383. TEST(MultipartFormDataTest, PutFormData) {
  8384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8385. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8386. const ContentReader &content_reader) {
  8387. if (req.is_multipart_form_data()) {
  8388. std::vector<FormData> items;
  8389. content_reader(
  8390. [&](const FormData &file) {
  8391. items.push_back(file);
  8392. return true;
  8393. },
  8394. [&](const char *data, size_t data_length) {
  8395. items.back().content.append(data, data_length);
  8396. return true;
  8397. });
  8398. EXPECT_TRUE(std::string(items[0].name) == "document");
  8399. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8400. EXPECT_TRUE(items[0].filename == "2MB_data");
  8401. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8402. EXPECT_TRUE(items[1].name == "hello");
  8403. EXPECT_TRUE(items[1].content == "world");
  8404. EXPECT_TRUE(items[1].filename == "");
  8405. EXPECT_TRUE(items[1].content_type == "");
  8406. } else {
  8407. std::string body;
  8408. content_reader([&](const char *data, size_t data_length) {
  8409. body.append(data, data_length);
  8410. return true;
  8411. });
  8412. }
  8413. });
  8414. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8415. auto se = detail::scope_exit([&] {
  8416. svr.stop();
  8417. t.join();
  8418. ASSERT_FALSE(svr.is_running());
  8419. });
  8420. svr.wait_until_ready();
  8421. {
  8422. std::string data(1024 * 1024 * 2, '&');
  8423. std::stringstream buffer;
  8424. buffer << data;
  8425. Client cli("https://localhost:8080");
  8426. cli.enable_server_certificate_verification(false);
  8427. UploadFormDataItems items{
  8428. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8429. {"hello", "world", "", ""},
  8430. };
  8431. auto res = cli.Put("/put", items);
  8432. ASSERT_TRUE(res);
  8433. ASSERT_EQ(StatusCode::OK_200, res->status);
  8434. }
  8435. }
  8436. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8437. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8438. svr.Put("/put_customboundary",
  8439. [&](const Request &req, const Response & /*res*/,
  8440. const ContentReader &content_reader) {
  8441. if (req.is_multipart_form_data()) {
  8442. std::vector<FormData> items;
  8443. content_reader(
  8444. [&](const FormData &file) {
  8445. items.push_back(file);
  8446. return true;
  8447. },
  8448. [&](const char *data, size_t data_length) {
  8449. items.back().content.append(data, data_length);
  8450. return true;
  8451. });
  8452. EXPECT_TRUE(std::string(items[0].name) == "document");
  8453. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8454. EXPECT_TRUE(items[0].filename == "2MB_data");
  8455. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8456. EXPECT_TRUE(items[1].name == "hello");
  8457. EXPECT_TRUE(items[1].content == "world");
  8458. EXPECT_TRUE(items[1].filename == "");
  8459. EXPECT_TRUE(items[1].content_type == "");
  8460. } else {
  8461. std::string body;
  8462. content_reader([&](const char *data, size_t data_length) {
  8463. body.append(data, data_length);
  8464. return true;
  8465. });
  8466. }
  8467. });
  8468. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. t.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. {
  8476. std::string data(1024 * 1024 * 2, '&');
  8477. std::stringstream buffer;
  8478. buffer << data;
  8479. Client cli("https://localhost:8080");
  8480. cli.enable_server_certificate_verification(false);
  8481. UploadFormDataItems items{
  8482. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8483. {"hello", "world", "", ""},
  8484. };
  8485. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8486. ASSERT_TRUE(res);
  8487. ASSERT_EQ(StatusCode::OK_200, res->status);
  8488. }
  8489. }
  8490. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8491. std::string data(1024 * 1024 * 2, '&');
  8492. std::stringstream buffer;
  8493. buffer << data;
  8494. Client cli("https://localhost:8080");
  8495. cli.enable_server_certificate_verification(false);
  8496. UploadFormDataItems items{
  8497. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8498. {"hello", "world", "", ""},
  8499. };
  8500. for (const char &c : " \t\r\n") {
  8501. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8502. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8503. ASSERT_FALSE(res);
  8504. }
  8505. }
  8506. TEST(MultipartFormDataTest, AlternateFilename) {
  8507. auto handled = false;
  8508. Server svr;
  8509. svr.Post("/test", [&](const Request &req, Response &res) {
  8510. ASSERT_EQ(2u, req.form.files.size());
  8511. ASSERT_EQ(1u, req.form.fields.size());
  8512. // Test files
  8513. const auto &file1 = req.form.get_file("file1");
  8514. ASSERT_EQ("file1", file1.name);
  8515. ASSERT_EQ("A.txt", file1.filename);
  8516. ASSERT_EQ("text/plain", file1.content_type);
  8517. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8518. const auto &file2 = req.form.get_file("file2");
  8519. ASSERT_EQ("file2", file2.name);
  8520. ASSERT_EQ("a.html", file2.filename);
  8521. ASSERT_EQ("text/html", file2.content_type);
  8522. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8523. file2.content);
  8524. // Test text field
  8525. const auto &text = req.form.get_field("text");
  8526. ASSERT_EQ("text default", text);
  8527. res.set_content("ok", "text/plain");
  8528. handled = true;
  8529. });
  8530. thread t = thread([&] { svr.listen(HOST, PORT); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop();
  8533. t.join();
  8534. ASSERT_FALSE(svr.is_running());
  8535. ASSERT_TRUE(handled);
  8536. });
  8537. svr.wait_until_ready();
  8538. auto req = "POST /test HTTP/1.1\r\n"
  8539. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8540. "Content-Length: 399\r\n"
  8541. "\r\n"
  8542. "----------\r\n"
  8543. "Content-Disposition: form-data; name=\"text\"\r\n"
  8544. "\r\n"
  8545. "text default\r\n"
  8546. "----------\r\n"
  8547. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8548. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8549. "Content-Type: text/plain\r\n"
  8550. "\r\n"
  8551. "Content of a.txt.\r\n"
  8552. "\r\n"
  8553. "----------\r\n"
  8554. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8555. "\"a.html\"\r\n"
  8556. "Content-Type: text/html\r\n"
  8557. "\r\n"
  8558. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8559. "\r\n"
  8560. "------------\r\n";
  8561. ASSERT_TRUE(send_request(1, req));
  8562. }
  8563. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8564. auto handled = false;
  8565. Server svr;
  8566. svr.Post("/test", [&](const Request &req, Response &) {
  8567. ASSERT_EQ(2u, req.form.fields.size());
  8568. const auto &text1 = req.form.get_field("text1");
  8569. ASSERT_EQ("text1", text1);
  8570. const auto &text2 = req.form.get_field("text2");
  8571. ASSERT_EQ("text2", text2);
  8572. handled = true;
  8573. });
  8574. thread t = thread([&] { svr.listen(HOST, PORT); });
  8575. auto se = detail::scope_exit([&] {
  8576. svr.stop();
  8577. t.join();
  8578. ASSERT_FALSE(svr.is_running());
  8579. ASSERT_TRUE(handled);
  8580. });
  8581. svr.wait_until_ready();
  8582. auto req = "POST /test HTTP/1.1\r\n"
  8583. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8584. "Content-Length: 146\r\n"
  8585. "\r\n----------\r\n"
  8586. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8587. "\r\n"
  8588. "text1"
  8589. "\r\n----------\r\n"
  8590. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8591. "\r\n"
  8592. "text2"
  8593. "\r\n------------";
  8594. std::string response;
  8595. ASSERT_TRUE(send_request(1, req, &response));
  8596. ASSERT_EQ("200", response.substr(9, 3));
  8597. }
  8598. TEST(MultipartFormDataTest, ContentLength) {
  8599. auto handled = false;
  8600. Server svr;
  8601. svr.Post("/test", [&](const Request &req, Response &) {
  8602. ASSERT_EQ(2u, req.form.fields.size());
  8603. const auto &text1 = req.form.get_field("text1");
  8604. ASSERT_EQ("text1", text1);
  8605. const auto &text2 = req.form.get_field("text2");
  8606. ASSERT_EQ("text2", text2);
  8607. handled = true;
  8608. });
  8609. thread t = thread([&] { svr.listen(HOST, PORT); });
  8610. auto se = detail::scope_exit([&] {
  8611. svr.stop();
  8612. t.join();
  8613. ASSERT_FALSE(svr.is_running());
  8614. ASSERT_TRUE(handled);
  8615. });
  8616. svr.wait_until_ready();
  8617. auto req = "POST /test HTTP/1.1\r\n"
  8618. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8619. "Content-Length: 167\r\n"
  8620. "\r\n----------\r\n"
  8621. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8622. "Content-Length: 5\r\n"
  8623. "\r\n"
  8624. "text1"
  8625. "\r\n----------\r\n"
  8626. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8627. "\r\n"
  8628. "text2"
  8629. "\r\n------------\r\n";
  8630. std::string response;
  8631. ASSERT_TRUE(send_request(1, req, &response));
  8632. ASSERT_EQ("200", response.substr(9, 3));
  8633. }
  8634. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8635. auto handled = false;
  8636. Server svr;
  8637. svr.Post("/test", [&](const Request &req, Response &) {
  8638. ASSERT_EQ(2u, req.form.fields.size());
  8639. const auto &text1 = req.form.get_field("text1");
  8640. ASSERT_EQ("text1", text1);
  8641. // TODO: Add header access for text fields if needed
  8642. const auto &text2 = req.form.get_field("text2");
  8643. ASSERT_EQ("text2", text2);
  8644. // TODO: Header access for text fields needs to be implemented
  8645. // auto &headers = it->second.headers;
  8646. // ASSERT_EQ(3U, headers.size());
  8647. // auto custom_header = headers.find("x-whatever");
  8648. // ASSERT_TRUE(custom_header != headers.end());
  8649. // ASSERT_NE("customvalue", custom_header->second);
  8650. // ASSERT_EQ("CustomValue", custom_header->second);
  8651. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8652. handled = true;
  8653. });
  8654. thread t = thread([&] { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. t.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. ASSERT_TRUE(handled);
  8660. });
  8661. svr.wait_until_ready();
  8662. auto req = "POST /test HTTP/1.1\r\n"
  8663. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8664. "Content-Length: 232\r\n"
  8665. "\r\n----------\r\n"
  8666. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8667. "Content-Length: 5\r\n"
  8668. "X-Test: 1\r\n"
  8669. "\r\n"
  8670. "text1"
  8671. "\r\n----------\r\n"
  8672. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8673. "Content-Type: text/plain\r\n"
  8674. "X-Whatever: CustomValue\r\n"
  8675. "\r\n"
  8676. "text2"
  8677. "\r\n------------\r\n"
  8678. "That should be disregarded. Not even read";
  8679. std::string response;
  8680. ASSERT_TRUE(send_request(1, req, &response));
  8681. ASSERT_EQ("200", response.substr(9, 3));
  8682. }
  8683. #endif
  8684. TEST(MultipartFormDataTest, LargeHeader) {
  8685. auto handled = false;
  8686. Server svr;
  8687. svr.Post("/test", [&](const Request &req, Response &) {
  8688. ASSERT_EQ(1u, req.form.fields.size());
  8689. const auto &text = req.form.get_field("name1");
  8690. ASSERT_EQ("text1", text);
  8691. handled = true;
  8692. });
  8693. thread t = thread([&] { svr.listen(HOST, PORT); });
  8694. auto se = detail::scope_exit([&] {
  8695. svr.stop();
  8696. t.join();
  8697. ASSERT_FALSE(svr.is_running());
  8698. ASSERT_TRUE(handled);
  8699. });
  8700. svr.wait_until_ready();
  8701. auto boundary = std::string("cpp-httplib-multipart-data");
  8702. std::string content = "--" + boundary +
  8703. "\r\n"
  8704. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8705. "\r\n"
  8706. "text1\r\n"
  8707. "--" +
  8708. boundary + "--\r\n";
  8709. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8710. "Content-Type: multipart/form-data;boundary=" +
  8711. boundary +
  8712. "\r\n"
  8713. "Content-Length: " +
  8714. std::to_string(content.size()) +
  8715. "\r\n"
  8716. "Dummy-Header: ";
  8717. std::string header_suffix = "\r\n"
  8718. "\r\n";
  8719. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8720. size_t header_dummy_size =
  8721. read_buff_size -
  8722. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8723. auto header_dummy = std::string(header_dummy_size, '@');
  8724. auto req = header_prefix + header_dummy + header_suffix + content;
  8725. std::string response;
  8726. ASSERT_TRUE(send_request(1, req, &response));
  8727. ASSERT_EQ("200", response.substr(9, 3));
  8728. }
  8729. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8730. static constexpr unsigned int number_of_tasks{1000000};
  8731. std::atomic_uint count{0};
  8732. std::unique_ptr<TaskQueue> task_queue{
  8733. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8734. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8735. auto queued = task_queue->enqueue(
  8736. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8737. EXPECT_TRUE(queued);
  8738. }
  8739. EXPECT_NO_THROW(task_queue->shutdown());
  8740. EXPECT_EQ(number_of_tasks, count.load());
  8741. }
  8742. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8743. static constexpr unsigned int number_of_tasks{1000000};
  8744. static constexpr unsigned int qlimit{2};
  8745. unsigned int queued_count{0};
  8746. std::atomic_uint count{0};
  8747. std::unique_ptr<TaskQueue> task_queue{
  8748. new ThreadPool{/*num_threads=*/1, qlimit}};
  8749. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8750. if (task_queue->enqueue(
  8751. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8752. queued_count++;
  8753. }
  8754. }
  8755. EXPECT_NO_THROW(task_queue->shutdown());
  8756. EXPECT_EQ(queued_count, count.load());
  8757. EXPECT_TRUE(queued_count <= number_of_tasks);
  8758. EXPECT_TRUE(queued_count >= qlimit);
  8759. }
  8760. TEST(TaskQueueTest, MaxQueuedRequests) {
  8761. static constexpr unsigned int qlimit{3};
  8762. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8763. std::condition_variable sem_cv;
  8764. std::mutex sem_mtx;
  8765. int credits = 0;
  8766. bool queued;
  8767. /* Fill up the queue with tasks that will block until we give them credits to
  8768. * complete. */
  8769. for (unsigned int n = 0; n <= qlimit;) {
  8770. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8771. std::unique_lock<std::mutex> lock(sem_mtx);
  8772. while (credits <= 0) {
  8773. sem_cv.wait(lock);
  8774. }
  8775. /* Consume the credit and signal the test code if they are all gone. */
  8776. if (--credits == 0) { sem_cv.notify_one(); }
  8777. });
  8778. if (n < qlimit) {
  8779. /* The first qlimit enqueues must succeed. */
  8780. EXPECT_TRUE(queued);
  8781. } else {
  8782. /* The last one will succeed only when the worker thread
  8783. * starts and dequeues the first blocking task. Although
  8784. * not necessary for the correctness of this test, we sleep for
  8785. * a short while to avoid busy waiting. */
  8786. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8787. }
  8788. if (queued) { n++; }
  8789. }
  8790. /* Further enqueues must fail since the queue is full. */
  8791. for (auto i = 0; i < 4; i++) {
  8792. queued = task_queue->enqueue([] {});
  8793. EXPECT_FALSE(queued);
  8794. }
  8795. /* Give the credits to allow the previous tasks to complete. */
  8796. {
  8797. std::unique_lock<std::mutex> lock(sem_mtx);
  8798. credits += qlimit + 1;
  8799. }
  8800. sem_cv.notify_all();
  8801. /* Wait for all the credits to be consumed. */
  8802. {
  8803. std::unique_lock<std::mutex> lock(sem_mtx);
  8804. while (credits > 0) {
  8805. sem_cv.wait(lock);
  8806. }
  8807. }
  8808. /* Check that we are able again to enqueue at least qlimit tasks. */
  8809. for (unsigned int i = 0; i < qlimit; i++) {
  8810. queued = task_queue->enqueue([] {});
  8811. EXPECT_TRUE(queued);
  8812. }
  8813. EXPECT_NO_THROW(task_queue->shutdown());
  8814. }
  8815. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8816. Server svr;
  8817. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8818. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8819. });
  8820. svr.Get("/hello", [](const Request &req, Response &res) {
  8821. res.set_content(req.get_param_value("key"), "text/plain");
  8822. });
  8823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8824. auto se = detail::scope_exit([&] {
  8825. svr.stop();
  8826. thread.join();
  8827. ASSERT_FALSE(svr.is_running());
  8828. });
  8829. svr.wait_until_ready();
  8830. {
  8831. Client cli(HOST, PORT);
  8832. cli.set_follow_location(true);
  8833. auto res = cli.Get("/");
  8834. ASSERT_TRUE(res);
  8835. EXPECT_EQ(StatusCode::OK_200, res->status);
  8836. EXPECT_EQ("val&key2=val2", res->body);
  8837. }
  8838. }
  8839. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8840. Server svr;
  8841. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8842. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8843. });
  8844. svr.Get("/hello", [](const Request &req, Response &res) {
  8845. res.set_content(req.get_param_value("key"), "text/plain");
  8846. });
  8847. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8848. auto se = detail::scope_exit([&] {
  8849. svr.stop();
  8850. thread.join();
  8851. ASSERT_FALSE(svr.is_running());
  8852. });
  8853. svr.wait_until_ready();
  8854. {
  8855. Client cli(HOST, PORT);
  8856. cli.set_follow_location(true);
  8857. auto res = cli.Get("/");
  8858. ASSERT_TRUE(res);
  8859. EXPECT_EQ(StatusCode::OK_200, res->status);
  8860. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8861. }
  8862. }
  8863. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8864. TEST(RedirectTest, Issue2185_Online) {
  8865. SSLClient client("github.com");
  8866. client.set_follow_location(true);
  8867. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8868. "Coollab-Windows.zip");
  8869. ASSERT_TRUE(res);
  8870. EXPECT_EQ(StatusCode::OK_200, res->status);
  8871. EXPECT_EQ(9920427U, res->body.size());
  8872. }
  8873. #endif
  8874. TEST(VulnerabilityTest, CRLFInjection) {
  8875. Server svr;
  8876. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8877. res.set_content("Hello 1", "text/plain");
  8878. });
  8879. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8880. res.set_content("Hello 2", "text/plain");
  8881. });
  8882. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8883. res.set_content("Hello 3", "text/plain");
  8884. });
  8885. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8886. res.set_content("Hello 4", "text/plain");
  8887. });
  8888. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8889. for (const auto &x : req.headers) {
  8890. auto key = x.first;
  8891. EXPECT_STRNE("evil", key.c_str());
  8892. }
  8893. });
  8894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8895. auto se = detail::scope_exit([&] {
  8896. svr.stop();
  8897. thread.join();
  8898. ASSERT_FALSE(svr.is_running());
  8899. });
  8900. svr.wait_until_ready();
  8901. {
  8902. Client cli(HOST, PORT);
  8903. cli.Post("/test1", "A=B",
  8904. "application/x-www-form-urlencoded\r\nevil: hello1");
  8905. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8906. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8907. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8908. }
  8909. }
  8910. TEST(PathParamsTest, StaticMatch) {
  8911. const auto pattern = "/users/all";
  8912. detail::PathParamsMatcher matcher(pattern);
  8913. Request request;
  8914. request.path = "/users/all";
  8915. ASSERT_TRUE(matcher.match(request));
  8916. std::unordered_map<std::string, std::string> expected_params = {};
  8917. EXPECT_EQ(request.path_params, expected_params);
  8918. }
  8919. TEST(PathParamsTest, StaticMismatch) {
  8920. const auto pattern = "/users/all";
  8921. detail::PathParamsMatcher matcher(pattern);
  8922. Request request;
  8923. request.path = "/users/1";
  8924. ASSERT_FALSE(matcher.match(request));
  8925. }
  8926. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8927. const auto pattern = "/users/:id/subscriptions";
  8928. detail::PathParamsMatcher matcher(pattern);
  8929. Request request;
  8930. request.path = "/users/42/subscriptions";
  8931. ASSERT_TRUE(matcher.match(request));
  8932. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8933. EXPECT_EQ(request.path_params, expected_params);
  8934. }
  8935. TEST(PathParamsTest, SingleParamInTheEnd) {
  8936. const auto pattern = "/users/:id";
  8937. detail::PathParamsMatcher matcher(pattern);
  8938. Request request;
  8939. request.path = "/users/24";
  8940. ASSERT_TRUE(matcher.match(request));
  8941. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8942. EXPECT_EQ(request.path_params, expected_params);
  8943. }
  8944. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8945. const auto pattern = "/users/:id/";
  8946. detail::PathParamsMatcher matcher(pattern);
  8947. Request request;
  8948. request.path = "/users/42/";
  8949. ASSERT_TRUE(matcher.match(request));
  8950. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8951. EXPECT_EQ(request.path_params, expected_params);
  8952. }
  8953. TEST(PathParamsTest, EmptyParam) {
  8954. const auto pattern = "/users/:id/";
  8955. detail::PathParamsMatcher matcher(pattern);
  8956. Request request;
  8957. request.path = "/users//";
  8958. ASSERT_TRUE(matcher.match(request));
  8959. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8960. EXPECT_EQ(request.path_params, expected_params);
  8961. }
  8962. TEST(PathParamsTest, FragmentMismatch) {
  8963. const auto pattern = "/users/:id/";
  8964. detail::PathParamsMatcher matcher(pattern);
  8965. Request request;
  8966. request.path = "/admins/24/";
  8967. ASSERT_FALSE(matcher.match(request));
  8968. }
  8969. TEST(PathParamsTest, ExtraFragments) {
  8970. const auto pattern = "/users/:id";
  8971. detail::PathParamsMatcher matcher(pattern);
  8972. Request request;
  8973. request.path = "/users/42/subscriptions";
  8974. ASSERT_FALSE(matcher.match(request));
  8975. }
  8976. TEST(PathParamsTest, MissingTrailingParam) {
  8977. const auto pattern = "/users/:id";
  8978. detail::PathParamsMatcher matcher(pattern);
  8979. Request request;
  8980. request.path = "/users";
  8981. ASSERT_FALSE(matcher.match(request));
  8982. }
  8983. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8984. const auto pattern = "/users/:id/subscriptions";
  8985. detail::PathParamsMatcher matcher(pattern);
  8986. Request request;
  8987. request.path = "/users/subscriptions";
  8988. ASSERT_FALSE(matcher.match(request));
  8989. }
  8990. TEST(PathParamsTest, MultipleParams) {
  8991. const auto pattern = "/users/:userid/subscriptions/:subid";
  8992. detail::PathParamsMatcher matcher(pattern);
  8993. Request request;
  8994. request.path = "/users/42/subscriptions/2";
  8995. ASSERT_TRUE(matcher.match(request));
  8996. std::unordered_map<std::string, std::string> expected_params = {
  8997. {"userid", "42"}, {"subid", "2"}};
  8998. EXPECT_EQ(request.path_params, expected_params);
  8999. }
  9000. TEST(PathParamsTest, SequenceOfParams) {
  9001. const auto pattern = "/values/:x/:y/:z";
  9002. detail::PathParamsMatcher matcher(pattern);
  9003. Request request;
  9004. request.path = "/values/1/2/3";
  9005. ASSERT_TRUE(matcher.match(request));
  9006. std::unordered_map<std::string, std::string> expected_params = {
  9007. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9008. EXPECT_EQ(request.path_params, expected_params);
  9009. }
  9010. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9011. const auto pattern = "/prefix:suffix";
  9012. detail::PathParamsMatcher matcher(pattern);
  9013. Request request;
  9014. request.path = "/prefix:suffix";
  9015. ASSERT_TRUE(matcher.match(request));
  9016. const std::unordered_map<std::string, std::string> expected_params = {};
  9017. EXPECT_EQ(request.path_params, expected_params);
  9018. }
  9019. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9020. // If ipv6 regex working, regex match codepath is taken.
  9021. // else port will default to 80 in Client impl
  9022. int clientImplMagicPort = 80;
  9023. int port = 4321;
  9024. // above ports must be different to avoid false negative
  9025. EXPECT_NE(clientImplMagicPort, port);
  9026. std::string ipV6TestURL = "http://[ff06::c3]";
  9027. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9028. CLIENT_PRIVATE_KEY_FILE);
  9029. EXPECT_EQ(cli.port(), port);
  9030. }
  9031. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9032. auto file_path = "./www/dir/index.html";
  9033. auto dir_path = "./www/dir";
  9034. detail::FileStat stat_file(file_path);
  9035. EXPECT_TRUE(stat_file.is_file());
  9036. EXPECT_FALSE(stat_file.is_dir());
  9037. detail::FileStat stat_dir(dir_path);
  9038. EXPECT_FALSE(stat_dir.is_file());
  9039. EXPECT_TRUE(stat_dir.is_dir());
  9040. }
  9041. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9042. // IPv4 with default HTTP port (80)
  9043. EXPECT_EQ("example.com",
  9044. detail::make_host_and_port_string("example.com", 80, false));
  9045. // IPv4 with default HTTPS port (443)
  9046. EXPECT_EQ("example.com",
  9047. detail::make_host_and_port_string("example.com", 443, true));
  9048. // IPv4 with non-default HTTP port
  9049. EXPECT_EQ("example.com:8080",
  9050. detail::make_host_and_port_string("example.com", 8080, false));
  9051. // IPv4 with non-default HTTPS port
  9052. EXPECT_EQ("example.com:8443",
  9053. detail::make_host_and_port_string("example.com", 8443, true));
  9054. // IPv6 with default HTTP port (80)
  9055. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9056. // IPv6 with default HTTPS port (443)
  9057. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9058. // IPv6 with non-default HTTP port
  9059. EXPECT_EQ("[::1]:8080",
  9060. detail::make_host_and_port_string("::1", 8080, false));
  9061. // IPv6 with non-default HTTPS port
  9062. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9063. // IPv6 full address with default port
  9064. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9065. detail::make_host_and_port_string(
  9066. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9067. // IPv6 full address with non-default port
  9068. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9069. detail::make_host_and_port_string(
  9070. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9071. // IPv6 localhost with non-default port
  9072. EXPECT_EQ("[::1]:3000",
  9073. detail::make_host_and_port_string("::1", 3000, false));
  9074. // IPv6 with zone ID (link-local address) with default port
  9075. EXPECT_EQ("[fe80::1%eth0]",
  9076. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9077. // IPv6 with zone ID (link-local address) with non-default port
  9078. EXPECT_EQ("[fe80::1%eth0]:8080",
  9079. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9080. // Edge case: Port 443 with is_ssl=false (should add port)
  9081. EXPECT_EQ("example.com:443",
  9082. detail::make_host_and_port_string("example.com", 443, false));
  9083. // Edge case: Port 80 with is_ssl=true (should add port)
  9084. EXPECT_EQ("example.com:80",
  9085. detail::make_host_and_port_string("example.com", 80, true));
  9086. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9087. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9088. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9089. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9090. // Security fix: Already bracketed IPv6 should not get double brackets
  9091. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9092. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9093. EXPECT_EQ("[::1]:8080",
  9094. detail::make_host_and_port_string("[::1]", 8080, false));
  9095. EXPECT_EQ("[2001:db8::1]:8080",
  9096. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9097. EXPECT_EQ("[fe80::1%eth0]",
  9098. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9099. EXPECT_EQ("[fe80::1%eth0]:8080",
  9100. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9101. // Edge case: Empty host (should return as-is)
  9102. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9103. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9104. // This is a known limitation but shouldn't crash
  9105. EXPECT_EQ("[host:name]",
  9106. detail::make_host_and_port_string("host:name", 80, false));
  9107. // Port number edge cases (no validation, but should not crash)
  9108. EXPECT_EQ("example.com:0",
  9109. detail::make_host_and_port_string("example.com", 0, false));
  9110. EXPECT_EQ("example.com:-1",
  9111. detail::make_host_and_port_string("example.com", -1, false));
  9112. EXPECT_EQ("example.com:65535",
  9113. detail::make_host_and_port_string("example.com", 65535, false));
  9114. EXPECT_EQ("example.com:65536",
  9115. detail::make_host_and_port_string("example.com", 65536, false));
  9116. }
  9117. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9118. Server svr;
  9119. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9120. EXPECT_EQ(res.status, 400);
  9121. });
  9122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9123. auto se = detail::scope_exit([&] {
  9124. svr.stop();
  9125. thread.join();
  9126. ASSERT_FALSE(svr.is_running());
  9127. });
  9128. svr.wait_until_ready();
  9129. Client cli(HOST, PORT);
  9130. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9131. }
  9132. TEST(InvalidHeaderCharsTest, is_field_name) {
  9133. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9134. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9135. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9136. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9137. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9138. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9139. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9140. EXPECT_FALSE(detail::fields::is_field_name(""));
  9141. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9142. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9143. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9144. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9145. }
  9146. TEST(InvalidHeaderCharsTest, is_field_value) {
  9147. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9148. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9149. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9150. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9151. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9152. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9153. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9154. EXPECT_TRUE(detail::fields::is_field_value(""));
  9155. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9156. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9157. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9158. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9159. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9160. }
  9161. TEST(InvalidHeaderCharsTest, OnServer) {
  9162. Server svr;
  9163. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9164. std::string header = "Not Set";
  9165. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9166. res.set_header(header, "value");
  9167. res.set_content("Page Content Page Content", "text/plain");
  9168. });
  9169. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9170. std::string header = "Not Set";
  9171. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9172. res.set_header("X-Test", header);
  9173. res.set_content("Page Content Page Content", "text/plain");
  9174. });
  9175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9176. auto se = detail::scope_exit([&] {
  9177. svr.stop();
  9178. thread.join();
  9179. ASSERT_FALSE(svr.is_running());
  9180. });
  9181. svr.wait_until_ready();
  9182. Client cli(HOST, PORT);
  9183. {
  9184. auto res = cli.Get(
  9185. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9186. ASSERT_TRUE(res);
  9187. EXPECT_EQ("Page Content Page Content", res->body);
  9188. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9189. }
  9190. {
  9191. auto res = cli.Get(
  9192. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9193. ASSERT_TRUE(res);
  9194. EXPECT_EQ("Page Content Page Content", res->body);
  9195. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9196. }
  9197. }
  9198. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9199. auto handled = false;
  9200. Server svr;
  9201. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9202. thread t = thread([&] { svr.listen(HOST, PORT); });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. t.join();
  9206. ASSERT_FALSE(svr.is_running());
  9207. ASSERT_FALSE(handled);
  9208. });
  9209. svr.wait_until_ready();
  9210. auto req = "POST /test HTTP/1.1\r\n"
  9211. "Content-Length: x\r\n"
  9212. "\r\n";
  9213. std::string response;
  9214. ASSERT_TRUE(send_request(1, req, &response));
  9215. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9216. response.substr(0, response.find("\r\n")));
  9217. }
  9218. #ifndef _WIN32
  9219. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9220. static constexpr char reject[] = "Unauthorized";
  9221. static constexpr char accept[] = "Upload accepted";
  9222. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9223. Server svr;
  9224. svr.set_expect_100_continue_handler(
  9225. [](const Request & /*req*/, Response &res) {
  9226. res.status = StatusCode::Unauthorized_401;
  9227. res.set_content(reject, "text/plain");
  9228. return res.status;
  9229. });
  9230. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9231. res.set_content(accept, "text/plain");
  9232. });
  9233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9234. auto se = detail::scope_exit([&] {
  9235. svr.stop();
  9236. thread.join();
  9237. ASSERT_FALSE(svr.is_running());
  9238. });
  9239. svr.wait_until_ready();
  9240. {
  9241. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9242. curl_easy_init(), &curl_easy_cleanup};
  9243. ASSERT_NE(curl, nullptr);
  9244. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9245. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9246. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9247. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9248. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9249. &curl_slist_free_all};
  9250. ASSERT_NE(list, nullptr);
  9251. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9252. struct read_data {
  9253. size_t read_size;
  9254. size_t total_size;
  9255. } data = {0, total_size};
  9256. using read_callback_t =
  9257. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9258. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9259. void *userdata) -> size_t {
  9260. read_data *data = (read_data *)userdata;
  9261. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9262. std::fill_n(ptr, size * nmemb, 'A');
  9263. data->read_size += size * nmemb;
  9264. return size * nmemb;
  9265. };
  9266. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9267. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9268. std::vector<char> buffer;
  9269. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9270. using write_callback_t =
  9271. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9272. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9273. void *userdata) -> size_t {
  9274. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9275. buffer->reserve(buffer->size() + size * nmemb + 1);
  9276. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9277. return size * nmemb;
  9278. };
  9279. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9280. {
  9281. const auto res = curl_easy_perform(curl.get());
  9282. ASSERT_EQ(res, CURLE_OK);
  9283. }
  9284. {
  9285. auto response_code = long{};
  9286. const auto res =
  9287. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9288. ASSERT_EQ(res, CURLE_OK);
  9289. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9290. }
  9291. {
  9292. auto dl = curl_off_t{};
  9293. const auto res =
  9294. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9295. ASSERT_EQ(res, CURLE_OK);
  9296. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9297. }
  9298. {
  9299. buffer.push_back('\0');
  9300. ASSERT_STRCASEEQ(buffer.data(), reject);
  9301. }
  9302. }
  9303. }
  9304. #endif
  9305. template <typename S, typename C>
  9306. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9307. svr.Get("/stream", [&](const Request &, Response &res) {
  9308. auto data = new std::string("01234567890123456789");
  9309. res.set_content_provider(
  9310. data->size(), "text/plain",
  9311. [&, data](size_t offset, size_t length, DataSink &sink) {
  9312. const size_t DATA_CHUNK_SIZE = 4;
  9313. const auto &d = *data;
  9314. std::this_thread::sleep_for(std::chrono::seconds(1));
  9315. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9316. return true;
  9317. },
  9318. [data](bool success) {
  9319. EXPECT_FALSE(success);
  9320. delete data;
  9321. });
  9322. });
  9323. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9324. auto i = new size_t(0);
  9325. res.set_content_provider(
  9326. "text/plain",
  9327. [i](size_t, DataSink &sink) {
  9328. if (*i < 5) {
  9329. std::this_thread::sleep_for(std::chrono::seconds(1));
  9330. sink.write("abcd", 4);
  9331. (*i)++;
  9332. } else {
  9333. sink.done();
  9334. }
  9335. return true;
  9336. },
  9337. [i](bool success) {
  9338. EXPECT_FALSE(success);
  9339. delete i;
  9340. });
  9341. });
  9342. svr.Get("/chunked", [&](const Request &, Response &res) {
  9343. auto i = new size_t(0);
  9344. res.set_chunked_content_provider(
  9345. "text/plain",
  9346. [i](size_t, DataSink &sink) {
  9347. if (*i < 5) {
  9348. std::this_thread::sleep_for(std::chrono::seconds(1));
  9349. sink.os << "abcd";
  9350. (*i)++;
  9351. } else {
  9352. sink.done();
  9353. }
  9354. return true;
  9355. },
  9356. [i](bool success) {
  9357. EXPECT_FALSE(success);
  9358. delete i;
  9359. });
  9360. });
  9361. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9362. auto se = detail::scope_exit([&] {
  9363. svr.stop();
  9364. listen_thread.join();
  9365. ASSERT_FALSE(svr.is_running());
  9366. });
  9367. svr.wait_until_ready();
  9368. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9369. {
  9370. auto start = std::chrono::steady_clock::now();
  9371. auto res = cli.Get("/stream");
  9372. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9373. std::chrono::steady_clock::now() - start)
  9374. .count();
  9375. ASSERT_FALSE(res);
  9376. EXPECT_EQ(Error::Read, res.error());
  9377. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9378. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9379. }
  9380. {
  9381. auto start = std::chrono::steady_clock::now();
  9382. auto res = cli.Get("/stream_without_length");
  9383. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9384. std::chrono::steady_clock::now() - start)
  9385. .count();
  9386. ASSERT_FALSE(res);
  9387. EXPECT_EQ(Error::Read, res.error());
  9388. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9389. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9390. }
  9391. {
  9392. auto start = std::chrono::steady_clock::now();
  9393. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9394. EXPECT_EQ("abcd", string(data, data_length));
  9395. return true;
  9396. });
  9397. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9398. std::chrono::steady_clock::now() - start)
  9399. .count();
  9400. ASSERT_FALSE(res);
  9401. EXPECT_EQ(Error::Read, res.error());
  9402. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9403. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9404. }
  9405. }
  9406. TEST(MaxTimeoutTest, ContentStream) {
  9407. time_t timeout = 2000;
  9408. time_t threshold = 200;
  9409. Server svr;
  9410. Client cli("localhost", PORT);
  9411. max_timeout_test(svr, cli, timeout, threshold);
  9412. }
  9413. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9414. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9415. time_t timeout = 2000;
  9416. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9418. SSLClient cli("localhost", PORT);
  9419. cli.enable_server_certificate_verification(false);
  9420. max_timeout_test(svr, cli, timeout, threshold);
  9421. }
  9422. #endif
  9423. class EventDispatcher {
  9424. public:
  9425. EventDispatcher() {}
  9426. bool wait_event(DataSink *sink) {
  9427. unique_lock<mutex> lk(m_);
  9428. int id = id_;
  9429. // Wait with timeout to prevent hanging if client disconnects
  9430. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9431. [&] { return cid_ == id; })) {
  9432. return false; // Timeout occurred
  9433. }
  9434. sink->write(message_.data(), message_.size());
  9435. return true;
  9436. }
  9437. void send_event(const string &message) {
  9438. lock_guard<mutex> lk(m_);
  9439. cid_ = id_++;
  9440. message_ = message;
  9441. cv_.notify_all();
  9442. }
  9443. private:
  9444. mutex m_;
  9445. condition_variable cv_;
  9446. atomic_int id_{0};
  9447. atomic_int cid_{-1};
  9448. string message_;
  9449. };
  9450. TEST(ClientInThreadTest, Issue2068) {
  9451. EventDispatcher ed;
  9452. Server svr;
  9453. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9454. res.set_chunked_content_provider("text/event-stream",
  9455. [&](size_t /*offset*/, DataSink &sink) {
  9456. return ed.wait_event(&sink);
  9457. });
  9458. });
  9459. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9460. svr.wait_until_ready();
  9461. thread event_thread([&] {
  9462. int id = 0;
  9463. while (svr.is_running()) {
  9464. this_thread::sleep_for(chrono::milliseconds(500));
  9465. std::stringstream ss;
  9466. ss << "data: " << id << "\n\n";
  9467. ed.send_event(ss.str());
  9468. id++;
  9469. }
  9470. });
  9471. auto se = detail::scope_exit([&] {
  9472. svr.stop();
  9473. listen_thread.join();
  9474. event_thread.join();
  9475. ASSERT_FALSE(svr.is_running());
  9476. });
  9477. {
  9478. auto client = detail::make_unique<Client>(HOST, PORT);
  9479. client->set_read_timeout(std::chrono::minutes(10));
  9480. std::atomic<bool> stop{false};
  9481. std::thread t([&] {
  9482. client->Get("/event1",
  9483. [&](const char *, size_t) -> bool { return !stop; });
  9484. });
  9485. std::this_thread::sleep_for(std::chrono::seconds(2));
  9486. stop = true;
  9487. client->stop();
  9488. t.join();
  9489. // Reset client after thread has finished
  9490. client.reset();
  9491. }
  9492. }
  9493. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9494. Server svr;
  9495. svr.Get("/", [](const Request &req, Response &res) {
  9496. EXPECT_EQ(2U, req.trailers.size());
  9497. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9498. // Denied
  9499. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9500. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9501. // Accepted
  9502. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9503. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9504. EXPECT_TRUE(req.has_trailer("X-World"));
  9505. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9506. res.set_content("ok", "text/plain");
  9507. });
  9508. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. const std::string req = "GET / HTTP/1.1\r\n"
  9516. "Transfer-Encoding: chunked\r\n"
  9517. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9518. "\r\n"
  9519. "0\r\n"
  9520. "Content-Length: 10\r\n"
  9521. "Host: internal.local\r\n"
  9522. "Content-Type: malicious/content\r\n"
  9523. "Cookie: any\r\n"
  9524. "Set-Cookie: any\r\n"
  9525. "X-Forwarded-For: attacker.com\r\n"
  9526. "X-Real-Ip: 1.1.1.1\r\n"
  9527. "X-Hello: hello\r\n"
  9528. "X-World: world\r\n"
  9529. "\r\n";
  9530. std::string res;
  9531. ASSERT_TRUE(send_request(1, req, &res));
  9532. }
  9533. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9534. Server svr;
  9535. std::string observed_remote_addr;
  9536. std::string observed_xff;
  9537. svr.Get("/ip", [&](const Request &req, Response &res) {
  9538. observed_remote_addr = req.remote_addr;
  9539. observed_xff = req.get_header_value("X-Forwarded-For");
  9540. res.set_content("ok", "text/plain");
  9541. });
  9542. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9543. auto se = detail::scope_exit([&] {
  9544. svr.stop();
  9545. t.join();
  9546. ASSERT_FALSE(svr.is_running());
  9547. });
  9548. svr.wait_until_ready();
  9549. Client cli(HOST, PORT);
  9550. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9551. ASSERT_TRUE(res);
  9552. EXPECT_EQ(StatusCode::OK_200, res->status);
  9553. EXPECT_EQ(observed_xff, "203.0.113.66");
  9554. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9555. observed_remote_addr == "127.0.0.1");
  9556. }
  9557. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9558. Server svr;
  9559. svr.set_trusted_proxies({"203.0.113.66"});
  9560. std::string observed_remote_addr;
  9561. std::string observed_xff;
  9562. svr.Get("/ip", [&](const Request &req, Response &res) {
  9563. observed_remote_addr = req.remote_addr;
  9564. observed_xff = req.get_header_value("X-Forwarded-For");
  9565. res.set_content("ok", "text/plain");
  9566. });
  9567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9568. auto se = detail::scope_exit([&] {
  9569. svr.stop();
  9570. t.join();
  9571. ASSERT_FALSE(svr.is_running());
  9572. });
  9573. svr.wait_until_ready();
  9574. Client cli(HOST, PORT);
  9575. auto res = cli.Get("/ip");
  9576. ASSERT_TRUE(res);
  9577. EXPECT_EQ(StatusCode::OK_200, res->status);
  9578. EXPECT_EQ(observed_xff, "");
  9579. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9580. observed_remote_addr == "127.0.0.1");
  9581. }
  9582. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9583. Server svr;
  9584. svr.set_trusted_proxies({"203.0.113.66"});
  9585. std::string observed_remote_addr;
  9586. std::string observed_xff;
  9587. svr.Get("/ip", [&](const Request &req, Response &res) {
  9588. observed_remote_addr = req.remote_addr;
  9589. observed_xff = req.get_header_value("X-Forwarded-For");
  9590. res.set_content("ok", "text/plain");
  9591. });
  9592. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9593. auto se = detail::scope_exit([&] {
  9594. svr.stop();
  9595. t.join();
  9596. ASSERT_FALSE(svr.is_running());
  9597. });
  9598. svr.wait_until_ready();
  9599. Client cli(HOST, PORT);
  9600. auto res =
  9601. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9602. ASSERT_TRUE(res);
  9603. EXPECT_EQ(StatusCode::OK_200, res->status);
  9604. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9605. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9606. }
  9607. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9608. Server svr;
  9609. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9610. std::string observed_remote_addr;
  9611. std::string observed_xff;
  9612. svr.Get("/ip", [&](const Request &req, Response &res) {
  9613. observed_remote_addr = req.remote_addr;
  9614. observed_xff = req.get_header_value("X-Forwarded-For");
  9615. res.set_content("ok", "text/plain");
  9616. });
  9617. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9618. auto se = detail::scope_exit([&] {
  9619. svr.stop();
  9620. t.join();
  9621. ASSERT_FALSE(svr.is_running());
  9622. });
  9623. svr.wait_until_ready();
  9624. Client cli(HOST, PORT);
  9625. auto res = cli.Get(
  9626. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9627. ASSERT_TRUE(res);
  9628. EXPECT_EQ(StatusCode::OK_200, res->status);
  9629. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9630. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9631. }
  9632. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9633. Server svr;
  9634. svr.set_trusted_proxies({"192.0.2.45"});
  9635. std::string observed_remote_addr;
  9636. std::string observed_xff;
  9637. svr.Get("/ip", [&](const Request &req, Response &res) {
  9638. observed_remote_addr = req.remote_addr;
  9639. observed_xff = req.get_header_value("X-Forwarded-For");
  9640. res.set_content("ok", "text/plain");
  9641. });
  9642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. t.join();
  9646. ASSERT_FALSE(svr.is_running());
  9647. });
  9648. svr.wait_until_ready();
  9649. Client cli(HOST, PORT);
  9650. auto res =
  9651. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9652. ASSERT_TRUE(res);
  9653. EXPECT_EQ(StatusCode::OK_200, res->status);
  9654. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9655. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9656. }
  9657. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9658. Server svr;
  9659. svr.set_trusted_proxies({"192.0.2.45"});
  9660. std::string observed_remote_addr;
  9661. std::string observed_xff;
  9662. svr.Get("/ip", [&](const Request &req, Response &res) {
  9663. observed_remote_addr = req.remote_addr;
  9664. observed_xff = req.get_header_value("X-Forwarded-For");
  9665. res.set_content("ok", "text/plain");
  9666. });
  9667. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. t.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. Client cli(HOST, PORT);
  9675. auto res = cli.Get(
  9676. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9677. ASSERT_TRUE(res);
  9678. EXPECT_EQ(StatusCode::OK_200, res->status);
  9679. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9680. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9681. }
  9682. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9683. Server svr;
  9684. svr.set_trusted_proxies({"192.0.2.45"});
  9685. std::string observed_remote_addr;
  9686. std::string observed_xff;
  9687. svr.Get("/ip", [&](const Request &req, Response &res) {
  9688. observed_remote_addr = req.remote_addr;
  9689. observed_xff = req.get_header_value("X-Forwarded-For");
  9690. res.set_content("ok", "text/plain");
  9691. });
  9692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9693. auto se = detail::scope_exit([&] {
  9694. svr.stop();
  9695. t.join();
  9696. ASSERT_FALSE(svr.is_running());
  9697. });
  9698. svr.wait_until_ready();
  9699. Client cli(HOST, PORT);
  9700. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9701. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9702. ASSERT_TRUE(res);
  9703. EXPECT_EQ(StatusCode::OK_200, res->status);
  9704. // Header parser trims surrounding whitespace of the header value
  9705. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9706. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9707. }
  9708. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9709. Server svr;
  9710. svr.Post("/post", [&](const Request &req, Response &res) {
  9711. res.set_content(req.body, "text/plain");
  9712. });
  9713. svr.Put("/put", [&](const Request &req, Response &res) {
  9714. res.set_content(req.body, "text/plain");
  9715. });
  9716. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9717. res.set_content(req.body, "text/plain");
  9718. });
  9719. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9720. res.set_content(req.body, "text/plain");
  9721. });
  9722. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9723. auto se = detail::scope_exit([&] {
  9724. svr.stop();
  9725. t.join();
  9726. ASSERT_FALSE(svr.is_running());
  9727. });
  9728. svr.wait_until_ready();
  9729. std::string resp;
  9730. // POST without Content-Length
  9731. ASSERT_TRUE(send_request(5,
  9732. "POST /post HTTP/1.1\r\n"
  9733. "Host: localhost\r\n"
  9734. "Connection: close\r\n"
  9735. "\r\n",
  9736. &resp));
  9737. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9738. // PUT without Content-Length
  9739. resp.clear();
  9740. ASSERT_TRUE(send_request(5,
  9741. "PUT /put HTTP/1.1\r\n"
  9742. "Host: localhost\r\n"
  9743. "Connection: close\r\n"
  9744. "\r\n",
  9745. &resp));
  9746. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9747. // PATCH without Content-Length
  9748. resp.clear();
  9749. ASSERT_TRUE(send_request(5,
  9750. "PATCH /patch HTTP/1.1\r\n"
  9751. "Host: localhost\r\n"
  9752. "Connection: close\r\n"
  9753. "\r\n",
  9754. &resp));
  9755. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9756. // DELETE without Content-Length
  9757. resp.clear();
  9758. ASSERT_TRUE(send_request(5,
  9759. "DELETE /delete HTTP/1.1\r\n"
  9760. "Host: localhost\r\n"
  9761. "Connection: close\r\n"
  9762. "\r\n",
  9763. &resp));
  9764. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9765. }
  9766. //==============================================================================
  9767. // open_stream() Tests
  9768. //==============================================================================
  9769. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9770. std::string result;
  9771. char buf[8192];
  9772. ssize_t n;
  9773. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9774. result.append(buf, static_cast<size_t>(n));
  9775. }
  9776. return result;
  9777. }
  9778. // Mock stream for unit tests
  9779. class MockStream : public Stream {
  9780. public:
  9781. std::string data;
  9782. size_t pos = 0;
  9783. ssize_t error_after = -1; // -1 = no error
  9784. explicit MockStream(const std::string &d, ssize_t err = -1)
  9785. : data(d), error_after(err) {}
  9786. bool is_readable() const override { return true; }
  9787. bool wait_readable() const override { return true; }
  9788. bool wait_writable() const override { return true; }
  9789. ssize_t read(char *ptr, size_t size) override {
  9790. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9791. if (pos >= data.size()) return 0;
  9792. size_t limit =
  9793. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9794. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9795. std::memcpy(ptr, data.data() + pos, to_read);
  9796. pos += to_read;
  9797. return static_cast<ssize_t>(to_read);
  9798. }
  9799. ssize_t write(const char *, size_t) override { return -1; }
  9800. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9801. ip = "127.0.0.1";
  9802. port = 0;
  9803. }
  9804. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9805. ip = "127.0.0.1";
  9806. port = 0;
  9807. }
  9808. socket_t socket() const override { return INVALID_SOCKET; }
  9809. time_t duration() const override { return 0; }
  9810. };
  9811. TEST(StreamHandleTest, Basic) {
  9812. ClientImpl::StreamHandle handle;
  9813. EXPECT_FALSE(handle.is_valid());
  9814. handle.response = detail::make_unique<Response>();
  9815. handle.error = Error::Connection;
  9816. EXPECT_FALSE(handle.is_valid());
  9817. handle.error = Error::Success;
  9818. EXPECT_TRUE(handle.is_valid());
  9819. }
  9820. TEST(BodyReaderTest, Basic) {
  9821. MockStream stream("Hello, World!");
  9822. detail::BodyReader reader;
  9823. reader.stream = &stream;
  9824. reader.content_length = 13;
  9825. char buf[32];
  9826. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9827. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9828. EXPECT_TRUE(reader.eof);
  9829. }
  9830. TEST(BodyReaderTest, NoStream) {
  9831. detail::BodyReader reader;
  9832. char buf[32];
  9833. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9834. EXPECT_EQ(Error::Connection, reader.last_error);
  9835. }
  9836. TEST(BodyReaderTest, Error) {
  9837. MockStream stream("Hello, World!", 5);
  9838. detail::BodyReader reader;
  9839. reader.stream = &stream;
  9840. reader.content_length = 13;
  9841. char buf[32];
  9842. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9843. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9844. EXPECT_EQ(Error::Read, reader.last_error);
  9845. }
  9846. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9847. // Mock-based StreamHandle tests relying on private internals are removed.
  9848. class OpenStreamTest : public ::testing::Test {
  9849. protected:
  9850. void SetUp() override {
  9851. svr_.Get("/hello", [](const Request &, Response &res) {
  9852. res.set_content("Hello World!", "text/plain");
  9853. });
  9854. svr_.Get("/large", [](const Request &, Response &res) {
  9855. res.set_content(std::string(10000, 'X'), "text/plain");
  9856. });
  9857. svr_.Get("/chunked", [](const Request &, Response &res) {
  9858. res.set_chunked_content_provider("text/plain",
  9859. [](size_t offset, DataSink &sink) {
  9860. if (offset < 15) {
  9861. sink.write("chunk", 5);
  9862. return true;
  9863. }
  9864. sink.done();
  9865. return true;
  9866. });
  9867. });
  9868. svr_.Get("/compressible", [](const Request &, Response &res) {
  9869. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9870. DataSink &sink) {
  9871. if (offset < 100 * 1024) {
  9872. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9873. sink.write(chunk.data(), chunk.size());
  9874. return true;
  9875. }
  9876. sink.done();
  9877. return true;
  9878. });
  9879. });
  9880. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9881. [](const Request & /*req*/, Response &res) {
  9882. auto i = new int(0);
  9883. res.set_header("Trailer", "Content-Length, X-Allowed");
  9884. res.set_chunked_content_provider(
  9885. "text/plain",
  9886. [i](size_t /*offset*/, DataSink &sink) {
  9887. switch (*i) {
  9888. case 0: sink.os << "123"; break;
  9889. case 1: sink.os << "456"; break;
  9890. case 2: sink.os << "789"; break;
  9891. case 3: {
  9892. sink.done_with_trailer(
  9893. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9894. } break;
  9895. }
  9896. (*i)++;
  9897. return true;
  9898. },
  9899. [i](bool success) {
  9900. EXPECT_TRUE(success);
  9901. delete i;
  9902. });
  9903. });
  9904. // Echo headers endpoint for header-related tests
  9905. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9906. std::string body;
  9907. for (const auto &h : req.headers) {
  9908. body.append(h.first);
  9909. body.push_back(':');
  9910. body.append(h.second);
  9911. body.push_back('\n');
  9912. }
  9913. res.set_content(body, "text/plain");
  9914. });
  9915. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9916. std::string body;
  9917. for (const auto &h : req.headers) {
  9918. body.append(h.first);
  9919. body.push_back(':');
  9920. body.append(h.second);
  9921. body.push_back('\n');
  9922. }
  9923. res.set_content(body, "text/plain");
  9924. });
  9925. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9926. svr_.wait_until_ready();
  9927. }
  9928. void TearDown() override {
  9929. svr_.stop();
  9930. if (thread_.joinable()) thread_.join();
  9931. }
  9932. Server svr_;
  9933. std::thread thread_;
  9934. };
  9935. TEST_F(OpenStreamTest, Basic) {
  9936. Client cli("127.0.0.1", 8787);
  9937. auto handle = cli.open_stream("GET", "/hello");
  9938. EXPECT_TRUE(handle.is_valid());
  9939. EXPECT_EQ("Hello World!", read_all(handle));
  9940. }
  9941. TEST_F(OpenStreamTest, SmallBuffer) {
  9942. Client cli("127.0.0.1", 8787);
  9943. auto handle = cli.open_stream("GET", "/hello");
  9944. std::string result;
  9945. char buf[4];
  9946. ssize_t n;
  9947. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9948. result.append(buf, static_cast<size_t>(n));
  9949. EXPECT_EQ("Hello World!", result);
  9950. }
  9951. TEST_F(OpenStreamTest, DefaultHeaders) {
  9952. Client cli("127.0.0.1", 8787);
  9953. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9954. {
  9955. auto handle = cli.open_stream("GET", "/echo-headers");
  9956. ASSERT_TRUE(handle.is_valid());
  9957. auto body = read_all(handle);
  9958. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  9959. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  9960. std::string::npos);
  9961. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  9962. }
  9963. // open_stream POST with body and no explicit content_type should NOT add
  9964. // text/plain Content-Type (behavior differs from non-streaming path), but
  9965. // should include Content-Length
  9966. {
  9967. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  9968. ASSERT_TRUE(handle.is_valid());
  9969. auto body = read_all(handle);
  9970. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  9971. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  9972. }
  9973. // open_stream POST with explicit Content-Type should preserve it
  9974. {
  9975. auto handle = cli.open_stream("POST", "/echo-headers", {},
  9976. {{"Content-Type", "application/custom"}},
  9977. "{}", "application/custom");
  9978. ASSERT_TRUE(handle.is_valid());
  9979. auto body = read_all(handle);
  9980. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  9981. }
  9982. // User-specified User-Agent must not be overwritten for stream API
  9983. {
  9984. auto handle = cli.open_stream("GET", "/echo-headers", {},
  9985. {{"User-Agent", "MyAgent/1.2"}});
  9986. ASSERT_TRUE(handle.is_valid());
  9987. auto body = read_all(handle);
  9988. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  9989. }
  9990. }
  9991. TEST_F(OpenStreamTest, Large) {
  9992. Client cli("127.0.0.1", 8787);
  9993. auto handle = cli.open_stream("GET", "/large");
  9994. EXPECT_EQ(10000u, read_all(handle).size());
  9995. }
  9996. TEST_F(OpenStreamTest, ConnectionError) {
  9997. Client cli("127.0.0.1", 9999);
  9998. auto handle = cli.open_stream("GET", "/hello");
  9999. EXPECT_FALSE(handle.is_valid());
  10000. }
  10001. TEST_F(OpenStreamTest, Chunked) {
  10002. Client cli("127.0.0.1", 8787);
  10003. auto handle = cli.open_stream("GET", "/chunked");
  10004. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10005. "Transfer-Encoding") == "chunked");
  10006. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10007. }
  10008. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10009. Client cli("127.0.0.1", 8787);
  10010. auto handle =
  10011. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10012. ASSERT_TRUE(handle.is_valid());
  10013. // Consume body to allow trailers to be received/parsed
  10014. auto body = read_all(handle);
  10015. // Explicitly parse trailers (ensure trailers are available for assertion)
  10016. handle.parse_trailers_if_needed();
  10017. EXPECT_EQ(std::string("123456789"), body);
  10018. // The response should include a Trailer header declaring both names
  10019. ASSERT_TRUE(handle.response);
  10020. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10021. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10022. handle.response->get_header_value("Trailer"));
  10023. // Prohibited trailer must not be present
  10024. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10025. // Allowed trailer should be present
  10026. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10027. EXPECT_EQ(std::string("yes"),
  10028. handle.response->get_trailer_value("X-Allowed"));
  10029. // Verify trailers are NOT present as regular headers
  10030. EXPECT_EQ(std::string(""),
  10031. handle.response->get_header_value("Content-Length"));
  10032. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10033. }
  10034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10035. TEST_F(OpenStreamTest, Gzip) {
  10036. Client cli("127.0.0.1", 8787);
  10037. auto handle = cli.open_stream("GET", "/compressible", {},
  10038. {{"Accept-Encoding", "gzip"}});
  10039. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10040. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10041. }
  10042. #endif
  10043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10044. TEST_F(OpenStreamTest, Brotli) {
  10045. Client cli("127.0.0.1", 8787);
  10046. auto handle =
  10047. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10048. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10049. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10050. }
  10051. #endif
  10052. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10053. TEST_F(OpenStreamTest, Zstd) {
  10054. Client cli("127.0.0.1", 8787);
  10055. auto handle = cli.open_stream("GET", "/compressible", {},
  10056. {{"Accept-Encoding", "zstd"}});
  10057. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10058. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10059. }
  10060. #endif
  10061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10062. class SSLOpenStreamTest : public ::testing::Test {
  10063. protected:
  10064. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10065. void SetUp() override {
  10066. svr_.Get("/hello", [](const Request &, Response &res) {
  10067. res.set_content("Hello SSL World!", "text/plain");
  10068. });
  10069. svr_.Get("/chunked", [](const Request &, Response &res) {
  10070. res.set_chunked_content_provider("text/plain",
  10071. [](size_t offset, DataSink &sink) {
  10072. if (offset < 15) {
  10073. sink.write("chunk", 5);
  10074. return true;
  10075. }
  10076. sink.done();
  10077. return true;
  10078. });
  10079. });
  10080. svr_.Post("/echo", [](const Request &req, Response &res) {
  10081. res.set_content(req.body, req.get_header_value("Content-Type"));
  10082. });
  10083. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10084. std::string body = req.body;
  10085. res.set_chunked_content_provider(
  10086. "text/plain", [body](size_t offset, DataSink &sink) {
  10087. if (offset < body.size()) {
  10088. sink.write(body.data() + offset, body.size() - offset);
  10089. }
  10090. sink.done();
  10091. return true;
  10092. });
  10093. });
  10094. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10095. svr_.wait_until_ready();
  10096. }
  10097. void TearDown() override {
  10098. svr_.stop();
  10099. if (thread_.joinable()) thread_.join();
  10100. }
  10101. SSLServer svr_;
  10102. std::thread thread_;
  10103. };
  10104. TEST_F(SSLOpenStreamTest, Basic) {
  10105. SSLClient cli("127.0.0.1", 8788);
  10106. cli.enable_server_certificate_verification(false);
  10107. auto handle = cli.open_stream("GET", "/hello");
  10108. ASSERT_TRUE(handle.is_valid());
  10109. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10110. }
  10111. TEST_F(SSLOpenStreamTest, Chunked) {
  10112. SSLClient cli("127.0.0.1", 8788);
  10113. cli.enable_server_certificate_verification(false);
  10114. auto handle = cli.open_stream("GET", "/chunked");
  10115. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10116. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10117. "Transfer-Encoding") == "chunked");
  10118. auto body = read_all(handle);
  10119. EXPECT_EQ("chunkchunkchunk", body);
  10120. }
  10121. TEST_F(SSLOpenStreamTest, Post) {
  10122. SSLClient cli("127.0.0.1", 8788);
  10123. cli.enable_server_certificate_verification(false);
  10124. auto handle =
  10125. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10126. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10127. EXPECT_EQ(200, handle.response->status);
  10128. auto body = read_all(handle);
  10129. EXPECT_EQ("Hello SSL POST", body);
  10130. }
  10131. TEST_F(SSLOpenStreamTest, PostChunked) {
  10132. SSLClient cli("127.0.0.1", 8788);
  10133. cli.enable_server_certificate_verification(false);
  10134. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10135. "Chunked SSL Data", "text/plain");
  10136. ASSERT_TRUE(handle.is_valid());
  10137. EXPECT_EQ(200, handle.response->status);
  10138. auto body = read_all(handle);
  10139. EXPECT_EQ("Chunked SSL Data", body);
  10140. }
  10141. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10142. //==============================================================================
  10143. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10144. // results for various scenarios.
  10145. //==============================================================================
  10146. TEST(ParityTest, GetVsOpenStream) {
  10147. Server svr;
  10148. const std::string path = "/parity";
  10149. const std::string content = "Parity test content: hello world";
  10150. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10151. res.set_content(content, "text/plain");
  10152. });
  10153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. t.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. });
  10159. svr.wait_until_ready();
  10160. Client cli(HOST, PORT);
  10161. // Non-stream path
  10162. auto r1 = cli.Get(path);
  10163. ASSERT_TRUE(r1);
  10164. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10165. // Stream path
  10166. auto h = cli.open_stream("GET", path);
  10167. ASSERT_TRUE(h.is_valid());
  10168. EXPECT_EQ(r1->body, read_all(h));
  10169. }
  10170. // Helper to compress data with provided compressor type T
  10171. template <typename Compressor>
  10172. static std::string compress_payload_for_parity(const std::string &in) {
  10173. std::string out;
  10174. Compressor compressor;
  10175. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10176. [&](const char *data, size_t n) {
  10177. out.append(data, n);
  10178. return true;
  10179. });
  10180. EXPECT_TRUE(ok);
  10181. return out;
  10182. }
  10183. // Helper function for compression parity tests
  10184. template <typename Compressor>
  10185. static void test_compression_parity(const std::string &original,
  10186. const std::string &path,
  10187. const std::string &encoding) {
  10188. const std::string compressed =
  10189. compress_payload_for_parity<Compressor>(original);
  10190. Server svr;
  10191. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10192. res.set_content(compressed, "application/octet-stream");
  10193. res.set_header("Content-Encoding", encoding);
  10194. });
  10195. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. t.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. Client cli("localhost", 1234);
  10203. // Non-streaming
  10204. {
  10205. auto res = cli.Get(path);
  10206. ASSERT_TRUE(res);
  10207. EXPECT_EQ(StatusCode::OK_200, res->status);
  10208. EXPECT_EQ(original, res->body);
  10209. }
  10210. // Streaming
  10211. {
  10212. auto h = cli.open_stream("GET", path);
  10213. ASSERT_TRUE(h.is_valid());
  10214. EXPECT_EQ(original, read_all(h));
  10215. }
  10216. }
  10217. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10218. TEST(ParityTest, Gzip) {
  10219. test_compression_parity<detail::gzip_compressor>(
  10220. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10221. }
  10222. #endif
  10223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10224. TEST(ParityTest, Brotli) {
  10225. test_compression_parity<detail::brotli_compressor>(
  10226. "Hello, brotli parity test payload", "/parity-br", "br");
  10227. }
  10228. #endif
  10229. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10230. TEST(ParityTest, Zstd) {
  10231. test_compression_parity<detail::zstd_compressor>(
  10232. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10233. }
  10234. #endif
  10235. //==============================================================================
  10236. // New Stream API Tests
  10237. //==============================================================================
  10238. inline std::string read_body(httplib::stream::Result &result) {
  10239. std::string body;
  10240. while (result.next()) {
  10241. body.append(result.data(), result.size());
  10242. }
  10243. return body;
  10244. }
  10245. TEST(ClientConnectionTest, Basic) {
  10246. httplib::ClientConnection conn;
  10247. EXPECT_FALSE(conn.is_open());
  10248. conn.sock = 1;
  10249. EXPECT_TRUE(conn.is_open());
  10250. httplib::ClientConnection conn2(std::move(conn));
  10251. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10252. conn2.sock = INVALID_SOCKET;
  10253. }
  10254. // Unified test server for all stream::* tests
  10255. class StreamApiTest : public ::testing::Test {
  10256. protected:
  10257. void SetUp() override {
  10258. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10259. res.set_content("Hello World!", "text/plain");
  10260. });
  10261. svr_.Get("/echo-params",
  10262. [](const httplib::Request &req, httplib::Response &res) {
  10263. std::string r;
  10264. for (const auto &p : req.params) {
  10265. if (!r.empty()) r += "&";
  10266. r += p.first + "=" + p.second;
  10267. }
  10268. res.set_content(r, "text/plain");
  10269. });
  10270. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10271. res.set_content(req.body, req.get_header_value("Content-Type"));
  10272. });
  10273. svr_.Post("/echo-headers",
  10274. [](const httplib::Request &req, httplib::Response &res) {
  10275. std::string r;
  10276. for (const auto &h : req.headers)
  10277. r += h.first + ": " + h.second + "\n";
  10278. res.set_content(r, "text/plain");
  10279. });
  10280. svr_.Post("/echo-params",
  10281. [](const httplib::Request &req, httplib::Response &res) {
  10282. std::string r = "params:";
  10283. for (const auto &p : req.params)
  10284. r += p.first + "=" + p.second + ";";
  10285. res.set_content(r + " body:" + req.body, "text/plain");
  10286. });
  10287. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10288. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10289. });
  10290. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10291. res.set_content("PUT:" + req.body, "text/plain");
  10292. });
  10293. svr_.Patch("/echo",
  10294. [](const httplib::Request &req, httplib::Response &res) {
  10295. res.set_content("PATCH:" + req.body, "text/plain");
  10296. });
  10297. svr_.Delete(
  10298. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10299. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10300. "text/plain");
  10301. });
  10302. svr_.Get("/head-test",
  10303. [](const httplib::Request &, httplib::Response &res) {
  10304. res.set_content("body for HEAD", "text/plain");
  10305. });
  10306. svr_.Options("/options",
  10307. [](const httplib::Request &, httplib::Response &res) {
  10308. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10309. });
  10310. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10311. svr_.wait_until_ready();
  10312. }
  10313. void TearDown() override {
  10314. svr_.stop();
  10315. if (thread_.joinable()) thread_.join();
  10316. }
  10317. httplib::Server svr_;
  10318. std::thread thread_;
  10319. };
  10320. // stream::Get tests
  10321. TEST_F(StreamApiTest, GetBasic) {
  10322. httplib::Client cli("localhost", 8790);
  10323. auto result = httplib::stream::Get(cli, "/hello");
  10324. ASSERT_TRUE(result.is_valid());
  10325. EXPECT_EQ(200, result.status());
  10326. EXPECT_EQ("Hello World!", read_body(result));
  10327. }
  10328. TEST_F(StreamApiTest, GetWithParams) {
  10329. httplib::Client cli("localhost", 8790);
  10330. httplib::Params params{{"foo", "bar"}};
  10331. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10332. ASSERT_TRUE(result.is_valid());
  10333. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10334. }
  10335. TEST_F(StreamApiTest, GetConnectionError) {
  10336. httplib::Client cli("localhost", 9999);
  10337. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10338. }
  10339. TEST_F(StreamApiTest, Get404) {
  10340. httplib::Client cli("localhost", 8790);
  10341. auto result = httplib::stream::Get(cli, "/nonexistent");
  10342. EXPECT_TRUE(result.is_valid());
  10343. EXPECT_EQ(404, result.status());
  10344. }
  10345. // stream::Post tests
  10346. TEST_F(StreamApiTest, PostBasic) {
  10347. httplib::Client cli("localhost", 8790);
  10348. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10349. "application/json");
  10350. ASSERT_TRUE(result.is_valid());
  10351. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10352. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10353. }
  10354. TEST_F(StreamApiTest, PostWithHeaders) {
  10355. httplib::Client cli("localhost", 8790);
  10356. httplib::Headers headers{{"X-Custom", "value"}};
  10357. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10358. "text/plain");
  10359. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10360. }
  10361. TEST_F(StreamApiTest, PostWithParams) {
  10362. httplib::Client cli("localhost", 8790);
  10363. httplib::Params params{{"k", "v"}};
  10364. auto result =
  10365. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10366. auto body = read_body(result);
  10367. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10368. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10369. }
  10370. TEST_F(StreamApiTest, PostLarge) {
  10371. httplib::Client cli("localhost", 8790);
  10372. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10373. size_t total = 0;
  10374. while (result.next()) {
  10375. total += result.size();
  10376. }
  10377. EXPECT_EQ(100u * 1024u, total);
  10378. }
  10379. // stream::Put/Patch tests
  10380. TEST_F(StreamApiTest, PutAndPatch) {
  10381. httplib::Client cli("localhost", 8790);
  10382. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10383. EXPECT_EQ("PUT:test", read_body(put));
  10384. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10385. EXPECT_EQ("PATCH:test", read_body(patch));
  10386. }
  10387. // stream::Delete tests
  10388. TEST_F(StreamApiTest, Delete) {
  10389. httplib::Client cli("localhost", 8790);
  10390. auto del1 = httplib::stream::Delete(cli, "/resource");
  10391. EXPECT_EQ("Deleted", read_body(del1));
  10392. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10393. EXPECT_EQ("Deleted:data", read_body(del2));
  10394. }
  10395. // stream::Head/Options tests
  10396. TEST_F(StreamApiTest, HeadAndOptions) {
  10397. httplib::Client cli("localhost", 8790);
  10398. auto head = httplib::stream::Head(cli, "/head-test");
  10399. EXPECT_TRUE(head.is_valid());
  10400. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10401. auto opts = httplib::stream::Options(cli, "/options");
  10402. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10403. }
  10404. // SSL stream::* tests
  10405. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10406. class SSLStreamApiTest : public ::testing::Test {
  10407. protected:
  10408. void SetUp() override {
  10409. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10410. res.set_content("Hello SSL!", "text/plain");
  10411. });
  10412. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10413. res.set_content(req.body, "text/plain");
  10414. });
  10415. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10416. svr_.wait_until_ready();
  10417. }
  10418. void TearDown() override {
  10419. svr_.stop();
  10420. if (thread_.joinable()) thread_.join();
  10421. }
  10422. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10423. std::thread thread_;
  10424. };
  10425. TEST_F(SSLStreamApiTest, GetAndPost) {
  10426. httplib::SSLClient cli("127.0.0.1", 8803);
  10427. cli.enable_server_certificate_verification(false);
  10428. auto get = httplib::stream::Get(cli, "/hello");
  10429. EXPECT_EQ("Hello SSL!", read_body(get));
  10430. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10431. EXPECT_EQ("test", read_body(post));
  10432. }
  10433. #endif
  10434. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10435. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10436. // BodyReader
  10437. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10438. // Test that read timeout during streaming is detected
  10439. // Use a large content-length response where server delays mid-stream
  10440. Server svr;
  10441. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10442. // Send a large response with delay in the middle
  10443. res.set_content_provider(
  10444. 1000, // content_length
  10445. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10446. if (offset < 100) {
  10447. // Send first 100 bytes immediately
  10448. std::string data(100, 'A');
  10449. sink.write(data.c_str(), data.size());
  10450. return true;
  10451. }
  10452. // Then delay longer than client timeout
  10453. std::this_thread::sleep_for(std::chrono::seconds(3));
  10454. std::string data(900, 'B');
  10455. sink.write(data.c_str(), data.size());
  10456. return true;
  10457. });
  10458. });
  10459. auto port = 8091;
  10460. std::thread t([&]() { svr.listen("localhost", port); });
  10461. svr.wait_until_ready();
  10462. Client cli("localhost", port);
  10463. cli.set_read_timeout(1, 0); // 1 second timeout
  10464. auto handle = cli.open_stream("GET", "/slow-stream");
  10465. ASSERT_TRUE(handle.is_valid());
  10466. char buf[256];
  10467. ssize_t total = 0;
  10468. ssize_t n;
  10469. bool got_error = false;
  10470. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10471. total += n;
  10472. }
  10473. if (n < 0) {
  10474. got_error = true;
  10475. // Should be timeout or read error
  10476. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10477. handle.get_read_error() == Error::Read)
  10478. << "Actual error: " << to_string(handle.get_read_error());
  10479. }
  10480. // Either we got an error, or we got less data than expected
  10481. EXPECT_TRUE(got_error || total < 1000)
  10482. << "Expected timeout but got all " << total << " bytes";
  10483. svr.stop();
  10484. t.join();
  10485. }
  10486. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10487. // Test connection closed detection via BodyReader
  10488. Server svr;
  10489. std::atomic<bool> close_now{false};
  10490. svr.Get("/will-close", [&](const Request &, Response &res) {
  10491. res.set_content_provider(
  10492. 10000, // Large content_length that we won't fully send
  10493. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10494. if (offset < 100) {
  10495. std::string data(100, 'X');
  10496. sink.write(data.c_str(), data.size());
  10497. return true;
  10498. }
  10499. // Wait for signal then abort
  10500. while (!close_now) {
  10501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10502. }
  10503. return false; // Abort - server will close connection
  10504. });
  10505. });
  10506. auto port = 8092;
  10507. std::thread t([&]() { svr.listen("localhost", port); });
  10508. svr.wait_until_ready();
  10509. Client cli("localhost", port);
  10510. auto handle = cli.open_stream("GET", "/will-close");
  10511. ASSERT_TRUE(handle.is_valid());
  10512. char buf[256];
  10513. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10514. EXPECT_GT(n, 0) << "First read should succeed";
  10515. // Signal server to close
  10516. close_now = true;
  10517. // Keep reading until error or EOF
  10518. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10519. // Keep reading
  10520. }
  10521. // Should get an error since content_length wasn't satisfied
  10522. if (n < 0) {
  10523. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10524. handle.get_read_error() == Error::Read)
  10525. << "Actual error: " << to_string(handle.get_read_error());
  10526. }
  10527. svr.stop();
  10528. t.join();
  10529. }
  10530. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10531. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10532. // Test that read timeout during SSL streaming is detected
  10533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10534. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10535. res.set_content_provider(
  10536. 1000, "text/plain",
  10537. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10538. if (offset < 100) {
  10539. std::string data(100, 'A');
  10540. sink.write(data.c_str(), data.size());
  10541. return true;
  10542. }
  10543. std::this_thread::sleep_for(std::chrono::seconds(3));
  10544. std::string data(900, 'B');
  10545. sink.write(data.c_str(), data.size());
  10546. return true;
  10547. });
  10548. });
  10549. auto port = 8093;
  10550. std::thread t([&]() { svr.listen("localhost", port); });
  10551. svr.wait_until_ready();
  10552. SSLClient cli("localhost", port);
  10553. cli.enable_server_certificate_verification(false);
  10554. cli.set_read_timeout(1, 0); // 1 second timeout
  10555. auto handle = cli.open_stream("GET", "/slow-stream");
  10556. ASSERT_TRUE(handle.is_valid());
  10557. char buf[256];
  10558. ssize_t total = 0;
  10559. ssize_t n;
  10560. bool got_error = false;
  10561. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10562. total += n;
  10563. }
  10564. if (n < 0) {
  10565. got_error = true;
  10566. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10567. handle.get_read_error() == Error::Read)
  10568. << "Actual error: " << to_string(handle.get_read_error());
  10569. }
  10570. EXPECT_TRUE(got_error || total < 1000)
  10571. << "Expected timeout but got all " << total << " bytes";
  10572. svr.stop();
  10573. t.join();
  10574. }
  10575. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10576. // Test SSL connection closed detection
  10577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10578. std::atomic<bool> close_now{false};
  10579. svr.Get("/will-close", [&](const Request &, Response &res) {
  10580. res.set_content_provider(
  10581. 10000, "text/plain",
  10582. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10583. if (offset < 100) {
  10584. std::string data(100, 'X');
  10585. sink.write(data.c_str(), data.size());
  10586. return true;
  10587. }
  10588. while (!close_now) {
  10589. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10590. }
  10591. return false;
  10592. });
  10593. });
  10594. auto port = 8094;
  10595. std::thread t([&]() { svr.listen("localhost", port); });
  10596. svr.wait_until_ready();
  10597. SSLClient cli("localhost", port);
  10598. cli.enable_server_certificate_verification(false);
  10599. auto handle = cli.open_stream("GET", "/will-close");
  10600. ASSERT_TRUE(handle.is_valid());
  10601. char buf[256];
  10602. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10603. EXPECT_GT(n, 0);
  10604. // Signal server to close
  10605. close_now = true;
  10606. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10607. // Keep reading
  10608. }
  10609. if (n < 0) {
  10610. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10611. handle.get_read_error() == Error::Read)
  10612. << "Actual error: " << to_string(handle.get_read_error());
  10613. }
  10614. svr.stop();
  10615. t.join();
  10616. }
  10617. #endif
  10618. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10619. using namespace httplib;
  10620. // Create a test file
  10621. const char *fname = "etag_testfile.txt";
  10622. const char *content = "etag-content";
  10623. {
  10624. std::ofstream ofs(fname);
  10625. ofs << content;
  10626. ASSERT_TRUE(ofs.good());
  10627. }
  10628. Server svr;
  10629. svr.set_mount_point("/static", ".");
  10630. auto t = std::thread([&]() { svr.listen("localhost", 8087); });
  10631. svr.wait_until_ready();
  10632. Client cli("localhost", 8087);
  10633. // First request: should get 200 with ETag header
  10634. auto res1 = cli.Get("/static/etag_testfile.txt");
  10635. ASSERT_TRUE(res1);
  10636. ASSERT_EQ(200, res1->status);
  10637. ASSERT_TRUE(res1->has_header("ETag"));
  10638. std::string etag = res1->get_header_value("ETag");
  10639. EXPECT_FALSE(etag.empty());
  10640. // Verify ETag format: W/"hex-hex"
  10641. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10642. EXPECT_EQ('W', etag[0]);
  10643. EXPECT_EQ('/', etag[1]);
  10644. EXPECT_EQ('"', etag[2]);
  10645. EXPECT_EQ('"', etag.back());
  10646. // Exact match: expect 304 Not Modified
  10647. Headers h2 = {{"If-None-Match", etag}};
  10648. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10649. ASSERT_TRUE(res2);
  10650. EXPECT_EQ(304, res2->status);
  10651. // Wildcard match: expect 304 Not Modified
  10652. Headers h3 = {{"If-None-Match", "*"}};
  10653. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10654. ASSERT_TRUE(res3);
  10655. EXPECT_EQ(304, res3->status);
  10656. // Non-matching ETag: expect 200
  10657. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10658. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10659. ASSERT_TRUE(res4);
  10660. EXPECT_EQ(200, res4->status);
  10661. // Multiple ETags with one matching: expect 304
  10662. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10663. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10664. ASSERT_TRUE(res5);
  10665. EXPECT_EQ(304, res5->status);
  10666. svr.stop();
  10667. t.join();
  10668. std::remove(fname);
  10669. }
  10670. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10671. using namespace httplib;
  10672. Server svr;
  10673. svr.set_mount_point("/static", ".");
  10674. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10675. svr.wait_until_ready();
  10676. Client cli("localhost", 8090);
  10677. // Send If-None-Match: * to a non-existent file
  10678. Headers h = {{"If-None-Match", "*"}};
  10679. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10680. ASSERT_TRUE(res);
  10681. EXPECT_EQ(404, res->status);
  10682. svr.stop();
  10683. t.join();
  10684. }
  10685. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10686. using namespace httplib;
  10687. // Create a test file
  10688. const char *fname = "ims_testfile.txt";
  10689. const char *content = "if-modified-since-test";
  10690. {
  10691. std::ofstream ofs(fname);
  10692. ofs << content;
  10693. ASSERT_TRUE(ofs.good());
  10694. }
  10695. Server svr;
  10696. svr.set_mount_point("/static", ".");
  10697. auto t = std::thread([&]() { svr.listen("localhost", 8088); });
  10698. svr.wait_until_ready();
  10699. Client cli("localhost", 8088);
  10700. // First request: should get 200 with Last-Modified header
  10701. auto res1 = cli.Get("/static/ims_testfile.txt");
  10702. ASSERT_TRUE(res1);
  10703. ASSERT_EQ(200, res1->status);
  10704. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10705. std::string last_modified = res1->get_header_value("Last-Modified");
  10706. EXPECT_FALSE(last_modified.empty());
  10707. // If-Modified-Since with same time: expect 304
  10708. Headers h2 = {{"If-Modified-Since", last_modified}};
  10709. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10710. ASSERT_TRUE(res2);
  10711. EXPECT_EQ(304, res2->status);
  10712. // If-Modified-Since with future time: expect 304
  10713. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10714. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10715. ASSERT_TRUE(res3);
  10716. EXPECT_EQ(304, res3->status);
  10717. // If-Modified-Since with past time: expect 200
  10718. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10719. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10720. ASSERT_TRUE(res4);
  10721. EXPECT_EQ(200, res4->status);
  10722. // If-None-Match takes precedence over If-Modified-Since
  10723. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10724. ASSERT_TRUE(res1->has_header("ETag"));
  10725. std::string etag = res1->get_header_value("ETag");
  10726. Headers h5 = {{"If-None-Match", etag},
  10727. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10728. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10729. ASSERT_TRUE(res5);
  10730. EXPECT_EQ(304, res5->status);
  10731. svr.stop();
  10732. t.join();
  10733. std::remove(fname);
  10734. }
  10735. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10736. using namespace httplib;
  10737. Server svr;
  10738. // Endpoint that returns compressible content
  10739. svr.Get("/compressible", [](const Request &, Response &res) {
  10740. // Return a large enough body to trigger compression
  10741. std::string body(1000, 'a');
  10742. res.set_content(body, "text/plain");
  10743. });
  10744. auto t = std::thread([&]() { svr.listen("localhost", 8089); });
  10745. svr.wait_until_ready();
  10746. Client cli("localhost", 8089);
  10747. // Request with gzip support: should get Vary header when compressed
  10748. cli.set_compress(true);
  10749. auto res1 = cli.Get("/compressible");
  10750. ASSERT_TRUE(res1);
  10751. EXPECT_EQ(200, res1->status);
  10752. // If Content-Encoding is set, Vary should also be set
  10753. if (res1->has_header("Content-Encoding")) {
  10754. EXPECT_TRUE(res1->has_header("Vary"));
  10755. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10756. }
  10757. // Request without Accept-Encoding header: should not have compression
  10758. Headers h_no_compress;
  10759. auto res2 = cli.Get("/compressible", h_no_compress);
  10760. ASSERT_TRUE(res2);
  10761. EXPECT_EQ(200, res2->status);
  10762. // Verify Vary header is present when compression is applied
  10763. // (the exact behavior depends on server configuration)
  10764. svr.stop();
  10765. t.join();
  10766. }
  10767. TEST(ETagTest, IfRangeWithETag) {
  10768. using namespace httplib;
  10769. // Create a test file with known content
  10770. const char *fname = "if_range_testfile.txt";
  10771. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10772. {
  10773. std::ofstream ofs(fname);
  10774. ofs << content;
  10775. ASSERT_TRUE(ofs.good());
  10776. }
  10777. Server svr;
  10778. svr.set_mount_point("/static", ".");
  10779. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10780. svr.wait_until_ready();
  10781. Client cli("localhost", 8090);
  10782. // First request: get ETag
  10783. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10784. ASSERT_TRUE(res1);
  10785. ASSERT_EQ(200, res1->status);
  10786. ASSERT_TRUE(res1->has_header("ETag"));
  10787. std::string etag = res1->get_header_value("ETag");
  10788. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10789. // Since our server generates weak ETags (W/"..."), If-Range with our
  10790. // ETag should NOT result in partial content - it should return full content.
  10791. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10792. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10793. ASSERT_TRUE(res2);
  10794. // Weak ETag in If-Range -> full content (200), not partial (206)
  10795. EXPECT_EQ(200, res2->status);
  10796. EXPECT_EQ(content, res2->body);
  10797. EXPECT_FALSE(res2->has_header("Content-Range"));
  10798. // Range request with non-matching If-Range (ETag): should get 200 (full
  10799. // content)
  10800. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10801. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10802. ASSERT_TRUE(res3);
  10803. EXPECT_EQ(200, res3->status);
  10804. EXPECT_EQ(content, res3->body);
  10805. EXPECT_FALSE(res3->has_header("Content-Range"));
  10806. // Range request with strong ETag (hypothetical - our server doesn't generate
  10807. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10808. // should return full content)
  10809. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10810. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10811. ASSERT_TRUE(res4);
  10812. EXPECT_EQ(200, res4->status);
  10813. EXPECT_EQ(content, res4->body);
  10814. EXPECT_FALSE(res4->has_header("Content-Range"));
  10815. svr.stop();
  10816. t.join();
  10817. std::remove(fname);
  10818. }
  10819. TEST(ETagTest, IfRangeWithDate) {
  10820. using namespace httplib;
  10821. // Create a test file
  10822. const char *fname = "if_range_date_testfile.txt";
  10823. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10824. {
  10825. std::ofstream ofs(fname);
  10826. ofs << content;
  10827. ASSERT_TRUE(ofs.good());
  10828. }
  10829. Server svr;
  10830. svr.set_mount_point("/static", ".");
  10831. auto t = std::thread([&]() { svr.listen("localhost", 8091); });
  10832. svr.wait_until_ready();
  10833. Client cli("localhost", 8091);
  10834. // First request: get Last-Modified
  10835. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10836. ASSERT_TRUE(res1);
  10837. ASSERT_EQ(200, res1->status);
  10838. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10839. std::string last_modified = res1->get_header_value("Last-Modified");
  10840. // Range request with matching If-Range (date): should get 206
  10841. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10842. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10843. ASSERT_TRUE(res2);
  10844. EXPECT_EQ(206, res2->status);
  10845. EXPECT_EQ("FGHIJ", res2->body);
  10846. // Range request with old If-Range date: should get 200 (full content)
  10847. Headers h3 = {{"Range", "bytes=5-9"},
  10848. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10849. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10850. ASSERT_TRUE(res3);
  10851. EXPECT_EQ(200, res3->status);
  10852. EXPECT_EQ(content, res3->body);
  10853. // Range request with future If-Range date: should get 206
  10854. Headers h4 = {{"Range", "bytes=0-4"},
  10855. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10856. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10857. ASSERT_TRUE(res4);
  10858. EXPECT_EQ(206, res4->status);
  10859. EXPECT_EQ("ABCDE", res4->body);
  10860. svr.stop();
  10861. t.join();
  10862. std::remove(fname);
  10863. }
  10864. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10865. using namespace httplib;
  10866. const char *fname = "etag_malformed.txt";
  10867. const char *content = "malformed-etag";
  10868. {
  10869. std::ofstream ofs(fname);
  10870. ofs << content;
  10871. ASSERT_TRUE(ofs.good());
  10872. }
  10873. Server svr;
  10874. svr.set_mount_point("/static", ".");
  10875. auto t = std::thread([&]() { svr.listen("localhost", 8092); });
  10876. svr.wait_until_ready();
  10877. Client cli("localhost", 8092);
  10878. // baseline: should get 200 and an ETag
  10879. auto res1 = cli.Get("/static/etag_malformed.txt");
  10880. ASSERT_TRUE(res1);
  10881. ASSERT_EQ(200, res1->status);
  10882. ASSERT_TRUE(res1->has_header("ETag"));
  10883. // Malformed ETag value (missing quotes) should be treated as non-matching
  10884. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10885. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10886. ASSERT_TRUE(res_bad);
  10887. EXPECT_EQ(200, res_bad->status);
  10888. // Whitespace-only header value should be considered invalid / non-matching
  10889. Headers h_space = {{"If-None-Match", " "}};
  10890. auto res_space = cli.Get("/static/etag_malformed.txt", h_space);
  10891. ASSERT_TRUE(res_space);
  10892. EXPECT_EQ(200, res_space->status);
  10893. svr.stop();
  10894. t.join();
  10895. std::remove(fname);
  10896. }
  10897. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10898. using namespace httplib;
  10899. const char *fname = "ims_invalid_format.txt";
  10900. const char *content = "ims-bad-format";
  10901. {
  10902. std::ofstream ofs(fname);
  10903. ofs << content;
  10904. ASSERT_TRUE(ofs.good());
  10905. }
  10906. Server svr;
  10907. svr.set_mount_point("/static", ".");
  10908. auto t = std::thread([&]() { svr.listen("localhost", 8093); });
  10909. svr.wait_until_ready();
  10910. Client cli("localhost", 8093);
  10911. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10912. ASSERT_TRUE(res1);
  10913. ASSERT_EQ(200, res1->status);
  10914. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10915. // If-Modified-Since with invalid format should not result in 304
  10916. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  10917. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  10918. ASSERT_TRUE(res_bad);
  10919. EXPECT_EQ(200, res_bad->status);
  10920. // If-Range with invalid date format should be treated as mismatch -> full
  10921. // content (200)
  10922. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  10923. {"If-Range", "invalid-date"}};
  10924. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  10925. ASSERT_TRUE(res_ifrange);
  10926. EXPECT_EQ(200, res_ifrange->status);
  10927. svr.stop();
  10928. t.join();
  10929. std::remove(fname);
  10930. }
  10931. TEST(ETagTest, IfRangeWithMalformedETag) {
  10932. using namespace httplib;
  10933. const char *fname = "ifrange_malformed.txt";
  10934. const std::string content = "0123456789";
  10935. {
  10936. std::ofstream ofs(fname);
  10937. ofs << content;
  10938. ASSERT_TRUE(ofs.good());
  10939. }
  10940. Server svr;
  10941. svr.set_mount_point("/static", ".");
  10942. auto t = std::thread([&]() { svr.listen("localhost", 8094); });
  10943. svr.wait_until_ready();
  10944. Client cli("localhost", 8094);
  10945. // First request: get ETag
  10946. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  10947. ASSERT_TRUE(res1);
  10948. ASSERT_EQ(200, res1->status);
  10949. ASSERT_TRUE(res1->has_header("ETag"));
  10950. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  10951. // full content (200)
  10952. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  10953. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  10954. ASSERT_TRUE(res2);
  10955. EXPECT_EQ(200, res2->status);
  10956. EXPECT_EQ(content, res2->body);
  10957. svr.stop();
  10958. t.join();
  10959. std::remove(fname);
  10960. }
  10961. TEST(ETagTest, ExtremeLargeDateValues) {
  10962. using namespace httplib;
  10963. const char *fname = "ims_extreme_date.txt";
  10964. const char *content = "ims-extreme-date";
  10965. {
  10966. std::ofstream ofs(fname);
  10967. ofs << content;
  10968. ASSERT_TRUE(ofs.good());
  10969. }
  10970. Server svr;
  10971. svr.set_mount_point("/static", ".");
  10972. auto t = std::thread([&]() { svr.listen("localhost", 8095); });
  10973. svr.wait_until_ready();
  10974. Client cli("localhost", 8095);
  10975. auto res1 = cli.Get(std::string("/static/") + fname);
  10976. ASSERT_TRUE(res1);
  10977. ASSERT_EQ(200, res1->status);
  10978. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10979. // Extremely large year that may overflow date parsing routines.
  10980. Headers h_large_date = {
  10981. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  10982. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  10983. ASSERT_TRUE(res_bad);
  10984. // Expect server to treat this as invalid/mismatch and return full content
  10985. EXPECT_EQ(200, res_bad->status);
  10986. // If-Range with extremely large date should be treated as mismatch -> full
  10987. // content (200)
  10988. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  10989. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  10990. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  10991. ASSERT_TRUE(res_ifrange);
  10992. EXPECT_EQ(200, res_ifrange->status);
  10993. svr.stop();
  10994. t.join();
  10995. std::remove(fname);
  10996. }
  10997. TEST(ETagTest, NegativeFileModificationTime) {
  10998. using namespace httplib;
  10999. const char *fname = "ims_negative_mtime.txt";
  11000. const std::string content = "negative-mtime";
  11001. {
  11002. std::ofstream ofs(fname);
  11003. ofs << content;
  11004. ASSERT_TRUE(ofs.good());
  11005. }
  11006. // Try to set file mtime to a negative value. This may fail on some
  11007. // platforms/filesystems; if it fails, the test will still verify server
  11008. // behaves safely by performing a regular conditional request.
  11009. #if defined(__APPLE__) || defined(__linux__)
  11010. bool set_negative = false;
  11011. do {
  11012. struct timeval times[2];
  11013. // access time: now
  11014. times[0].tv_sec = time(nullptr);
  11015. times[0].tv_usec = 0;
  11016. // modification time: negative (e.g., -1)
  11017. times[1].tv_sec = -1;
  11018. times[1].tv_usec = 0;
  11019. if (utimes(fname, times) == 0) { set_negative = true; }
  11020. } while (0);
  11021. #else
  11022. bool set_negative = false;
  11023. #endif
  11024. Server svr;
  11025. svr.set_mount_point("/static", ".");
  11026. auto t = std::thread([&]() { svr.listen("localhost", 8096); });
  11027. svr.wait_until_ready();
  11028. Client cli("localhost", 8096);
  11029. auto res1 = cli.Get(std::string("/static/") + fname);
  11030. ASSERT_TRUE(res1);
  11031. ASSERT_EQ(200, res1->status);
  11032. bool has_last_modified = res1->has_header("Last-Modified");
  11033. std::string last_modified;
  11034. if (has_last_modified) {
  11035. last_modified = res1->get_header_value("Last-Modified");
  11036. }
  11037. if (set_negative) {
  11038. // If we successfully set a negative mtime, ensure server returns a
  11039. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11040. // with an old date and ensure server handles it without crash.
  11041. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11042. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11043. ASSERT_TRUE(res2);
  11044. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11045. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11046. } else {
  11047. // Could not set negative mtime on this platform; fall back to verifying
  11048. // that normal invalid/malformed dates are treated safely (non-304).
  11049. Headers h_bad_date = {
  11050. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11051. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11052. ASSERT_TRUE(res_bad);
  11053. EXPECT_EQ(200, res_bad->status);
  11054. }
  11055. svr.stop();
  11056. t.join();
  11057. std::remove(fname);
  11058. }