test.cc 450 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690
  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. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) throw std::runtime_error("File not found: " + path);
  74. fs.seekg(0, std::ios_base::end);
  75. auto size = fs.tellg();
  76. fs.seekg(0);
  77. out.resize(static_cast<size_t>(size));
  78. fs.read(&out[0], static_cast<std::streamsize>(size));
  79. }
  80. void performance_test(const char *host) {
  81. Server svr;
  82. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  83. res.set_content("Benchmark Response", "text/plain");
  84. });
  85. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  86. auto se = detail::scope_exit([&] {
  87. svr.stop();
  88. listen_thread.join();
  89. ASSERT_FALSE(svr.is_running());
  90. });
  91. svr.wait_until_ready();
  92. Client cli(host, PORT);
  93. // Warm-up request to establish connection and resolve DNS
  94. auto warmup_res = cli.Get("/benchmark");
  95. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  96. // Run multiple trials and collect timings
  97. const int num_trials = 20;
  98. std::vector<int64_t> timings;
  99. timings.reserve(num_trials);
  100. for (int i = 0; i < num_trials; i++) {
  101. auto start = std::chrono::high_resolution_clock::now();
  102. auto res = cli.Get("/benchmark");
  103. auto end = std::chrono::high_resolution_clock::now();
  104. auto elapsed =
  105. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  106. .count();
  107. // Assertions after timing measurement to avoid overhead
  108. ASSERT_TRUE(res);
  109. EXPECT_EQ(StatusCode::OK_200, res->status);
  110. timings.push_back(elapsed);
  111. }
  112. // Calculate 25th percentile (lower quartile)
  113. std::sort(timings.begin(), timings.end());
  114. auto p25 = timings[num_trials / 4];
  115. // Format timings for output
  116. std::ostringstream timings_str;
  117. timings_str << "[";
  118. for (size_t i = 0; i < timings.size(); i++) {
  119. if (i > 0) timings_str << ", ";
  120. timings_str << timings[i];
  121. }
  122. timings_str << "]";
  123. // Localhost HTTP GET should be fast even in CI environments
  124. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  125. << "ms (Issue #1777). Timings: " << timings_str.str();
  126. }
  127. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  128. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  129. class UnixSocketTest : public ::testing::Test {
  130. protected:
  131. void TearDown() override { std::remove(pathname_.c_str()); }
  132. void client_GET(const std::string &addr) {
  133. httplib::Client cli{addr};
  134. cli.set_address_family(AF_UNIX);
  135. ASSERT_TRUE(cli.is_valid());
  136. const auto &result = cli.Get(pattern_);
  137. ASSERT_TRUE(result) << "error: " << result.error();
  138. const auto &resp = result.value();
  139. EXPECT_EQ(resp.status, StatusCode::OK_200);
  140. EXPECT_EQ(resp.body, content_);
  141. }
  142. const std::string pathname_{"./httplib-server.sock"};
  143. const std::string pattern_{"/hi"};
  144. const std::string content_{"Hello World!"};
  145. };
  146. TEST_F(UnixSocketTest, pathname) {
  147. httplib::Server svr;
  148. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  149. res.set_content(content_, "text/plain");
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_EQ(0, close(fds[1]));
  254. EXPECT_FALSE(s0.wait_writable());
  255. return true;
  256. });
  257. EXPECT_EQ(0, close(fds[0]));
  258. }
  259. TEST(SocketStream, wait_writable_INET) {
  260. sockaddr_in addr;
  261. memset(&addr, 0, sizeof(addr));
  262. addr.sin_family = AF_INET;
  263. addr.sin_port = htons(PORT + 1);
  264. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  265. int disconnected_svr_sock = -1;
  266. std::thread svr{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. EXPECT_FALSE(ss.wait_writable());
  292. return true;
  293. });
  294. ASSERT_EQ(0, close(disconnected_svr_sock));
  295. }
  296. #endif // #ifndef _WIN32
  297. TEST(ClientTest, MoveConstructible) {
  298. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  299. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  300. }
  301. TEST(ClientTest, MoveAssignable) {
  302. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  303. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  304. }
  305. #ifdef _WIN32
  306. TEST(StartupTest, WSAStartup) {
  307. WSADATA wsaData;
  308. int ret = WSAStartup(0x0002, &wsaData);
  309. ASSERT_EQ(0, ret);
  310. }
  311. #endif
  312. TEST(DecodePathTest, PercentCharacter) {
  313. EXPECT_EQ(
  314. decode_path_component(
  315. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  316. U8("descrip=Gastos áéíóúñÑ 6"));
  317. }
  318. TEST(DecodePathTest, PercentCharacterNUL) {
  319. string expected;
  320. expected.push_back('x');
  321. expected.push_back('\0');
  322. expected.push_back('x');
  323. EXPECT_EQ(decode_path_component("x%00x"), expected);
  324. }
  325. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  326. string unescapedCharacters = "-_.!~*'()";
  327. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  328. }
  329. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  330. string reservedCharacters = ";,/?:@&=+$";
  331. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  332. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  333. }
  334. TEST(ClientQueryOrder, PreserveOrder) {
  335. // This test reproduces Issue #2259: client may reorder query parameters
  336. // when sending a GET request. The expected behavior is that the client
  337. // preserves the original query string order when the caller supplied it
  338. // as part of the path.
  339. Server svr;
  340. svr.Get("/", [&](const Request &req, Response &res) {
  341. // Echo back the raw target so the test can assert ordering
  342. res.set_content(req.target, "text/plain");
  343. });
  344. std::thread t{[&] { svr.listen(HOST, PORT); }};
  345. auto se = detail::scope_exit([&] {
  346. svr.stop();
  347. t.join();
  348. ASSERT_FALSE(svr.is_running());
  349. });
  350. svr.wait_until_ready();
  351. Client cli(HOST, PORT);
  352. ASSERT_TRUE(cli.is_valid());
  353. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  354. auto res = cli.Get(original);
  355. ASSERT_TRUE(res);
  356. // Expect the echoed target to exactly match the original path (order
  357. // preserved)
  358. EXPECT_EQ(res->body, original);
  359. }
  360. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  361. string chineseCharacters = U8("中国語");
  362. string russianCharacters = U8("дом");
  363. string brazilianCharacters = U8("óculos");
  364. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  365. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  366. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  367. "%D0%B4%D0%BE%D0%BC");
  368. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  369. }
  370. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  371. string unescapedCharacters = "-_.!~*'()";
  372. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  373. }
  374. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  375. string reservedCharacters = ";,/?:@&=+$";
  376. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  377. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  378. }
  379. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  380. string chineseCharacters = U8("中国語");
  381. string russianCharacters = U8("дом");
  382. string brazilianCharacters = U8("óculos");
  383. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  384. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  385. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  386. "%D0%B4%D0%BE%D0%BC");
  387. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  388. }
  389. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  390. // Issue #2082 use case: encoding path component with ampersand
  391. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  392. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  393. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  394. }
  395. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  400. string reservedCharacters = ";,/?:@&=+$#";
  401. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  402. }
  403. TEST(EncodeUriTest, TestUTF8Characters) {
  404. string chineseCharacters = U8("中国語");
  405. string russianCharacters = U8("дом");
  406. string brazilianCharacters = U8("óculos");
  407. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  408. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  409. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  410. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  411. }
  412. TEST(EncodeUriTest, TestCompleteUri) {
  413. string uri =
  414. "https://example.com/path/to/resource?query=value&param=test#fragment";
  415. EXPECT_EQ(
  416. httplib::encode_uri(uri),
  417. "https://example.com/path/to/resource?query=value&param=test#fragment");
  418. }
  419. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  420. string uri =
  421. "https://example.com/path with spaces/file name.html?q=hello world";
  422. EXPECT_EQ(httplib::encode_uri(uri),
  423. "https://example.com/path%20with%20spaces/"
  424. "file%20name.html?q=hello%20world");
  425. }
  426. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  427. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  428. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  429. }
  430. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  435. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  436. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  437. string encodedBrazilian = "%C3%B3culos";
  438. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  441. }
  442. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  443. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  445. "Piri Tommy Villiers - on & on");
  446. }
  447. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  449. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  450. }
  451. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  453. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  454. }
  455. TEST(DecodeUriTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriTest, TestCompleteUri) {
  464. string encodedUri = "https://example.com/path%20with%20spaces/"
  465. "file%20name.html?q=hello%20world";
  466. EXPECT_EQ(
  467. httplib::decode_uri(encodedUri),
  468. "https://example.com/path with spaces/file name.html?q=hello world");
  469. }
  470. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  471. string original =
  472. "https://example.com/path with spaces/file name.html?q=hello world";
  473. string encoded = httplib::encode_uri(original);
  474. string decoded = httplib::decode_uri(encoded);
  475. EXPECT_EQ(decoded, original);
  476. }
  477. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  478. string original = "Piri Tommy Villiers - on & on";
  479. string encoded = httplib::encode_uri_component(original);
  480. string decoded = httplib::decode_uri_component(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(TrimTests, TrimStringTests) {
  484. EXPECT_EQ("abc", detail::trim_copy("abc"));
  485. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  486. EXPECT_TRUE(detail::trim_copy("").empty());
  487. }
  488. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  489. // Simple case without quality values
  490. std::vector<std::string> result1;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html,application/json,text/plain", result1));
  493. EXPECT_EQ(result1.size(), 3U);
  494. EXPECT_EQ(result1[0], "text/html");
  495. EXPECT_EQ(result1[1], "application/json");
  496. EXPECT_EQ(result1[2], "text/plain");
  497. // With quality values
  498. std::vector<std::string> result2;
  499. EXPECT_TRUE(detail::parse_accept_header(
  500. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  501. EXPECT_EQ(result2.size(), 3U);
  502. EXPECT_EQ(result2[0], "application/json"); // highest q value
  503. EXPECT_EQ(result2[1], "text/html");
  504. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  505. }
  506. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  507. // Mixed with and without quality values
  508. std::vector<std::string> result;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  511. EXPECT_EQ(result.size(), 3U);
  512. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  513. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  514. EXPECT_EQ(result[2], "application/json"); // q=0.5
  515. }
  516. TEST(ParseAcceptHeaderTest, EdgeCases) {
  517. // Empty header
  518. std::vector<std::string> empty_result;
  519. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  520. EXPECT_TRUE(empty_result.empty());
  521. // Single type
  522. std::vector<std::string> single_result;
  523. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  524. EXPECT_EQ(single_result.size(), 1U);
  525. EXPECT_EQ(single_result[0], "application/json");
  526. // Wildcard types
  527. std::vector<std::string> wildcard_result;
  528. EXPECT_TRUE(detail::parse_accept_header(
  529. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  530. EXPECT_EQ(wildcard_result.size(), 3U);
  531. EXPECT_EQ(wildcard_result[0], "application/json");
  532. EXPECT_EQ(wildcard_result[1], "text/*");
  533. EXPECT_EQ(wildcard_result[2], "*/*");
  534. }
  535. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  536. // Common browser Accept header
  537. std::vector<std::string> browser_result;
  538. EXPECT_TRUE(
  539. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  540. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  541. browser_result));
  542. EXPECT_EQ(browser_result.size(), 6U);
  543. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  548. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  549. // API client header
  550. std::vector<std::string> api_result;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  553. api_result));
  554. EXPECT_EQ(api_result.size(), 3U);
  555. EXPECT_EQ(api_result[0], "application/json");
  556. EXPECT_EQ(api_result[1], "application/xml");
  557. EXPECT_EQ(api_result[2], "text/plain");
  558. }
  559. TEST(ParseAcceptHeaderTest, SpecialCases) {
  560. // Quality value with 3 decimal places
  561. std::vector<std::string> decimal_result;
  562. EXPECT_TRUE(detail::parse_accept_header(
  563. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  564. EXPECT_EQ(decimal_result.size(), 2U);
  565. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  566. EXPECT_EQ(decimal_result[1], "text/html");
  567. // Zero quality (should still be included but with lowest priority)
  568. std::vector<std::string> zero_q_result;
  569. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  570. zero_q_result));
  571. EXPECT_EQ(zero_q_result.size(), 2U);
  572. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  573. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  574. // No spaces around commas
  575. std::vector<std::string> no_space_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  578. no_space_result));
  579. EXPECT_EQ(no_space_result.size(), 3U);
  580. EXPECT_EQ(no_space_result[0], "text/html");
  581. EXPECT_EQ(no_space_result[1], "application/json");
  582. EXPECT_EQ(no_space_result[2], "text/plain");
  583. }
  584. TEST(ParseAcceptHeaderTest, InvalidCases) {
  585. std::vector<std::string> result;
  586. // Invalid quality value (> 1.0)
  587. EXPECT_FALSE(
  588. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  589. // Invalid quality value (< 0.0)
  590. EXPECT_FALSE(
  591. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  592. // Invalid quality value (not a number)
  593. EXPECT_FALSE(detail::parse_accept_header(
  594. "text/html;q=invalid,application/json", result));
  595. // Empty quality value
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=,application/json", result));
  598. // Invalid media type format (no slash and not wildcard)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("invalidtype,application/json", result));
  601. // Empty media type
  602. result.clear();
  603. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  604. // Only commas
  605. result.clear();
  606. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  607. // Valid cases should still work
  608. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  609. EXPECT_EQ(result.size(), 1U);
  610. EXPECT_EQ(result[0], "*/*");
  611. EXPECT_TRUE(detail::parse_accept_header("*", result));
  612. EXPECT_EQ(result.size(), 1U);
  613. EXPECT_EQ(result[0], "*");
  614. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "text/*");
  617. }
  618. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  619. Server svr;
  620. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  621. EXPECT_EQ(req.accept_content_types.size(), 3U);
  622. EXPECT_EQ(req.accept_content_types[0], "application/json");
  623. EXPECT_EQ(req.accept_content_types[1], "text/html");
  624. EXPECT_EQ(req.accept_content_types[2], "*/*");
  625. res.set_content("ok", "text/plain");
  626. });
  627. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  628. EXPECT_TRUE(false);
  629. res.set_content("bad request", "text/plain");
  630. });
  631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  632. auto se = detail::scope_exit([&] {
  633. svr.stop();
  634. listen_thread.join();
  635. ASSERT_FALSE(svr.is_running());
  636. });
  637. svr.wait_until_ready();
  638. Client cli("localhost", PORT);
  639. {
  640. auto res =
  641. cli.Get("/accept_ok",
  642. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  643. ASSERT_TRUE(res);
  644. EXPECT_EQ(StatusCode::OK_200, res->status);
  645. }
  646. {
  647. auto res = cli.Get("/accept_bad_request",
  648. {{"Accept", "text/html;q=abc,application/json"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  651. }
  652. }
  653. TEST(DivideTest, DivideStringTests) {
  654. auto divide = [](const std::string &str, char d) {
  655. std::string lhs;
  656. std::string rhs;
  657. detail::divide(str, d,
  658. [&](const char *lhs_data, std::size_t lhs_size,
  659. const char *rhs_data, std::size_t rhs_size) {
  660. lhs.assign(lhs_data, lhs_size);
  661. rhs.assign(rhs_data, rhs_size);
  662. });
  663. return std::make_pair(std::move(lhs), std::move(rhs));
  664. };
  665. {
  666. const auto res = divide("", '=');
  667. EXPECT_EQ(res.first, "");
  668. EXPECT_EQ(res.second, "");
  669. }
  670. {
  671. const auto res = divide("=", '=');
  672. EXPECT_EQ(res.first, "");
  673. EXPECT_EQ(res.second, "");
  674. }
  675. {
  676. const auto res = divide(" ", '=');
  677. EXPECT_EQ(res.first, " ");
  678. EXPECT_EQ(res.second, "");
  679. }
  680. {
  681. const auto res = divide("a", '=');
  682. EXPECT_EQ(res.first, "a");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("a=", '=');
  687. EXPECT_EQ(res.first, "a");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide("=b", '=');
  692. EXPECT_EQ(res.first, "");
  693. EXPECT_EQ(res.second, "b");
  694. }
  695. {
  696. const auto res = divide("a=b", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "b");
  699. }
  700. {
  701. const auto res = divide("a=b=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "b=");
  704. }
  705. {
  706. const auto res = divide("a=b=c", '=');
  707. EXPECT_EQ(res.first, "a");
  708. EXPECT_EQ(res.second, "b=c");
  709. }
  710. }
  711. TEST(SplitTest, ParseQueryString) {
  712. string s = "key1=val1&key2=val2&key3=val3";
  713. Params dic;
  714. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  715. [&](const char *b, const char *e) {
  716. string key, val;
  717. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  718. if (key.empty()) {
  719. key.assign(b2, e2);
  720. } else {
  721. val.assign(b2, e2);
  722. }
  723. });
  724. dic.emplace(key, val);
  725. });
  726. EXPECT_EQ("val1", dic.find("key1")->second);
  727. EXPECT_EQ("val2", dic.find("key2")->second);
  728. EXPECT_EQ("val3", dic.find("key3")->second);
  729. }
  730. TEST(SplitTest, ParseInvalidQueryTests) {
  731. {
  732. string s = " ";
  733. Params dict;
  734. detail::parse_query_text(s, dict);
  735. EXPECT_TRUE(dict.empty());
  736. }
  737. {
  738. string s = " = =";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. }
  744. TEST(ParseQueryTest, ParseQueryString) {
  745. {
  746. std::string s = "key1=val1&key2=val2&key3=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("val1", dic.find("key1")->second);
  750. EXPECT_EQ("val2", dic.find("key2")->second);
  751. EXPECT_EQ("val3", dic.find("key3")->second);
  752. }
  753. {
  754. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  755. Params dic;
  756. detail::parse_query_text(s, dic);
  757. EXPECT_EQ("", dic.find("key1")->second);
  758. EXPECT_EQ("val1", dic.find("key2")->second);
  759. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  760. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  761. }
  762. }
  763. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  764. Params dic;
  765. EXPECT_EQ(detail::params_to_query_str(dic), "");
  766. dic.emplace("key1", "val1");
  767. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  768. dic.emplace("key2", "val2");
  769. dic.emplace("key3", "val3");
  770. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  771. }
  772. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  773. string content_type = "multipart/form-data; boundary=something";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "something");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  780. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  795. string content_type =
  796. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  797. string boundary;
  798. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  801. }
  802. TEST(GetHeaderValueTest, DefaultValue) {
  803. Headers headers = {{"Dummy", "Dummy"}};
  804. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  805. EXPECT_STREQ("text/plain", val);
  806. }
  807. TEST(GetHeaderValueTest, DefaultValueInt) {
  808. Headers headers = {{"Dummy", "Dummy"}};
  809. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  810. EXPECT_EQ(100ull, val);
  811. }
  812. TEST(GetHeaderValueTest, RegularValue) {
  813. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  814. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  815. EXPECT_STREQ("text/html", val);
  816. }
  817. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  818. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  820. EXPECT_STREQ("text/html", val);
  821. }
  822. TEST(GetHeaderValueTest, SetContent) {
  823. Response res;
  824. res.set_content("html", "text/html");
  825. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  826. res.set_content("text", "text/plain");
  827. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  828. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  829. }
  830. TEST(GetHeaderValueTest, RegularValueInt) {
  831. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  833. EXPECT_EQ(100ull, val);
  834. }
  835. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  836. Headers headers = {{"Content-Length", "x"}};
  837. auto is_invalid_value = false;
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  839. is_invalid_value);
  840. EXPECT_EQ(0ull, val);
  841. EXPECT_TRUE(is_invalid_value);
  842. }
  843. TEST(GetHeaderValueTest, Range) {
  844. {
  845. Headers headers = {make_range_header({{1, -1}})};
  846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  847. EXPECT_STREQ("bytes=1-", val);
  848. }
  849. {
  850. Headers headers = {make_range_header({{-1, 1}})};
  851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  852. EXPECT_STREQ("bytes=-1", val);
  853. }
  854. {
  855. Headers headers = {make_range_header({{1, 10}})};
  856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  857. EXPECT_STREQ("bytes=1-10", val);
  858. }
  859. {
  860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-10, 100-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=0-0, -1", val);
  873. }
  874. }
  875. TEST(ParseHeaderValueTest, Range) {
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=1-", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(1u, ranges[0].first);
  882. EXPECT_EQ(-1, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=-1", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(-1, ranges[0].first);
  890. EXPECT_EQ(1u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  895. EXPECT_TRUE(ret);
  896. EXPECT_EQ(1u, ranges.size());
  897. EXPECT_EQ(1u, ranges[0].first);
  898. EXPECT_EQ(10u, ranges[0].second);
  899. }
  900. {
  901. Ranges ranges;
  902. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  903. EXPECT_FALSE(ret);
  904. }
  905. {
  906. Ranges ranges;
  907. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  908. EXPECT_TRUE(ret);
  909. EXPECT_EQ(2u, ranges.size());
  910. EXPECT_EQ(1u, ranges[0].first);
  911. EXPECT_EQ(10u, ranges[0].second);
  912. EXPECT_EQ(100u, ranges[1].first);
  913. EXPECT_EQ(-1, ranges[1].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret =
  918. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  919. EXPECT_TRUE(ret);
  920. EXPECT_EQ(3u, ranges.size());
  921. EXPECT_EQ(1u, ranges[0].first);
  922. EXPECT_EQ(10u, ranges[0].second);
  923. EXPECT_EQ(100u, ranges[1].first);
  924. EXPECT_EQ(200u, ranges[1].second);
  925. EXPECT_EQ(300u, ranges[2].first);
  926. EXPECT_EQ(400u, ranges[2].second);
  927. }
  928. {
  929. Ranges ranges;
  930. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  943. EXPECT_TRUE(ranges.empty());
  944. }
  945. }
  946. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  947. Request req;
  948. req.set_header("Accept-Encoding", "gzip");
  949. Response res;
  950. res.set_header("Content-Type", "text/plain");
  951. auto ret = detail::encoding_type(req, res);
  952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  966. #elif CPPHTTPLIB_ZLIB_SUPPORT
  967. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  968. #elif CPPHTTPLIB_ZSTD_SUPPORT
  969. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  970. #else
  971. EXPECT_TRUE(ret == detail::EncodingType::None);
  972. #endif
  973. }
  974. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  975. Request req;
  976. req.set_header("Accept-Encoding",
  977. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  978. Response res;
  979. res.set_header("Content-Type", "text/plain");
  980. auto ret = detail::encoding_type(req, res);
  981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  983. #elif CPPHTTPLIB_ZLIB_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  985. #elif CPPHTTPLIB_ZSTD_SUPPORT
  986. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  987. #else
  988. EXPECT_TRUE(ret == detail::EncodingType::None);
  989. #endif
  990. }
  991. TEST(BufferStreamTest, read) {
  992. detail::BufferStream strm1;
  993. Stream &strm = strm1;
  994. EXPECT_EQ(5, strm.write("hello"));
  995. char buf[512];
  996. EXPECT_EQ(2, strm.read(buf, 2));
  997. EXPECT_EQ('h', buf[0]);
  998. EXPECT_EQ('e', buf[1]);
  999. EXPECT_EQ(2, strm.read(buf, 2));
  1000. EXPECT_EQ('l', buf[0]);
  1001. EXPECT_EQ('l', buf[1]);
  1002. EXPECT_EQ(1, strm.read(buf, 1));
  1003. EXPECT_EQ('o', buf[0]);
  1004. EXPECT_EQ(0, strm.read(buf, 1));
  1005. }
  1006. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1007. auto host = "www.httpwatch.com";
  1008. auto ip = hosted_at(host);
  1009. EXPECT_EQ("23.96.13.243", ip);
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(1u, addrs.size());
  1013. }
  1014. #if 0 // It depends on each test environment...
  1015. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1016. auto host = "www.youtube.com";
  1017. std::vector<std::string> addrs;
  1018. hosted_at(host, addrs);
  1019. EXPECT_EQ(20u, addrs.size());
  1020. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1021. EXPECT_TRUE(it != addrs.end());
  1022. }
  1023. #endif
  1024. class ChunkedEncodingTest : public ::testing::Test {
  1025. protected:
  1026. ChunkedEncodingTest()
  1027. : cli_(HOST, PORT)
  1028. #ifdef CPPHTTPLIB_SSL_ENABLED
  1029. ,
  1030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1031. #endif
  1032. {
  1033. cli_.set_connection_timeout(2);
  1034. #ifdef CPPHTTPLIB_SSL_ENABLED
  1035. cli_.enable_server_certificate_verification(false);
  1036. #endif
  1037. }
  1038. virtual void SetUp() {
  1039. read_file("./image.jpg", image_data_);
  1040. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content("Hello World!", "text/plain");
  1042. });
  1043. svr_.Get(
  1044. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1045. res.set_chunked_content_provider(
  1046. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1047. size_t remaining = image_data_.size() - offset;
  1048. if (remaining == 0) {
  1049. sink.done();
  1050. } else {
  1051. constexpr size_t CHUNK_SIZE = 1024;
  1052. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1053. sink.write(&image_data_[offset], send_size);
  1054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1055. }
  1056. return true;
  1057. });
  1058. });
  1059. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1060. svr_.wait_until_ready();
  1061. }
  1062. virtual void TearDown() {
  1063. svr_.stop();
  1064. if (!request_threads_.empty()) {
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. for (auto &t : request_threads_) {
  1067. t.join();
  1068. }
  1069. }
  1070. t_.join();
  1071. }
  1072. #ifdef CPPHTTPLIB_SSL_ENABLED
  1073. SSLClient cli_;
  1074. SSLServer svr_;
  1075. #else
  1076. Client cli_;
  1077. Server svr_;
  1078. #endif
  1079. thread t_;
  1080. std::vector<thread> request_threads_;
  1081. std::string image_data_;
  1082. };
  1083. TEST_F(ChunkedEncodingTest, NormalGet) {
  1084. auto res = cli_.Get("/chunked");
  1085. ASSERT_TRUE(res);
  1086. std::string out;
  1087. read_file("./image.jpg", out);
  1088. EXPECT_EQ(StatusCode::OK_200, res->status);
  1089. EXPECT_EQ(out, res->body);
  1090. }
  1091. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1092. std::string body;
  1093. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1094. body.append(data, data_length);
  1095. return true;
  1096. });
  1097. ASSERT_TRUE(res);
  1098. std::string out;
  1099. read_file("./image.jpg", out);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. EXPECT_EQ(out, body);
  1102. }
  1103. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1104. std::string body;
  1105. auto res = cli_.Get(
  1106. "/chunked",
  1107. [&](const Response &response) {
  1108. EXPECT_EQ(StatusCode::OK_200, response.status);
  1109. return true;
  1110. },
  1111. [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST(RangeTest, FromHTTPBin_Online) {
  1122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1123. auto host = "httpcan.org";
  1124. auto path = std::string{"/range/32"};
  1125. #else
  1126. auto host = "nghttp2.org";
  1127. auto path = std::string{"/httpbin/range/32"};
  1128. #endif
  1129. #ifdef CPPHTTPLIB_SSL_ENABLED
  1130. auto port = 443;
  1131. SSLClient cli(host, port);
  1132. #else
  1133. auto port = 80;
  1134. Client cli(host, port);
  1135. #endif
  1136. cli.set_connection_timeout(5);
  1137. {
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::OK_200, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, -1}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{1, 10}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("bcdefghijk", res->body);
  1155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, 31}})};
  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, -1}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. }
  1171. {
  1172. Headers headers = {make_range_header({{0, 32}})};
  1173. auto res = cli.Get(path, headers);
  1174. ASSERT_TRUE(res);
  1175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1176. }
  1177. }
  1178. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1179. auto host = "unresolvableaddress.local";
  1180. auto path = std::string{"/"};
  1181. #ifdef CPPHTTPLIB_SSL_ENABLED
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(1);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_FALSE(res);
  1192. }
  1193. std::this_thread::sleep_for(std::chrono::seconds(8));
  1194. }
  1195. TEST(ConnectionErrorTest, InvalidHost) {
  1196. auto host = "-abcde.com";
  1197. #ifdef CPPHTTPLIB_SSL_ENABLED
  1198. auto port = 443;
  1199. SSLClient cli(host, port);
  1200. #else
  1201. auto port = 80;
  1202. Client cli(host, port);
  1203. #endif
  1204. cli.set_connection_timeout(std::chrono::seconds(2));
  1205. auto res = cli.Get("/");
  1206. ASSERT_TRUE(!res);
  1207. EXPECT_EQ(Error::Connection, res.error());
  1208. }
  1209. TEST(ConnectionErrorTest, InvalidHost2) {
  1210. auto host = "httpcan.org/";
  1211. #ifdef CPPHTTPLIB_SSL_ENABLED
  1212. SSLClient cli(host);
  1213. #else
  1214. Client cli(host);
  1215. #endif
  1216. cli.set_connection_timeout(std::chrono::seconds(2));
  1217. auto res = cli.Get("/");
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Connection, res.error());
  1220. }
  1221. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1222. auto host = "httpcan.org/";
  1223. #ifdef CPPHTTPLIB_SSL_ENABLED
  1224. SSLClient cli(host);
  1225. #else
  1226. Client cli(host);
  1227. #endif
  1228. cli.set_connection_timeout(std::chrono::seconds(2));
  1229. auto res = cli.Get("/");
  1230. ASSERT_TRUE(!res);
  1231. stringstream s;
  1232. s << "error code: " << res.error();
  1233. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1234. }
  1235. TEST(ConnectionErrorTest, InvalidPort) {
  1236. auto host = "localhost";
  1237. auto port = 44380;
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host, port);
  1240. #else
  1241. Client cli(host, port);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. EXPECT_TRUE(Error::Connection == res.error() ||
  1247. Error::ConnectionTimeout == res.error());
  1248. }
  1249. TEST(ConnectionErrorTest, Timeout_Online) {
  1250. auto host = "google.com";
  1251. #ifdef CPPHTTPLIB_SSL_ENABLED
  1252. auto port = 44380;
  1253. SSLClient cli(host, port);
  1254. #else
  1255. auto port = 8080;
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. // only probe one address type so that the error reason
  1260. // correlates to the timed-out IPv4, not the unsupported
  1261. // IPv6 connection attempt
  1262. cli.set_address_family(AF_INET);
  1263. auto res = cli.Get("/");
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1266. }
  1267. TEST(CancelTest, NoCancel_Online) {
  1268. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1269. auto host = "httpcan.org";
  1270. auto path = std::string{"/range/32"};
  1271. #else
  1272. auto host = "nghttp2.org";
  1273. auto path = std::string{"/httpbin/range/32"};
  1274. #endif
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. auto port = 443;
  1277. SSLClient cli(host, port);
  1278. #else
  1279. auto port = 80;
  1280. Client cli(host, port);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(5));
  1283. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1284. ASSERT_TRUE(res);
  1285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1286. EXPECT_EQ(StatusCode::OK_200, res->status);
  1287. }
  1288. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1289. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1290. auto host = "httpcan.org";
  1291. auto path = std::string{"/range/32"};
  1292. #else
  1293. auto host = "nghttp2.org";
  1294. auto path = std::string{"/httpbin/range/32"};
  1295. #endif
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1304. cli.set_connection_timeout(std::chrono::seconds(5));
  1305. ASSERT_TRUE(!res);
  1306. EXPECT_EQ(Error::Canceled, res.error());
  1307. }
  1308. TEST(CancelTest, WithCancelLargePayload_Online) {
  1309. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1310. auto host = "httpcan.org";
  1311. auto path = std::string{"/range/65536"};
  1312. #else
  1313. auto host = "nghttp2.org";
  1314. auto path = std::string{"/httpbin/range/65536"};
  1315. #endif
  1316. #ifdef CPPHTTPLIB_SSL_ENABLED
  1317. auto port = 443;
  1318. SSLClient cli(host, port);
  1319. #else
  1320. auto port = 80;
  1321. Client cli(host, port);
  1322. #endif
  1323. cli.set_connection_timeout(std::chrono::seconds(5));
  1324. uint32_t count = 0;
  1325. auto res =
  1326. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1327. ASSERT_TRUE(!res);
  1328. EXPECT_EQ(Error::Canceled, res.error());
  1329. }
  1330. TEST(CancelTest, NoCancelPost) {
  1331. Server svr;
  1332. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1333. res.set_content("Hello World!", "text/plain");
  1334. });
  1335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1336. auto se = detail::scope_exit([&] {
  1337. svr.stop();
  1338. thread.join();
  1339. ASSERT_FALSE(svr.is_running());
  1340. });
  1341. svr.wait_until_ready();
  1342. Client cli(HOST, PORT);
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res =
  1345. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1346. "application/json", [](uint64_t, uint64_t) { return true; });
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("Hello World!", res->body);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1352. Server svr;
  1353. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1354. res.set_content("Hello World!", "text/plain");
  1355. });
  1356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1357. auto se = detail::scope_exit([&] {
  1358. svr.stop();
  1359. thread.join();
  1360. ASSERT_FALSE(svr.is_running());
  1361. });
  1362. svr.wait_until_ready();
  1363. Client cli(HOST, PORT);
  1364. cli.set_connection_timeout(std::chrono::seconds(5));
  1365. auto res =
  1366. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1367. "application/json", [](uint64_t, uint64_t) { return false; });
  1368. ASSERT_TRUE(!res);
  1369. EXPECT_EQ(Error::Canceled, res.error());
  1370. }
  1371. TEST(CancelTest, WithCancelLargePayloadPost) {
  1372. Server svr;
  1373. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1374. res.set_content(LARGE_DATA, "text/plain");
  1375. });
  1376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1377. auto se = detail::scope_exit([&] {
  1378. svr.stop();
  1379. thread.join();
  1380. ASSERT_FALSE(svr.is_running());
  1381. });
  1382. svr.wait_until_ready();
  1383. Client cli(HOST, PORT);
  1384. cli.set_connection_timeout(std::chrono::seconds(5));
  1385. auto res =
  1386. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1387. "application/json", [](uint64_t, uint64_t) { return false; });
  1388. ASSERT_TRUE(!res);
  1389. EXPECT_EQ(Error::Canceled, res.error());
  1390. }
  1391. TEST(CancelTest, NoCancelPut) {
  1392. Server svr;
  1393. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. });
  1396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. thread.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. Client cli(HOST, PORT);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return true; });
  1408. ASSERT_TRUE(res);
  1409. EXPECT_EQ("Hello World!", res->body);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. }
  1412. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1413. Server svr;
  1414. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1415. res.set_content("Hello World!", "text/plain");
  1416. });
  1417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1418. auto se = detail::scope_exit([&] {
  1419. svr.stop();
  1420. thread.join();
  1421. ASSERT_FALSE(svr.is_running());
  1422. });
  1423. svr.wait_until_ready();
  1424. Client cli(HOST, PORT);
  1425. cli.set_connection_timeout(std::chrono::seconds(5));
  1426. auto res =
  1427. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1428. "application/json", [](uint64_t, uint64_t) { return false; });
  1429. ASSERT_TRUE(!res);
  1430. EXPECT_EQ(Error::Canceled, res.error());
  1431. }
  1432. TEST(CancelTest, WithCancelLargePayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content(LARGE_DATA, "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, NoCancelPatch) {
  1453. Server svr;
  1454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("Hello World!", "text/plain");
  1456. });
  1457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1458. auto se = detail::scope_exit([&] {
  1459. svr.stop();
  1460. thread.join();
  1461. ASSERT_FALSE(svr.is_running());
  1462. });
  1463. svr.wait_until_ready();
  1464. Client cli(HOST, PORT);
  1465. cli.set_connection_timeout(std::chrono::seconds(5));
  1466. auto res =
  1467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1468. "application/json", [](uint64_t, uint64_t) { return true; });
  1469. ASSERT_TRUE(res);
  1470. EXPECT_EQ("Hello World!", res->body);
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1474. Server svr;
  1475. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1476. res.set_content("Hello World!", "text/plain");
  1477. });
  1478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. thread.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. Client cli(HOST, PORT);
  1486. cli.set_connection_timeout(std::chrono::seconds(5));
  1487. auto res =
  1488. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1489. "application/json", [](uint64_t, uint64_t) { return false; });
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_EQ(Error::Canceled, res.error());
  1492. }
  1493. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1494. Server svr;
  1495. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1496. res.set_content(LARGE_DATA, "text/plain");
  1497. });
  1498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1499. auto se = detail::scope_exit([&] {
  1500. svr.stop();
  1501. thread.join();
  1502. ASSERT_FALSE(svr.is_running());
  1503. });
  1504. svr.wait_until_ready();
  1505. Client cli(HOST, PORT);
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. auto res =
  1508. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1509. "application/json", [](uint64_t, uint64_t) { return false; });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelDelete) {
  1514. Server svr;
  1515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1555. Server svr;
  1556. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1557. res.set_content(LARGE_DATA, "text/plain");
  1558. });
  1559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. thread.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. Client cli(HOST, PORT);
  1567. cli.set_connection_timeout(std::chrono::seconds(5));
  1568. auto res =
  1569. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1570. "application/json", [](uint64_t, uint64_t) { return false; });
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Canceled, res.error());
  1573. }
  1574. static std::string remove_whitespace(const std::string &input) {
  1575. std::string output;
  1576. output.reserve(input.size());
  1577. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1578. [](unsigned char c) { return !std::isspace(c); });
  1579. return output;
  1580. }
  1581. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1582. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1583. auto host = "httpcan.org";
  1584. auto path = std::string{"/basic-auth/hello/world"};
  1585. #else
  1586. auto host = "nghttp2.org";
  1587. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1588. #endif
  1589. #ifdef CPPHTTPLIB_SSL_ENABLED
  1590. auto port = 443;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 80;
  1594. Client cli(host, port);
  1595. #endif
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1600. }
  1601. {
  1602. auto res =
  1603. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "world");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1614. remove_whitespace(res->body));
  1615. EXPECT_EQ(StatusCode::OK_200, res->status);
  1616. }
  1617. {
  1618. cli.set_basic_auth("hello", "bad");
  1619. auto res = cli.Get(path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("bad", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. }
  1630. #ifdef CPPHTTPLIB_SSL_ENABLED
  1631. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1632. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1633. auto host = "httpcan.org";
  1634. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/digest-auth/auth/hello/world/MD5",
  1637. "/digest-auth/auth/hello/world/SHA-256",
  1638. "/digest-auth/auth/hello/world/SHA-512",
  1639. };
  1640. #else
  1641. auto host = "nghttp2.org";
  1642. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1643. auto paths = std::vector<std::string>{
  1644. "/httpbin/digest-auth/auth/hello/world/MD5",
  1645. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1646. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1647. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1648. };
  1649. #endif
  1650. auto port = 443;
  1651. SSLClient cli(host, port);
  1652. {
  1653. auto res = cli.Get(unauth_path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. cli.set_digest_auth("hello", "world");
  1659. for (const auto &path : paths) {
  1660. auto res = cli.Get(path.c_str());
  1661. ASSERT_TRUE(res);
  1662. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1663. std::string algo(path.substr(path.rfind('/') + 1));
  1664. EXPECT_EQ(
  1665. remove_whitespace("{\"algorithm\":\"" + algo +
  1666. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1667. remove_whitespace(res->body));
  1668. #else
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. #endif
  1672. EXPECT_EQ(StatusCode::OK_200, res->status);
  1673. }
  1674. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1675. cli.set_digest_auth("hello", "bad");
  1676. for (const auto &path : paths) {
  1677. auto res = cli.Get(path.c_str());
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. #endif
  1682. }
  1683. }
  1684. #endif
  1685. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1686. auto host = "google.com";
  1687. auto another_host = "example.com";
  1688. auto wrong_ip = "0.0.0.0";
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. SSLClient cli(host);
  1691. #else
  1692. Client cli(host);
  1693. #endif
  1694. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1695. auto res = cli.Get("/");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1698. }
  1699. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1700. auto host = "google.com";
  1701. auto wrong_ip = "0.0.0.0";
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_hostname_addr_map({{host, wrong_ip}});
  1708. auto res = cli.Get("/");
  1709. ASSERT_TRUE(!res);
  1710. EXPECT_EQ(Error::Connection, res.error());
  1711. }
  1712. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_SSL_ENABLED
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(StatusCode::OK_200, res->status);
  1723. }
  1724. TEST(RedirectTest, Redirect_Online) {
  1725. auto host = "nghttp2.org";
  1726. #ifdef CPPHTTPLIB_SSL_ENABLED
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_follow_location(true);
  1732. auto res = cli.Get("/httpbin/redirect/3");
  1733. ASSERT_TRUE(res);
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. TEST(RelativeRedirectTest, Redirect_Online) {
  1737. auto host = "nghttp2.org";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_follow_location(true);
  1744. auto res = cli.Get("/httpbin/relative-redirect/3");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. }
  1748. TEST(TooManyRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_SSL_ENABLED
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/redirect/21");
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1759. }
  1760. #ifdef CPPHTTPLIB_SSL_ENABLED
  1761. TEST(YahooRedirectTest, Redirect_Online) {
  1762. Client cli("yahoo.com");
  1763. auto res = cli.Get("/");
  1764. ASSERT_TRUE(res);
  1765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1766. cli.set_follow_location(true);
  1767. res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1771. }
  1772. #endif
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1775. #define REDIR_HOST "httpbingo.org"
  1776. #define REDIR_PATH "/redirect-to"
  1777. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1778. SSLClient cli(REDIR_HOST);
  1779. cli.set_follow_location(true);
  1780. auto res =
  1781. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. params.emplace("status_code", "302");
  1791. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1792. ASSERT_TRUE(res);
  1793. EXPECT_EQ(StatusCode::OK_200, res->status);
  1794. }
  1795. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1796. SSLClient cli(REDIR_HOST);
  1797. cli.set_follow_location(true);
  1798. Params params;
  1799. params.emplace("url", "http://example.com");
  1800. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(StatusCode::OK_200, res->status);
  1803. }
  1804. #endif
  1805. #ifdef CPPHTTPLIB_SSL_ENABLED
  1806. TEST(UrlWithSpace, Redirect_Online) {
  1807. SSLClient cli("edge.forgecdn.net");
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::OK_200, res->status);
  1812. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1813. }
  1814. #endif
  1815. #if !defined(_WIN32) && !defined(_WIN64)
  1816. TEST(ReceiveSignals, Signal) {
  1817. auto setupSignalHandlers = []() {
  1818. struct sigaction act;
  1819. sigemptyset(&act.sa_mask);
  1820. act.sa_flags = SA_SIGINFO;
  1821. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1822. switch (sig) {
  1823. case SIGINT:
  1824. default: break;
  1825. }
  1826. };
  1827. ::sigaction(SIGINT, &act, nullptr);
  1828. };
  1829. Server svr;
  1830. int port = 0;
  1831. auto thread = std::thread([&]() {
  1832. setupSignalHandlers();
  1833. port = svr.bind_to_any_port(HOST);
  1834. svr.listen_after_bind();
  1835. });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. thread.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. ASSERT_TRUE(svr.is_running());
  1843. pthread_kill(thread.native_handle(), SIGINT);
  1844. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1845. ASSERT_TRUE(svr.is_running());
  1846. }
  1847. #endif
  1848. TEST(RedirectToDifferentPort, Redirect) {
  1849. Server svr1;
  1850. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. int svr1_port = 0;
  1854. auto thread1 = std::thread([&]() {
  1855. svr1_port = svr1.bind_to_any_port(HOST);
  1856. svr1.listen_after_bind();
  1857. });
  1858. Server svr2;
  1859. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1860. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1861. });
  1862. int svr2_port = 0;
  1863. auto thread2 = std::thread([&]() {
  1864. svr2_port = svr2.bind_to_any_port(HOST);
  1865. svr2.listen_after_bind();
  1866. });
  1867. auto se = detail::scope_exit([&] {
  1868. svr2.stop();
  1869. thread2.join();
  1870. svr1.stop();
  1871. thread1.join();
  1872. ASSERT_FALSE(svr2.is_running());
  1873. ASSERT_FALSE(svr1.is_running());
  1874. });
  1875. svr1.wait_until_ready();
  1876. svr2.wait_until_ready();
  1877. Client cli("localhost", svr2_port);
  1878. cli.set_follow_location(true);
  1879. auto res = cli.Get("/2");
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::OK_200, res->status);
  1882. EXPECT_EQ("Hello World!", res->body);
  1883. }
  1884. TEST(RedirectFromPageWithContent, Redirect) {
  1885. Server svr;
  1886. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("___", "text/plain");
  1888. res.set_redirect("/2");
  1889. });
  1890. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1891. res.set_content("Hello World!", "text/plain");
  1892. });
  1893. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1894. auto se = detail::scope_exit([&] {
  1895. svr.stop();
  1896. th.join();
  1897. ASSERT_FALSE(svr.is_running());
  1898. });
  1899. svr.wait_until_ready();
  1900. {
  1901. Client cli("localhost", PORT);
  1902. cli.set_follow_location(true);
  1903. std::string body;
  1904. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1905. body.append(data, data_length);
  1906. return true;
  1907. });
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(StatusCode::OK_200, res->status);
  1910. EXPECT_EQ("Hello World!", body);
  1911. }
  1912. {
  1913. Client cli("localhost", PORT);
  1914. std::string body;
  1915. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1916. body.append(data, data_length);
  1917. return true;
  1918. });
  1919. ASSERT_TRUE(res);
  1920. EXPECT_EQ(StatusCode::Found_302, res->status);
  1921. EXPECT_EQ("___", body);
  1922. }
  1923. }
  1924. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1925. Server svr;
  1926. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1927. res.set_content("___", "text/plain");
  1928. // res.set_redirect("/2");
  1929. res.set_redirect("http://[::1]:1234/2");
  1930. });
  1931. svr.Get("/2", [&](const Request &req, Response &res) {
  1932. auto host_header = req.headers.find("Host");
  1933. ASSERT_TRUE(host_header != req.headers.end());
  1934. EXPECT_EQ("[::1]:1234", host_header->second);
  1935. res.set_content("Hello World!", "text/plain");
  1936. });
  1937. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1938. auto se = detail::scope_exit([&] {
  1939. svr.stop();
  1940. th.join();
  1941. ASSERT_FALSE(svr.is_running());
  1942. });
  1943. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1944. // actually starts anything, so the condition !svr.is_running() will
  1945. // always remain true, and the loop never stops.
  1946. // This basically counts how many milliseconds have passed since the
  1947. // call to svr.listen(), and if after 5 seconds nothing started yet
  1948. // aborts the test.
  1949. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1950. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1951. ASSERT_LT(milliseconds, 5000U);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. cli.set_follow_location(true);
  1956. std::string body;
  1957. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1958. body.append(data, data_length);
  1959. return true;
  1960. });
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ("Hello World!", body);
  1964. }
  1965. {
  1966. Client cli("http://[::1]:1234");
  1967. std::string body;
  1968. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1969. body.append(data, data_length);
  1970. return true;
  1971. });
  1972. ASSERT_TRUE(res);
  1973. EXPECT_EQ(StatusCode::Found_302, res->status);
  1974. EXPECT_EQ("___", body);
  1975. }
  1976. }
  1977. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1978. Server svr;
  1979. svr.Get("/foo", [](const Request &req, Response &res) {
  1980. auto a = req.params.find("a");
  1981. if (a != req.params.end()) {
  1982. res.set_content((*a).second, "text/plain");
  1983. res.status = StatusCode::OK_200;
  1984. } else {
  1985. res.status = StatusCode::BadRequest_400;
  1986. }
  1987. });
  1988. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1989. auto se = detail::scope_exit([&] {
  1990. svr.stop();
  1991. thread.join();
  1992. ASSERT_FALSE(svr.is_running());
  1993. });
  1994. svr.wait_until_ready();
  1995. {
  1996. Client cli(HOST, PORT);
  1997. cli.set_path_encode(false);
  1998. auto res = cli.Get("/foo?a=explicitly+encoded");
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(StatusCode::OK_200, res->status);
  2001. // This expects it back with a space, as the `+` won't have been
  2002. // url-encoded, and server-side the params get decoded turning `+`
  2003. // into spaces.
  2004. EXPECT_EQ("explicitly encoded", res->body);
  2005. }
  2006. }
  2007. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2008. Server svr;
  2009. svr.Get("/", [](const Request &req, Response &) {
  2010. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2011. });
  2012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. thread.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli(HOST, PORT);
  2021. cli.set_path_encode(false);
  2022. auto res = cli.Get("/?something=%0A");
  2023. ASSERT_TRUE(res);
  2024. EXPECT_EQ(StatusCode::OK_200, res->status);
  2025. }
  2026. }
  2027. TEST(BindServerTest, DISABLED_BindDualStack) {
  2028. Server svr;
  2029. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2030. res.set_content("Hello World!", "text/plain");
  2031. });
  2032. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2033. auto se = detail::scope_exit([&] {
  2034. svr.stop();
  2035. thread.join();
  2036. ASSERT_FALSE(svr.is_running());
  2037. });
  2038. svr.wait_until_ready();
  2039. {
  2040. Client cli("127.0.0.1", PORT);
  2041. auto res = cli.Get("/1");
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(StatusCode::OK_200, res->status);
  2044. EXPECT_EQ("Hello World!", res->body);
  2045. }
  2046. {
  2047. Client cli("::1", PORT);
  2048. auto res = cli.Get("/1");
  2049. ASSERT_TRUE(res);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. EXPECT_EQ("Hello World!", res->body);
  2052. }
  2053. }
  2054. TEST(BindServerTest, BindAndListenSeparately) {
  2055. Server svr;
  2056. int port = svr.bind_to_any_port("0.0.0.0");
  2057. ASSERT_TRUE(svr.is_valid());
  2058. ASSERT_TRUE(port > 0);
  2059. svr.stop();
  2060. }
  2061. #ifdef CPPHTTPLIB_SSL_ENABLED
  2062. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2064. CLIENT_CA_CERT_DIR);
  2065. int port = svr.bind_to_any_port("0.0.0.0");
  2066. ASSERT_TRUE(svr.is_valid());
  2067. ASSERT_TRUE(port > 0);
  2068. svr.stop();
  2069. }
  2070. #endif
  2071. #ifdef CPPHTTPLIB_SSL_ENABLED
  2072. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2073. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2074. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2075. int port = svr.bind_to_any_port("0.0.0.0");
  2076. ASSERT_TRUE(svr.is_valid());
  2077. ASSERT_TRUE(port > 0);
  2078. svr.stop();
  2079. }
  2080. #endif
  2081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2082. X509 *readCertificate(const std::string &strFileName) {
  2083. std::ifstream inStream(strFileName);
  2084. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2085. std::istreambuf_iterator<char>());
  2086. if (strCertPEM.empty()) return (nullptr);
  2087. BIO *pbCert = BIO_new(BIO_s_mem());
  2088. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2089. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2090. BIO_free(pbCert);
  2091. return (pCert);
  2092. }
  2093. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2094. std::ifstream inStream(strFileName);
  2095. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2096. std::istreambuf_iterator<char>());
  2097. if (strPrivateKeyPEM.empty()) return (nullptr);
  2098. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2099. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2100. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2101. BIO_free(pbPrivKey);
  2102. return (pPrivateKey);
  2103. }
  2104. TEST(BindServerTest, UpdateCerts) {
  2105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2106. int port = svr.bind_to_any_port("0.0.0.0");
  2107. ASSERT_TRUE(svr.is_valid());
  2108. ASSERT_TRUE(port > 0);
  2109. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2110. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2111. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2112. ASSERT_TRUE(cert != nullptr);
  2113. ASSERT_TRUE(ca_cert != nullptr);
  2114. ASSERT_TRUE(key != nullptr);
  2115. X509_STORE *cert_store = X509_STORE_new();
  2116. X509_STORE_add_cert(cert_store, ca_cert);
  2117. svr.update_certs(cert, key, cert_store);
  2118. ASSERT_TRUE(svr.is_valid());
  2119. svr.stop();
  2120. X509_free(cert);
  2121. X509_free(ca_cert);
  2122. EVP_PKEY_free(key);
  2123. }
  2124. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  2125. // client CA list correctly for TLS handshake
  2126. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  2127. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2128. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2129. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2130. ASSERT_TRUE(cert != nullptr);
  2131. ASSERT_TRUE(ca_cert != nullptr);
  2132. ASSERT_TRUE(key != nullptr);
  2133. X509_STORE *cert_store = X509_STORE_new();
  2134. X509_STORE_add_cert(cert_store, ca_cert);
  2135. // Use X509-based constructor (deprecated but should still work correctly)
  2136. #pragma GCC diagnostic push
  2137. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  2138. SSLServer svr(cert, key, cert_store);
  2139. #pragma GCC diagnostic pop
  2140. ASSERT_TRUE(svr.is_valid());
  2141. // Verify that client CA list is set in SSL_CTX
  2142. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  2143. ASSERT_TRUE(ssl_ctx != nullptr);
  2144. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  2145. ASSERT_TRUE(ca_list != nullptr);
  2146. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  2147. X509_free(cert);
  2148. X509_free(ca_cert);
  2149. EVP_PKEY_free(key);
  2150. }
  2151. // Test that update_certs() updates client CA list correctly
  2152. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  2153. // Start with file-based constructor
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2155. ASSERT_TRUE(svr.is_valid());
  2156. // Initially no client CA list should be set
  2157. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  2158. ASSERT_TRUE(ssl_ctx != nullptr);
  2159. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  2160. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  2161. EXPECT_EQ(0, count_before);
  2162. // Now update with client CA
  2163. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2164. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2165. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2166. ASSERT_TRUE(cert != nullptr);
  2167. ASSERT_TRUE(ca_cert != nullptr);
  2168. ASSERT_TRUE(key != nullptr);
  2169. X509_STORE *cert_store = X509_STORE_new();
  2170. X509_STORE_add_cert(cert_store, ca_cert);
  2171. #pragma GCC diagnostic push
  2172. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  2173. svr.update_certs(cert, key, cert_store);
  2174. #pragma GCC diagnostic pop
  2175. ASSERT_TRUE(svr.is_valid());
  2176. // Now client CA list should be set
  2177. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  2178. ASSERT_TRUE(ca_list_after != nullptr);
  2179. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  2180. X509_free(cert);
  2181. X509_free(ca_cert);
  2182. EVP_PKEY_free(key);
  2183. }
  2184. #endif
  2185. TEST(ErrorHandlerTest, ContentLength) {
  2186. Server svr;
  2187. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2188. res.status = StatusCode::OK_200;
  2189. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2190. "text/html"); // <= Content-Length still 13
  2191. });
  2192. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!\n", "text/plain");
  2194. res.status = 524;
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2206. ASSERT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::OK_200, res->status);
  2208. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2209. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2211. }
  2212. }
  2213. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2214. TEST(ExceptionTest, WithoutExceptionHandler) {
  2215. Server svr;
  2216. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2217. throw std::runtime_error("exception...");
  2218. });
  2219. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2220. throw std::runtime_error("exception\r\n...");
  2221. });
  2222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2223. auto se = detail::scope_exit([&] {
  2224. svr.stop();
  2225. listen_thread.join();
  2226. ASSERT_FALSE(svr.is_running());
  2227. });
  2228. svr.wait_until_ready();
  2229. Client cli("localhost", PORT);
  2230. {
  2231. auto res = cli.Get("/exception");
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2234. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2235. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2236. }
  2237. {
  2238. auto res = cli.Get("/unknown");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2241. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2242. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2243. }
  2244. }
  2245. TEST(ExceptionTest, WithExceptionHandler) {
  2246. Server svr;
  2247. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2248. std::exception_ptr ep) {
  2249. EXPECT_FALSE(ep == nullptr);
  2250. try {
  2251. std::rethrow_exception(ep);
  2252. } catch (std::exception &e) {
  2253. EXPECT_EQ("abc", std::string(e.what()));
  2254. } catch (...) {}
  2255. res.status = StatusCode::InternalServerError_500;
  2256. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2257. "text/html"); // <= Content-Length still 13 at this point
  2258. });
  2259. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2260. res.set_content("Hello World!\n", "text/plain");
  2261. throw std::runtime_error("abc");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. for (size_t i = 0; i < 10; i++) {
  2271. Client cli(HOST, PORT);
  2272. for (size_t j = 0; j < 100; j++) {
  2273. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2274. ASSERT_TRUE(res);
  2275. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2277. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2279. }
  2280. cli.set_keep_alive(true);
  2281. for (size_t j = 0; j < 100; j++) {
  2282. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2283. ASSERT_TRUE(res);
  2284. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2285. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2286. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2288. }
  2289. }
  2290. }
  2291. TEST(ExceptionTest, AndErrorHandler) {
  2292. Server svr;
  2293. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2294. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2295. });
  2296. svr.set_exception_handler(
  2297. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2298. EXPECT_FALSE(ep == nullptr);
  2299. try {
  2300. std::rethrow_exception(ep);
  2301. } catch (std::exception &e) {
  2302. res.set_content(e.what(), "text/html");
  2303. } catch (...) {}
  2304. res.status = StatusCode::InternalServerError_500;
  2305. });
  2306. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2307. throw std::runtime_error("EXCEPTION");
  2308. });
  2309. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2310. res.set_content("ERROR", "text/html");
  2311. res.status = StatusCode::InternalServerError_500;
  2312. });
  2313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2314. auto se = detail::scope_exit([&] {
  2315. svr.stop();
  2316. thread.join();
  2317. ASSERT_FALSE(svr.is_running());
  2318. });
  2319. svr.wait_until_ready();
  2320. Client cli(HOST, PORT);
  2321. {
  2322. auto res = cli.Get("/exception");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2325. EXPECT_EQ("EXCEPTION", res->body);
  2326. }
  2327. {
  2328. auto res = cli.Get("/error");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2331. EXPECT_EQ("ERROR", res->body);
  2332. }
  2333. {
  2334. auto res = cli.Get("/invalid");
  2335. ASSERT_TRUE(res);
  2336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2337. EXPECT_EQ("NOT_FOUND", res->body);
  2338. }
  2339. }
  2340. #endif
  2341. TEST(NoContentTest, ContentLength) {
  2342. Server svr;
  2343. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2344. res.status = StatusCode::NoContent_204;
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. {
  2354. Client cli(HOST, PORT);
  2355. auto res = cli.Get("/hi");
  2356. ASSERT_TRUE(res);
  2357. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2358. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2359. }
  2360. }
  2361. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2362. #ifdef CPPHTTPLIB_SSL_ENABLED
  2363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2364. ASSERT_TRUE(svr.is_valid());
  2365. #else
  2366. Server svr;
  2367. #endif
  2368. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2369. if (req.path == "/routing_handler") {
  2370. res.set_header("PRE_ROUTING", "on");
  2371. res.set_content("Routing Handler", "text/plain");
  2372. return httplib::Server::HandlerResponse::Handled;
  2373. }
  2374. return httplib::Server::HandlerResponse::Unhandled;
  2375. });
  2376. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2377. res.set_content("Error", "text/html");
  2378. });
  2379. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2380. if (req.path == "/routing_handler") {
  2381. res.set_header("POST_ROUTING", "on");
  2382. }
  2383. });
  2384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2385. res.set_content("Hello World!\n", "text/plain");
  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. {
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. SSLClient cli(HOST, PORT);
  2397. cli.enable_server_certificate_verification(false);
  2398. #else
  2399. Client cli(HOST, PORT);
  2400. #endif
  2401. auto res = cli.Get("/routing_handler");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. EXPECT_EQ("Routing Handler", res->body);
  2405. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2406. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2407. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2408. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2409. }
  2410. {
  2411. #ifdef CPPHTTPLIB_SSL_ENABLED
  2412. SSLClient cli(HOST, PORT);
  2413. cli.enable_server_certificate_verification(false);
  2414. #else
  2415. Client cli(HOST, PORT);
  2416. #endif
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. EXPECT_EQ("Hello World!\n", res->body);
  2421. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2422. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2423. }
  2424. {
  2425. #ifdef CPPHTTPLIB_SSL_ENABLED
  2426. SSLClient cli(HOST, PORT);
  2427. cli.enable_server_certificate_verification(false);
  2428. #else
  2429. Client cli(HOST, PORT);
  2430. #endif
  2431. auto res = cli.Get("/aaa");
  2432. ASSERT_TRUE(res);
  2433. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2434. EXPECT_EQ("Error", res->body);
  2435. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2436. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2437. }
  2438. }
  2439. TEST(RequestHandlerTest, PreRequestHandler) {
  2440. auto route_path = "/user/:user";
  2441. Server svr;
  2442. svr.Get("/hi", [](const Request &, Response &res) {
  2443. res.set_content("hi", "text/plain");
  2444. });
  2445. svr.Get(route_path, [](const Request &req, Response &res) {
  2446. res.set_content(req.path_params.at("user"), "text/plain");
  2447. });
  2448. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2449. if (req.matched_route == route_path) {
  2450. auto user = req.path_params.at("user");
  2451. if (user != "john") {
  2452. res.status = StatusCode::Forbidden_403;
  2453. res.set_content("error", "text/html");
  2454. return Server::HandlerResponse::Handled;
  2455. }
  2456. }
  2457. return Server::HandlerResponse::Unhandled;
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. {
  2468. auto res = cli.Get("/hi");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("hi", res->body);
  2472. }
  2473. {
  2474. auto res = cli.Get("/user/john");
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::OK_200, res->status);
  2477. EXPECT_EQ("john", res->body);
  2478. }
  2479. {
  2480. auto res = cli.Get("/user/invalid-user");
  2481. ASSERT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2483. EXPECT_EQ("error", res->body);
  2484. }
  2485. }
  2486. TEST(InvalidFormatTest, StatusCode) {
  2487. Server svr;
  2488. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2489. res.set_content("Hello World!\n", "text/plain");
  2490. res.status = 9999; // Status should be a three-digit code...
  2491. });
  2492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2493. auto se = detail::scope_exit([&] {
  2494. svr.stop();
  2495. thread.join();
  2496. ASSERT_FALSE(svr.is_running());
  2497. });
  2498. svr.wait_until_ready();
  2499. {
  2500. Client cli(HOST, PORT);
  2501. auto res = cli.Get("/hi");
  2502. ASSERT_FALSE(res);
  2503. }
  2504. }
  2505. TEST(URLFragmentTest, WithFragment) {
  2506. Server svr;
  2507. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2508. EXPECT_TRUE(req.target == "/hi");
  2509. });
  2510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2511. auto se = detail::scope_exit([&] {
  2512. svr.stop();
  2513. thread.join();
  2514. ASSERT_FALSE(svr.is_running());
  2515. });
  2516. svr.wait_until_ready();
  2517. {
  2518. Client cli(HOST, PORT);
  2519. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2520. EXPECT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. res = cli.Get("/hi%23key1=val1=key2=val2");
  2523. EXPECT_TRUE(res);
  2524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2525. }
  2526. }
  2527. TEST(HeaderWriter, SetHeaderWriter) {
  2528. Server svr;
  2529. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2530. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2531. return detail::write_headers(strm, hdrs);
  2532. });
  2533. svr.Get("/hi", [](const Request &req, Response &res) {
  2534. auto it = req.headers.find("CustomClientHeader");
  2535. EXPECT_TRUE(it != req.headers.end());
  2536. EXPECT_EQ(it->second, "CustomClientValue");
  2537. res.set_content("Hello World!\n", "text/plain");
  2538. });
  2539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2540. auto se = detail::scope_exit([&] {
  2541. svr.stop();
  2542. thread.join();
  2543. ASSERT_FALSE(svr.is_running());
  2544. });
  2545. svr.wait_until_ready();
  2546. {
  2547. Client cli(HOST, PORT);
  2548. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2549. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2550. return detail::write_headers(strm, hdrs);
  2551. });
  2552. auto res = cli.Get("/hi");
  2553. EXPECT_TRUE(res);
  2554. EXPECT_EQ(StatusCode::OK_200, res->status);
  2555. auto it = res->headers.find("CustomServerHeader");
  2556. EXPECT_TRUE(it != res->headers.end());
  2557. EXPECT_EQ(it->second, "CustomServerValue");
  2558. }
  2559. }
  2560. class ServerTest : public ::testing::Test {
  2561. protected:
  2562. ServerTest()
  2563. : cli_(HOST, PORT)
  2564. #ifdef CPPHTTPLIB_SSL_ENABLED
  2565. ,
  2566. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2567. #endif
  2568. {
  2569. #ifdef CPPHTTPLIB_SSL_ENABLED
  2570. cli_.enable_server_certificate_verification(false);
  2571. #endif
  2572. }
  2573. virtual void SetUp() {
  2574. svr_.set_mount_point("/", "./www");
  2575. svr_.set_mount_point("/mount", "./www2");
  2576. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2577. svr_.Get("/hi",
  2578. [&](const Request & /*req*/, Response &res) {
  2579. res.set_content("Hello World!", "text/plain");
  2580. })
  2581. .Get("/file_content",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. res.set_file_content("./www/dir/test.html");
  2584. })
  2585. .Get("/file_content_with_content_type",
  2586. [&](const Request & /*req*/, Response &res) {
  2587. res.set_file_content("./www/file", "text/plain");
  2588. })
  2589. .Get("/invalid_file_content",
  2590. [&](const Request & /*req*/, Response &res) {
  2591. res.set_file_content("./www/dir/invalid_file_path");
  2592. })
  2593. .Get("/http_response_splitting",
  2594. [&](const Request & /*req*/, Response &res) {
  2595. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2596. EXPECT_EQ(0U, res.headers.size());
  2597. EXPECT_FALSE(res.has_header("a"));
  2598. res.set_header("a", "1\nSet-Cookie: a=1");
  2599. EXPECT_EQ(0U, res.headers.size());
  2600. EXPECT_FALSE(res.has_header("a"));
  2601. res.set_header("a", "1\rSet-Cookie: a=1");
  2602. EXPECT_EQ(0U, res.headers.size());
  2603. EXPECT_FALSE(res.has_header("a"));
  2604. res.set_header("a\r\nb", "0");
  2605. EXPECT_EQ(0U, res.headers.size());
  2606. EXPECT_FALSE(res.has_header("a"));
  2607. res.set_header("a\rb", "0");
  2608. EXPECT_EQ(0U, res.headers.size());
  2609. EXPECT_FALSE(res.has_header("a"));
  2610. res.set_header("a\nb", "0");
  2611. EXPECT_EQ(0U, res.headers.size());
  2612. EXPECT_FALSE(res.has_header("a"));
  2613. res.set_redirect("1\r\nSet-Cookie: a=1");
  2614. EXPECT_EQ(0U, res.headers.size());
  2615. EXPECT_FALSE(res.has_header("Location"));
  2616. })
  2617. .Get("/slow",
  2618. [&](const Request & /*req*/, Response &res) {
  2619. std::this_thread::sleep_for(std::chrono::seconds(2));
  2620. res.set_content("slow", "text/plain");
  2621. })
  2622. #if 0
  2623. .Post("/slowpost",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. std::this_thread::sleep_for(std::chrono::seconds(2));
  2626. res.set_content("slow", "text/plain");
  2627. })
  2628. #endif
  2629. .Get("/remote_addr",
  2630. [&](const Request &req, Response &res) {
  2631. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2632. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2633. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2634. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2635. res.set_content(req.remote_addr, "text/plain");
  2636. })
  2637. .Get("/local_addr",
  2638. [&](const Request &req, Response &res) {
  2639. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2640. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2641. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2642. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2643. auto local_addr = req.local_addr;
  2644. auto local_port = std::to_string(req.local_port);
  2645. res.set_content(local_addr.append(":").append(local_port),
  2646. "text/plain");
  2647. })
  2648. .Get("/endwith%",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_content("Hello World!", "text/plain");
  2651. })
  2652. .Get("/a\\+\\+b",
  2653. [&](const Request &req, Response &res) {
  2654. ASSERT_TRUE(req.has_param("a +b"));
  2655. auto val = req.get_param_value("a +b");
  2656. res.set_content(val, "text/plain");
  2657. })
  2658. .Get("/", [&](const Request & /*req*/,
  2659. Response &res) { res.set_redirect("/hi"); })
  2660. .Post("/1",
  2661. [](const Request & /*req*/, Response &res) {
  2662. res.set_redirect("/2", StatusCode::SeeOther_303);
  2663. })
  2664. .Get("/2",
  2665. [](const Request & /*req*/, Response &res) {
  2666. res.set_content("redirected.", "text/plain");
  2667. res.status = StatusCode::OK_200;
  2668. })
  2669. .Post("/person",
  2670. [&](const Request &req, Response &res) {
  2671. if (req.has_param("name") && req.has_param("note")) {
  2672. persons_[req.get_param_value("name")] =
  2673. req.get_param_value("note");
  2674. } else {
  2675. res.status = StatusCode::BadRequest_400;
  2676. }
  2677. })
  2678. .Put("/person",
  2679. [&](const Request &req, Response &res) {
  2680. if (req.has_param("name") && req.has_param("note")) {
  2681. persons_[req.get_param_value("name")] =
  2682. req.get_param_value("note");
  2683. } else {
  2684. res.status = StatusCode::BadRequest_400;
  2685. }
  2686. })
  2687. .Get("/person/(.*)",
  2688. [&](const Request &req, Response &res) {
  2689. string name = req.matches[1];
  2690. if (persons_.find(name) != persons_.end()) {
  2691. auto note = persons_[name];
  2692. res.set_content(note, "text/plain");
  2693. } else {
  2694. res.status = StatusCode::NotFound_404;
  2695. }
  2696. })
  2697. .Delete("/person",
  2698. [&](const Request &req, Response &res) {
  2699. if (req.has_param("name")) {
  2700. string name = req.get_param_value("name");
  2701. if (persons_.find(name) != persons_.end()) {
  2702. persons_.erase(name);
  2703. res.set_content("DELETED", "text/plain");
  2704. } else {
  2705. res.status = StatusCode::NotFound_404;
  2706. }
  2707. } else {
  2708. res.status = StatusCode::BadRequest_400;
  2709. }
  2710. })
  2711. .Post("/x-www-form-urlencoded-json",
  2712. [&](const Request &req, Response &res) {
  2713. auto json = req.get_param_value("json");
  2714. ASSERT_EQ(JSON_DATA, json);
  2715. res.set_content(json, "appliation/json");
  2716. res.status = StatusCode::OK_200;
  2717. })
  2718. .Get("/streamed-chunked",
  2719. [&](const Request & /*req*/, Response &res) {
  2720. res.set_chunked_content_provider(
  2721. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2722. sink.os << "123";
  2723. sink.os << "456";
  2724. sink.os << "789";
  2725. sink.done();
  2726. return true;
  2727. });
  2728. })
  2729. .Get("/streamed-chunked-with-prohibited-trailer",
  2730. [&](const Request & /*req*/, Response &res) {
  2731. auto i = new int(0);
  2732. // Declare both a prohibited trailer (Content-Length) and an
  2733. // allowed one
  2734. res.set_header("Trailer", "Content-Length, X-Allowed");
  2735. res.set_chunked_content_provider(
  2736. "text/plain",
  2737. [i](size_t /*offset*/, DataSink &sink) {
  2738. switch (*i) {
  2739. case 0: sink.os << "123"; break;
  2740. case 1: sink.os << "456"; break;
  2741. case 2: sink.os << "789"; break;
  2742. case 3: {
  2743. sink.done_with_trailer(
  2744. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2745. } break;
  2746. }
  2747. (*i)++;
  2748. return true;
  2749. },
  2750. [i](bool success) {
  2751. EXPECT_TRUE(success);
  2752. delete i;
  2753. });
  2754. })
  2755. .Get("/streamed-chunked2",
  2756. [&](const Request & /*req*/, Response &res) {
  2757. auto i = new int(0);
  2758. res.set_chunked_content_provider(
  2759. "text/plain",
  2760. [i](size_t /*offset*/, DataSink &sink) {
  2761. switch (*i) {
  2762. case 0: sink.os << "123"; break;
  2763. case 1: sink.os << "456"; break;
  2764. case 2: sink.os << "789"; break;
  2765. case 3: sink.done(); break;
  2766. }
  2767. (*i)++;
  2768. return true;
  2769. },
  2770. [i](bool success) {
  2771. EXPECT_TRUE(success);
  2772. delete i;
  2773. });
  2774. })
  2775. .Get("/streamed-chunked-with-trailer",
  2776. [&](const Request & /*req*/, Response &res) {
  2777. auto i = new int(0);
  2778. res.set_header("Trailer", "Dummy1, Dummy2");
  2779. res.set_chunked_content_provider(
  2780. "text/plain",
  2781. [i](size_t /*offset*/, DataSink &sink) {
  2782. switch (*i) {
  2783. case 0: sink.os << "123"; break;
  2784. case 1: sink.os << "456"; break;
  2785. case 2: sink.os << "789"; break;
  2786. case 3: {
  2787. sink.done_with_trailer(
  2788. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2789. } break;
  2790. }
  2791. (*i)++;
  2792. return true;
  2793. },
  2794. [i](bool success) {
  2795. EXPECT_TRUE(success);
  2796. delete i;
  2797. });
  2798. })
  2799. .Get("/streamed",
  2800. [&](const Request & /*req*/, Response &res) {
  2801. res.set_content_provider(
  2802. 6, "text/plain",
  2803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2804. sink.os << (offset < 3 ? "a" : "b");
  2805. return true;
  2806. });
  2807. })
  2808. .Get("/streamed-with-range",
  2809. [&](const Request &req, Response &res) {
  2810. auto data = new std::string("abcdefg");
  2811. res.set_content_provider(
  2812. data->size(), "text/plain",
  2813. [data](size_t offset, size_t length, DataSink &sink) {
  2814. size_t DATA_CHUNK_SIZE = 4;
  2815. const auto &d = *data;
  2816. auto out_len =
  2817. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2818. auto ret =
  2819. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2820. EXPECT_TRUE(ret);
  2821. return true;
  2822. },
  2823. [data, &req](bool success) {
  2824. EXPECT_EQ(success, !req.has_param("error"));
  2825. delete data;
  2826. });
  2827. })
  2828. .Get("/streamed-cancel",
  2829. [&](const Request & /*req*/, Response &res) {
  2830. res.set_content_provider(
  2831. size_t(-1), "text/plain",
  2832. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2833. sink.os << "data_chunk";
  2834. return true;
  2835. });
  2836. })
  2837. .Get("/regex-with-delimiter",
  2838. [&](const Request &req, Response & /*res*/) {
  2839. ASSERT_TRUE(req.has_param("key"));
  2840. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2841. })
  2842. .Get("/with-range",
  2843. [&](const Request & /*req*/, Response &res) {
  2844. res.set_content("abcdefg", "text/plain");
  2845. })
  2846. .Get("/test-start-time",
  2847. [&](const Request &req, Response & /*res*/) {
  2848. EXPECT_NE(req.start_time_,
  2849. std::chrono::steady_clock::time_point::min());
  2850. })
  2851. .Get("/with-range-customized-response",
  2852. [&](const Request & /*req*/, Response &res) {
  2853. res.status = StatusCode::BadRequest_400;
  2854. res.set_content(JSON_DATA, "application/json");
  2855. })
  2856. .Post("/chunked",
  2857. [&](const Request &req, Response & /*res*/) {
  2858. EXPECT_EQ(req.body, "dechunked post body");
  2859. })
  2860. .Post("/large-chunked",
  2861. [&](const Request &req, Response & /*res*/) {
  2862. std::string expected(6 * 30 * 1024u, 'a');
  2863. EXPECT_EQ(req.body, expected);
  2864. })
  2865. .Post("/multipart",
  2866. [&](const Request &req, Response & /*res*/) {
  2867. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2868. req.form.get_field_count("text2") +
  2869. req.form.get_field_count("file3") +
  2870. req.form.get_field_count("file4"));
  2871. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2872. req.form.get_file_count("file2"));
  2873. ASSERT_TRUE(!req.form.has_file("???"));
  2874. ASSERT_TRUE(!req.form.has_field("???"));
  2875. ASSERT_TRUE(req.body.empty());
  2876. {
  2877. const auto &text = req.form.get_field("text1");
  2878. EXPECT_EQ("text default", text);
  2879. }
  2880. {
  2881. const auto &text = req.form.get_field("text2");
  2882. EXPECT_EQ("aωb", text);
  2883. }
  2884. {
  2885. const auto &file = req.form.get_file("file1");
  2886. EXPECT_EQ("hello.txt", file.filename);
  2887. EXPECT_EQ("text/plain", file.content_type);
  2888. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2889. }
  2890. {
  2891. const auto &file = req.form.get_file("file2");
  2892. EXPECT_EQ("world.json", file.filename);
  2893. EXPECT_EQ("application/json", file.content_type);
  2894. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2895. }
  2896. {
  2897. const auto &text = req.form.get_field("file3");
  2898. EXPECT_EQ(0u, text.size());
  2899. }
  2900. {
  2901. const auto &text = req.form.get_field("file4");
  2902. EXPECT_EQ(0u, text.size());
  2903. }
  2904. })
  2905. .Post("/multipart/multi_file_values",
  2906. [&](const Request &req, Response & /*res*/) {
  2907. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2908. req.form.get_field_count("multi_text1"));
  2909. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2910. ASSERT_TRUE(!req.form.has_file("???"));
  2911. ASSERT_TRUE(!req.form.has_field("???"));
  2912. ASSERT_TRUE(req.body.empty());
  2913. {
  2914. const auto &text = req.form.get_field("text");
  2915. EXPECT_EQ("default text", text);
  2916. }
  2917. {
  2918. const auto &text1_values = req.form.get_fields("multi_text1");
  2919. EXPECT_EQ(2u, text1_values.size());
  2920. EXPECT_EQ("aaaaa", text1_values[0]);
  2921. EXPECT_EQ("bbbbb", text1_values[1]);
  2922. }
  2923. {
  2924. const auto &file1_values = req.form.get_files("multi_file1");
  2925. EXPECT_EQ(2u, file1_values.size());
  2926. auto file1 = file1_values[0];
  2927. EXPECT_EQ(file1.filename, "hello.txt");
  2928. EXPECT_EQ(file1.content_type, "text/plain");
  2929. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2930. auto file2 = file1_values[1];
  2931. EXPECT_EQ(file2.filename, "world.json");
  2932. EXPECT_EQ(file2.content_type, "application/json");
  2933. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2934. }
  2935. })
  2936. .Post("/empty",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "");
  2939. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2940. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2941. res.set_content("empty", "text/plain");
  2942. })
  2943. .Post("/empty-no-content-type",
  2944. [&](const Request &req, Response &res) {
  2945. EXPECT_EQ(req.body, "");
  2946. EXPECT_FALSE(req.has_header("Content-Type"));
  2947. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2948. res.set_content("empty-no-content-type", "text/plain");
  2949. })
  2950. .Post("/path-only",
  2951. [&](const Request &req, Response &res) {
  2952. EXPECT_EQ(req.body, "");
  2953. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2954. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2955. res.set_content("path-only", "text/plain");
  2956. })
  2957. .Post("/path-headers-only",
  2958. [&](const Request &req, Response &res) {
  2959. EXPECT_EQ(req.body, "");
  2960. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2961. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2962. EXPECT_EQ("world", req.get_header_value("hello"));
  2963. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2964. res.set_content("path-headers-only", "text/plain");
  2965. })
  2966. .Post("/post-large",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(req.body, LARGE_DATA);
  2969. res.set_content(req.body, "text/plain");
  2970. })
  2971. .Post("/post-loopback",
  2972. [&](const Request &, Response &res,
  2973. ContentReader const &content_reader) {
  2974. std::string body;
  2975. content_reader([&](const char *data, size_t data_length) {
  2976. body.append(data, data_length);
  2977. return true;
  2978. });
  2979. res.set_content(body, "text/plain");
  2980. })
  2981. .Put("/put-loopback",
  2982. [&](const Request &, Response &res,
  2983. ContentReader const &content_reader) {
  2984. std::string body;
  2985. content_reader([&](const char *data, size_t data_length) {
  2986. body.append(data, data_length);
  2987. return true;
  2988. });
  2989. res.set_content(body, "text/plain");
  2990. })
  2991. .Patch("/patch-loopback",
  2992. [&](const Request &, Response &res,
  2993. ContentReader const &content_reader) {
  2994. std::string body;
  2995. content_reader([&](const char *data, size_t data_length) {
  2996. body.append(data, data_length);
  2997. return true;
  2998. });
  2999. res.set_content(body, "text/plain");
  3000. })
  3001. .Put("/empty-no-content-type",
  3002. [&](const Request &req, Response &res) {
  3003. EXPECT_EQ(req.body, "");
  3004. EXPECT_FALSE(req.has_header("Content-Type"));
  3005. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3006. res.set_content("empty-no-content-type", "text/plain");
  3007. })
  3008. .Put("/put",
  3009. [&](const Request &req, Response &res) {
  3010. EXPECT_EQ(req.body, "PUT");
  3011. res.set_content(req.body, "text/plain");
  3012. })
  3013. .Put("/put-large",
  3014. [&](const Request &req, Response &res) {
  3015. EXPECT_EQ(req.body, LARGE_DATA);
  3016. res.set_content(req.body, "text/plain");
  3017. })
  3018. .Patch("/patch",
  3019. [&](const Request &req, Response &res) {
  3020. EXPECT_EQ(req.body, "PATCH");
  3021. res.set_content(req.body, "text/plain");
  3022. })
  3023. .Delete("/delete",
  3024. [&](const Request & /*req*/, Response &res) {
  3025. res.set_content("DELETE", "text/plain");
  3026. })
  3027. .Delete("/delete-body",
  3028. [&](const Request &req, Response &res) {
  3029. EXPECT_EQ(req.body, "content");
  3030. res.set_content(req.body, "text/plain");
  3031. })
  3032. .Options(R"(\*)",
  3033. [&](const Request & /*req*/, Response &res) {
  3034. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3035. })
  3036. .Get("/request-target",
  3037. [&](const Request &req, Response & /*res*/) {
  3038. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3039. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3040. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3041. })
  3042. .Get("/long-query-value",
  3043. [&](const Request &req, Response & /*res*/) {
  3044. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3045. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3046. })
  3047. .Get("/too-long-query-value",
  3048. [&](const Request &req, Response & /*res*/) {
  3049. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3050. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3051. })
  3052. .Get("/array-param",
  3053. [&](const Request &req, Response & /*res*/) {
  3054. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3055. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3056. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3057. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3058. })
  3059. .Post("/validate-no-multiple-headers",
  3060. [&](const Request &req, Response & /*res*/) {
  3061. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3062. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3063. })
  3064. .Post("/content_receiver",
  3065. [&](const Request &req, Response &res,
  3066. const ContentReader &content_reader) {
  3067. if (req.is_multipart_form_data()) {
  3068. std::vector<FormData> items;
  3069. content_reader(
  3070. [&](const FormData &file) {
  3071. items.push_back(file);
  3072. return true;
  3073. },
  3074. [&](const char *data, size_t data_length) {
  3075. items.back().content.append(data, data_length);
  3076. return true;
  3077. });
  3078. EXPECT_EQ(5u, items.size());
  3079. {
  3080. const auto &file = get_file_value(items, "text1");
  3081. EXPECT_TRUE(file.filename.empty());
  3082. EXPECT_EQ("text default", file.content);
  3083. }
  3084. {
  3085. const auto &file = get_file_value(items, "text2");
  3086. EXPECT_TRUE(file.filename.empty());
  3087. EXPECT_EQ("aωb", file.content);
  3088. }
  3089. {
  3090. const auto &file = get_file_value(items, "file1");
  3091. EXPECT_EQ("hello.txt", file.filename);
  3092. EXPECT_EQ("text/plain", file.content_type);
  3093. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3094. }
  3095. {
  3096. const auto &file = get_file_value(items, "file2");
  3097. EXPECT_EQ("world.json", file.filename);
  3098. EXPECT_EQ("application/json", file.content_type);
  3099. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3100. }
  3101. {
  3102. const auto &file = get_file_value(items, "file3");
  3103. EXPECT_TRUE(file.filename.empty());
  3104. EXPECT_EQ("application/octet-stream", file.content_type);
  3105. EXPECT_EQ(0u, file.content.size());
  3106. }
  3107. } else {
  3108. std::string body;
  3109. content_reader([&](const char *data, size_t data_length) {
  3110. EXPECT_EQ(7U, data_length);
  3111. body.append(data, data_length);
  3112. return true;
  3113. });
  3114. EXPECT_EQ(body, "content");
  3115. res.set_content(body, "text/plain");
  3116. }
  3117. })
  3118. .Put("/content_receiver",
  3119. [&](const Request & /*req*/, Response &res,
  3120. const ContentReader &content_reader) {
  3121. std::string body;
  3122. content_reader([&](const char *data, size_t data_length) {
  3123. body.append(data, data_length);
  3124. return true;
  3125. });
  3126. EXPECT_EQ(body, "content");
  3127. res.set_content(body, "text/plain");
  3128. })
  3129. .Patch("/content_receiver",
  3130. [&](const Request & /*req*/, Response &res,
  3131. const ContentReader &content_reader) {
  3132. std::string body;
  3133. content_reader([&](const char *data, size_t data_length) {
  3134. body.append(data, data_length);
  3135. return true;
  3136. });
  3137. EXPECT_EQ(body, "content");
  3138. res.set_content(body, "text/plain");
  3139. })
  3140. .Post("/query-string-and-body",
  3141. [&](const Request &req, Response & /*res*/) {
  3142. ASSERT_TRUE(req.has_param("key"));
  3143. EXPECT_EQ(req.get_param_value("key"), "value");
  3144. EXPECT_EQ(req.body, "content");
  3145. })
  3146. .Get("/last-request",
  3147. [&](const Request &req, Response & /*res*/) {
  3148. EXPECT_EQ("close", req.get_header_value("Connection"));
  3149. })
  3150. .Get(R"(/redirect/(\d+))",
  3151. [&](const Request &req, Response &res) {
  3152. auto num = std::stoi(req.matches[1]) + 1;
  3153. std::string url = "/redirect/" + std::to_string(num);
  3154. res.set_redirect(url);
  3155. })
  3156. .Post("/binary",
  3157. [&](const Request &req, Response &res) {
  3158. EXPECT_EQ(4U, req.body.size());
  3159. EXPECT_EQ("application/octet-stream",
  3160. req.get_header_value("Content-Type"));
  3161. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3162. res.set_content(req.body, "application/octet-stream");
  3163. })
  3164. .Put("/binary",
  3165. [&](const Request &req, Response &res) {
  3166. EXPECT_EQ(4U, req.body.size());
  3167. EXPECT_EQ("application/octet-stream",
  3168. req.get_header_value("Content-Type"));
  3169. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3170. res.set_content(req.body, "application/octet-stream");
  3171. })
  3172. .Patch("/binary",
  3173. [&](const Request &req, Response &res) {
  3174. EXPECT_EQ(4U, req.body.size());
  3175. EXPECT_EQ("application/octet-stream",
  3176. req.get_header_value("Content-Type"));
  3177. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3178. res.set_content(req.body, "application/octet-stream");
  3179. })
  3180. .Delete("/binary",
  3181. [&](const Request &req, Response &res) {
  3182. EXPECT_EQ(4U, req.body.size());
  3183. EXPECT_EQ("application/octet-stream",
  3184. req.get_header_value("Content-Type"));
  3185. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3186. res.set_content(req.body, "application/octet-stream");
  3187. })
  3188. .Get("/issue1772",
  3189. [&](const Request & /*req*/, Response &res) {
  3190. res.status = 401;
  3191. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3192. })
  3193. .Delete("/issue609",
  3194. [](const httplib::Request &, httplib::Response &res,
  3195. const httplib::ContentReader &) {
  3196. res.set_content("ok", "text/plain");
  3197. })
  3198. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3199. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3200. .Get("/compress",
  3201. [&](const Request & /*req*/, Response &res) {
  3202. res.set_content(
  3203. "12345678901234567890123456789012345678901234567890123456789"
  3204. "01234567890123456789012345678901234567890",
  3205. "text/plain");
  3206. })
  3207. .Get("/nocompress",
  3208. [&](const Request & /*req*/, Response &res) {
  3209. res.set_content(
  3210. "12345678901234567890123456789012345678901234567890123456789"
  3211. "01234567890123456789012345678901234567890",
  3212. "application/octet-stream");
  3213. })
  3214. .Post("/compress-multipart",
  3215. [&](const Request &req, Response & /*res*/) {
  3216. EXPECT_EQ(2u, req.form.fields.size());
  3217. ASSERT_TRUE(!req.form.has_field("???"));
  3218. {
  3219. const auto &text = req.form.get_field("key1");
  3220. EXPECT_EQ("test", text);
  3221. }
  3222. {
  3223. const auto &text = req.form.get_field("key2");
  3224. EXPECT_EQ("--abcdefg123", text);
  3225. }
  3226. })
  3227. #endif
  3228. ;
  3229. persons_["john"] = "programmer";
  3230. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3231. svr_.wait_until_ready();
  3232. }
  3233. virtual void TearDown() {
  3234. svr_.stop();
  3235. if (!request_threads_.empty()) {
  3236. std::this_thread::sleep_for(std::chrono::seconds(1));
  3237. for (auto &t : request_threads_) {
  3238. t.join();
  3239. }
  3240. }
  3241. t_.join();
  3242. }
  3243. map<string, string> persons_;
  3244. #ifdef CPPHTTPLIB_SSL_ENABLED
  3245. SSLClient cli_;
  3246. SSLServer svr_;
  3247. #else
  3248. Client cli_;
  3249. Server svr_;
  3250. #endif
  3251. thread t_;
  3252. std::vector<thread> request_threads_;
  3253. };
  3254. TEST_F(ServerTest, GetMethod200) {
  3255. auto res = cli_.Get("/hi");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ("HTTP/1.1", res->version);
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("OK", res->reason);
  3260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3261. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. TEST_F(ServerTest, GetEmptyFile) {
  3265. auto res = cli_.Get("/empty_file");
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3269. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3270. EXPECT_EQ("", res->body);
  3271. }
  3272. TEST_F(ServerTest, GetFileContent) {
  3273. auto res = cli_.Get("/file_content");
  3274. ASSERT_TRUE(res);
  3275. EXPECT_EQ(StatusCode::OK_200, res->status);
  3276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3277. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3278. EXPECT_EQ("test.html", res->body);
  3279. }
  3280. TEST_F(ServerTest, GetFileContentWithRange) {
  3281. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3282. ASSERT_TRUE(res);
  3283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3284. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3285. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3286. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3287. EXPECT_EQ("est", res->body);
  3288. }
  3289. TEST_F(ServerTest, GetFileContentWithContentType) {
  3290. auto res = cli_.Get("/file_content_with_content_type");
  3291. ASSERT_TRUE(res);
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3294. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3295. EXPECT_EQ("file\n", res->body);
  3296. }
  3297. TEST_F(ServerTest, GetInvalidFileContent) {
  3298. auto res = cli_.Get("/invalid_file_content");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3301. }
  3302. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3303. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ("HTTP/1.1", res->version);
  3306. EXPECT_EQ(StatusCode::OK_200, res->status);
  3307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3308. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3309. EXPECT_EQ("Hello World!", res->body);
  3310. }
  3311. TEST_F(ServerTest, GetMethod302) {
  3312. auto res = cli_.Get("/");
  3313. ASSERT_TRUE(res);
  3314. EXPECT_EQ(StatusCode::Found_302, res->status);
  3315. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3316. }
  3317. TEST_F(ServerTest, GetMethod302Redirect) {
  3318. cli_.set_follow_location(true);
  3319. auto res = cli_.Get("/");
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::OK_200, res->status);
  3322. EXPECT_EQ("Hello World!", res->body);
  3323. EXPECT_EQ("/hi", res->location);
  3324. }
  3325. TEST_F(ServerTest, GetMethod404) {
  3326. auto res = cli_.Get("/invalid");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3329. }
  3330. TEST_F(ServerTest, HeadMethod200) {
  3331. auto res = cli_.Head("/hi");
  3332. ASSERT_TRUE(res);
  3333. EXPECT_EQ(StatusCode::OK_200, res->status);
  3334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3335. EXPECT_TRUE(res->body.empty());
  3336. }
  3337. TEST_F(ServerTest, HeadMethod200Static) {
  3338. auto res = cli_.Head("/mount/dir/index.html");
  3339. ASSERT_TRUE(res);
  3340. EXPECT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3342. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3343. EXPECT_TRUE(res->body.empty());
  3344. }
  3345. TEST_F(ServerTest, HeadMethod404) {
  3346. auto res = cli_.Head("/invalid");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3349. EXPECT_TRUE(res->body.empty());
  3350. }
  3351. TEST_F(ServerTest, GetMethodPersonJohn) {
  3352. auto res = cli_.Get("/person/john");
  3353. ASSERT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::OK_200, res->status);
  3355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3356. EXPECT_EQ("programmer", res->body);
  3357. }
  3358. TEST_F(ServerTest, PostMethod1) {
  3359. auto res = cli_.Get("/person/john1");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3362. res = cli_.Post("/person", "name=john1&note=coder",
  3363. "application/x-www-form-urlencoded");
  3364. ASSERT_TRUE(res);
  3365. ASSERT_EQ(StatusCode::OK_200, res->status);
  3366. res = cli_.Get("/person/john1");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3370. ASSERT_EQ("coder", res->body);
  3371. }
  3372. TEST_F(ServerTest, PostMethod2) {
  3373. auto res = cli_.Get("/person/john2");
  3374. ASSERT_TRUE(res);
  3375. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3376. Params params;
  3377. params.emplace("name", "john2");
  3378. params.emplace("note", "coder");
  3379. res = cli_.Post("/person", params);
  3380. ASSERT_TRUE(res);
  3381. ASSERT_EQ(StatusCode::OK_200, res->status);
  3382. res = cli_.Get("/person/john2");
  3383. ASSERT_TRUE(res);
  3384. ASSERT_EQ(StatusCode::OK_200, res->status);
  3385. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3386. ASSERT_EQ("coder", res->body);
  3387. }
  3388. TEST_F(ServerTest, PutMethod3) {
  3389. auto res = cli_.Get("/person/john3");
  3390. ASSERT_TRUE(res);
  3391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3392. Params params;
  3393. params.emplace("name", "john3");
  3394. params.emplace("note", "coder");
  3395. res = cli_.Put("/person", params);
  3396. ASSERT_TRUE(res);
  3397. ASSERT_EQ(StatusCode::OK_200, res->status);
  3398. res = cli_.Get("/person/john3");
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3402. ASSERT_EQ("coder", res->body);
  3403. }
  3404. TEST_F(ServerTest, DeleteMethod1) {
  3405. auto res = cli_.Get("/person/john4");
  3406. ASSERT_TRUE(res);
  3407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3408. Params params;
  3409. params.emplace("name", "john4");
  3410. params.emplace("note", "coder");
  3411. res = cli_.Post("/person", params);
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. res = cli_.Get("/person/john4");
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3418. ASSERT_EQ("coder", res->body);
  3419. Params delete_params;
  3420. delete_params.emplace("name", "john4");
  3421. res = cli_.Delete("/person", delete_params);
  3422. ASSERT_TRUE(res);
  3423. ASSERT_EQ(StatusCode::OK_200, res->status);
  3424. ASSERT_EQ("DELETED", res->body);
  3425. res = cli_.Get("/person/john4");
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3428. }
  3429. TEST_F(ServerTest, DeleteMethod2) {
  3430. auto res = cli_.Get("/person/john5");
  3431. ASSERT_TRUE(res);
  3432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3433. Params params;
  3434. params.emplace("name", "john5");
  3435. params.emplace("note", "developer");
  3436. res = cli_.Post("/person", params);
  3437. ASSERT_TRUE(res);
  3438. ASSERT_EQ(StatusCode::OK_200, res->status);
  3439. res = cli_.Get("/person/john5");
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3443. ASSERT_EQ("developer", res->body);
  3444. Params delete_params;
  3445. delete_params.emplace("name", "john5");
  3446. Headers headers;
  3447. headers.emplace("Custom-Header", "test-value");
  3448. res = cli_.Delete("/person", headers, delete_params);
  3449. ASSERT_TRUE(res);
  3450. ASSERT_EQ(StatusCode::OK_200, res->status);
  3451. ASSERT_EQ("DELETED", res->body);
  3452. res = cli_.Get("/person/john5");
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3455. }
  3456. TEST_F(ServerTest, DeleteMethod3) {
  3457. auto res = cli_.Get("/person/john6");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3460. Params params;
  3461. params.emplace("name", "john6");
  3462. params.emplace("note", "tester");
  3463. res = cli_.Post("/person", params);
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. res = cli_.Get("/person/john6");
  3467. ASSERT_TRUE(res);
  3468. ASSERT_EQ(StatusCode::OK_200, res->status);
  3469. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3470. ASSERT_EQ("tester", res->body);
  3471. Params delete_params;
  3472. delete_params.emplace("name", "john6");
  3473. Headers headers;
  3474. headers.emplace("Custom-Header", "test-value");
  3475. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("DELETED", res->body);
  3479. res = cli_.Get("/person/john6");
  3480. ASSERT_TRUE(res);
  3481. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3482. }
  3483. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3484. Params params;
  3485. params.emplace("json", JSON_DATA);
  3486. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3487. ASSERT_TRUE(res);
  3488. ASSERT_EQ(StatusCode::OK_200, res->status);
  3489. ASSERT_EQ(JSON_DATA, res->body);
  3490. }
  3491. TEST_F(ServerTest, PostEmptyContent) {
  3492. auto res = cli_.Post("/empty", "", "text/plain");
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ("empty", res->body);
  3496. }
  3497. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3498. auto res = cli_.Post("/empty-no-content-type");
  3499. ASSERT_TRUE(res);
  3500. ASSERT_EQ(StatusCode::OK_200, res->status);
  3501. ASSERT_EQ("empty-no-content-type", res->body);
  3502. }
  3503. TEST_F(ServerTest, PostPathOnly) {
  3504. auto res = cli_.Post("/path-only");
  3505. ASSERT_TRUE(res);
  3506. ASSERT_EQ(StatusCode::OK_200, res->status);
  3507. ASSERT_EQ("path-only", res->body);
  3508. }
  3509. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3510. auto res = cli_.Post("/path-headers-only",
  3511. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3512. ASSERT_TRUE(res);
  3513. ASSERT_EQ(StatusCode::OK_200, res->status);
  3514. ASSERT_EQ("path-headers-only", res->body);
  3515. }
  3516. TEST_F(ServerTest, PostLarge) {
  3517. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ(LARGE_DATA, res->body);
  3521. }
  3522. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3523. auto res = cli_.Put("/empty-no-content-type");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ("empty-no-content-type", res->body);
  3527. }
  3528. TEST_F(ServerTest, GetMethodDir) {
  3529. auto res = cli_.Get("/dir/");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3533. auto body = R"(<html>
  3534. <head>
  3535. </head>
  3536. <body>
  3537. <a href="/dir/test.html">Test</a>
  3538. <a href="/hi">hi</a>
  3539. </body>
  3540. </html>
  3541. )";
  3542. EXPECT_EQ(body, res->body);
  3543. }
  3544. TEST_F(ServerTest, GetMethodDirTest) {
  3545. auto res = cli_.Get("/dir/test.html");
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(StatusCode::OK_200, res->status);
  3548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3549. EXPECT_EQ("test.html", res->body);
  3550. }
  3551. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3552. auto res = cli_.Get("/dir/../dir/test.html");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3556. EXPECT_EQ("test.html", res->body);
  3557. }
  3558. TEST_F(ServerTest, GetMethodInvalidPath) {
  3559. auto res = cli_.Get("/dir/../test.html");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3562. }
  3563. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3564. auto res = cli_.Get("/../www/dir/test.html");
  3565. ASSERT_TRUE(res);
  3566. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3567. }
  3568. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3569. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3570. ASSERT_TRUE(res);
  3571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3572. }
  3573. TEST_F(ServerTest, GetMethodDirMountTest) {
  3574. auto res = cli_.Get("/mount/dir/test.html");
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("test.html", res->body);
  3579. }
  3580. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3581. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3585. EXPECT_EQ("test.html", res->body);
  3586. }
  3587. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3588. auto res = cli_.Get("/mount/dir/../test.html");
  3589. ASSERT_TRUE(res);
  3590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3591. }
  3592. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3593. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3596. }
  3597. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3598. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3601. }
  3602. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3603. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3604. ASSERT_TRUE(res);
  3605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3606. }
  3607. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3608. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3609. ASSERT_TRUE(res);
  3610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3611. }
  3612. TEST_F(ServerTest, PostMethod303) {
  3613. auto res = cli_.Post("/1", "body", "text/plain");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3616. EXPECT_EQ("/2", res->get_header_value("Location"));
  3617. }
  3618. TEST_F(ServerTest, PostMethod303Redirect) {
  3619. cli_.set_follow_location(true);
  3620. auto res = cli_.Post("/1", "body", "text/plain");
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::OK_200, res->status);
  3623. EXPECT_EQ("redirected.", res->body);
  3624. EXPECT_EQ("/2", res->location);
  3625. }
  3626. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3627. auto res = cli_.Get("/dir/test.abcde");
  3628. ASSERT_TRUE(res);
  3629. EXPECT_EQ(StatusCode::OK_200, res->status);
  3630. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3631. EXPECT_EQ("abcde", res->body);
  3632. }
  3633. TEST_F(ServerTest, StaticFileRange) {
  3634. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3635. ASSERT_TRUE(res);
  3636. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3637. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3638. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3639. EXPECT_EQ(true, res->has_header("Content-Range"));
  3640. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3641. EXPECT_EQ(std::string("cd"), res->body);
  3642. }
  3643. TEST_F(ServerTest, StaticFileRanges) {
  3644. auto res =
  3645. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3648. EXPECT_TRUE(
  3649. res->get_header_value("Content-Type")
  3650. .find(
  3651. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3652. 0);
  3653. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3654. }
  3655. TEST_F(ServerTest, StaticFileRangeHead) {
  3656. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3657. ASSERT_TRUE(res);
  3658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3659. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3660. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3661. EXPECT_EQ(true, res->has_header("Content-Range"));
  3662. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3663. }
  3664. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3665. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3668. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3670. EXPECT_EQ(true, res->has_header("Content-Range"));
  3671. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3672. res->get_header_value("Content-Range"));
  3673. EXPECT_EQ("LAST\n", res->body);
  3674. }
  3675. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3676. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3680. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3681. EXPECT_EQ(true, res->has_header("Content-Range"));
  3682. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3683. }
  3684. TEST_F(ServerTest, StaticFileBigFile) {
  3685. auto res = cli_.Get("/dir/1MB.txt");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3689. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3690. }
  3691. TEST_F(ServerTest, InvalidBaseDirMount) {
  3692. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3693. }
  3694. TEST_F(ServerTest, Binary) {
  3695. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3696. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3697. "application/octet-stream");
  3698. ASSERT_TRUE(res);
  3699. ASSERT_EQ(StatusCode::OK_200, res->status);
  3700. ASSERT_EQ(4U, res->body.size());
  3701. res = cli_.Put("/binary", binary.data(), binary.size(),
  3702. "application/octet-stream");
  3703. ASSERT_TRUE(res);
  3704. ASSERT_EQ(StatusCode::OK_200, res->status);
  3705. ASSERT_EQ(4U, res->body.size());
  3706. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3707. "application/octet-stream");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ(4U, res->body.size());
  3711. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3712. "application/octet-stream");
  3713. ASSERT_TRUE(res);
  3714. ASSERT_EQ(StatusCode::OK_200, res->status);
  3715. ASSERT_EQ(4U, res->body.size());
  3716. }
  3717. TEST_F(ServerTest, BinaryString) {
  3718. auto binary = std::string("\x00\x01\x02\x03", 4);
  3719. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3720. ASSERT_TRUE(res);
  3721. ASSERT_EQ(StatusCode::OK_200, res->status);
  3722. ASSERT_EQ(4U, res->body.size());
  3723. res = cli_.Put("/binary", binary, "application/octet-stream");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::OK_200, res->status);
  3726. ASSERT_EQ(4U, res->body.size());
  3727. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3728. ASSERT_TRUE(res);
  3729. ASSERT_EQ(StatusCode::OK_200, res->status);
  3730. ASSERT_EQ(4U, res->body.size());
  3731. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3732. ASSERT_TRUE(res);
  3733. ASSERT_EQ(StatusCode::OK_200, res->status);
  3734. ASSERT_EQ(4U, res->body.size());
  3735. }
  3736. TEST_F(ServerTest, EmptyRequest) {
  3737. auto res = cli_.Get("");
  3738. ASSERT_TRUE(!res);
  3739. EXPECT_EQ(Error::Connection, res.error());
  3740. }
  3741. TEST_F(ServerTest, LongRequest) {
  3742. std::string request;
  3743. for (size_t i = 0; i < 545; i++) {
  3744. request += "/TooLongRequest";
  3745. }
  3746. request += "OK";
  3747. auto res = cli_.Get(request.c_str());
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3750. }
  3751. TEST_F(ServerTest, TooLongRequest) {
  3752. std::string request;
  3753. for (size_t i = 0; i < 546; i++) {
  3754. request += "/TooLongRequest";
  3755. }
  3756. request += "_NG";
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(request.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, AlmostTooLongRequest) {
  3771. // test for #2046 - URI length check shouldn't include other content on req
  3772. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3773. // leading /, space, HTTP/1.1)
  3774. std::string request =
  3775. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3776. auto res = cli_.Get(request.c_str());
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3779. }
  3780. TEST_F(ServerTest, LongHeader) {
  3781. Request req;
  3782. req.method = "GET";
  3783. req.path = "/hi";
  3784. std::string host_and_port;
  3785. host_and_port += HOST;
  3786. host_and_port += ":";
  3787. host_and_port += std::to_string(PORT);
  3788. req.headers.emplace("Host", host_and_port.c_str());
  3789. req.headers.emplace("Accept", "*/*");
  3790. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3791. req.headers.emplace(
  3792. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@");
  3822. auto res = std::make_shared<Response>();
  3823. auto error = Error::Success;
  3824. auto ret = cli_.send(req, *res, error);
  3825. ASSERT_TRUE(ret);
  3826. EXPECT_EQ(StatusCode::OK_200, res->status);
  3827. }
  3828. TEST_F(ServerTest, LongQueryValue) {
  3829. auto start = std::chrono::high_resolution_clock::now();
  3830. cli_.set_keep_alive(true);
  3831. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3832. auto end = std::chrono::high_resolution_clock::now();
  3833. auto elapsed =
  3834. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3835. .count();
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3838. EXPECT_LE(elapsed, 100);
  3839. EXPECT_EQ("close", res->get_header_value("Connection"));
  3840. EXPECT_FALSE(cli_.is_socket_open());
  3841. }
  3842. TEST_F(ServerTest, TooLongQueryValue) {
  3843. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3844. ASSERT_FALSE(res);
  3845. EXPECT_EQ(Error::Read, res.error());
  3846. }
  3847. TEST_F(ServerTest, TooLongHeader) {
  3848. Request req;
  3849. req.method = "GET";
  3850. req.path = "/hi";
  3851. std::string host_and_port;
  3852. host_and_port += HOST;
  3853. host_and_port += ":";
  3854. host_and_port += std::to_string(PORT);
  3855. req.headers.emplace("Host", host_and_port.c_str());
  3856. req.headers.emplace("Accept", "*/*");
  3857. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3858. req.headers.emplace(
  3859. "Header-Name",
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3888. "@@@@@@@@@@@@@@@@@");
  3889. auto res = std::make_shared<Response>();
  3890. auto error = Error::Success;
  3891. auto ret = cli_.send(req, *res, error);
  3892. ASSERT_TRUE(ret);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. }
  3895. TEST_F(ServerTest, HeaderCountAtLimit) {
  3896. // Test with headers just under the 100 limit
  3897. httplib::Headers headers;
  3898. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3899. // This should keep us just under the 100 header limit
  3900. for (int i = 0; i < 95; i++) {
  3901. std::string name = "X-Test-Header-" + std::to_string(i);
  3902. std::string value = "value" + std::to_string(i);
  3903. headers.emplace(name, value);
  3904. }
  3905. // This should work fine as we're under the limit
  3906. auto res = cli_.Get("/hi", headers);
  3907. EXPECT_TRUE(res);
  3908. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3909. }
  3910. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3911. // Test with many headers to exceed the 100 limit
  3912. httplib::Headers headers;
  3913. // Add 150 headers to definitely exceed the 100 limit
  3914. for (int i = 0; i < 150; i++) {
  3915. std::string name = "X-Test-Header-" + std::to_string(i);
  3916. std::string value = "value" + std::to_string(i);
  3917. headers.emplace(name, value);
  3918. }
  3919. // This should fail due to exceeding header count limit
  3920. cli_.set_keep_alive(true);
  3921. auto res = cli_.Get("/hi", headers);
  3922. // The request should either fail or return 400 Bad Request
  3923. if (res) {
  3924. // If we get a response, it should be 400 Bad Request
  3925. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3926. } else {
  3927. // Or the request should fail entirely
  3928. EXPECT_FALSE(res);
  3929. }
  3930. EXPECT_EQ("close", res->get_header_value("Connection"));
  3931. EXPECT_FALSE(cli_.is_socket_open());
  3932. }
  3933. TEST_F(ServerTest, PercentEncoding) {
  3934. auto res = cli_.Get("/e%6edwith%");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(StatusCode::OK_200, res->status);
  3937. }
  3938. TEST_F(ServerTest, PercentEncodingUnicode) {
  3939. auto res = cli_.Get("/e%u006edwith%");
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. }
  3943. TEST_F(ServerTest, InvalidPercentEncoding) {
  3944. auto res = cli_.Get("/%endwith%");
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3947. }
  3948. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3949. auto res = cli_.Get("/%uendwith%");
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3952. }
  3953. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3954. auto res = cli_.Get("/hello?aaa=bbb%");
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3957. }
  3958. TEST_F(ServerTest, PlusSignEncoding) {
  3959. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("a +b", res->body);
  3963. }
  3964. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3965. // This test simulates a potential DoS attack using many headers
  3966. // to verify our security fix prevents memory exhaustion
  3967. httplib::Headers attack_headers;
  3968. // Attempt to add many headers like an attacker would (200 headers to far
  3969. // exceed limit)
  3970. for (int i = 0; i < 200; i++) {
  3971. std::string name = "X-Attack-Header-" + std::to_string(i);
  3972. std::string value = "attack_payload_" + std::to_string(i);
  3973. attack_headers.emplace(name, value);
  3974. }
  3975. // Try to POST with excessive headers
  3976. cli_.set_keep_alive(true);
  3977. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3978. // Should either fail or return 400 Bad Request due to security limit
  3979. if (res) {
  3980. // If we get a response, it should be 400 Bad Request
  3981. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3982. } else {
  3983. // Request failed, which is the expected behavior for DoS protection
  3984. EXPECT_FALSE(res);
  3985. }
  3986. EXPECT_EQ("close", res->get_header_value("Connection"));
  3987. EXPECT_FALSE(cli_.is_socket_open());
  3988. }
  3989. TEST_F(ServerTest, MultipartFormData) {
  3990. UploadFormDataItems items = {
  3991. {"text1", "text default", "", ""},
  3992. {"text2", "aωb", "", ""},
  3993. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3994. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3995. {"file3", "", "", "application/octet-stream"},
  3996. {"file4", "", "", " application/json tmp-string "}};
  3997. auto res = cli_.Post("/multipart", items);
  3998. ASSERT_TRUE(res);
  3999. EXPECT_EQ(StatusCode::OK_200, res->status);
  4000. }
  4001. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4002. UploadFormDataItems items = {
  4003. {"text", "default text", "", ""},
  4004. {"multi_text1", "aaaaa", "", ""},
  4005. {"multi_text1", "bbbbb", "", ""},
  4006. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4007. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4008. "application/json"},
  4009. };
  4010. auto res = cli_.Post("/multipart/multi_file_values", items);
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::OK_200, res->status);
  4013. }
  4014. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4015. auto res = cli_.Get("/hi");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::OK_200, res->status);
  4018. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4019. EXPECT_EQ("Hello World!", res->body);
  4020. }
  4021. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4022. Request req;
  4023. req.method = "POST";
  4024. req.path = "/chunked";
  4025. std::string host_and_port;
  4026. host_and_port += HOST;
  4027. host_and_port += ":";
  4028. host_and_port += std::to_string(PORT);
  4029. req.headers.emplace("Host", host_and_port.c_str());
  4030. req.headers.emplace("Accept", "*/*");
  4031. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4032. req.headers.emplace("Content-Type", "text/plain");
  4033. req.headers.emplace("Content-Length", "0");
  4034. req.headers.emplace(
  4035. "Transfer-Encoding",
  4036. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4037. // Client does not chunk, so make a chunked body manually.
  4038. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4039. auto res = std::make_shared<Response>();
  4040. auto error = Error::Success;
  4041. auto ret = cli_.send(req, *res, error);
  4042. ASSERT_TRUE(ret);
  4043. EXPECT_EQ(StatusCode::OK_200, res->status);
  4044. }
  4045. TEST_F(ServerTest, GetStreamed2) {
  4046. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4049. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4050. EXPECT_EQ(true, res->has_header("Content-Range"));
  4051. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4052. EXPECT_EQ(std::string("ab"), res->body);
  4053. }
  4054. TEST_F(ServerTest, GetStreamed) {
  4055. auto res = cli_.Get("/streamed");
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ(std::string("aaabbb"), res->body);
  4060. }
  4061. TEST_F(ServerTest, GetStreamedWithRange1) {
  4062. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4068. EXPECT_EQ(std::string("def"), res->body);
  4069. }
  4070. TEST_F(ServerTest, GetStreamedWithRange2) {
  4071. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4074. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4075. EXPECT_EQ(true, res->has_header("Content-Range"));
  4076. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4077. EXPECT_EQ(std::string("bcdefg"), res->body);
  4078. }
  4079. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4080. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4083. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4084. EXPECT_EQ(true, res->has_header("Content-Range"));
  4085. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4086. EXPECT_EQ(std::string("efg"), res->body);
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4089. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4092. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ(false, res->has_header("Content-Range"));
  4094. EXPECT_EQ(0U, res->body.size());
  4095. }
  4096. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4097. auto res = cli_.Get("/streamed-with-range",
  4098. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4099. "92233720368547758079223372036854775807"}});
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4102. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(false, res->has_header("Content-Range"));
  4104. EXPECT_EQ(0U, res->body.size());
  4105. }
  4106. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4107. auto res = cli_.Get(
  4108. "/with-range",
  4109. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4110. {"Accept-Encoding", ""}});
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4113. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(true, res->has_header("Content-Range"));
  4115. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4116. EXPECT_EQ(std::string("abcdefg"), res->body);
  4117. }
  4118. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4119. auto res = cli_.Get("/with-range", {
  4120. {"Range", "bytes=0-"},
  4121. {"Accept-Encoding", ""},
  4122. });
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4125. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4126. EXPECT_EQ(true, res->has_header("Content-Range"));
  4127. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4128. EXPECT_EQ(std::string("abcdefg"), res->body);
  4129. }
  4130. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4131. auto res =
  4132. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4135. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4136. EXPECT_EQ(false, res->has_header("Content-Range"));
  4137. EXPECT_EQ(267U, res->body.size());
  4138. // Check that both range contents are present
  4139. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4140. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4141. // Check that Content-Range headers are present for both ranges
  4142. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4143. std::string::npos);
  4144. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4145. std::string::npos);
  4146. }
  4147. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4148. Ranges ranges;
  4149. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4150. ranges.emplace_back(0, -1);
  4151. }
  4152. auto res =
  4153. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4154. ASSERT_TRUE(res);
  4155. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4157. EXPECT_EQ(false, res->has_header("Content-Range"));
  4158. EXPECT_EQ(0U, res->body.size());
  4159. }
  4160. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4161. auto res =
  4162. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4165. EXPECT_EQ(5U, res->body.size());
  4166. // Check that overlapping ranges are coalesced into a single range
  4167. EXPECT_EQ("bcdef", res->body);
  4168. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4169. // Should be single range, not multipart
  4170. EXPECT_TRUE(res->has_header("Content-Range"));
  4171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4172. }
  4173. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4174. auto res =
  4175. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ(268U, res->body.size());
  4179. // Check that both range contents are present
  4180. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4181. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4182. // Check that Content-Range headers are present for both ranges
  4183. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4184. std::string::npos);
  4185. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4186. std::string::npos);
  4187. }
  4188. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4189. auto res =
  4190. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ(269U, res->body.size());
  4194. // Check that both duplicate range contents are present
  4195. size_t first_abc = res->body.find("abc\r\n");
  4196. EXPECT_TRUE(first_abc != std::string::npos);
  4197. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4198. EXPECT_TRUE(second_abc != std::string::npos);
  4199. // Check that Content-Range headers are present for both ranges
  4200. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4201. EXPECT_TRUE(first_range != std::string::npos);
  4202. size_t second_range =
  4203. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4204. EXPECT_TRUE(second_range != std::string::npos);
  4205. }
  4206. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4207. auto res = cli_.Get("/streamed-with-range?error",
  4208. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4209. ASSERT_TRUE(res);
  4210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(false, res->has_header("Content-Range"));
  4213. EXPECT_EQ(0U, res->body.size());
  4214. }
  4215. TEST_F(ServerTest, GetStreamedEndless) {
  4216. uint64_t offset = 0;
  4217. auto res = cli_.Get("/streamed-cancel",
  4218. [&](const char * /*data*/, uint64_t data_length) {
  4219. if (offset < 100) {
  4220. offset += data_length;
  4221. return true;
  4222. }
  4223. return false;
  4224. });
  4225. ASSERT_TRUE(!res);
  4226. EXPECT_EQ(Error::Canceled, res.error());
  4227. }
  4228. TEST_F(ServerTest, ClientStop) {
  4229. std::atomic_size_t count{4};
  4230. std::vector<std::thread> threads;
  4231. for (auto i = count.load(); i != 0; --i) {
  4232. threads.emplace_back([&]() {
  4233. auto res = cli_.Get("/streamed-cancel",
  4234. [&](const char *, uint64_t) { return true; });
  4235. --count;
  4236. ASSERT_TRUE(!res);
  4237. EXPECT_TRUE(res.error() == Error::Canceled ||
  4238. res.error() == Error::Read || res.error() == Error::Write);
  4239. });
  4240. }
  4241. std::this_thread::sleep_for(std::chrono::seconds(2));
  4242. while (count != 0) {
  4243. cli_.stop();
  4244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4245. }
  4246. for (auto &t : threads) {
  4247. t.join();
  4248. }
  4249. }
  4250. TEST_F(ServerTest, GetWithRange1) {
  4251. auto res = cli_.Get("/with-range", {
  4252. make_range_header({{3, 5}}),
  4253. {"Accept-Encoding", ""},
  4254. });
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4258. EXPECT_EQ(true, res->has_header("Content-Range"));
  4259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4260. EXPECT_EQ(std::string("def"), res->body);
  4261. }
  4262. TEST_F(ServerTest, GetWithRange2) {
  4263. auto res = cli_.Get("/with-range", {
  4264. make_range_header({{1, -1}}),
  4265. {"Accept-Encoding", ""},
  4266. });
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(true, res->has_header("Content-Range"));
  4271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4272. EXPECT_EQ(std::string("bcdefg"), res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRange3) {
  4275. auto res = cli_.Get("/with-range", {
  4276. make_range_header({{0, 0}}),
  4277. {"Accept-Encoding", ""},
  4278. });
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4282. EXPECT_EQ(true, res->has_header("Content-Range"));
  4283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4284. EXPECT_EQ(std::string("a"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetWithRange4) {
  4287. auto res = cli_.Get("/with-range", {
  4288. make_range_header({{-1, 2}}),
  4289. {"Accept-Encoding", ""},
  4290. });
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4294. EXPECT_EQ(true, res->has_header("Content-Range"));
  4295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4296. EXPECT_EQ(std::string("fg"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetWithRange5) {
  4299. auto res = cli_.Get("/with-range", {
  4300. make_range_header({{0, 5}}),
  4301. {"Accept-Encoding", ""},
  4302. });
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(true, res->has_header("Content-Range"));
  4307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4308. EXPECT_EQ(std::string("abcdef"), res->body);
  4309. }
  4310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4311. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4314. }
  4315. TEST_F(ServerTest, GetWithRangeMultipart) {
  4316. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4317. ASSERT_TRUE(res);
  4318. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4319. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4320. EXPECT_EQ(false, res->has_header("Content-Range"));
  4321. EXPECT_EQ(267U, res->body.size());
  4322. }
  4323. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4324. auto res =
  4325. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4328. }
  4329. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4330. auto res = cli_.Get("/with-range-customized-response",
  4331. {{make_range_header({{1, 2}})}});
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4334. EXPECT_EQ(true, res->has_header("Content-Length"));
  4335. EXPECT_EQ(false, res->has_header("Content-Range"));
  4336. EXPECT_EQ(JSON_DATA, res->body);
  4337. }
  4338. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4339. auto res = cli_.Get("/with-range-customized-response",
  4340. {{make_range_header({{1, 2}, {4, 5}})}});
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4343. EXPECT_EQ(true, res->has_header("Content-Length"));
  4344. EXPECT_EQ(false, res->has_header("Content-Range"));
  4345. EXPECT_EQ(JSON_DATA, res->body);
  4346. }
  4347. TEST_F(ServerTest, Issue1772) {
  4348. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4351. }
  4352. TEST_F(ServerTest, Issue609) {
  4353. auto res = cli_.Delete("/issue609");
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::OK_200, res->status);
  4356. EXPECT_EQ(std::string("ok"), res->body);
  4357. }
  4358. TEST_F(ServerTest, GetStreamedChunked) {
  4359. auto res = cli_.Get("/streamed-chunked");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. EXPECT_EQ(std::string("123456789"), res->body);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedChunked2) {
  4365. auto res = cli_.Get("/streamed-chunked2");
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. EXPECT_EQ(std::string("123456789"), res->body);
  4369. }
  4370. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4371. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ(std::string("123456789"), res->body);
  4375. EXPECT_TRUE(res->has_header("Trailer"));
  4376. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4377. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4378. // Trailers are now stored separately from headers (security fix)
  4379. EXPECT_EQ(2U, res->trailers.size());
  4380. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4381. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4382. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4383. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4384. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4385. // Verify trailers are NOT in headers (security verification)
  4386. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4387. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4388. }
  4389. TEST_F(ServerTest, LargeChunkedPost) {
  4390. Request req;
  4391. req.method = "POST";
  4392. req.path = "/large-chunked";
  4393. std::string host_and_port;
  4394. host_and_port += HOST;
  4395. host_and_port += ":";
  4396. host_and_port += std::to_string(PORT);
  4397. req.headers.emplace("Host", host_and_port.c_str());
  4398. req.headers.emplace("Accept", "*/*");
  4399. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4400. req.headers.emplace("Content-Type", "text/plain");
  4401. req.headers.emplace("Content-Length", "0");
  4402. req.headers.emplace("Transfer-Encoding", "chunked");
  4403. std::string long_string(30 * 1024u, 'a');
  4404. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4405. // Attempt to make a large enough post to exceed OS buffers, to test that
  4406. // the server handles short reads if the full chunk data isn't available.
  4407. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4408. auto res = std::make_shared<Response>();
  4409. auto error = Error::Success;
  4410. auto ret = cli_.send(req, *res, error);
  4411. ASSERT_TRUE(ret);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. }
  4414. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4415. auto res = cli_.Get("/remote_addr");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4419. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4420. }
  4421. TEST_F(ServerTest, GetMethodLocalAddr) {
  4422. auto res = cli_.Get("/local_addr");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4426. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4427. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4428. }
  4429. TEST_F(ServerTest, HTTPResponseSplitting) {
  4430. auto res = cli_.Get("/http_response_splitting");
  4431. ASSERT_TRUE(res);
  4432. EXPECT_EQ(StatusCode::OK_200, res->status);
  4433. }
  4434. TEST_F(ServerTest, SlowRequest) {
  4435. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4436. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4438. }
  4439. #if 0
  4440. TEST_F(ServerTest, SlowPost) {
  4441. char buffer[64 * 1024];
  4442. memset(buffer, 0x42, sizeof(buffer));
  4443. auto res = cli_.Post(
  4444. "/slowpost", 64 * 1024 * 1024,
  4445. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4446. auto ret = sink.write(buffer, sizeof(buffer));
  4447. EXPECT_TRUE(ret);
  4448. return true;
  4449. },
  4450. "text/plain");
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(StatusCode::OK_200, res->status);
  4453. }
  4454. TEST_F(ServerTest, SlowPostFail) {
  4455. char buffer[64 * 1024];
  4456. memset(buffer, 0x42, sizeof(buffer));
  4457. cli_.set_write_timeout(std::chrono::seconds(0));
  4458. auto res = cli_.Post(
  4459. "/slowpost", 64 * 1024 * 1024,
  4460. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4461. sink.write(buffer, sizeof(buffer));
  4462. return true;
  4463. },
  4464. "text/plain");
  4465. ASSERT_TRUE(!res);
  4466. EXPECT_EQ(Error::Write, res.error());
  4467. }
  4468. #endif
  4469. TEST_F(ServerTest, Put) {
  4470. auto res = cli_.Put("/put", "PUT", "text/plain");
  4471. ASSERT_TRUE(res);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("PUT", res->body);
  4474. }
  4475. TEST_F(ServerTest, PutWithContentProvider) {
  4476. auto res = cli_.Put(
  4477. "/put", 3,
  4478. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4479. sink.os << "PUT";
  4480. return true;
  4481. },
  4482. "text/plain");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ("PUT", res->body);
  4486. }
  4487. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4488. auto res = cli_.Post(
  4489. "/post", 42,
  4490. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4491. return false;
  4492. },
  4493. "text/plain");
  4494. ASSERT_TRUE(!res);
  4495. EXPECT_EQ(Error::Canceled, res.error());
  4496. }
  4497. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4498. auto res = cli_.Put(
  4499. "/put",
  4500. [](size_t /*offset*/, DataSink &sink) {
  4501. sink.os << "PUT";
  4502. sink.done();
  4503. return true;
  4504. },
  4505. "text/plain");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("PUT", res->body);
  4509. }
  4510. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4511. auto res = cli_.Post(
  4512. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4513. "text/plain");
  4514. ASSERT_TRUE(!res);
  4515. EXPECT_EQ(Error::Canceled, res.error());
  4516. }
  4517. TEST_F(ServerTest, PostLoopBack) {
  4518. std::string body;
  4519. auto res = cli_.Post(
  4520. "/post-loopback", 9,
  4521. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4522. EXPECT_EQ(9u, length);
  4523. sink.write("123", 3);
  4524. sink.write("456", 3);
  4525. sink.write("789", 3);
  4526. return true;
  4527. },
  4528. "text/plain",
  4529. [&body](const char *data, size_t data_length) {
  4530. body.append(data, data_length);
  4531. return true;
  4532. });
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ("123456789", body);
  4536. }
  4537. TEST_F(ServerTest, PutLoopBack) {
  4538. std::string body;
  4539. auto res = cli_.Put(
  4540. "/put-loopback", 9,
  4541. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4542. EXPECT_EQ(9u, length);
  4543. sink.write("123", 3);
  4544. sink.write("456", 3);
  4545. sink.write("789", 3);
  4546. return true;
  4547. },
  4548. "text/plain",
  4549. [&body](const char *data, size_t data_length) {
  4550. body.append(data, data_length);
  4551. return true;
  4552. });
  4553. ASSERT_TRUE(res);
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("123456789", body);
  4556. }
  4557. TEST_F(ServerTest, PatchLoopBack) {
  4558. std::string body;
  4559. auto res = cli_.Patch(
  4560. "/patch-loopback", 9,
  4561. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4562. EXPECT_EQ(9u, length);
  4563. sink.write("123", 3);
  4564. sink.write("456", 3);
  4565. sink.write("789", 3);
  4566. return true;
  4567. },
  4568. "text/plain",
  4569. [&body](const char *data, size_t data_length) {
  4570. body.append(data, data_length);
  4571. return true;
  4572. });
  4573. ASSERT_TRUE(res);
  4574. EXPECT_EQ(StatusCode::OK_200, res->status);
  4575. EXPECT_EQ("123456789", body);
  4576. }
  4577. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4578. std::string body;
  4579. auto res = cli_.Post(
  4580. "/post-loopback",
  4581. [](size_t /*offset*/, DataSink &sink) {
  4582. sink.write("123", 3);
  4583. sink.write("456", 3);
  4584. sink.write("789", 3);
  4585. sink.done();
  4586. return true;
  4587. },
  4588. "text/plain",
  4589. [&body](const char *data, size_t data_length) {
  4590. body.append(data, data_length);
  4591. return true;
  4592. });
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("123456789", body);
  4596. }
  4597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4598. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4599. cli_.set_compress(true);
  4600. auto res = cli_.Put(
  4601. "/put", 3,
  4602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4603. sink.os << "PUT";
  4604. return true;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. EXPECT_EQ("PUT", res->body);
  4610. }
  4611. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4612. cli_.set_compress(true);
  4613. auto res = cli_.Post(
  4614. "/post", 42,
  4615. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4616. return false;
  4617. },
  4618. "text/plain");
  4619. ASSERT_TRUE(!res);
  4620. EXPECT_EQ(Error::Canceled, res.error());
  4621. }
  4622. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4623. cli_.set_compress(true);
  4624. auto res = cli_.Put(
  4625. "/put",
  4626. [](size_t /*offset*/, DataSink &sink) {
  4627. sink.os << "PUT";
  4628. sink.done();
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("PUT", res->body);
  4635. }
  4636. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4637. cli_.set_compress(true);
  4638. auto res = cli_.Post(
  4639. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4640. "text/plain");
  4641. ASSERT_TRUE(!res);
  4642. EXPECT_EQ(Error::Canceled, res.error());
  4643. }
  4644. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4645. cli_.set_compress(true);
  4646. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ(LARGE_DATA, res->body);
  4650. }
  4651. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4652. #ifdef CPPHTTPLIB_SSL_ENABLED
  4653. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4654. Client cli(s.c_str());
  4655. cli.enable_server_certificate_verification(false);
  4656. #else
  4657. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4658. Client cli(s.c_str());
  4659. #endif
  4660. cli.set_compress(true);
  4661. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ(LARGE_DATA, res->body);
  4665. // The compressed size should be less than a 10th of the original. May vary
  4666. // depending on the zlib library.
  4667. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4668. static_cast<uint64_t>(10 * 1024 * 1024));
  4669. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4670. }
  4671. TEST_F(ServerTest, PutContentWithDeflate) {
  4672. cli_.set_compress(false);
  4673. Headers headers;
  4674. headers.emplace("Content-Encoding", "deflate");
  4675. // PUT in deflate format:
  4676. auto res = cli_.Put("/put", headers,
  4677. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ("PUT", res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4683. Headers headers;
  4684. headers.emplace("Accept-Encoding", "gzip, deflate");
  4685. auto res = cli_.Get("/streamed-chunked", headers);
  4686. ASSERT_TRUE(res);
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ(std::string("123456789"), res->body);
  4689. }
  4690. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4691. Headers headers;
  4692. headers.emplace("Accept-Encoding", "gzip, deflate");
  4693. auto res = cli_.Get("/streamed-chunked2", headers);
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ(std::string("123456789"), res->body);
  4697. }
  4698. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4699. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::OK_200, res->status);
  4702. }
  4703. TEST(GzipDecompressor, ChunkedDecompression) {
  4704. std::string data;
  4705. for (size_t i = 0; i < 32 * 1024; ++i) {
  4706. data.push_back(static_cast<char>('a' + i % 26));
  4707. }
  4708. std::string compressed_data;
  4709. {
  4710. httplib::detail::gzip_compressor compressor;
  4711. bool result = compressor.compress(
  4712. data.data(), data.size(),
  4713. /*last=*/true,
  4714. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4715. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4716. compressed_data_size);
  4717. return true;
  4718. });
  4719. ASSERT_TRUE(result);
  4720. }
  4721. std::string decompressed_data;
  4722. {
  4723. httplib::detail::gzip_decompressor decompressor;
  4724. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4725. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4726. size_t chunk_size = 130;
  4727. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4728. chunk_begin += chunk_size) {
  4729. size_t current_chunk_size =
  4730. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4731. bool result = decompressor.decompress(
  4732. compressed_data.data() + chunk_begin, current_chunk_size,
  4733. [&](const char *decompressed_data_chunk,
  4734. size_t decompressed_data_chunk_size) {
  4735. decompressed_data.insert(decompressed_data.size(),
  4736. decompressed_data_chunk,
  4737. decompressed_data_chunk_size);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(result);
  4741. }
  4742. }
  4743. ASSERT_EQ(data, decompressed_data);
  4744. }
  4745. TEST(GzipDecompressor, DeflateDecompression) {
  4746. std::string original_text = "Raw deflate without gzip";
  4747. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4748. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4749. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4750. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4751. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4752. std::string decompressed_data;
  4753. {
  4754. httplib::detail::gzip_decompressor decompressor;
  4755. bool result = decompressor.decompress(
  4756. compressed_data.data(), compressed_data.size(),
  4757. [&](const char *decompressed_data_chunk,
  4758. size_t decompressed_data_chunk_size) {
  4759. decompressed_data.insert(decompressed_data.size(),
  4760. decompressed_data_chunk,
  4761. decompressed_data_chunk_size);
  4762. return true;
  4763. });
  4764. ASSERT_TRUE(result);
  4765. }
  4766. ASSERT_EQ(original_text, decompressed_data);
  4767. }
  4768. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4769. std::string original_text = "Raw deflate without gzip";
  4770. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4771. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4772. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4773. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4774. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4775. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4776. std::string decompressed_data;
  4777. {
  4778. httplib::detail::gzip_decompressor decompressor;
  4779. bool result = decompressor.decompress(
  4780. compressed_data.data(), compressed_data.size(),
  4781. [&](const char *decompressed_data_chunk,
  4782. size_t decompressed_data_chunk_size) {
  4783. decompressed_data.insert(decompressed_data.size(),
  4784. decompressed_data_chunk,
  4785. decompressed_data_chunk_size);
  4786. return true;
  4787. });
  4788. ASSERT_TRUE(result);
  4789. }
  4790. ASSERT_EQ(original_text, decompressed_data);
  4791. }
  4792. #ifdef _WIN32
  4793. TEST(GzipDecompressor, LargeRandomData) {
  4794. // prepare large random data that is difficult to be compressed and is
  4795. // expected to have large size even when compressed
  4796. std::random_device seed_gen;
  4797. std::mt19937 random(seed_gen());
  4798. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4799. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4800. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4801. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4802. // compress data over 4GiB
  4803. std::string compressed_data;
  4804. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4805. httplib::detail::gzip_compressor compressor;
  4806. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4807. data.size() * sizeof(std::uint32_t), true,
  4808. [&](const char *data, size_t size) {
  4809. compressed_data.insert(
  4810. compressed_data.size(), data, size);
  4811. return true;
  4812. });
  4813. ASSERT_TRUE(result);
  4814. // FIXME: compressed data size is expected to be greater than 4GiB,
  4815. // but there is no guarantee
  4816. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4817. // decompress data over 4GiB
  4818. std::string decompressed_data;
  4819. decompressed_data.reserve(data_size);
  4820. httplib::detail::gzip_decompressor decompressor;
  4821. result = decompressor.decompress(
  4822. compressed_data.data(), compressed_data.size(),
  4823. [&](const char *data, size_t size) {
  4824. decompressed_data.insert(decompressed_data.size(), data, size);
  4825. return true;
  4826. });
  4827. ASSERT_TRUE(result);
  4828. // compare
  4829. ASSERT_EQ(data_size, decompressed_data.size());
  4830. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4831. 0);
  4832. }
  4833. #endif
  4834. #endif
  4835. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4836. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4837. Headers headers;
  4838. headers.emplace("Accept-Encoding", "br");
  4839. auto res = cli_.Get("/streamed-chunked", headers);
  4840. ASSERT_TRUE(res);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ(std::string("123456789"), res->body);
  4843. }
  4844. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4845. Headers headers;
  4846. headers.emplace("Accept-Encoding", "br");
  4847. auto res = cli_.Get("/streamed-chunked2", headers);
  4848. ASSERT_TRUE(res);
  4849. EXPECT_EQ(StatusCode::OK_200, res->status);
  4850. EXPECT_EQ(std::string("123456789"), res->body);
  4851. }
  4852. #endif
  4853. TEST_F(ServerTest, Patch) {
  4854. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. EXPECT_EQ("PATCH", res->body);
  4858. }
  4859. TEST_F(ServerTest, Delete) {
  4860. auto res = cli_.Delete("/delete");
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ(StatusCode::OK_200, res->status);
  4863. EXPECT_EQ("DELETE", res->body);
  4864. }
  4865. TEST_F(ServerTest, DeleteContentReceiver) {
  4866. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ("content", res->body);
  4870. }
  4871. TEST_F(ServerTest, Options) {
  4872. auto res = cli_.Options("*");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4876. EXPECT_TRUE(res->body.empty());
  4877. }
  4878. TEST_F(ServerTest, URL) {
  4879. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, ArrayParam) {
  4884. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST_F(ServerTest, NoMultipleHeaders) {
  4889. Headers headers = {{"Content-Length", "5"}};
  4890. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4891. "text/plain");
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. }
  4895. TEST_F(ServerTest, PostContentReceiver) {
  4896. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4897. ASSERT_TRUE(res);
  4898. ASSERT_EQ(StatusCode::OK_200, res->status);
  4899. ASSERT_EQ("content", res->body);
  4900. }
  4901. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4902. UploadFormDataItems items = {
  4903. {"text1", "text default", "", ""},
  4904. {"text2", "aωb", "", ""},
  4905. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4906. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4907. {"file3", "", "", "application/octet-stream"},
  4908. };
  4909. auto res = cli_.Post("/content_receiver", items);
  4910. ASSERT_TRUE(res);
  4911. EXPECT_EQ(StatusCode::OK_200, res->status);
  4912. }
  4913. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4914. UploadFormDataItems items = {
  4915. {"text1", "text default", "", ""},
  4916. {"text2", "aωb", "", ""},
  4917. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4918. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4919. {"file3", "", "", "application/octet-stream"},
  4920. };
  4921. auto boundary = std::string("+++++");
  4922. std::string body;
  4923. for (const auto &item : items) {
  4924. body += "--" + boundary + "\r\n";
  4925. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4926. if (!item.filename.empty()) {
  4927. body += "; filename=\"" + item.filename + "\"";
  4928. }
  4929. body += "\r\n";
  4930. if (!item.content_type.empty()) {
  4931. body += "Content-Type: " + item.content_type + "\r\n";
  4932. }
  4933. body += "\r\n";
  4934. body += item.content + "\r\n";
  4935. }
  4936. body += "--" + boundary + "--\r\n";
  4937. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4938. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4939. ASSERT_TRUE(res);
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. }
  4942. TEST_F(ServerTest, PostContentReceiverGzip) {
  4943. cli_.set_compress(true);
  4944. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4945. ASSERT_TRUE(res);
  4946. ASSERT_EQ(StatusCode::OK_200, res->status);
  4947. ASSERT_EQ("content", res->body);
  4948. }
  4949. TEST_F(ServerTest, PutContentReceiver) {
  4950. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4951. ASSERT_TRUE(res);
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. ASSERT_EQ("content", res->body);
  4954. }
  4955. TEST_F(ServerTest, PatchContentReceiver) {
  4956. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4957. ASSERT_TRUE(res);
  4958. ASSERT_EQ(StatusCode::OK_200, res->status);
  4959. ASSERT_EQ("content", res->body);
  4960. }
  4961. template <typename ClientType>
  4962. void TestWithHeadersAndContentReceiver(
  4963. ClientType &cli,
  4964. std::function<Result(ClientType &, const std::string &, const Headers &,
  4965. const std::string &, const std::string &,
  4966. ContentReceiver, DownloadProgress)>
  4967. request_func) {
  4968. Headers headers;
  4969. headers.emplace("X-Custom-Header", "test-value");
  4970. std::string received_body;
  4971. auto res = request_func(
  4972. cli, "/content_receiver", headers, "content", "application/json",
  4973. [&](const char *data, size_t data_length) {
  4974. received_body.append(data, data_length);
  4975. return true;
  4976. },
  4977. nullptr);
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("content", received_body);
  4981. }
  4982. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4983. #ifdef CPPHTTPLIB_SSL_ENABLED
  4984. using ClientT = SSLClient;
  4985. #else
  4986. using ClientT = Client;
  4987. #endif
  4988. TestWithHeadersAndContentReceiver<ClientT>(
  4989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4990. const std::string &body, const std::string &content_type,
  4991. ContentReceiver receiver, DownloadProgress progress) {
  4992. return cli.Post(path, headers, body, content_type, receiver, progress);
  4993. });
  4994. }
  4995. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4996. #ifdef CPPHTTPLIB_SSL_ENABLED
  4997. using ClientT = SSLClient;
  4998. #else
  4999. using ClientT = Client;
  5000. #endif
  5001. TestWithHeadersAndContentReceiver<ClientT>(
  5002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5003. const std::string &body, const std::string &content_type,
  5004. ContentReceiver receiver, DownloadProgress progress) {
  5005. return cli.Put(path, headers, body, content_type, receiver, progress);
  5006. });
  5007. }
  5008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5009. #ifdef CPPHTTPLIB_SSL_ENABLED
  5010. using ClientT = SSLClient;
  5011. #else
  5012. using ClientT = Client;
  5013. #endif
  5014. TestWithHeadersAndContentReceiver<ClientT>(
  5015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5016. const std::string &body, const std::string &content_type,
  5017. ContentReceiver receiver, DownloadProgress progress) {
  5018. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5019. });
  5020. }
  5021. template <typename ClientType>
  5022. void TestWithHeadersAndContentReceiverWithProgress(
  5023. ClientType &cli,
  5024. std::function<Result(ClientType &, const std::string &, const Headers &,
  5025. const std::string &, const std::string &,
  5026. ContentReceiver, DownloadProgress)>
  5027. request_func) {
  5028. Headers headers;
  5029. headers.emplace("X-Test-Header", "progress-test");
  5030. std::string received_body;
  5031. auto progress_called = false;
  5032. auto res = request_func(
  5033. cli, "/content_receiver", headers, "content", "text/plain",
  5034. [&](const char *data, size_t data_length) {
  5035. received_body.append(data, data_length);
  5036. return true;
  5037. },
  5038. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5039. progress_called = true;
  5040. return true;
  5041. });
  5042. ASSERT_TRUE(res);
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ("content", received_body);
  5045. EXPECT_TRUE(progress_called);
  5046. }
  5047. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5048. #ifdef CPPHTTPLIB_SSL_ENABLED
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  5057. return cli.Post(path, headers, body, content_type, receiver, progress);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5061. #ifdef CPPHTTPLIB_SSL_ENABLED
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  5070. return cli.Put(path, headers, body, content_type, receiver, progress);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5074. #ifdef CPPHTTPLIB_SSL_ENABLED
  5075. using ClientT = SSLClient;
  5076. #else
  5077. using ClientT = Client;
  5078. #endif
  5079. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5080. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5081. const std::string &body, const std::string &content_type,
  5082. ContentReceiver receiver, DownloadProgress progress) {
  5083. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5084. });
  5085. }
  5086. template <typename ClientType>
  5087. void TestWithHeadersAndContentReceiverError(
  5088. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5089. const Headers &, const std::string &,
  5090. const std::string &, ContentReceiver)>
  5091. request_func) {
  5092. Headers headers;
  5093. headers.emplace("X-Error-Test", "true");
  5094. std::string received_body;
  5095. auto receiver_failed = false;
  5096. auto res =
  5097. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5098. [&](const char *data, size_t data_length) {
  5099. received_body.append(data, data_length);
  5100. receiver_failed = true;
  5101. return false;
  5102. });
  5103. ASSERT_FALSE(res);
  5104. EXPECT_TRUE(receiver_failed);
  5105. }
  5106. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5107. #ifdef CPPHTTPLIB_SSL_ENABLED
  5108. using ClientT = SSLClient;
  5109. #else
  5110. using ClientT = Client;
  5111. #endif
  5112. TestWithHeadersAndContentReceiverError<ClientT>(
  5113. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5114. const std::string &body, const std::string &content_type,
  5115. ContentReceiver receiver) {
  5116. return cli.Post(path, headers, body, content_type, receiver);
  5117. });
  5118. }
  5119. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5120. #ifdef CPPHTTPLIB_SSL_ENABLED
  5121. using ClientT = SSLClient;
  5122. #else
  5123. using ClientT = Client;
  5124. #endif
  5125. TestWithHeadersAndContentReceiverError<ClientT>(
  5126. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5127. const std::string &body, const std::string &content_type,
  5128. ContentReceiver receiver) {
  5129. return cli.Put(path, headers, body, content_type, receiver);
  5130. });
  5131. }
  5132. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5133. #ifdef CPPHTTPLIB_SSL_ENABLED
  5134. using ClientT = SSLClient;
  5135. #else
  5136. using ClientT = Client;
  5137. #endif
  5138. TestWithHeadersAndContentReceiverError<ClientT>(
  5139. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5140. const std::string &body, const std::string &content_type,
  5141. ContentReceiver receiver) {
  5142. return cli.Patch(path, headers, body, content_type, receiver);
  5143. });
  5144. }
  5145. TEST_F(ServerTest, PostQueryStringAndBody) {
  5146. auto res =
  5147. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5148. ASSERT_TRUE(res);
  5149. ASSERT_EQ(StatusCode::OK_200, res->status);
  5150. }
  5151. TEST_F(ServerTest, HTTP2Magic) {
  5152. Request req;
  5153. req.method = "PRI";
  5154. req.path = "*";
  5155. req.body = "SM";
  5156. auto res = std::make_shared<Response>();
  5157. auto error = Error::Success;
  5158. auto ret = cli_.send(req, *res, error);
  5159. ASSERT_TRUE(ret);
  5160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5161. }
  5162. TEST_F(ServerTest, KeepAlive) {
  5163. auto res = cli_.Get("/hi");
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("Hello World!", res->body);
  5168. res = cli_.Get("/hi");
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("Hello World!", res->body);
  5173. res = cli_.Get("/hi");
  5174. ASSERT_TRUE(res);
  5175. EXPECT_EQ(StatusCode::OK_200, res->status);
  5176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5177. EXPECT_EQ("Hello World!", res->body);
  5178. res = cli_.Get("/not-exist");
  5179. ASSERT_TRUE(res);
  5180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5181. res = cli_.Post("/empty", "", "text/plain");
  5182. ASSERT_TRUE(res);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5185. EXPECT_EQ("empty", res->body);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. res = cli_.Post(
  5188. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5189. "text/plain");
  5190. ASSERT_TRUE(res);
  5191. EXPECT_EQ(StatusCode::OK_200, res->status);
  5192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5193. EXPECT_EQ("empty", res->body);
  5194. cli_.set_keep_alive(false);
  5195. res = cli_.Get("/last-request");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. EXPECT_EQ("close", res->get_header_value("Connection"));
  5199. }
  5200. TEST_F(ServerTest, TooManyRedirect) {
  5201. cli_.set_follow_location(true);
  5202. auto res = cli_.Get("/redirect/0");
  5203. ASSERT_TRUE(!res);
  5204. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5205. }
  5206. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5207. Request req;
  5208. req.method = "FOOBAR";
  5209. req.path = "/hi";
  5210. cli_.set_keep_alive(true);
  5211. auto res = cli_.send(req);
  5212. ASSERT_TRUE(res);
  5213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5214. EXPECT_EQ("close", res->get_header_value("Connection"));
  5215. EXPECT_FALSE(cli_.is_socket_open());
  5216. }
  5217. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5218. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5219. TEST_F(ServerTest, Gzip) {
  5220. Headers headers;
  5221. headers.emplace("Accept-Encoding", "gzip, deflate");
  5222. auto res = cli_.Get("/compress", headers);
  5223. ASSERT_TRUE(res);
  5224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5226. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5228. "7890123456789012345678901234567890",
  5229. res->body);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. }
  5232. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5233. Headers headers;
  5234. headers.emplace("Accept-Encoding", "");
  5235. auto res = cli_.Get("/compress", headers);
  5236. ASSERT_TRUE(res);
  5237. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5239. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5240. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5241. "7890123456789012345678901234567890",
  5242. res->body);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. }
  5245. TEST_F(ServerTest, GzipWithContentReceiver) {
  5246. Headers headers;
  5247. headers.emplace("Accept-Encoding", "gzip, deflate");
  5248. std::string body;
  5249. auto res = cli_.Get("/compress", headers,
  5250. [&](const char *data, uint64_t data_length) {
  5251. EXPECT_EQ(100U, data_length);
  5252. body.append(data, data_length);
  5253. return true;
  5254. });
  5255. ASSERT_TRUE(res);
  5256. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5258. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5259. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5260. "7890123456789012345678901234567890",
  5261. body);
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. }
  5264. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5265. Headers headers;
  5266. headers.emplace("Accept-Encoding", "gzip, deflate");
  5267. cli_.set_decompress(false);
  5268. auto res = cli_.Get("/compress", headers);
  5269. ASSERT_TRUE(res);
  5270. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5271. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5272. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5273. EXPECT_EQ(33U, res->body.size());
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. }
  5276. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5277. Headers headers;
  5278. headers.emplace("Accept-Encoding", "");
  5279. std::string body;
  5280. auto res = cli_.Get("/compress", headers,
  5281. [&](const char *data, uint64_t data_length) {
  5282. EXPECT_EQ(100U, data_length);
  5283. body.append(data, data_length);
  5284. return true;
  5285. });
  5286. ASSERT_TRUE(res);
  5287. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, NoGzip) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "gzip, deflate");
  5298. auto res = cli_.Get("/nocompress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5301. EXPECT_EQ("application/octet-stream", 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, NoGzipWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "gzip, deflate");
  5311. std::string body;
  5312. auto res = cli_.Get("/nocompress", 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(false, res->has_header("Content-Encoding"));
  5320. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("100", 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, MultipartFormDataGzip) {
  5328. UploadFormDataItems items = {
  5329. {"key1", "test", "", ""},
  5330. {"key2", "--abcdefg123", "", ""},
  5331. };
  5332. cli_.set_compress(true);
  5333. auto res = cli_.Post("/compress-multipart", items);
  5334. ASSERT_TRUE(res);
  5335. EXPECT_EQ(StatusCode::OK_200, res->status);
  5336. }
  5337. #endif
  5338. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5339. TEST_F(ServerTest, Brotli) {
  5340. Headers headers;
  5341. headers.emplace("Accept-Encoding", "br");
  5342. auto res = cli_.Get("/compress", headers);
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. res->body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. #endif
  5353. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5354. TEST_F(ServerTest, Zstd) {
  5355. Headers headers;
  5356. headers.emplace("Accept-Encoding", "zstd");
  5357. auto res = cli_.Get("/compress", headers);
  5358. ASSERT_TRUE(res);
  5359. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5360. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5361. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5362. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5363. "7890123456789012345678901234567890",
  5364. res->body);
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. }
  5367. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5368. Headers headers;
  5369. headers.emplace("Accept-Encoding", "");
  5370. auto res = cli_.Get("/compress", headers);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5374. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5376. "7890123456789012345678901234567890",
  5377. res->body);
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. }
  5380. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5381. Headers headers;
  5382. headers.emplace("Accept-Encoding", "zstd");
  5383. std::string body;
  5384. auto res = cli_.Get("/compress", headers,
  5385. [&](const char *data, uint64_t data_length) {
  5386. EXPECT_EQ(100U, data_length);
  5387. body.append(data, data_length);
  5388. return true;
  5389. });
  5390. ASSERT_TRUE(res);
  5391. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5393. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5394. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5395. "7890123456789012345678901234567890",
  5396. body);
  5397. EXPECT_EQ(StatusCode::OK_200, res->status);
  5398. }
  5399. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5400. Headers headers;
  5401. headers.emplace("Accept-Encoding", "zstd");
  5402. cli_.set_decompress(false);
  5403. auto res = cli_.Get("/compress", headers);
  5404. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5405. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5406. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5407. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5411. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. ASSERT_EQ(26U, res->body.size());
  5414. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5415. 0);
  5416. }
  5417. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, NoZstd) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "zstd");
  5439. auto res = cli_.Get("/nocompress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5442. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "zstd");
  5452. std::string body;
  5453. auto res = cli_.Get("/nocompress", headers,
  5454. [&](const char *data, uint64_t data_length) {
  5455. EXPECT_EQ(100U, data_length);
  5456. body.append(data, data_length);
  5457. return true;
  5458. });
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5464. "7890123456789012345678901234567890",
  5465. body);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. // TODO: How to enable zstd ??
  5469. TEST_F(ServerTest, MultipartFormDataZstd) {
  5470. UploadFormDataItems items = {
  5471. {"key1", "test", "", ""},
  5472. {"key2", "--abcdefg123", "", ""},
  5473. };
  5474. Headers headers;
  5475. headers.emplace("Accept-Encoding", "zstd");
  5476. cli_.set_compress(true);
  5477. auto res = cli_.Post("/compress-multipart", headers, items);
  5478. ASSERT_TRUE(res);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. }
  5481. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5482. Headers headers;
  5483. headers.emplace("Accept-Encoding", "zstd");
  5484. cli_.set_compress(true);
  5485. auto res = cli_.Put(
  5486. "/put", headers, 3,
  5487. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5488. sink.os << "PUT";
  5489. return true;
  5490. },
  5491. "text/plain");
  5492. ASSERT_TRUE(res);
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. EXPECT_EQ("PUT", res->body);
  5495. }
  5496. // Pre-compression logging tests
  5497. TEST_F(ServerTest, PreCompressionLogging) {
  5498. // Test data for compression (matches the actual /compress endpoint content)
  5499. const std::string test_content =
  5500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5501. "3456789012345678901234567890";
  5502. // Variables to capture logging data
  5503. std::string pre_compression_body;
  5504. std::string pre_compression_content_type;
  5505. std::string pre_compression_content_encoding;
  5506. std::string post_compression_body;
  5507. std::string post_compression_content_type;
  5508. std::string post_compression_content_encoding;
  5509. // Set up pre-compression logger
  5510. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5511. const Response &res) {
  5512. pre_compression_body = res.body;
  5513. pre_compression_content_type = res.get_header_value("Content-Type");
  5514. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5515. });
  5516. // Set up post-compression logger
  5517. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5518. post_compression_body = res.body;
  5519. post_compression_content_type = res.get_header_value("Content-Type");
  5520. post_compression_content_encoding =
  5521. res.get_header_value("Content-Encoding");
  5522. });
  5523. // Test with gzip compression
  5524. Headers headers;
  5525. headers.emplace("Accept-Encoding", "gzip");
  5526. auto res = cli_.Get("/compress", headers);
  5527. // Verify response was compressed
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5531. // Verify pre-compression logger captured uncompressed content
  5532. EXPECT_EQ(test_content, pre_compression_body);
  5533. EXPECT_EQ("text/plain", pre_compression_content_type);
  5534. EXPECT_TRUE(pre_compression_content_encoding
  5535. .empty()); // No encoding header before compression
  5536. // Verify post-compression logger captured compressed content
  5537. EXPECT_NE(test_content,
  5538. post_compression_body); // Should be different after compression
  5539. EXPECT_EQ("text/plain", post_compression_content_type);
  5540. EXPECT_EQ("gzip", post_compression_content_encoding);
  5541. // Verify compressed content is smaller
  5542. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5543. }
  5544. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5545. const std::string test_content =
  5546. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5547. "3456789012345678901234567890";
  5548. std::string pre_compression_body;
  5549. std::string post_compression_body;
  5550. svr_.set_pre_compression_logger(
  5551. [&](const Request & /*req*/, const Response &res) {
  5552. pre_compression_body = res.body;
  5553. });
  5554. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5555. post_compression_body = res.body;
  5556. });
  5557. Headers headers;
  5558. headers.emplace("Accept-Encoding", "br");
  5559. auto res = cli_.Get("/compress", headers);
  5560. ASSERT_TRUE(res);
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5563. // Verify pre-compression content is uncompressed
  5564. EXPECT_EQ(test_content, pre_compression_body);
  5565. // Verify post-compression content is compressed
  5566. EXPECT_NE(test_content, post_compression_body);
  5567. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5568. }
  5569. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5570. const std::string test_content =
  5571. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5572. "3456789012345678901234567890";
  5573. std::string pre_compression_body;
  5574. std::string post_compression_body;
  5575. svr_.set_pre_compression_logger(
  5576. [&](const Request & /*req*/, const Response &res) {
  5577. pre_compression_body = res.body;
  5578. });
  5579. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5580. post_compression_body = res.body;
  5581. });
  5582. // Request without compression (use /nocompress endpoint)
  5583. Headers headers;
  5584. auto res = cli_.Get("/nocompress", headers);
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5588. // Pre-compression logger should not be called when no compression is applied
  5589. EXPECT_TRUE(
  5590. pre_compression_body.empty()); // Pre-compression logger not called
  5591. EXPECT_EQ(
  5592. test_content,
  5593. post_compression_body); // Post-compression logger captures final content
  5594. }
  5595. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5596. const std::string test_content =
  5597. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5598. "3456789012345678901234567890";
  5599. std::string pre_compression_body;
  5600. bool pre_logger_called = false;
  5601. // Set only pre-compression logger
  5602. svr_.set_pre_compression_logger(
  5603. [&](const Request & /*req*/, const Response &res) {
  5604. pre_compression_body = res.body;
  5605. pre_logger_called = true;
  5606. });
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "gzip");
  5609. auto res = cli_.Get("/compress", headers);
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5613. // Verify pre-compression logger was called
  5614. EXPECT_TRUE(pre_logger_called);
  5615. EXPECT_EQ(test_content, pre_compression_body);
  5616. }
  5617. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5618. {
  5619. // Test with Expect: 100-continue header - success case
  5620. // Server returns 100 Continue, client sends body, server returns 200 OK
  5621. Request req;
  5622. req.method = "POST";
  5623. req.path = "/post-large";
  5624. req.set_header("Expect", "100-continue");
  5625. req.body = LARGE_DATA;
  5626. Response res;
  5627. auto error = Error::Success;
  5628. cli_.set_keep_alive(true);
  5629. auto ret = cli_.send(req, res, error);
  5630. EXPECT_TRUE(ret);
  5631. EXPECT_EQ(StatusCode::OK_200, res.status);
  5632. EXPECT_EQ(LARGE_DATA, res.body);
  5633. }
  5634. {
  5635. // Test with Expect: 100-continue header - error case
  5636. // Client should not send the body when server returns an error
  5637. Request req;
  5638. req.method = "POST";
  5639. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5640. req.set_header("Expect", "100-continue");
  5641. req.body = LARGE_DATA;
  5642. Response res;
  5643. auto error = Error::Success;
  5644. auto start = std::chrono::high_resolution_clock::now();
  5645. cli_.set_keep_alive(true);
  5646. auto ret = cli_.send(req, res, error);
  5647. auto end = std::chrono::high_resolution_clock::now();
  5648. auto elapsed =
  5649. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5650. .count();
  5651. // With Expect: 100-continue, request completes successfully but with error
  5652. EXPECT_TRUE(ret);
  5653. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5654. EXPECT_EQ("close", res.get_header_value("Connection"));
  5655. EXPECT_FALSE(cli_.is_socket_open());
  5656. EXPECT_LE(elapsed, 200);
  5657. }
  5658. {
  5659. // Send an extra GET request to ensure error recovery without hanging
  5660. Request req;
  5661. req.method = "GET";
  5662. req.path = "/hi";
  5663. auto start = std::chrono::high_resolution_clock::now();
  5664. auto res = cli_.send(req);
  5665. auto end = std::chrono::high_resolution_clock::now();
  5666. auto elapsed =
  5667. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5668. .count();
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("Hello World!", res->body);
  5672. EXPECT_LE(elapsed, 500);
  5673. }
  5674. }
  5675. TEST(ZstdDecompressor, ChunkedDecompression) {
  5676. std::string data;
  5677. for (size_t i = 0; i < 32 * 1024; ++i) {
  5678. data.push_back(static_cast<char>('a' + i % 26));
  5679. }
  5680. std::string compressed_data;
  5681. {
  5682. httplib::detail::zstd_compressor compressor;
  5683. bool result = compressor.compress(
  5684. data.data(), data.size(),
  5685. /*last=*/true,
  5686. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5687. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5688. compressed_data_size);
  5689. return true;
  5690. });
  5691. ASSERT_TRUE(result);
  5692. }
  5693. std::string decompressed_data;
  5694. {
  5695. httplib::detail::zstd_decompressor decompressor;
  5696. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5697. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5698. size_t chunk_size = 130;
  5699. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5700. chunk_begin += chunk_size) {
  5701. size_t current_chunk_size =
  5702. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5703. bool result = decompressor.decompress(
  5704. compressed_data.data() + chunk_begin, current_chunk_size,
  5705. [&](const char *decompressed_data_chunk,
  5706. size_t decompressed_data_chunk_size) {
  5707. decompressed_data.insert(decompressed_data.size(),
  5708. decompressed_data_chunk,
  5709. decompressed_data_chunk_size);
  5710. return true;
  5711. });
  5712. ASSERT_TRUE(result);
  5713. }
  5714. }
  5715. ASSERT_EQ(data, decompressed_data);
  5716. }
  5717. TEST(ZstdDecompressor, Decompress) {
  5718. std::string original_text = "Compressed with ZSTD";
  5719. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5720. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5721. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5722. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5723. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5724. std::string decompressed_data;
  5725. {
  5726. httplib::detail::zstd_decompressor decompressor;
  5727. bool result = decompressor.decompress(
  5728. compressed_data.data(), compressed_data.size(),
  5729. [&](const char *decompressed_data_chunk,
  5730. size_t decompressed_data_chunk_size) {
  5731. decompressed_data.insert(decompressed_data.size(),
  5732. decompressed_data_chunk,
  5733. decompressed_data_chunk_size);
  5734. return true;
  5735. });
  5736. ASSERT_TRUE(result);
  5737. }
  5738. ASSERT_EQ(original_text, decompressed_data);
  5739. }
  5740. #endif
  5741. // Sends a raw request to a server listening at HOST:PORT.
  5742. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5743. std::string *resp = nullptr) {
  5744. auto error = Error::Success;
  5745. auto client_sock = detail::create_client_socket(
  5746. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5747. /*connection_timeout_sec=*/5, 0,
  5748. /*read_timeout_sec=*/5, 0,
  5749. /*write_timeout_sec=*/5, 0, std::string(), error);
  5750. if (client_sock == INVALID_SOCKET) { return false; }
  5751. auto ret = detail::process_client_socket(
  5752. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5753. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5754. if (req.size() !=
  5755. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5756. return false;
  5757. }
  5758. char buf[512];
  5759. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5760. while (line_reader.getline()) {
  5761. if (resp) { *resp += line_reader.ptr(); }
  5762. }
  5763. return true;
  5764. });
  5765. detail::close_socket(client_sock);
  5766. return ret;
  5767. }
  5768. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5769. Server svr;
  5770. std::string header_value;
  5771. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5772. header_value = req.get_header_value("foo");
  5773. res.set_content("ok", "text/plain");
  5774. });
  5775. thread t = thread([&] { svr.listen(HOST, PORT); });
  5776. auto se = detail::scope_exit([&] {
  5777. svr.stop();
  5778. t.join();
  5779. ASSERT_FALSE(svr.is_running());
  5780. });
  5781. svr.wait_until_ready();
  5782. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5783. // like characters are not treated the same - use vertical tab and escape.
  5784. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5785. "foo: \t \v bar \x1B\t \r\n"
  5786. "Connection: close\r\n"
  5787. "\r\n";
  5788. std::string res;
  5789. ASSERT_TRUE(send_request(5, req, &res));
  5790. EXPECT_EQ(header_value, "");
  5791. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5792. }
  5793. // Sends a raw request and verifies that there isn't a crash or exception.
  5794. static void test_raw_request(const std::string &req,
  5795. std::string *out = nullptr) {
  5796. Server svr;
  5797. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5798. res.set_content("ok", "text/plain");
  5799. });
  5800. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5801. res.set_content("ok", "text/plain");
  5802. });
  5803. svr.Get("/header_field_value_check",
  5804. [&](const Request & /*req*/, Response &res) {
  5805. res.set_content("ok", "text/plain");
  5806. });
  5807. // Server read timeout must be longer than the client read timeout for the
  5808. // bug to reproduce, probably to force the server to process a request
  5809. // without a trailing blank line.
  5810. const time_t client_read_timeout_sec = 1;
  5811. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5812. bool listen_thread_ok = false;
  5813. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5814. auto se = detail::scope_exit([&] {
  5815. svr.stop();
  5816. t.join();
  5817. ASSERT_FALSE(svr.is_running());
  5818. EXPECT_TRUE(listen_thread_ok);
  5819. });
  5820. svr.wait_until_ready();
  5821. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5822. }
  5823. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5824. // A certain header line causes an exception if the header property is parsed
  5825. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5826. test_raw_request(
  5827. "GET /hi HTTP/1.1\r\n"
  5828. " : "
  5829. " "
  5830. " ");
  5831. }
  5832. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5833. // A certain header line causes an exception if the header property *name* is
  5834. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5835. // greedy matcher and requires backtracking when there are a lot of ":"
  5836. // characters.
  5837. // This occurs with libc++ but not libstdc++.
  5838. test_raw_request(
  5839. "GET /hi HTTP/1.1\r\n"
  5840. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5841. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5842. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5843. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5844. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5845. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5846. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5847. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5848. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5849. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5850. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5851. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5852. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5853. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5854. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5855. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5856. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5857. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5858. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5859. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5860. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5861. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5862. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5863. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5864. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5865. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5866. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5867. "&&&%%%");
  5868. }
  5869. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5870. // Make sure this doesn't crash the server.
  5871. // In a previous version of the header line regex, the "\r" rendered the line
  5872. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5873. // a new position where the leading white space ended and the field value
  5874. // began.
  5875. // The crash occurs with libc++ but not libstdc++.
  5876. test_raw_request("GET /hi HTTP/1.1\r\n"
  5877. "a:" +
  5878. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5879. "\r\n"
  5880. "\r\n");
  5881. }
  5882. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5883. std::string out;
  5884. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5885. "Content-Type: text/plain\r\n"
  5886. "Transfer-Encoding: chunked\r\n"
  5887. "\r\n"
  5888. "nothex\r\n",
  5889. &out);
  5890. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5891. }
  5892. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5893. std::string out;
  5894. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5895. "Content-Type: text/plain\r\n"
  5896. "Transfer-Encoding: chunked\r\n"
  5897. "\r\n"
  5898. "3\r\n"
  5899. "xyz\r\n"
  5900. "NaN\r\n",
  5901. &out);
  5902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5903. }
  5904. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5905. std::string out;
  5906. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5907. "Content-Type: text/plain\r\n"
  5908. "Transfer-Encoding: chunked\r\n"
  5909. "\r\n"
  5910. // Length is too large for 64 bits.
  5911. "1ffffffffffffffff\r\n"
  5912. "xyz\r\n",
  5913. &out);
  5914. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5915. }
  5916. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5917. test_raw_request("GET /hi HTTP/1.1\r\n"
  5918. "Content-Type: text/plain\r\n\r");
  5919. }
  5920. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5921. std::string out;
  5922. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5923. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5924. }
  5925. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5926. Server svr;
  5927. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5928. EXPECT_TRUE(!req.remote_addr.empty());
  5929. });
  5930. thread t = thread([&] { svr.listen(HOST, PORT); });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. t.join();
  5934. ASSERT_FALSE(svr.is_running());
  5935. });
  5936. svr.wait_until_ready();
  5937. // Send an invalid request line to trigger Bad Request
  5938. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5939. std::string out;
  5940. ASSERT_TRUE(send_request(5, bad_req, &out));
  5941. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5942. }
  5943. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5944. std::string out;
  5945. std::string request(
  5946. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5947. test_raw_request(request, &out);
  5948. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5949. }
  5950. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5951. std::string out;
  5952. std::string request(
  5953. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5954. test_raw_request(request, &out);
  5955. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5956. }
  5957. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5958. std::string out;
  5959. std::string request(
  5960. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5961. test_raw_request(request, &out);
  5962. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5963. }
  5964. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5965. std::string out;
  5966. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5967. "Test: \r\n\r\n",
  5968. &out);
  5969. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5970. }
  5971. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5972. Server svr;
  5973. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5974. res.set_header("Cache-Control", "no-cache");
  5975. res.set_chunked_content_provider(
  5976. "text/event-stream", [](size_t offset, DataSink &sink) {
  5977. std::string s = "data:";
  5978. s += std::to_string(offset);
  5979. s += "\n\n";
  5980. auto ret = sink.write(s.data(), s.size());
  5981. EXPECT_TRUE(ret);
  5982. std::this_thread::sleep_for(std::chrono::seconds(1));
  5983. return true;
  5984. });
  5985. });
  5986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5987. svr.wait_until_ready();
  5988. Client client(HOST, PORT);
  5989. const Headers headers = {{"Accept", "text/event-stream"}};
  5990. auto get_thread = std::thread([&client, &headers]() {
  5991. auto res = client.Get(
  5992. "/events", headers,
  5993. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5994. });
  5995. auto se = detail::scope_exit([&] {
  5996. svr.stop();
  5997. get_thread.join();
  5998. listen_thread.join();
  5999. ASSERT_FALSE(svr.is_running());
  6000. });
  6001. // Give GET time to get a few messages.
  6002. std::this_thread::sleep_for(std::chrono::seconds(2));
  6003. }
  6004. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6005. httplib::Server svr;
  6006. svr.Post("/hi",
  6007. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6008. res.status = StatusCode::OK_200;
  6009. });
  6010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. auto res = cli.Post("/hi", "data", "text/plain");
  6014. ASSERT_TRUE(res);
  6015. EXPECT_EQ(StatusCode::OK_200, res->status);
  6016. svr.stop();
  6017. thread.join();
  6018. ASSERT_FALSE(svr.is_running());
  6019. res = cli.Post("/hi", "data", "text/plain");
  6020. ASSERT_FALSE(res);
  6021. }
  6022. TEST(ServerStopTest, ListenFailure) {
  6023. Server svr;
  6024. auto t = thread([&]() {
  6025. auto ret = svr.listen("????", PORT);
  6026. EXPECT_FALSE(ret);
  6027. });
  6028. svr.wait_until_ready();
  6029. svr.stop();
  6030. t.join();
  6031. }
  6032. TEST(ServerStopTest, Decommision) {
  6033. Server svr;
  6034. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6035. for (int i = 0; i < 4; i++) {
  6036. auto is_even = !(i % 2);
  6037. std::thread t{[&] {
  6038. try {
  6039. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6040. if (is_even) {
  6041. throw std::runtime_error("Some thing that happens to go wrong.");
  6042. }
  6043. svr.listen(HOST, PORT);
  6044. } catch (...) { svr.decommission(); }
  6045. }};
  6046. svr.wait_until_ready();
  6047. // Server is up
  6048. {
  6049. Client cli(HOST, PORT);
  6050. auto res = cli.Get("/hi");
  6051. if (is_even) {
  6052. EXPECT_FALSE(res);
  6053. } else {
  6054. EXPECT_TRUE(res);
  6055. EXPECT_EQ("hi...", res->body);
  6056. }
  6057. }
  6058. svr.stop();
  6059. t.join();
  6060. // Server is down...
  6061. {
  6062. Client cli(HOST, PORT);
  6063. auto res = cli.Get("/hi");
  6064. EXPECT_FALSE(res);
  6065. }
  6066. }
  6067. }
  6068. // Helper function for string body upload progress tests
  6069. template <typename SetupHandler, typename ClientCall>
  6070. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6071. ClientCall &&client_call,
  6072. const string &body) {
  6073. Server svr;
  6074. setup_handler(svr);
  6075. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6076. auto se = detail::scope_exit([&] {
  6077. svr.stop();
  6078. t.join();
  6079. });
  6080. svr.wait_until_ready();
  6081. Client cli(HOST, PORT);
  6082. vector<uint64_t> progress_values;
  6083. bool progress_called = false;
  6084. auto res =
  6085. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6086. progress_values.push_back(current);
  6087. progress_called = true;
  6088. return true;
  6089. });
  6090. ASSERT_TRUE(res);
  6091. EXPECT_EQ(200, res->status);
  6092. EXPECT_TRUE(progress_called);
  6093. }
  6094. TEST(UploadProgressTest, PostStringBodyBasic) {
  6095. TestStringBodyUploadProgress(
  6096. [](Server &svr) {
  6097. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6098. res.set_content("received", "text/plain");
  6099. });
  6100. },
  6101. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6102. return cli.Post("/test", body, "text/plain", progress_callback);
  6103. },
  6104. "test data for upload progress");
  6105. }
  6106. TEST(UploadProgressTest, PutStringBodyBasic) {
  6107. TestStringBodyUploadProgress(
  6108. [](Server &svr) {
  6109. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6110. res.set_content("put received", "text/plain");
  6111. });
  6112. },
  6113. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6114. return cli.Put("/test", body, "text/plain", progress_callback);
  6115. },
  6116. "put test data for upload progress");
  6117. }
  6118. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6119. TestStringBodyUploadProgress(
  6120. [](Server &svr) {
  6121. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6122. res.set_content("patch received", "text/plain");
  6123. });
  6124. },
  6125. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6126. return cli.Patch("/test", body, "text/plain", progress_callback);
  6127. },
  6128. "patch test data for upload progress");
  6129. }
  6130. // Helper function for content provider upload progress tests
  6131. template <typename SetupHandler, typename ClientCall>
  6132. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6133. ClientCall &&client_call) {
  6134. Server svr;
  6135. setup_handler(svr);
  6136. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6137. auto se = detail::scope_exit([&] {
  6138. svr.stop();
  6139. t.join();
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli(HOST, PORT);
  6143. vector<uint64_t> progress_values;
  6144. auto res =
  6145. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(res);
  6150. EXPECT_EQ(200, res->status);
  6151. EXPECT_FALSE(progress_values.empty());
  6152. }
  6153. TEST(UploadProgressTest, PostContentProviderProgress) {
  6154. TestContentProviderUploadProgress(
  6155. [](Server &svr) {
  6156. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6157. res.set_content("provider received", "text/plain");
  6158. });
  6159. },
  6160. [](Client &cli, UploadProgress progress_callback) {
  6161. return cli.Post(
  6162. "/test", 10,
  6163. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6164. sink.os << "test data";
  6165. return true;
  6166. },
  6167. "text/plain", progress_callback);
  6168. });
  6169. }
  6170. // Helper function for multipart upload progress tests
  6171. template <typename SetupHandler, typename ClientCall>
  6172. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6173. ClientCall &&client_call,
  6174. const string &endpoint) {
  6175. Server svr;
  6176. setup_handler(svr);
  6177. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6178. auto se = detail::scope_exit([&] {
  6179. svr.stop();
  6180. t.join();
  6181. });
  6182. svr.wait_until_ready();
  6183. Client cli(HOST, PORT);
  6184. vector<uint64_t> progress_values;
  6185. UploadFormDataItems items = {
  6186. {"field1", "value1", "", ""},
  6187. {"field2", "longer value for progress tracking test", "", ""},
  6188. {"file1", "file content data for upload progress", "test.txt",
  6189. "text/plain"}};
  6190. auto res = client_call(cli, endpoint, items,
  6191. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6192. progress_values.push_back(current);
  6193. return true;
  6194. });
  6195. ASSERT_TRUE(res);
  6196. EXPECT_EQ(200, res->status);
  6197. EXPECT_FALSE(progress_values.empty());
  6198. }
  6199. TEST(UploadProgressTest, PostMultipartProgress) {
  6200. TestMultipartUploadProgress(
  6201. [](Server &svr) {
  6202. svr.Post("/multipart", [](const Request &req, Response &res) {
  6203. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6204. res.set_content("multipart received", "text/plain");
  6205. });
  6206. },
  6207. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6208. UploadProgress progress_callback) {
  6209. return cli.Post(endpoint, items, progress_callback);
  6210. },
  6211. "/multipart");
  6212. }
  6213. // Helper function for basic download progress tests
  6214. template <typename SetupHandler, typename ClientCall>
  6215. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6216. ClientCall &&client_call, const string &endpoint,
  6217. size_t expected_content_size) {
  6218. Server svr;
  6219. setup_handler(svr);
  6220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6221. auto se = detail::scope_exit([&] {
  6222. svr.stop();
  6223. t.join();
  6224. });
  6225. svr.wait_until_ready();
  6226. Client cli(HOST, PORT);
  6227. vector<uint64_t> progress_values;
  6228. auto res = client_call(cli, endpoint,
  6229. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6230. progress_values.push_back(current);
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(200, res->status);
  6235. EXPECT_FALSE(progress_values.empty());
  6236. EXPECT_EQ(expected_content_size, res->body.size());
  6237. }
  6238. TEST(DownloadProgressTest, GetBasic) {
  6239. TestBasicDownloadProgress(
  6240. [](Server &svr) {
  6241. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6242. string content(1000, 'D');
  6243. res.set_content(content, "text/plain");
  6244. });
  6245. },
  6246. [](Client &cli, const string &endpoint,
  6247. DownloadProgress progress_callback) {
  6248. return cli.Get(endpoint, progress_callback);
  6249. },
  6250. "/download", 1000u);
  6251. }
  6252. // Helper function for content receiver download progress tests
  6253. template <typename SetupHandler, typename ClientCall>
  6254. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6255. ClientCall &&client_call,
  6256. const string &endpoint,
  6257. size_t expected_content_size) {
  6258. Server svr;
  6259. setup_handler(svr);
  6260. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. });
  6265. svr.wait_until_ready();
  6266. Client cli(HOST, PORT);
  6267. vector<uint64_t> progress_values;
  6268. string received_body;
  6269. auto res = client_call(
  6270. cli, endpoint,
  6271. [&](const char *data, size_t data_length) -> bool {
  6272. received_body.append(data, data_length);
  6273. return true;
  6274. },
  6275. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6276. progress_values.push_back(current);
  6277. return true;
  6278. });
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ(200, res->status);
  6281. EXPECT_FALSE(progress_values.empty());
  6282. EXPECT_EQ(expected_content_size, received_body.size());
  6283. EXPECT_TRUE(res->body.empty());
  6284. }
  6285. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6286. TestContentReceiverDownloadProgress(
  6287. [](Server &svr) {
  6288. svr.Get("/download-receiver",
  6289. [](const Request & /*req*/, Response &res) {
  6290. string content(2000, 'R');
  6291. res.set_content(content, "text/plain");
  6292. });
  6293. },
  6294. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6295. DownloadProgress progress_callback) {
  6296. return cli.Get(endpoint, content_receiver, progress_callback);
  6297. },
  6298. "/download-receiver", 2000u);
  6299. }
  6300. TEST(StreamingTest, NoContentLengthStreaming) {
  6301. Server svr;
  6302. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6303. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6304. if (offset < 6) {
  6305. sink.os << (offset < 3 ? "a" : "b");
  6306. } else {
  6307. sink.done();
  6308. }
  6309. return true;
  6310. });
  6311. });
  6312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6313. auto listen_se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. listen_thread.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client client(HOST, PORT);
  6320. auto get_thread = std::thread([&client]() {
  6321. std::string s;
  6322. auto res =
  6323. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6324. s += std::string(data, len);
  6325. return true;
  6326. });
  6327. ASSERT_TRUE(res);
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ("aaabbb", s);
  6330. });
  6331. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6332. // Give GET time to get a few messages.
  6333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6334. }
  6335. TEST(MountTest, Unmount) {
  6336. Server svr;
  6337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6338. auto se = detail::scope_exit([&] {
  6339. svr.stop();
  6340. listen_thread.join();
  6341. ASSERT_FALSE(svr.is_running());
  6342. });
  6343. svr.wait_until_ready();
  6344. Client cli("localhost", PORT);
  6345. svr.set_mount_point("/mount2", "./www2");
  6346. auto res = cli.Get("/");
  6347. ASSERT_TRUE(res);
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. res = cli.Get("/mount2/dir/test.html");
  6350. ASSERT_TRUE(res);
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. svr.set_mount_point("/", "./www");
  6353. res = cli.Get("/dir/");
  6354. ASSERT_TRUE(res);
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. svr.remove_mount_point("/");
  6357. res = cli.Get("/dir/");
  6358. ASSERT_TRUE(res);
  6359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6360. svr.remove_mount_point("/mount2");
  6361. res = cli.Get("/mount2/dir/test.html");
  6362. ASSERT_TRUE(res);
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST(MountTest, Redicect) {
  6366. Server svr;
  6367. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6368. auto se = detail::scope_exit([&] {
  6369. svr.stop();
  6370. listen_thread.join();
  6371. ASSERT_FALSE(svr.is_running());
  6372. });
  6373. svr.set_mount_point("/", "./www");
  6374. svr.wait_until_ready();
  6375. Client cli("localhost", PORT);
  6376. auto res = cli.Get("/dir/");
  6377. ASSERT_TRUE(res);
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. res = cli.Get("/dir");
  6380. ASSERT_TRUE(res);
  6381. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6382. res = cli.Get("/file");
  6383. ASSERT_TRUE(res);
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. res = cli.Get("/file/");
  6386. ASSERT_TRUE(res);
  6387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6388. cli.set_follow_location(true);
  6389. res = cli.Get("/dir");
  6390. ASSERT_TRUE(res);
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. TEST(MountTest, MultibytesPathName) {
  6394. Server svr;
  6395. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6396. auto se = detail::scope_exit([&] {
  6397. svr.stop();
  6398. listen_thread.join();
  6399. ASSERT_FALSE(svr.is_running());
  6400. });
  6401. svr.set_mount_point("/", "./www");
  6402. svr.wait_until_ready();
  6403. Client cli("localhost", PORT);
  6404. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6408. }
  6409. TEST(KeepAliveTest, ReadTimeout) {
  6410. Server svr;
  6411. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6412. std::this_thread::sleep_for(std::chrono::seconds(2));
  6413. res.set_content("a", "text/plain");
  6414. });
  6415. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6416. res.set_content("b", "text/plain");
  6417. });
  6418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6419. auto se = detail::scope_exit([&] {
  6420. svr.stop();
  6421. listen_thread.join();
  6422. ASSERT_FALSE(svr.is_running());
  6423. });
  6424. svr.wait_until_ready();
  6425. Client cli("localhost", PORT);
  6426. cli.set_keep_alive(true);
  6427. cli.set_read_timeout(std::chrono::seconds(1));
  6428. auto resa = cli.Get("/a");
  6429. ASSERT_FALSE(resa);
  6430. EXPECT_EQ(Error::Read, resa.error());
  6431. auto resb = cli.Get("/b");
  6432. ASSERT_TRUE(resb);
  6433. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6434. EXPECT_EQ("b", resb->body);
  6435. }
  6436. TEST(KeepAliveTest, MaxCount) {
  6437. size_t keep_alive_max_count = 3;
  6438. Server svr;
  6439. svr.set_keep_alive_max_count(keep_alive_max_count);
  6440. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6441. res.set_content("Hello World!", "text/plain");
  6442. });
  6443. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6444. auto se = detail::scope_exit([&] {
  6445. svr.stop();
  6446. listen_thread.join();
  6447. ASSERT_FALSE(svr.is_running());
  6448. });
  6449. svr.wait_until_ready();
  6450. Client cli(HOST, PORT);
  6451. cli.set_keep_alive(true);
  6452. for (size_t i = 0; i < 5; i++) {
  6453. auto result = cli.Get("/hi");
  6454. ASSERT_TRUE(result);
  6455. EXPECT_EQ(StatusCode::OK_200, result->status);
  6456. if (i == keep_alive_max_count - 1) {
  6457. EXPECT_EQ("close", result->get_header_value("Connection"));
  6458. } else {
  6459. EXPECT_FALSE(result->has_header("Connection"));
  6460. }
  6461. }
  6462. }
  6463. TEST(KeepAliveTest, Issue1041) {
  6464. Server svr;
  6465. svr.set_keep_alive_timeout(3);
  6466. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6467. res.set_content("Hello World!", "text/plain");
  6468. });
  6469. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6470. auto se = detail::scope_exit([&] {
  6471. svr.stop();
  6472. listen_thread.join();
  6473. ASSERT_FALSE(svr.is_running());
  6474. });
  6475. svr.wait_until_ready();
  6476. Client cli(HOST, PORT);
  6477. cli.set_keep_alive(true);
  6478. auto result = cli.Get("/hi");
  6479. ASSERT_TRUE(result);
  6480. EXPECT_EQ(StatusCode::OK_200, result->status);
  6481. std::this_thread::sleep_for(std::chrono::seconds(5));
  6482. result = cli.Get("/hi");
  6483. ASSERT_TRUE(result);
  6484. EXPECT_EQ(StatusCode::OK_200, result->status);
  6485. }
  6486. TEST(KeepAliveTest, Issue1959) {
  6487. Server svr;
  6488. svr.set_keep_alive_timeout(5);
  6489. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6490. res.set_content("a", "text/plain");
  6491. });
  6492. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6493. auto se = detail::scope_exit([&] {
  6494. if (!svr.is_running()) return;
  6495. svr.stop();
  6496. listen_thread.join();
  6497. ASSERT_FALSE(svr.is_running());
  6498. });
  6499. svr.wait_until_ready();
  6500. Client cli("localhost", PORT);
  6501. cli.set_keep_alive(true);
  6502. using namespace std::chrono;
  6503. auto start = steady_clock::now();
  6504. cli.Get("/a");
  6505. svr.stop();
  6506. listen_thread.join();
  6507. auto end = steady_clock::now();
  6508. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6509. EXPECT_LT(elapsed, 5000);
  6510. }
  6511. #ifdef CPPHTTPLIB_SSL_ENABLED
  6512. TEST(KeepAliveTest, SSLClientReconnection) {
  6513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6514. ASSERT_TRUE(svr.is_valid());
  6515. svr.set_keep_alive_timeout(1);
  6516. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6517. res.set_content("Hello World!", "text/plain");
  6518. });
  6519. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6520. auto se = detail::scope_exit([&] {
  6521. svr.stop();
  6522. listen_thread.join();
  6523. ASSERT_FALSE(svr.is_running());
  6524. });
  6525. svr.wait_until_ready();
  6526. SSLClient cli(HOST, PORT);
  6527. cli.enable_server_certificate_verification(false);
  6528. cli.set_keep_alive(true);
  6529. auto result = cli.Get("/hi");
  6530. ASSERT_TRUE(result);
  6531. EXPECT_EQ(StatusCode::OK_200, result->status);
  6532. result = cli.Get("/hi");
  6533. ASSERT_TRUE(result);
  6534. EXPECT_EQ(StatusCode::OK_200, result->status);
  6535. std::this_thread::sleep_for(std::chrono::seconds(2));
  6536. // Recoonect
  6537. result = cli.Get("/hi");
  6538. ASSERT_TRUE(result);
  6539. EXPECT_EQ(StatusCode::OK_200, result->status);
  6540. result = cli.Get("/hi");
  6541. ASSERT_TRUE(result);
  6542. EXPECT_EQ(StatusCode::OK_200, result->status);
  6543. }
  6544. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6546. ASSERT_TRUE(svr.is_valid());
  6547. svr.set_keep_alive_timeout(1);
  6548. std::string content = "reconnect";
  6549. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6550. res.set_content("Hello World!", "text/plain");
  6551. });
  6552. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6553. auto se = detail::scope_exit([&] {
  6554. svr.stop();
  6555. listen_thread.join();
  6556. ASSERT_FALSE(svr.is_running());
  6557. });
  6558. svr.wait_until_ready();
  6559. SSLClient cli(HOST, PORT);
  6560. cli.enable_server_certificate_verification(false);
  6561. cli.set_keep_alive(true);
  6562. auto result = cli.Post(
  6563. "/hi", content.size(),
  6564. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6565. sink.write(content.c_str(), content.size());
  6566. return true;
  6567. },
  6568. "text/plain");
  6569. ASSERT_TRUE(result);
  6570. EXPECT_EQ(200, result->status);
  6571. std::this_thread::sleep_for(std::chrono::seconds(2));
  6572. // Recoonect
  6573. result = cli.Post(
  6574. "/hi", content.size(),
  6575. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6576. sink.write(content.c_str(), content.size());
  6577. return true;
  6578. },
  6579. "text/plain");
  6580. ASSERT_TRUE(result);
  6581. EXPECT_EQ(200, result->status);
  6582. result = cli.Post(
  6583. "/hi", content.size(),
  6584. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6585. sink.write(content.c_str(), content.size());
  6586. return true;
  6587. },
  6588. "text/plain");
  6589. ASSERT_TRUE(result);
  6590. EXPECT_EQ(200, result->status);
  6591. }
  6592. #endif
  6593. #ifdef CPPHTTPLIB_SSL_ENABLED
  6594. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6595. using namespace httplib::tls;
  6596. {
  6597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6598. ASSERT_TRUE(svr.is_valid());
  6599. svr.Get("/sni", [&](const Request &req, Response &res) {
  6600. std::string expected;
  6601. if (req.ssl) {
  6602. // Use backend-agnostic TLS API to get SNI
  6603. if (const char *sni = tls_get_sni(const_cast<void *>(req.ssl))) {
  6604. expected = sni;
  6605. }
  6606. }
  6607. EXPECT_EQ(expected, req.get_param_value("expected"));
  6608. res.set_content("ok", "text/plain");
  6609. });
  6610. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6611. auto se = detail::scope_exit([&] {
  6612. svr.stop();
  6613. listen_thread.join();
  6614. ASSERT_FALSE(svr.is_running());
  6615. });
  6616. svr.wait_until_ready();
  6617. {
  6618. SSLClient cli("localhost", PORT);
  6619. cli.enable_server_certificate_verification(false);
  6620. auto res = cli.Get("/sni?expected=localhost");
  6621. ASSERT_TRUE(res);
  6622. }
  6623. {
  6624. SSLClient cli("::1", PORT);
  6625. cli.enable_server_certificate_verification(false);
  6626. auto res = cli.Get("/sni?expected=");
  6627. // NOTE: This may fail if the server is listening on IPv4 only
  6628. // (e.g., when localhost resolves to 127.0.0.1 only)
  6629. if (res) {
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. } else {
  6632. EXPECT_EQ(Error::Connection, res.error());
  6633. }
  6634. }
  6635. }
  6636. }
  6637. #endif
  6638. TEST(ClientProblemDetectionTest, ContentProvider) {
  6639. Server svr;
  6640. size_t content_length = 1024 * 1024;
  6641. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6642. res.set_content_provider(
  6643. content_length, "text/plain",
  6644. [&](size_t offset, size_t length, DataSink &sink) {
  6645. auto out_len = std::min(length, static_cast<size_t>(1024));
  6646. std::string out(out_len, '@');
  6647. sink.write(out.data(), out_len);
  6648. return offset < 4096;
  6649. },
  6650. [](bool success) { ASSERT_FALSE(success); });
  6651. });
  6652. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6653. res.set_content_provider(
  6654. 0, "text/plain",
  6655. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6656. EXPECT_TRUE(false);
  6657. return true;
  6658. },
  6659. [](bool success) { ASSERT_FALSE(success); });
  6660. });
  6661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6662. auto se = detail::scope_exit([&] {
  6663. svr.stop();
  6664. listen_thread.join();
  6665. ASSERT_FALSE(svr.is_running());
  6666. });
  6667. svr.wait_until_ready();
  6668. Client cli("localhost", PORT);
  6669. {
  6670. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6671. size_t /*data_length*/) { return false; });
  6672. ASSERT_FALSE(res);
  6673. }
  6674. {
  6675. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6676. size_t /*data_length*/) { return false; });
  6677. ASSERT_TRUE(res);
  6678. }
  6679. }
  6680. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6681. Server svr;
  6682. svr.set_error_handler([](Request const &, Response &res) -> void {
  6683. res.set_chunked_content_provider(
  6684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6685. sink.os << "hello";
  6686. sink.os << "world";
  6687. sink.done();
  6688. return true;
  6689. });
  6690. });
  6691. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6692. auto se = detail::scope_exit([&] {
  6693. svr.stop();
  6694. listen_thread.join();
  6695. ASSERT_FALSE(svr.is_running());
  6696. });
  6697. svr.wait_until_ready();
  6698. Client cli("localhost", PORT);
  6699. auto res = cli.Get("/");
  6700. ASSERT_TRUE(res);
  6701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6702. EXPECT_EQ("helloworld", res->body);
  6703. }
  6704. TEST(LongPollingTest, ClientCloseDetection) {
  6705. Server svr;
  6706. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6707. res.set_chunked_content_provider(
  6708. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6709. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6710. sink.os << "hello";
  6711. auto count = 10;
  6712. while (count > 0 && sink.is_writable()) {
  6713. this_thread::sleep_for(chrono::milliseconds(10));
  6714. count--;
  6715. }
  6716. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6717. return true;
  6718. });
  6719. });
  6720. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6721. auto se = detail::scope_exit([&] {
  6722. svr.stop();
  6723. listen_thread.join();
  6724. ASSERT_FALSE(svr.is_running());
  6725. });
  6726. svr.wait_until_ready();
  6727. Client cli("localhost", PORT);
  6728. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6729. EXPECT_EQ("hello", string(data, data_length));
  6730. return false; // close the socket immediately.
  6731. });
  6732. ASSERT_FALSE(res);
  6733. }
  6734. TEST(GetWithParametersTest, GetWithParameters) {
  6735. Server svr;
  6736. svr.Get("/", [&](const Request &req, Response &) {
  6737. EXPECT_EQ("world", req.get_param_value("hello"));
  6738. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6739. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6740. });
  6741. svr.Get("/params", [&](const Request &req, Response &) {
  6742. EXPECT_EQ("world", req.get_param_value("hello"));
  6743. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6744. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6745. });
  6746. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6747. EXPECT_EQ("resource-id", req.matches[1]);
  6748. EXPECT_EQ("foo", req.get_param_value("param1"));
  6749. EXPECT_EQ("bar", req.get_param_value("param2"));
  6750. });
  6751. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6752. EXPECT_EQ("user-id", req.path_params.at("id"));
  6753. EXPECT_EQ("foo", req.get_param_value("param1"));
  6754. EXPECT_EQ("bar", req.get_param_value("param2"));
  6755. });
  6756. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6757. auto se = detail::scope_exit([&] {
  6758. svr.stop();
  6759. listen_thread.join();
  6760. ASSERT_FALSE(svr.is_running());
  6761. });
  6762. svr.wait_until_ready();
  6763. {
  6764. Client cli(HOST, PORT);
  6765. Params params;
  6766. params.emplace("hello", "world");
  6767. params.emplace("hello2", "world2");
  6768. params.emplace("hello3", "world3");
  6769. auto res = cli.Get("/", params, Headers{});
  6770. ASSERT_TRUE(res);
  6771. EXPECT_EQ(StatusCode::OK_200, res->status);
  6772. }
  6773. {
  6774. Client cli(HOST, PORT);
  6775. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6776. ASSERT_TRUE(res);
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. }
  6779. {
  6780. Client cli(HOST, PORT);
  6781. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6782. ASSERT_TRUE(res);
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. }
  6785. {
  6786. Client cli(HOST, PORT);
  6787. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6788. ASSERT_TRUE(res);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. }
  6792. TEST(GetWithParametersTest, GetWithParameters2) {
  6793. Server svr;
  6794. svr.Get("/", [&](const Request &req, Response &res) {
  6795. auto text = req.get_param_value("hello");
  6796. res.set_content(text, "text/plain");
  6797. });
  6798. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6799. auto se = detail::scope_exit([&] {
  6800. svr.stop();
  6801. listen_thread.join();
  6802. ASSERT_FALSE(svr.is_running());
  6803. });
  6804. svr.wait_until_ready();
  6805. Client cli("localhost", PORT);
  6806. Params params;
  6807. params.emplace("hello", "world");
  6808. std::string body;
  6809. auto res = cli.Get("/", params, Headers{},
  6810. [&](const char *data, size_t data_length) {
  6811. body.append(data, data_length);
  6812. return true;
  6813. });
  6814. ASSERT_TRUE(res);
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ("world", body);
  6817. }
  6818. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6819. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6820. auto host = "httpcan.org";
  6821. auto path = std::string{"/range/32"};
  6822. #else
  6823. auto host = "nghttp2.org";
  6824. auto path = std::string{"/httpbin/range/32"};
  6825. #endif
  6826. #ifdef CPPHTTPLIB_SSL_ENABLED
  6827. SSLClient cli(host);
  6828. #else
  6829. Client cli(host);
  6830. #endif
  6831. cli.set_default_headers({make_range_header({{1, 10}})});
  6832. cli.set_connection_timeout(5);
  6833. {
  6834. auto res = cli.Get(path);
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ("bcdefghijk", res->body);
  6837. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6838. }
  6839. {
  6840. auto res = cli.Get(path);
  6841. ASSERT_TRUE(res);
  6842. EXPECT_EQ("bcdefghijk", res->body);
  6843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6844. }
  6845. }
  6846. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6847. Server svr;
  6848. svr.set_default_headers({{"Hello", "World"}});
  6849. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6850. res.set_content("ok", "text/plain");
  6851. });
  6852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6853. auto se = detail::scope_exit([&] {
  6854. svr.stop();
  6855. listen_thread.join();
  6856. ASSERT_FALSE(svr.is_running());
  6857. });
  6858. svr.wait_until_ready();
  6859. Client cli("localhost", PORT);
  6860. auto res = cli.Get("/");
  6861. ASSERT_TRUE(res);
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("ok", res->body);
  6864. EXPECT_EQ("World", res->get_header_value("Hello"));
  6865. }
  6866. #ifdef CPPHTTPLIB_SSL_ENABLED
  6867. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6869. ASSERT_TRUE(svr.is_valid());
  6870. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6871. std::this_thread::sleep_for(std::chrono::seconds(2));
  6872. res.set_content("a", "text/plain");
  6873. });
  6874. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6875. res.set_content("b", "text/plain");
  6876. });
  6877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6878. auto se = detail::scope_exit([&] {
  6879. svr.stop();
  6880. listen_thread.join();
  6881. ASSERT_FALSE(svr.is_running());
  6882. });
  6883. svr.wait_until_ready();
  6884. SSLClient cli("localhost", PORT);
  6885. cli.enable_server_certificate_verification(false);
  6886. cli.set_keep_alive(true);
  6887. cli.set_read_timeout(std::chrono::seconds(1));
  6888. auto resa = cli.Get("/a");
  6889. ASSERT_TRUE(!resa);
  6890. EXPECT_EQ(Error::Read, resa.error());
  6891. auto resb = cli.Get("/b");
  6892. ASSERT_TRUE(resb);
  6893. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6894. EXPECT_EQ("b", resb->body);
  6895. }
  6896. #endif
  6897. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6898. protected:
  6899. ServerTestWithAI_PASSIVE()
  6900. : cli_(HOST, PORT)
  6901. #ifdef CPPHTTPLIB_SSL_ENABLED
  6902. ,
  6903. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6904. #endif
  6905. {
  6906. #ifdef CPPHTTPLIB_SSL_ENABLED
  6907. cli_.enable_server_certificate_verification(false);
  6908. #endif
  6909. }
  6910. virtual void SetUp() {
  6911. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6912. res.set_content("Hello World!", "text/plain");
  6913. });
  6914. t_ = thread(
  6915. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6916. svr_.wait_until_ready();
  6917. }
  6918. virtual void TearDown() {
  6919. svr_.stop();
  6920. t_.join();
  6921. }
  6922. #ifdef CPPHTTPLIB_SSL_ENABLED
  6923. SSLClient cli_;
  6924. SSLServer svr_;
  6925. #else
  6926. Client cli_;
  6927. Server svr_;
  6928. #endif
  6929. thread t_;
  6930. };
  6931. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6932. auto res = cli_.Get("/hi");
  6933. ASSERT_TRUE(res);
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6936. EXPECT_EQ("Hello World!", res->body);
  6937. }
  6938. class ServerUpDownTest : public ::testing::Test {
  6939. protected:
  6940. ServerUpDownTest() : cli_(HOST, PORT) {}
  6941. virtual void SetUp() {
  6942. t_ = thread([&]() {
  6943. svr_.bind_to_any_port(HOST);
  6944. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6945. ASSERT_TRUE(svr_.listen_after_bind());
  6946. });
  6947. svr_.wait_until_ready();
  6948. }
  6949. virtual void TearDown() {
  6950. svr_.stop();
  6951. t_.join();
  6952. }
  6953. Client cli_;
  6954. Server svr_;
  6955. thread t_;
  6956. };
  6957. TEST_F(ServerUpDownTest, QuickStartStop) {
  6958. // Should not crash, especially when run with
  6959. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6960. }
  6961. class PayloadMaxLengthTest : public ::testing::Test {
  6962. protected:
  6963. PayloadMaxLengthTest()
  6964. : cli_(HOST, PORT)
  6965. #ifdef CPPHTTPLIB_SSL_ENABLED
  6966. ,
  6967. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6968. #endif
  6969. {
  6970. #ifdef CPPHTTPLIB_SSL_ENABLED
  6971. cli_.enable_server_certificate_verification(false);
  6972. #endif
  6973. }
  6974. virtual void SetUp() {
  6975. svr_.set_payload_max_length(8);
  6976. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6977. res.set_content("test", "text/plain");
  6978. });
  6979. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6980. svr_.wait_until_ready();
  6981. }
  6982. virtual void TearDown() {
  6983. svr_.stop();
  6984. t_.join();
  6985. }
  6986. #ifdef CPPHTTPLIB_SSL_ENABLED
  6987. SSLClient cli_;
  6988. SSLServer svr_;
  6989. #else
  6990. Client cli_;
  6991. Server svr_;
  6992. #endif
  6993. thread t_;
  6994. };
  6995. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6996. auto res = cli_.Post("/test", "123456789", "text/plain");
  6997. ASSERT_TRUE(res);
  6998. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6999. res = cli_.Post("/test", "12345678", "text/plain");
  7000. ASSERT_TRUE(res);
  7001. EXPECT_EQ(StatusCode::OK_200, res->status);
  7002. }
  7003. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7004. // Test chunked encoding with payload exceeding the 8-byte limit
  7005. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7006. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7009. }
  7010. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7011. // Test chunked encoding with payload within the 8-byte limit
  7012. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7013. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7014. ASSERT_TRUE(res);
  7015. EXPECT_EQ(StatusCode::OK_200, res->status);
  7016. }
  7017. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7018. // Test using send_request to send chunked data exceeding payload limit
  7019. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7020. "Host: " +
  7021. std::string(HOST) + ":" + std::to_string(PORT) +
  7022. "\r\n"
  7023. "Transfer-Encoding: chunked\r\n"
  7024. "Connection: close\r\n"
  7025. "\r\n"
  7026. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7027. "0123456789\r\n"
  7028. "0\r\n" // End chunk
  7029. "\r\n";
  7030. std::string response;
  7031. bool result = send_request(1, chunked_request, &response);
  7032. if (!result) {
  7033. // If send_request fails, it might be because the server closed the
  7034. // connection due to payload limit enforcement, which is acceptable
  7035. SUCCEED()
  7036. << "Server rejected oversized chunked request (connection closed)";
  7037. } else {
  7038. // If we got a response, check if it's an error response or connection was
  7039. // closed early Short response length indicates connection was closed due to
  7040. // payload limit
  7041. if (response.length() <= 10) {
  7042. SUCCEED() << "Server closed connection for oversized chunked request";
  7043. } else {
  7044. // Check for error status codes
  7045. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7046. response.find("Payload Too Large") != std::string::npos ||
  7047. response.find("400") != std::string::npos);
  7048. }
  7049. }
  7050. }
  7051. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7052. // Test request without Content-Length header exceeding payload limit
  7053. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7054. "Host: " +
  7055. std::string(HOST) + ":" +
  7056. std::to_string(PORT) +
  7057. "\r\n"
  7058. "Connection: close\r\n"
  7059. "\r\n";
  7060. // Add payload exceeding the 8-byte limit
  7061. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7062. request_without_content_length += large_payload;
  7063. std::string response;
  7064. bool result = send_request(1, request_without_content_length, &response);
  7065. if (!result) {
  7066. // If send_request fails, server likely closed connection due to payload
  7067. // limit
  7068. SUCCEED() << "Server rejected oversized request without Content-Length "
  7069. "(connection closed)";
  7070. } else {
  7071. // Check if server responded with error or closed connection early
  7072. if (response.length() <= 10) {
  7073. SUCCEED() << "Server closed connection for oversized request without "
  7074. "Content-Length";
  7075. } else {
  7076. // Check for error status codes
  7077. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7078. response.find("Payload Too Large") != std::string::npos ||
  7079. response.find("400") != std::string::npos);
  7080. }
  7081. }
  7082. }
  7083. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7084. // Test request without Content-Length header within payload limit
  7085. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7086. "Host: " +
  7087. std::string(HOST) + ":" +
  7088. std::to_string(PORT) +
  7089. "\r\n"
  7090. "Connection: close\r\n"
  7091. "\r\n";
  7092. // Add payload within the 8-byte limit
  7093. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7094. request_without_content_length += small_payload;
  7095. std::string response;
  7096. bool result = send_request(1, request_without_content_length, &response);
  7097. // For requests without Content-Length, the server may have different behavior
  7098. // The key is that it should not reject due to payload limit for small
  7099. // payloads
  7100. if (result) {
  7101. // Check for any HTTP response (success or error, but not connection closed)
  7102. if (response.length() > 10) {
  7103. SUCCEED()
  7104. << "Server processed request without Content-Length within limit";
  7105. } else {
  7106. // Short response might indicate connection closed, which is acceptable
  7107. SUCCEED() << "Server closed connection for request without "
  7108. "Content-Length (acceptable behavior)";
  7109. }
  7110. } else {
  7111. // Connection failure might be due to protocol requirements
  7112. SUCCEED() << "Connection issue with request without Content-Length "
  7113. "(environment-specific)";
  7114. }
  7115. }
  7116. class LargePayloadMaxLengthTest : public ::testing::Test {
  7117. protected:
  7118. LargePayloadMaxLengthTest()
  7119. : cli_(HOST, PORT)
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. ,
  7122. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7123. #endif
  7124. {
  7125. #ifdef CPPHTTPLIB_SSL_ENABLED
  7126. cli_.enable_server_certificate_verification(false);
  7127. #endif
  7128. }
  7129. virtual void SetUp() {
  7130. // Set 10MB payload limit
  7131. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7132. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7133. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7134. res.set_content("Large payload test", "text/plain");
  7135. });
  7136. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7137. svr_.wait_until_ready();
  7138. }
  7139. virtual void TearDown() {
  7140. svr_.stop();
  7141. t_.join();
  7142. }
  7143. #ifdef CPPHTTPLIB_SSL_ENABLED
  7144. SSLClient cli_;
  7145. SSLServer svr_;
  7146. #else
  7147. Client cli_;
  7148. Server svr_;
  7149. #endif
  7150. thread t_;
  7151. };
  7152. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7153. // Test chunked encoding with payload within 10MB limit
  7154. std::string medium_payload(5 * 1024 * 1024,
  7155. 'A'); // 5MB payload, within 10MB limit
  7156. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7157. ASSERT_TRUE(res);
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7161. // Test chunked encoding with payload exceeding 10MB limit
  7162. std::string large_payload(12 * 1024 * 1024,
  7163. 'B'); // 12MB payload, exceeds 10MB limit
  7164. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7165. ASSERT_TRUE(res);
  7166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7167. }
  7168. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7169. // Test request without Content-Length header within 10MB limit
  7170. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7171. "Host: " +
  7172. std::string(HOST) + ":" +
  7173. std::to_string(PORT) +
  7174. "\r\n"
  7175. "Connection: close\r\n"
  7176. "\r\n";
  7177. // Add 1MB payload (within 10MB limit)
  7178. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7179. request_without_content_length += medium_payload;
  7180. std::string response;
  7181. bool result = send_request(5, request_without_content_length, &response);
  7182. if (result) {
  7183. // Should get a proper HTTP response for payloads within limit
  7184. if (response.length() > 10) {
  7185. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7186. "10MB limit";
  7187. } else {
  7188. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7189. "Content-Length)";
  7190. }
  7191. } else {
  7192. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7193. }
  7194. }
  7195. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7196. // Test request without Content-Length header exceeding 10MB limit
  7197. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7198. "Host: " +
  7199. std::string(HOST) + ":" +
  7200. std::to_string(PORT) +
  7201. "\r\n"
  7202. "Connection: close\r\n"
  7203. "\r\n";
  7204. // Add 12MB payload (exceeds 10MB limit)
  7205. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7206. request_without_content_length += large_payload;
  7207. std::string response;
  7208. bool result = send_request(10, request_without_content_length, &response);
  7209. if (!result) {
  7210. // Server should close connection due to payload limit
  7211. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7212. "(connection closed)";
  7213. } else {
  7214. // Check for error response
  7215. if (response.length() <= 10) {
  7216. SUCCEED()
  7217. << "Server closed connection for 12MB request exceeding 10MB limit";
  7218. } else {
  7219. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7220. response.find("Payload Too Large") != std::string::npos ||
  7221. response.find("400") != std::string::npos);
  7222. }
  7223. }
  7224. }
  7225. TEST(HostAndPortPropertiesTest, NoSSL) {
  7226. httplib::Client cli("www.google.com", 1234);
  7227. ASSERT_EQ("www.google.com", cli.host());
  7228. ASSERT_EQ(1234, cli.port());
  7229. }
  7230. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7231. httplib::Client cli("www.google.com:1234");
  7232. ASSERT_EQ("www.google.com", cli.host());
  7233. ASSERT_EQ(1234, cli.port());
  7234. }
  7235. #ifdef CPPHTTPLIB_SSL_ENABLED
  7236. TEST(HostAndPortPropertiesTest, SSL) {
  7237. httplib::SSLClient cli("www.google.com");
  7238. ASSERT_EQ("www.google.com", cli.host());
  7239. ASSERT_EQ(443, cli.port());
  7240. }
  7241. #endif
  7242. #ifdef CPPHTTPLIB_SSL_ENABLED
  7243. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7244. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7245. // This is the backend-agnostic equivalent of UpdateCAStore test
  7246. std::string cert;
  7247. read_file(CA_CERT_FILE, cert);
  7248. httplib::SSLClient httplib_client("www.google.com");
  7249. // Load CA store first time
  7250. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7251. // Load CA store second time (update)
  7252. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7253. // Verify client is still valid and can make connections
  7254. httplib_client.enable_server_certificate_verification(true);
  7255. auto res = httplib_client.Get("/");
  7256. ASSERT_TRUE(res);
  7257. // Google may return 200 or 301 depending on various factors
  7258. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7259. res->status == StatusCode::MovedPermanently_301);
  7260. }
  7261. #endif
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. TEST(SSLClientTest, ServerNameIndication_Online) {
  7264. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7265. auto host = "httpcan.org";
  7266. auto path = std::string{"/get"};
  7267. #else
  7268. auto host = "nghttp2.org";
  7269. auto path = std::string{"/httpbin/get"};
  7270. #endif
  7271. SSLClient cli(host, 443);
  7272. auto res = cli.Get(path);
  7273. ASSERT_TRUE(res);
  7274. ASSERT_EQ(StatusCode::OK_200, res->status);
  7275. }
  7276. #endif
  7277. #ifdef CPPHTTPLIB_SSL_ENABLED
  7278. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7279. // Use a site that will cause SSL verification failure due to self-signed cert
  7280. SSLClient cli("self-signed.badssl.com", 443);
  7281. cli.enable_server_certificate_verification(true);
  7282. auto res = cli.Get("/");
  7283. ASSERT_TRUE(!res);
  7284. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7285. // Verify backend error is captured for SSLServerVerification
  7286. // This occurs when certificate verification fails
  7287. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7288. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7289. EXPECT_NE(0UL, res.ssl_backend_error());
  7290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7291. // For OpenSSL, ssl_error is 0 for verification errors
  7292. EXPECT_EQ(0, res.ssl_error());
  7293. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7294. res.ssl_openssl_error());
  7295. #endif
  7296. }
  7297. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7298. // Use a site where hostname doesn't match the certificate
  7299. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7300. SSLClient cli("wrong.host.badssl.com", 443);
  7301. cli.enable_server_certificate_verification(true);
  7302. cli.enable_server_hostname_verification(true);
  7303. auto res = cli.Get("/");
  7304. ASSERT_TRUE(!res);
  7305. // The error type depends on when hostname verification occurs:
  7306. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7307. // - Mbed TLS: SSLServerVerification (during handshake)
  7308. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7309. res.error() == Error::SSLServerVerification);
  7310. // Verify backend error is captured for hostname verification failure
  7311. EXPECT_NE(0UL, res.ssl_backend_error());
  7312. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7313. // For OpenSSL, ssl_error is 0 for verification errors
  7314. EXPECT_EQ(0, res.ssl_error());
  7315. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7316. res.ssl_openssl_error());
  7317. #endif
  7318. }
  7319. #endif
  7320. #ifdef CPPHTTPLIB_SSL_ENABLED
  7321. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7322. Client cli("https://google.com");
  7323. auto res = cli.Get("/");
  7324. ASSERT_TRUE(res);
  7325. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7326. }
  7327. #endif
  7328. #ifdef CPPHTTPLIB_SSL_ENABLED
  7329. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7330. SSLClient cli("google.com");
  7331. cli.set_ca_cert_path(CA_CERT_FILE);
  7332. auto res = cli.Get("/");
  7333. ASSERT_TRUE(res);
  7334. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7335. }
  7336. #endif
  7337. #ifdef CPPHTTPLIB_SSL_ENABLED
  7338. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7339. SSLClient cli("google.com");
  7340. cli.enable_server_certificate_verification(true);
  7341. cli.set_ca_cert_path("hello");
  7342. auto res = cli.Get("/");
  7343. ASSERT_TRUE(!res);
  7344. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7345. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7346. // should be set
  7347. EXPECT_EQ(0, res.ssl_error());
  7348. // Verify backend error is captured for SSLLoadingCerts
  7349. // This error occurs when loading CA certificates fails
  7350. EXPECT_NE(0UL, res.ssl_backend_error());
  7351. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7352. // OpenSSL specific error codes:
  7353. // > openssl errstr 0x80000002
  7354. // error:80000002:system library::No such file or directory
  7355. // > openssl errstr 0xA000126
  7356. // error:0A000126:SSL routines::unexpected eof while reading
  7357. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7358. res.ssl_openssl_error() == 0xA000126);
  7359. #endif
  7360. }
  7361. #endif
  7362. #ifdef CPPHTTPLIB_SSL_ENABLED
  7363. TEST(SSLClientTest, ServerCertificateVerification4) {
  7364. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7365. ASSERT_TRUE(svr.is_valid());
  7366. svr.Get("/test", [&](const Request &, Response &res) {
  7367. res.set_content("test", "text/plain");
  7368. svr.stop();
  7369. ASSERT_TRUE(true);
  7370. });
  7371. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7372. auto se = detail::scope_exit([&] {
  7373. t.join();
  7374. ASSERT_FALSE(svr.is_running());
  7375. });
  7376. svr.wait_until_ready();
  7377. SSLClient cli("127.0.0.1", PORT);
  7378. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7379. cli.enable_server_certificate_verification(true);
  7380. cli.set_connection_timeout(30);
  7381. auto res = cli.Get("/test");
  7382. ASSERT_TRUE(res);
  7383. ASSERT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7386. std::string cert;
  7387. read_file(CA_CERT_FILE, cert);
  7388. SSLClient cli("google.com");
  7389. cli.load_ca_cert_store(cert.data(), cert.size());
  7390. const auto res = cli.Get("/");
  7391. ASSERT_TRUE(res);
  7392. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7393. }
  7394. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7395. // clang-format off
  7396. static constexpr char cert[] =
  7397. "GlobalSign Root CA\n"
  7398. "==================\n"
  7399. "-----BEGIN CERTIFICATE-----\n"
  7400. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7401. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7402. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7403. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7404. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7405. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7406. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7407. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7408. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7409. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7410. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7411. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7412. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7413. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7414. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7415. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7416. "-----END CERTIFICATE-----\n";
  7417. // clang-format on
  7418. SSLClient cli("google.com");
  7419. cli.load_ca_cert_store(cert, sizeof(cert));
  7420. const auto res = cli.Get("/");
  7421. ASSERT_TRUE(res);
  7422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7423. }
  7424. TEST(SSLClientTest, Issue2004_Online) {
  7425. Client client("https://google.com");
  7426. client.set_follow_location(true);
  7427. auto res = client.Get("/");
  7428. ASSERT_TRUE(res);
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. auto body = res->body;
  7431. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7432. }
  7433. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7434. // Create SSLClient with invalid cert/key to make is_valid() return false
  7435. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7436. "nonexistent_key.pem");
  7437. // is_valid() should be false due to cert loading failure
  7438. ASSERT_FALSE(cli.is_valid());
  7439. auto res = cli.Get("/");
  7440. ASSERT_FALSE(res);
  7441. EXPECT_EQ(Error::SSLConnection, res.error());
  7442. }
  7443. #endif
  7444. #ifdef CPPHTTPLIB_SSL_ENABLED
  7445. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7446. SSLClient cli("www.youtube.com");
  7447. cli.set_ca_cert_path(CA_CERT_FILE);
  7448. cli.enable_server_certificate_verification(true);
  7449. cli.set_follow_location(true);
  7450. auto res = cli.Get("/");
  7451. ASSERT_TRUE(res);
  7452. ASSERT_EQ(StatusCode::OK_200, res->status);
  7453. }
  7454. #endif
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7457. // Test for Issue #2251: SSL error not properly reported when client cert
  7458. // and key paths are swapped or mismatched
  7459. // This simulates the scenario where user accidentally swaps the cert and key
  7460. // files
  7461. // Using client cert file as private key and vice versa (completely wrong)
  7462. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7463. // Should fail validation due to cert/key mismatch
  7464. ASSERT_FALSE(cli.is_valid());
  7465. // Attempt to make a request should fail with proper error
  7466. auto res = cli.Get("/");
  7467. ASSERT_FALSE(res);
  7468. EXPECT_EQ(Error::SSLConnection, res.error());
  7469. // SSL error should be recorded in the Result object (this is the key fix for
  7470. // Issue #2251)
  7471. auto backend_error = res.ssl_backend_error();
  7472. EXPECT_NE(0u, backend_error);
  7473. }
  7474. // Backend-agnostic test using abstract TLS API
  7475. // Tests cert/key mismatch detection at the TLS context level
  7476. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7477. using namespace httplib::tls;
  7478. // Create client context
  7479. auto ctx = tls_create_client_context();
  7480. ASSERT_NE(nullptr, ctx);
  7481. // Try to set mismatched cert/key (client.cert.pem with key.pem from cert2)
  7482. // The behavior differs by backend:
  7483. // - OpenSSL: tls_set_client_cert_file returns false immediately
  7484. // - Mbed TLS: succeeds here but fails during handshake
  7485. bool result =
  7486. tls_set_client_cert_file(ctx, "client.cert.pem", "key.pem", nullptr);
  7487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7488. // OpenSSL checks key consistency in SSL_CTX_use_PrivateKey_file
  7489. // by calling SSL_CTX_check_private_key internally after loading.
  7490. EXPECT_FALSE(result);
  7491. auto err = tls_get_error();
  7492. EXPECT_NE(0u, err);
  7493. #endif
  7494. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7495. // Mbed TLS doesn't perform cert/key consistency check until handshake.
  7496. // The mismatch is tested at connection time by
  7497. // Issue2251_SwappedClientCertAndKey
  7498. EXPECT_TRUE(result);
  7499. #endif
  7500. tls_free_context(ctx);
  7501. }
  7502. #endif
  7503. #if 0
  7504. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7505. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7506. ASSERT_TRUE(cli != nullptr);
  7507. cli->set_address_family(AF_INET6);
  7508. cli->set_interface("en0");
  7509. auto res = cli->Get("/get");
  7510. ASSERT_TRUE(res);
  7511. ASSERT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. #endif
  7514. // ClientCertPresent uses tls_get_peer_cert() - works with all TLS backends
  7515. #ifdef CPPHTTPLIB_SSL_ENABLED
  7516. void ClientCertPresent(
  7517. const std::string &client_cert_file,
  7518. const std::string &client_private_key_file,
  7519. const std::string &client_encrypted_private_key_pass = std::string()) {
  7520. using namespace httplib::tls;
  7521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7522. CLIENT_CA_CERT_DIR);
  7523. ASSERT_TRUE(svr.is_valid());
  7524. svr.Get("/test", [&](const Request &req, Response &res) {
  7525. res.set_content("test", "text/plain");
  7526. // Cast away const for tls_get_peer_cert (session is not modified)
  7527. auto peer_cert = tls_get_peer_cert(const_cast<void *>(req.ssl));
  7528. ASSERT_TRUE(peer_cert != nullptr);
  7529. std::string common_name = tls_get_cert_subject_cn(peer_cert);
  7530. EXPECT_EQ("Common Name", common_name);
  7531. tls_free_cert(peer_cert);
  7532. });
  7533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7534. auto se = detail::scope_exit([&] {
  7535. svr.stop();
  7536. t.join();
  7537. ASSERT_FALSE(svr.is_running());
  7538. });
  7539. svr.wait_until_ready();
  7540. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7541. client_encrypted_private_key_pass);
  7542. cli.enable_server_certificate_verification(false);
  7543. cli.set_connection_timeout(30);
  7544. auto res = cli.Get("/test");
  7545. ASSERT_TRUE(res);
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. }
  7548. TEST(SSLClientServerTest, ClientCertPresent) {
  7549. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7550. }
  7551. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7552. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7553. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7554. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7555. }
  7556. #endif
  7557. #ifdef CPPHTTPLIB_SSL_ENABLED
  7558. // PEM memory-based constructor tests (works with all TLS backends)
  7559. void PemMemoryClientCertPresent(
  7560. const std::string &client_cert_file,
  7561. const std::string &client_private_key_file,
  7562. const std::string &client_encrypted_private_key_pass = std::string()) {
  7563. // Read PEM files into memory
  7564. std::string server_cert_pem, server_key_pem;
  7565. std::string client_ca_pem;
  7566. std::string client_cert_pem, client_key_pem;
  7567. read_file(SERVER_CERT_FILE, server_cert_pem);
  7568. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7569. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7570. read_file(client_cert_file, client_cert_pem);
  7571. read_file(client_private_key_file, client_key_pem);
  7572. // Create server with PEM memory
  7573. SSLServer::PemMemory server_pem = {
  7574. server_cert_pem.c_str(),
  7575. server_cert_pem.size(),
  7576. server_key_pem.c_str(),
  7577. server_key_pem.size(),
  7578. client_ca_pem.c_str(),
  7579. client_ca_pem.size(),
  7580. nullptr // no password for server key
  7581. };
  7582. SSLServer svr(server_pem);
  7583. ASSERT_TRUE(svr.is_valid());
  7584. svr.Get("/test", [&](const Request &, Response &res) {
  7585. res.set_content("test", "text/plain");
  7586. });
  7587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7588. auto se = detail::scope_exit([&] {
  7589. svr.stop();
  7590. t.join();
  7591. ASSERT_FALSE(svr.is_running());
  7592. });
  7593. svr.wait_until_ready();
  7594. // Create client with PEM memory
  7595. const char *password = client_encrypted_private_key_pass.empty()
  7596. ? nullptr
  7597. : client_encrypted_private_key_pass.c_str();
  7598. SSLClient::PemMemory client_pem = {
  7599. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7600. client_key_pem.size(), password};
  7601. SSLClient cli(HOST, PORT, client_pem);
  7602. cli.enable_server_certificate_verification(false);
  7603. cli.set_connection_timeout(30);
  7604. auto res = cli.Get("/test");
  7605. ASSERT_TRUE(res);
  7606. ASSERT_EQ(StatusCode::OK_200, res->status);
  7607. }
  7608. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7609. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7610. }
  7611. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7612. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7613. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7614. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7615. }
  7616. #endif
  7617. #ifdef CPPHTTPLIB_SSL_ENABLED
  7618. TEST(SSLClientServerTest, ClientCertMissing) {
  7619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7620. CLIENT_CA_CERT_DIR);
  7621. ASSERT_TRUE(svr.is_valid());
  7622. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7624. auto se = detail::scope_exit([&] {
  7625. svr.stop();
  7626. t.join();
  7627. ASSERT_FALSE(svr.is_running());
  7628. });
  7629. svr.wait_until_ready();
  7630. SSLClient cli(HOST, PORT);
  7631. cli.set_connection_timeout(30);
  7632. auto res = cli.Get("/test");
  7633. ASSERT_TRUE(!res);
  7634. // When client cert is missing and server requires it, connection fails
  7635. // Error type depends on backend implementation
  7636. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7637. res.error() == Error::SSLConnection);
  7638. // Verify backend error is captured
  7639. // Note: This test may have different error codes depending on the exact
  7640. // verification failure
  7641. EXPECT_NE(0UL, res.ssl_backend_error());
  7642. }
  7643. TEST(SSLClientServerTest, TrustDirOptional) {
  7644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7645. ASSERT_TRUE(svr.is_valid());
  7646. svr.Get("/test", [&](const Request &, Response &res) {
  7647. res.set_content("test", "text/plain");
  7648. });
  7649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7650. auto se = detail::scope_exit([&] {
  7651. svr.stop();
  7652. t.join();
  7653. ASSERT_FALSE(svr.is_running());
  7654. });
  7655. svr.wait_until_ready();
  7656. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7657. cli.enable_server_certificate_verification(false);
  7658. cli.set_connection_timeout(30);
  7659. auto res = cli.Get("/test");
  7660. ASSERT_TRUE(res);
  7661. ASSERT_EQ(StatusCode::OK_200, res->status);
  7662. }
  7663. #endif
  7664. #ifdef CPPHTTPLIB_SSL_ENABLED
  7665. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7666. class NoListenSSLServer : public SSLServer {
  7667. public:
  7668. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7669. const char *client_ca_cert_file_path,
  7670. const char *client_ca_cert_dir_path = nullptr)
  7671. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7672. client_ca_cert_dir_path),
  7673. stop_(false) {}
  7674. std::atomic_bool stop_;
  7675. private:
  7676. bool process_and_close_socket(socket_t /*sock*/) override {
  7677. // Don't create SSL context
  7678. while (!stop_.load()) {
  7679. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7680. }
  7681. return true;
  7682. }
  7683. };
  7684. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7685. CLIENT_CA_CERT_FILE);
  7686. ASSERT_TRUE(svr.is_valid());
  7687. svr.Get("/test", [&](const Request &, Response &res) {
  7688. res.set_content("test", "text/plain");
  7689. });
  7690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7691. auto se = detail::scope_exit([&] {
  7692. svr.stop_ = true;
  7693. svr.stop();
  7694. t.join();
  7695. ASSERT_FALSE(svr.is_running());
  7696. });
  7697. svr.wait_until_ready();
  7698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7699. cli.enable_server_certificate_verification(false);
  7700. cli.set_connection_timeout(1);
  7701. auto res = cli.Get("/test");
  7702. ASSERT_TRUE(!res);
  7703. EXPECT_EQ(Error::SSLConnection, res.error());
  7704. // Timeout results in WantRead error code (maps to backend-specific value)
  7705. EXPECT_NE(0, res.ssl_error());
  7706. }
  7707. #endif
  7708. // Backend-agnostic equivalent of CustomizeServerSSLCtx test
  7709. // Uses void* callback constructor and detail::tls API
  7710. #ifdef CPPHTTPLIB_SSL_ENABLED
  7711. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7712. using namespace httplib::tls;
  7713. auto setup_callback = [](void *ctx) {
  7714. // Load server certificate and key using backend-agnostic API
  7715. if (!tls_set_server_cert_file(static_cast<tls_ctx_t>(ctx), SERVER_CERT_FILE,
  7716. SERVER_PRIVATE_KEY_FILE, nullptr)) {
  7717. return false;
  7718. }
  7719. // Set up client certificate verification
  7720. if (!tls_set_client_ca_file(static_cast<tls_ctx_t>(ctx),
  7721. CLIENT_CA_CERT_FILE, CLIENT_CA_CERT_DIR)) {
  7722. return false;
  7723. }
  7724. tls_set_verify_client(static_cast<tls_ctx_t>(ctx), true);
  7725. return true;
  7726. };
  7727. SSLServer svr(setup_callback);
  7728. ASSERT_TRUE(svr.is_valid());
  7729. svr.Get("/test", [&](const Request &req, Response &res) {
  7730. res.set_content("test", "text/plain");
  7731. // Get peer certificate using backend-agnostic API
  7732. // Note: req.ssl is const void*, need const_cast for API compatibility
  7733. auto peer_cert = tls_get_peer_cert(const_cast<tls_session_t>(req.ssl));
  7734. ASSERT_TRUE(peer_cert != nullptr);
  7735. // Verify common name using backend-agnostic API
  7736. auto common_name = tls_get_cert_subject_cn(peer_cert);
  7737. EXPECT_EQ("Common Name", common_name);
  7738. tls_free_cert(peer_cert);
  7739. });
  7740. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7741. auto se = detail::scope_exit([&] {
  7742. svr.stop();
  7743. t.join();
  7744. ASSERT_FALSE(svr.is_running());
  7745. });
  7746. svr.wait_until_ready();
  7747. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7748. cli.enable_server_certificate_verification(false);
  7749. cli.set_connection_timeout(30);
  7750. auto res = cli.Get("/test");
  7751. ASSERT_TRUE(res);
  7752. ASSERT_EQ(StatusCode::OK_200, res->status);
  7753. }
  7754. #endif
  7755. // mbedTLS-specific callback constructor test
  7756. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  7757. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7758. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  7759. using namespace httplib::tls;
  7760. // Track if callback was invoked
  7761. bool callback_invoked = false;
  7762. // The callback receives void* ctx which is actually MbedTlsContext*
  7763. // We can access the mbedtls_ssl_config via the context
  7764. auto setup_callback = [&callback_invoked](void *ctx) {
  7765. callback_invoked = true;
  7766. // Cast to MbedTlsContext* to access the ssl config
  7767. auto *mbedtls_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  7768. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  7769. // Use static variables to hold certificate data (simplified for test)
  7770. static mbedtls_x509_crt own_cert;
  7771. static mbedtls_pk_context own_key;
  7772. static mbedtls_x509_crt ca_chain;
  7773. static bool initialized = false;
  7774. if (!initialized) {
  7775. mbedtls_x509_crt_init(&own_cert);
  7776. mbedtls_pk_init(&own_key);
  7777. mbedtls_x509_crt_init(&ca_chain);
  7778. // Load server certificate
  7779. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  7780. return false;
  7781. }
  7782. // Load server private key
  7783. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  7784. #if MBEDTLS_VERSION_MAJOR >= 3
  7785. ,
  7786. mbedtls_ctr_drbg_random, nullptr
  7787. #endif
  7788. ) != 0) {
  7789. return false;
  7790. }
  7791. // Load CA chain for client verification
  7792. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  7793. return false;
  7794. }
  7795. initialized = true;
  7796. }
  7797. // Configure the SSL config
  7798. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  7799. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  7800. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  7801. // Set minimum TLS version using mbedTLS native API
  7802. #if MBEDTLS_VERSION_MAJOR >= 3
  7803. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  7804. #else
  7805. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  7806. MBEDTLS_SSL_MINOR_VERSION_3);
  7807. #endif
  7808. return true;
  7809. };
  7810. SSLServer svr(setup_callback);
  7811. ASSERT_TRUE(svr.is_valid());
  7812. ASSERT_TRUE(callback_invoked);
  7813. svr.Get("/test", [&](const Request &req, Response &res) {
  7814. res.set_content("test", "text/plain");
  7815. // Get peer certificate using backend-agnostic API
  7816. auto peer_cert = tls_get_peer_cert(const_cast<tls_session_t>(req.ssl));
  7817. ASSERT_TRUE(peer_cert != nullptr);
  7818. auto common_name = tls_get_cert_subject_cn(peer_cert);
  7819. EXPECT_EQ("Common Name", common_name);
  7820. tls_free_cert(peer_cert);
  7821. });
  7822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7823. auto se = detail::scope_exit([&] {
  7824. svr.stop();
  7825. t.join();
  7826. ASSERT_FALSE(svr.is_running());
  7827. });
  7828. svr.wait_until_ready();
  7829. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7830. cli.enable_server_certificate_verification(false);
  7831. cli.set_connection_timeout(30);
  7832. auto res = cli.Get("/test");
  7833. ASSERT_TRUE(res);
  7834. ASSERT_EQ(StatusCode::OK_200, res->status);
  7835. }
  7836. #endif
  7837. #ifdef CPPHTTPLIB_SSL_ENABLED
  7838. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7840. ASSERT_TRUE(svr.is_valid());
  7841. // Set up a handler to verify client certificate is present
  7842. bool client_cert_verified = false;
  7843. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7844. // Verify that client certificate was provided
  7845. client_cert_verified = true;
  7846. res.set_content("success", "text/plain");
  7847. });
  7848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7849. auto se = detail::scope_exit([&] {
  7850. svr.stop();
  7851. t.join();
  7852. ASSERT_FALSE(svr.is_running());
  7853. });
  7854. svr.wait_until_ready();
  7855. // Client with certificate
  7856. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7857. cli.enable_server_certificate_verification(false);
  7858. cli.set_connection_timeout(30);
  7859. auto res = cli.Get("/test");
  7860. ASSERT_TRUE(res);
  7861. ASSERT_EQ(StatusCode::OK_200, res->status);
  7862. ASSERT_TRUE(client_cert_verified);
  7863. EXPECT_EQ("success", res->body);
  7864. }
  7865. #endif
  7866. // ClientCAListSetInContext uses tls_get_peer_cert() - works with all TLS
  7867. // backends
  7868. #ifdef CPPHTTPLIB_SSL_ENABLED
  7869. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7870. using namespace httplib::tls;
  7871. // Test that when client CA cert file is provided,
  7872. // the server properly requests and validates client certificates
  7873. // Create a server with client authentication
  7874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7875. ASSERT_TRUE(svr.is_valid());
  7876. bool handler_called = false;
  7877. svr.Get("/test", [&](const Request &req, Response &res) {
  7878. handler_called = true;
  7879. // Verify that a client certificate was provided
  7880. // Cast away const for tls_get_peer_cert (session is not modified)
  7881. auto peer_cert = tls_get_peer_cert(const_cast<void *>(req.ssl));
  7882. ASSERT_TRUE(peer_cert != nullptr);
  7883. // Get the issuer name
  7884. std::string issuer_str = tls_get_cert_issuer_name(peer_cert);
  7885. ASSERT_FALSE(issuer_str.empty());
  7886. // The client certificate should be issued by our test CA
  7887. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7888. tls_free_cert(peer_cert);
  7889. res.set_content("authenticated", "text/plain");
  7890. });
  7891. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7892. auto se = detail::scope_exit([&] {
  7893. svr.stop();
  7894. t.join();
  7895. ASSERT_FALSE(svr.is_running());
  7896. });
  7897. svr.wait_until_ready();
  7898. // Connect with a client certificate issued by the CA
  7899. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7900. cli.enable_server_certificate_verification(false);
  7901. cli.set_connection_timeout(30);
  7902. auto res = cli.Get("/test");
  7903. ASSERT_TRUE(res);
  7904. ASSERT_EQ(StatusCode::OK_200, res->status);
  7905. ASSERT_TRUE(handler_called);
  7906. EXPECT_EQ("authenticated", res->body);
  7907. }
  7908. #endif
  7909. #ifdef CPPHTTPLIB_SSL_ENABLED
  7910. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  7911. using namespace httplib::tls;
  7912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7913. ASSERT_TRUE(svr.is_valid());
  7914. svr.Get("/test", [](const Request &, Response &res) {
  7915. res.set_content("ok", "text/plain");
  7916. });
  7917. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7918. auto se = detail::scope_exit([&] {
  7919. svr.stop();
  7920. t.join();
  7921. });
  7922. svr.wait_until_ready();
  7923. SSLClient cli(HOST, PORT);
  7924. cli.enable_server_certificate_verification(false);
  7925. cli.set_connection_timeout(30);
  7926. bool cert_checked = false;
  7927. cli.set_server_certificate_verifier(
  7928. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  7929. (void)session;
  7930. if (peer_cert) {
  7931. std::vector<TlsSanEntry> sans;
  7932. bool result = tls_get_cert_sans(peer_cert, sans);
  7933. // tls_get_cert_sans should return true even if no SANs exist
  7934. EXPECT_TRUE(result);
  7935. // Test certificate may or may not have SANs - just verify the API
  7936. // works If SANs exist, verify the types are valid
  7937. for (const auto &san : sans) {
  7938. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  7939. san.type == SanType::EMAIL ||
  7940. san.type == SanType::URI || san.type == SanType::OTHER);
  7941. EXPECT_FALSE(san.value.empty());
  7942. }
  7943. cert_checked = true;
  7944. }
  7945. return true;
  7946. });
  7947. auto res = cli.Get("/test");
  7948. ASSERT_TRUE(res);
  7949. EXPECT_TRUE(cert_checked);
  7950. }
  7951. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  7952. using namespace httplib::tls;
  7953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7954. ASSERT_TRUE(svr.is_valid());
  7955. svr.Get("/test", [](const Request &, Response &res) {
  7956. res.set_content("ok", "text/plain");
  7957. });
  7958. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7959. auto se = detail::scope_exit([&] {
  7960. svr.stop();
  7961. t.join();
  7962. });
  7963. svr.wait_until_ready();
  7964. SSLClient cli(HOST, PORT);
  7965. cli.enable_server_certificate_verification(false);
  7966. cli.set_connection_timeout(30);
  7967. bool validity_checked = false;
  7968. cli.set_server_certificate_verifier(
  7969. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  7970. (void)session;
  7971. if (peer_cert) {
  7972. time_t not_before = 0, not_after = 0;
  7973. bool result = tls_get_cert_validity(peer_cert, not_before, not_after);
  7974. EXPECT_TRUE(result);
  7975. // Verify that not_before < now < not_after for a valid cert
  7976. time_t now = time(nullptr);
  7977. EXPECT_LT(not_before, now);
  7978. EXPECT_GT(not_after, now);
  7979. validity_checked = true;
  7980. }
  7981. return true;
  7982. });
  7983. auto res = cli.Get("/test");
  7984. ASSERT_TRUE(res);
  7985. EXPECT_TRUE(validity_checked);
  7986. }
  7987. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  7988. using namespace httplib::tls;
  7989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7990. ASSERT_TRUE(svr.is_valid());
  7991. svr.Get("/test", [](const Request &, Response &res) {
  7992. res.set_content("ok", "text/plain");
  7993. });
  7994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7995. auto se = detail::scope_exit([&] {
  7996. svr.stop();
  7997. t.join();
  7998. });
  7999. svr.wait_until_ready();
  8000. SSLClient cli(HOST, PORT);
  8001. cli.enable_server_certificate_verification(false);
  8002. cli.set_connection_timeout(30);
  8003. bool serial_checked = false;
  8004. cli.set_server_certificate_verifier(
  8005. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  8006. (void)session;
  8007. if (peer_cert) {
  8008. std::string serial = tls_get_cert_serial(peer_cert);
  8009. EXPECT_FALSE(serial.empty());
  8010. // Serial should be a hex string
  8011. for (char c : serial) {
  8012. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8013. (c >= 'a' && c <= 'f'));
  8014. }
  8015. serial_checked = true;
  8016. }
  8017. return true;
  8018. });
  8019. auto res = cli.Get("/test");
  8020. ASSERT_TRUE(res);
  8021. EXPECT_TRUE(serial_checked);
  8022. }
  8023. #endif
  8024. #ifdef CPPHTTPLIB_SSL_ENABLED
  8025. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8026. // Test 1: Valid CA file - no error should be recorded
  8027. {
  8028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8029. CLIENT_CA_CERT_FILE);
  8030. ASSERT_TRUE(svr.is_valid());
  8031. // With valid setup, last_ssl_error should be 0
  8032. EXPECT_EQ(0, svr.ssl_last_error());
  8033. }
  8034. // Test 2: Invalid CA file content
  8035. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8036. {
  8037. // Create a temporary file with completely invalid content
  8038. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8039. {
  8040. std::ofstream ofs(temp_invalid_ca);
  8041. ofs << "This is not a certificate file at all\n";
  8042. ofs << "Just plain text content\n";
  8043. }
  8044. // Create server with invalid CA file
  8045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8046. // Clean up temporary file
  8047. std::remove(temp_invalid_ca);
  8048. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8049. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8050. // Note: SSL_CTX_load_verify_locations typically fails first,
  8051. // but our error handling code path is still exercised
  8052. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8053. }
  8054. }
  8055. #endif
  8056. #ifdef CPPHTTPLIB_SSL_ENABLED
  8057. TEST(TlsVerifyCallbackExTest, ExtendedCallback) {
  8058. using namespace httplib::tls;
  8059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8060. ASSERT_TRUE(svr.is_valid());
  8061. svr.Get("/test", [](const Request &, Response &res) {
  8062. res.set_content("ok", "text/plain");
  8063. });
  8064. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8065. auto se = detail::scope_exit([&] {
  8066. svr.stop();
  8067. t.join();
  8068. });
  8069. svr.wait_until_ready();
  8070. SSLClient cli(HOST, PORT);
  8071. cli.enable_server_certificate_verification(false);
  8072. cli.set_connection_timeout(30);
  8073. int callback_count = 0;
  8074. bool saw_leaf_cert = false;
  8075. // Use the new extended callback via the context directly
  8076. // Note: This tests the internal API, real usage would be through
  8077. // set_server_certificate_verifier
  8078. cli.set_server_certificate_verifier(
  8079. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  8080. (void)session;
  8081. if (peer_cert) {
  8082. callback_count++;
  8083. // We should see at least one certificate (the leaf)
  8084. std::string cn = tls_get_cert_subject_cn(peer_cert);
  8085. if (!cn.empty()) { saw_leaf_cert = true; }
  8086. }
  8087. return true;
  8088. });
  8089. auto res = cli.Get("/test");
  8090. ASSERT_TRUE(res);
  8091. EXPECT_GT(callback_count, 0);
  8092. EXPECT_TRUE(saw_leaf_cert);
  8093. }
  8094. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8095. using namespace httplib::tls;
  8096. // Test that tls_verify_error_string returns empty for success
  8097. std::string success_str = tls_verify_error_string(0);
  8098. EXPECT_TRUE(success_str.empty());
  8099. // Test that tls_verify_error_string returns non-empty for error codes
  8100. // Using a common error code (certificate expired)
  8101. std::string error_str =
  8102. tls_verify_error_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8103. EXPECT_FALSE(error_str.empty());
  8104. }
  8105. #endif
  8106. #ifdef CPPHTTPLIB_SSL_ENABLED
  8107. TEST(CryptoHashTest, BasicHashing) {
  8108. namespace crypto = httplib::crypto;
  8109. // Test MD5
  8110. std::string md5_result = crypto::hash(crypto::HashAlgorithm::MD5, "hello");
  8111. EXPECT_EQ("5d41402abc4b2a76b9719d911017c592", md5_result);
  8112. // Test SHA256
  8113. std::string sha256_result =
  8114. crypto::hash(crypto::HashAlgorithm::SHA256, "hello");
  8115. EXPECT_EQ("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
  8116. sha256_result);
  8117. // Test SHA512
  8118. std::string sha512_result =
  8119. crypto::hash(crypto::HashAlgorithm::SHA512, "hello");
  8120. EXPECT_EQ(
  8121. "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d9"
  8122. "9ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043",
  8123. sha512_result);
  8124. }
  8125. TEST(CryptoHashTest, HashSize) {
  8126. namespace crypto = httplib::crypto;
  8127. EXPECT_EQ(16u, crypto::hash_size(crypto::HashAlgorithm::MD5));
  8128. EXPECT_EQ(20u, crypto::hash_size(crypto::HashAlgorithm::SHA1));
  8129. EXPECT_EQ(32u, crypto::hash_size(crypto::HashAlgorithm::SHA256));
  8130. EXPECT_EQ(48u, crypto::hash_size(crypto::HashAlgorithm::SHA384));
  8131. EXPECT_EQ(64u, crypto::hash_size(crypto::HashAlgorithm::SHA512));
  8132. }
  8133. TEST(CryptoHashTest, HashRaw) {
  8134. namespace crypto = httplib::crypto;
  8135. std::vector<uint8_t> digest;
  8136. bool result =
  8137. crypto::hash_raw(crypto::HashAlgorithm::SHA256, "test", 4, digest);
  8138. EXPECT_TRUE(result);
  8139. EXPECT_EQ(32u, digest.size());
  8140. // Verify first few bytes match known SHA256 of "test"
  8141. // SHA256("test") =
  8142. // 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
  8143. EXPECT_EQ(0x9f, digest[0]);
  8144. EXPECT_EQ(0x86, digest[1]);
  8145. EXPECT_EQ(0xd0, digest[2]);
  8146. }
  8147. #endif
  8148. #ifdef CPPHTTPLIB_SSL_ENABLED
  8149. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8150. // Test SSL server using PemMemory constructor with client CA certificates
  8151. // This is the backend-agnostic equivalent of ClientCAListFromX509Store test
  8152. // Read PEM files
  8153. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8154. read_file(SERVER_CERT_FILE, server_cert_pem);
  8155. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8156. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8157. // Create SSLServer with PemMemory constructor including client CA
  8158. SSLServer::PemMemory server_pem = {
  8159. server_cert_pem.c_str(),
  8160. server_cert_pem.size(),
  8161. server_key_pem.c_str(),
  8162. server_key_pem.size(),
  8163. client_ca_pem.c_str(),
  8164. client_ca_pem.size(),
  8165. nullptr // no password for server key
  8166. };
  8167. SSLServer svr(server_pem);
  8168. ASSERT_TRUE(svr.is_valid());
  8169. // No SSL error should be recorded for valid setup
  8170. EXPECT_EQ(0, svr.ssl_last_error());
  8171. // Set up server endpoints
  8172. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8173. res.set_content("ok", "text/plain");
  8174. });
  8175. // Start server in a thread
  8176. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8177. svr.wait_until_ready();
  8178. // Connect with client certificate (using constructor with paths)
  8179. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8180. cli.enable_server_certificate_verification(false);
  8181. auto res = cli.Get("/test-pem-ca");
  8182. ASSERT_TRUE(res);
  8183. EXPECT_EQ(200, res->status);
  8184. EXPECT_EQ("ok", res->body);
  8185. svr.stop();
  8186. server_thread.join();
  8187. }
  8188. #endif
  8189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8190. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  8191. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  8192. // prepare large data
  8193. std::random_device seed_gen;
  8194. std::mt19937 random(seed_gen());
  8195. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  8196. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  8197. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  8198. // server
  8199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8200. ASSERT_TRUE(svr.is_valid());
  8201. svr.Post("/binary", [&](const Request &req, Response &res) {
  8202. EXPECT_EQ(large_size_byte, req.body.size());
  8203. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  8204. res.set_content(req.body, "application/octet-stream");
  8205. });
  8206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8207. auto se = detail::scope_exit([&] {
  8208. svr.stop();
  8209. listen_thread.join();
  8210. ASSERT_FALSE(svr.is_running());
  8211. });
  8212. svr.wait_until_ready();
  8213. // client POST
  8214. SSLClient cli("localhost", PORT);
  8215. cli.enable_server_certificate_verification(false);
  8216. cli.set_read_timeout(std::chrono::seconds(100));
  8217. cli.set_write_timeout(std::chrono::seconds(100));
  8218. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  8219. large_size_byte, "application/octet-stream");
  8220. // compare
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. EXPECT_EQ(large_size_byte, res->body.size());
  8223. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  8224. }
  8225. #endif
  8226. #ifdef _WIN32
  8227. TEST(CleanupTest, WSACleanup) {
  8228. int ret = WSACleanup();
  8229. ASSERT_EQ(0, ret);
  8230. }
  8231. #endif
  8232. #ifndef CPPHTTPLIB_SSL_ENABLED
  8233. TEST(NoSSLSupport, SimpleInterface) {
  8234. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8235. }
  8236. #endif
  8237. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8238. TEST(InvalidScheme, SimpleInterface) {
  8239. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8240. }
  8241. #endif
  8242. TEST(NoScheme, SimpleInterface) {
  8243. Client cli("yahoo.com:80");
  8244. ASSERT_TRUE(cli.is_valid());
  8245. }
  8246. TEST(SendAPI, SimpleInterface_Online) {
  8247. Client cli("http://yahoo.com");
  8248. Request req;
  8249. req.method = "GET";
  8250. req.path = "/";
  8251. auto res = cli.send(req);
  8252. ASSERT_TRUE(res);
  8253. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8254. }
  8255. TEST(SendAPI, WithParamsInRequest) {
  8256. Server svr;
  8257. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8258. EXPECT_TRUE(req.has_param("test"));
  8259. EXPECT_EQ("test_value", req.get_param_value("test"));
  8260. });
  8261. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8262. auto se = detail::scope_exit([&] {
  8263. svr.stop();
  8264. t.join();
  8265. ASSERT_FALSE(svr.is_running());
  8266. });
  8267. svr.wait_until_ready();
  8268. Client cli(HOST, PORT);
  8269. {
  8270. Request req;
  8271. req.method = "GET";
  8272. req.path = "/";
  8273. req.params.emplace("test", "test_value");
  8274. auto res = cli.send(req);
  8275. ASSERT_TRUE(res);
  8276. }
  8277. {
  8278. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8279. ASSERT_TRUE(res);
  8280. }
  8281. }
  8282. TEST(ClientImplMethods, GetSocketTest) {
  8283. httplib::Server svr;
  8284. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8285. res.status = StatusCode::OK_200;
  8286. });
  8287. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8288. auto se = detail::scope_exit([&] {
  8289. svr.stop();
  8290. thread.join();
  8291. ASSERT_FALSE(svr.is_running());
  8292. });
  8293. svr.wait_until_ready();
  8294. {
  8295. httplib::Client cli("http://127.0.0.1:3333");
  8296. cli.set_keep_alive(true);
  8297. // Use the behavior of cpp-httplib of opening the connection
  8298. // only when the first request happens. If that changes,
  8299. // this test would be obsolete.
  8300. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8301. // This also implicitly tests the server. But other tests would fail much
  8302. // earlier than this one to be considered.
  8303. auto res = cli.Get("/");
  8304. ASSERT_TRUE(res);
  8305. EXPECT_EQ(StatusCode::OK_200, res->status);
  8306. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8307. }
  8308. }
  8309. // Disabled due to out-of-memory problem on GitHub Actions
  8310. #ifdef _WIN64
  8311. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8312. // allocate content size larger than 2GB in memory
  8313. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8314. char *content = (char *)malloc(content_size);
  8315. ASSERT_TRUE(content);
  8316. Server svr;
  8317. svr.Get("/foo",
  8318. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8319. res.set_content(content, content_size, "application/octet-stream");
  8320. });
  8321. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8322. auto se = detail::scope_exit([&] {
  8323. svr.stop();
  8324. listen_thread.join();
  8325. if (content) free(content);
  8326. ASSERT_FALSE(svr.is_running());
  8327. });
  8328. svr.wait_until_ready();
  8329. Client cli(HOST, PORT);
  8330. auto res = cli.Get("/foo");
  8331. ASSERT_TRUE(res);
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ(content_size, res->body.length());
  8334. }
  8335. #endif
  8336. #ifdef CPPHTTPLIB_SSL_ENABLED
  8337. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8338. Client cli("http://yahoo.com");
  8339. auto res = cli.Get("/");
  8340. ASSERT_TRUE(res);
  8341. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8342. cli.set_follow_location(true);
  8343. res = cli.Get("/");
  8344. ASSERT_TRUE(res);
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8347. }
  8348. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8349. Client cli("https://yahoo.com");
  8350. auto res = cli.Get("/");
  8351. ASSERT_TRUE(res);
  8352. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8353. cli.set_follow_location(true);
  8354. res = cli.Get("/");
  8355. ASSERT_TRUE(res);
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8358. }
  8359. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8360. Client cli("https://yahoo.com");
  8361. auto res = cli.Get("/");
  8362. ASSERT_TRUE(res);
  8363. ASSERT_FALSE(!res);
  8364. ASSERT_TRUE(res);
  8365. ASSERT_FALSE(res == nullptr);
  8366. ASSERT_TRUE(res != nullptr);
  8367. EXPECT_EQ(Error::Success, res.error());
  8368. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8369. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8370. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8371. cli.set_follow_location(true);
  8372. res = cli.Get("/");
  8373. ASSERT_TRUE(res);
  8374. EXPECT_EQ(Error::Success, res.error());
  8375. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8376. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8379. }
  8380. #endif
  8381. #ifdef CPPHTTPLIB_SSL_ENABLED
  8382. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8383. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8384. Client cli("https://cdnjs.cloudflare.com");
  8385. auto res =
  8386. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8387. ASSERT_TRUE(res);
  8388. EXPECT_EQ(StatusCode::OK_200, res->status);
  8389. EXPECT_EQ(287630U, res->body.size());
  8390. EXPECT_EQ("application/javascript; charset=utf-8",
  8391. res->get_header_value("Content-Type"));
  8392. }
  8393. #endif
  8394. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8395. #undef REDIR_HOST // Silence compiler warning
  8396. #define REDIR_HOST "https://httpbingo.org"
  8397. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8398. Client cli(REDIR_HOST);
  8399. cli.set_follow_location(true);
  8400. auto res =
  8401. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8402. ASSERT_TRUE(res);
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8406. Client cli(REDIR_HOST);
  8407. cli.set_follow_location(true);
  8408. Params params;
  8409. params.emplace("url", "http://example.com");
  8410. params.emplace("status_code", "302");
  8411. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8412. ASSERT_TRUE(res);
  8413. EXPECT_EQ(StatusCode::OK_200, res->status);
  8414. }
  8415. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8416. Client cli(REDIR_HOST);
  8417. cli.set_follow_location(true);
  8418. Params params;
  8419. params.emplace("url", "http://example.com");
  8420. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8421. ASSERT_TRUE(res);
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. }
  8424. #ifdef CPPHTTPLIB_SSL_ENABLED
  8425. TEST(HttpToHttpsRedirectTest, CertFile) {
  8426. Server svr;
  8427. ASSERT_TRUE(svr.is_valid());
  8428. svr.Get("/index", [&](const Request &, Response &res) {
  8429. res.set_redirect("https://127.0.0.1:1235/index");
  8430. svr.stop();
  8431. });
  8432. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8433. ASSERT_TRUE(ssl_svr.is_valid());
  8434. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8435. res.set_content("test", "text/plain");
  8436. ssl_svr.stop();
  8437. });
  8438. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8439. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8440. auto se = detail::scope_exit([&] {
  8441. t2.join();
  8442. t.join();
  8443. ASSERT_FALSE(svr.is_running());
  8444. });
  8445. svr.wait_until_ready();
  8446. ssl_svr.wait_until_ready();
  8447. Client cli("127.0.0.1", PORT);
  8448. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8449. cli.enable_server_certificate_verification(true);
  8450. cli.set_follow_location(true);
  8451. cli.set_connection_timeout(30);
  8452. auto res = cli.Get("/index");
  8453. ASSERT_TRUE(res);
  8454. ASSERT_EQ(StatusCode::OK_200, res->status);
  8455. }
  8456. TEST(SSLClientRedirectTest, CertFile) {
  8457. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8458. ASSERT_TRUE(ssl_svr1.is_valid());
  8459. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8460. res.set_redirect("https://127.0.0.1:1235/index");
  8461. ssl_svr1.stop();
  8462. });
  8463. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8464. ASSERT_TRUE(ssl_svr2.is_valid());
  8465. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8466. res.set_content("test", "text/plain");
  8467. ssl_svr2.stop();
  8468. });
  8469. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8470. thread t2 =
  8471. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8472. auto se = detail::scope_exit([&] {
  8473. t2.join();
  8474. t.join();
  8475. ASSERT_FALSE(ssl_svr1.is_running());
  8476. });
  8477. ssl_svr1.wait_until_ready();
  8478. ssl_svr2.wait_until_ready();
  8479. SSLClient cli("127.0.0.1", PORT);
  8480. std::string cert;
  8481. read_file(SERVER_CERT2_FILE, cert);
  8482. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8483. cli.enable_server_certificate_verification(true);
  8484. cli.set_follow_location(true);
  8485. cli.set_connection_timeout(30);
  8486. auto res = cli.Get("/index");
  8487. ASSERT_TRUE(res);
  8488. ASSERT_EQ(StatusCode::OK_200, res->status);
  8489. }
  8490. #endif
  8491. TEST(MultipartFormDataTest, LargeData) {
  8492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8493. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8494. const ContentReader &content_reader) {
  8495. if (req.is_multipart_form_data()) {
  8496. std::vector<FormData> items;
  8497. content_reader(
  8498. [&](const FormData &file) {
  8499. items.push_back(file);
  8500. return true;
  8501. },
  8502. [&](const char *data, size_t data_length) {
  8503. items.back().content.append(data, data_length);
  8504. return true;
  8505. });
  8506. EXPECT_TRUE(std::string(items[0].name) == "document");
  8507. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8508. EXPECT_TRUE(items[0].filename == "2MB_data");
  8509. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8510. EXPECT_TRUE(items[1].name == "hello");
  8511. EXPECT_TRUE(items[1].content == "world");
  8512. EXPECT_TRUE(items[1].filename == "");
  8513. EXPECT_TRUE(items[1].content_type == "");
  8514. } else {
  8515. std::string body;
  8516. content_reader([&](const char *data, size_t data_length) {
  8517. body.append(data, data_length);
  8518. return true;
  8519. });
  8520. }
  8521. });
  8522. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8523. auto se = detail::scope_exit([&] {
  8524. svr.stop();
  8525. t.join();
  8526. ASSERT_FALSE(svr.is_running());
  8527. });
  8528. svr.wait_until_ready();
  8529. {
  8530. std::string data(1024 * 1024 * 2, '.');
  8531. std::stringstream buffer;
  8532. buffer << data;
  8533. Client cli("https://localhost:8080");
  8534. cli.enable_server_certificate_verification(false);
  8535. UploadFormDataItems items{
  8536. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8537. {"hello", "world", "", ""},
  8538. };
  8539. auto res = cli.Post("/post", items);
  8540. ASSERT_TRUE(res);
  8541. ASSERT_EQ(StatusCode::OK_200, res->status);
  8542. }
  8543. }
  8544. TEST(MultipartFormDataTest, DataProviderItems) {
  8545. std::random_device seed_gen;
  8546. std::mt19937 random(seed_gen());
  8547. std::string rand1;
  8548. rand1.resize(1000);
  8549. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8550. std::string rand2;
  8551. rand2.resize(3000);
  8552. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8554. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8555. const ContentReader &content_reader) {
  8556. ASSERT_FALSE(req.is_multipart_form_data());
  8557. std::string body;
  8558. content_reader([&](const char *data, size_t data_length) {
  8559. body.append(data, data_length);
  8560. return true;
  8561. });
  8562. EXPECT_EQ(body, "");
  8563. });
  8564. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8565. const ContentReader &content_reader) {
  8566. ASSERT_TRUE(req.is_multipart_form_data());
  8567. std::vector<FormData> items;
  8568. content_reader(
  8569. [&](const FormData &file) {
  8570. items.push_back(file);
  8571. return true;
  8572. },
  8573. [&](const char *data, size_t data_length) {
  8574. items.back().content.append(data, data_length);
  8575. return true;
  8576. });
  8577. ASSERT_TRUE(items.size() == 2);
  8578. EXPECT_EQ(std::string(items[0].name), "name1");
  8579. EXPECT_EQ(items[0].content, "Testing123");
  8580. EXPECT_EQ(items[0].filename, "filename1");
  8581. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8582. EXPECT_EQ(items[1].name, "name2");
  8583. EXPECT_EQ(items[1].content, "Testing456");
  8584. EXPECT_EQ(items[1].filename, "");
  8585. EXPECT_EQ(items[1].content_type, "");
  8586. });
  8587. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8588. const ContentReader &content_reader) {
  8589. ASSERT_TRUE(req.is_multipart_form_data());
  8590. std::vector<FormData> items;
  8591. content_reader(
  8592. [&](const FormData &file) {
  8593. items.push_back(file);
  8594. return true;
  8595. },
  8596. [&](const char *data, size_t data_length) {
  8597. items.back().content.append(data, data_length);
  8598. return true;
  8599. });
  8600. ASSERT_TRUE(items.size() == 2);
  8601. EXPECT_EQ(items[0].name, "name3");
  8602. EXPECT_EQ(items[0].content, rand1);
  8603. EXPECT_EQ(items[0].filename, "filename3");
  8604. EXPECT_EQ(items[0].content_type, "");
  8605. EXPECT_EQ(items[1].name, "name4");
  8606. EXPECT_EQ(items[1].content, rand2);
  8607. EXPECT_EQ(items[1].filename, "filename4");
  8608. EXPECT_EQ(items[1].content_type, "");
  8609. });
  8610. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8611. const ContentReader &content_reader) {
  8612. ASSERT_TRUE(req.is_multipart_form_data());
  8613. std::vector<FormData> items;
  8614. content_reader(
  8615. [&](const FormData &file) {
  8616. items.push_back(file);
  8617. return true;
  8618. },
  8619. [&](const char *data, size_t data_length) {
  8620. items.back().content.append(data, data_length);
  8621. return true;
  8622. });
  8623. ASSERT_TRUE(items.size() == 4);
  8624. EXPECT_EQ(std::string(items[0].name), "name1");
  8625. EXPECT_EQ(items[0].content, "Testing123");
  8626. EXPECT_EQ(items[0].filename, "filename1");
  8627. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8628. EXPECT_EQ(items[1].name, "name2");
  8629. EXPECT_EQ(items[1].content, "Testing456");
  8630. EXPECT_EQ(items[1].filename, "");
  8631. EXPECT_EQ(items[1].content_type, "");
  8632. EXPECT_EQ(items[2].name, "name3");
  8633. EXPECT_EQ(items[2].content, rand1);
  8634. EXPECT_EQ(items[2].filename, "filename3");
  8635. EXPECT_EQ(items[2].content_type, "");
  8636. EXPECT_EQ(items[3].name, "name4");
  8637. EXPECT_EQ(items[3].content, rand2);
  8638. EXPECT_EQ(items[3].filename, "filename4");
  8639. EXPECT_EQ(items[3].content_type, "");
  8640. });
  8641. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8642. auto se = detail::scope_exit([&] {
  8643. svr.stop();
  8644. t.join();
  8645. ASSERT_FALSE(svr.is_running());
  8646. });
  8647. svr.wait_until_ready();
  8648. {
  8649. Client cli("https://localhost:8080");
  8650. cli.enable_server_certificate_verification(false);
  8651. UploadFormDataItems items{
  8652. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8653. {"name2", "Testing456", "", ""}, // not a file
  8654. };
  8655. {
  8656. auto res = cli.Post("/post-none", {}, {}, {});
  8657. ASSERT_TRUE(res);
  8658. ASSERT_EQ(StatusCode::OK_200, res->status);
  8659. }
  8660. FormDataProviderItems providers;
  8661. {
  8662. auto res =
  8663. cli.Post("/post-items", {}, items, providers); // empty providers
  8664. ASSERT_TRUE(res);
  8665. ASSERT_EQ(StatusCode::OK_200, res->status);
  8666. }
  8667. providers.push_back({"name3",
  8668. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8669. // test the offset is given correctly at each step
  8670. if (!offset)
  8671. sink.os.write(rand1.data(), 30);
  8672. else if (offset == 30)
  8673. sink.os.write(rand1.data() + 30, 300);
  8674. else if (offset == 330)
  8675. sink.os.write(rand1.data() + 330, 670);
  8676. else if (offset == rand1.size())
  8677. sink.done();
  8678. return true;
  8679. },
  8680. "filename3",
  8681. {}});
  8682. providers.push_back({"name4",
  8683. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8684. // test the offset is given correctly at each step
  8685. if (!offset)
  8686. sink.os.write(rand2.data(), 2000);
  8687. else if (offset == 2000)
  8688. sink.os.write(rand2.data() + 2000, 1);
  8689. else if (offset == 2001)
  8690. sink.os.write(rand2.data() + 2001, 999);
  8691. else if (offset == rand2.size())
  8692. sink.done();
  8693. return true;
  8694. },
  8695. "filename4",
  8696. {}});
  8697. {
  8698. auto res = cli.Post("/post-providers", {}, {}, providers);
  8699. ASSERT_TRUE(res);
  8700. ASSERT_EQ(StatusCode::OK_200, res->status);
  8701. }
  8702. {
  8703. auto res = cli.Post("/post-both", {}, items, providers);
  8704. ASSERT_TRUE(res);
  8705. ASSERT_EQ(StatusCode::OK_200, res->status);
  8706. }
  8707. }
  8708. }
  8709. TEST(MultipartFormDataTest, BadHeader) {
  8710. Server svr;
  8711. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8712. res.set_content("ok", "text/plain");
  8713. });
  8714. thread t = thread([&] { svr.listen(HOST, PORT); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. t.join();
  8718. ASSERT_FALSE(svr.is_running());
  8719. });
  8720. svr.wait_until_ready();
  8721. const std::string body =
  8722. "This is the preamble. It is to be ignored, though it\r\n"
  8723. "is a handy place for composition agents to include an\r\n"
  8724. "explanatory note to non-MIME conformant readers.\r\n"
  8725. "\r\n"
  8726. "\r\n"
  8727. "--simple boundary\r\n"
  8728. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8729. ": BAD...\r\n"
  8730. "\r\n"
  8731. "value1\r\n"
  8732. "--simple boundary\r\n"
  8733. "Content-Disposition: form-data; name=\"field2\"; "
  8734. "filename=\"example.txt\"\r\n"
  8735. "\r\n"
  8736. "value2\r\n"
  8737. "--simple boundary--\r\n"
  8738. "This is the epilogue. It is also to be ignored.\r\n";
  8739. std::string content_type =
  8740. R"(multipart/form-data; boundary="simple boundary")";
  8741. Client cli(HOST, PORT);
  8742. auto res = cli.Post("/post", body, content_type.c_str());
  8743. ASSERT_TRUE(res);
  8744. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8745. }
  8746. TEST(MultipartFormDataTest, WithPreamble) {
  8747. Server svr;
  8748. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8749. res.set_content("ok", "text/plain");
  8750. });
  8751. thread t = thread([&] { svr.listen(HOST, PORT); });
  8752. auto se = detail::scope_exit([&] {
  8753. svr.stop();
  8754. t.join();
  8755. ASSERT_FALSE(svr.is_running());
  8756. });
  8757. svr.wait_until_ready();
  8758. const std::string body =
  8759. "This is the preamble. It is to be ignored, though it\r\n"
  8760. "is a handy place for composition agents to include an\r\n"
  8761. "explanatory note to non-MIME conformant readers.\r\n"
  8762. "\r\n"
  8763. "\r\n"
  8764. "--simple boundary\r\n"
  8765. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8766. "\r\n"
  8767. "value1\r\n"
  8768. "--simple boundary\r\n"
  8769. "Content-Disposition: form-data; name=\"field2\"; "
  8770. "filename=\"example.txt\"\r\n"
  8771. "\r\n"
  8772. "value2\r\n"
  8773. "--simple boundary--\r\n"
  8774. "This is the epilogue. It is also to be ignored.\r\n";
  8775. std::string content_type =
  8776. R"(multipart/form-data; boundary="simple boundary")";
  8777. Client cli(HOST, PORT);
  8778. auto res = cli.Post("/post", body, content_type.c_str());
  8779. ASSERT_TRUE(res);
  8780. EXPECT_EQ(StatusCode::OK_200, res->status);
  8781. }
  8782. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8784. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8785. const ContentReader &content_reader) {
  8786. if (req.is_multipart_form_data()) {
  8787. std::vector<FormData> items;
  8788. content_reader(
  8789. [&](const FormData &file) {
  8790. items.push_back(file);
  8791. return true;
  8792. },
  8793. [&](const char *data, size_t data_length) {
  8794. items.back().content.append(data, data_length);
  8795. return true;
  8796. });
  8797. EXPECT_TRUE(std::string(items[0].name) == "document");
  8798. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8799. EXPECT_TRUE(items[0].filename == "2MB_data");
  8800. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8801. EXPECT_TRUE(items[1].name == "hello");
  8802. EXPECT_TRUE(items[1].content == "world");
  8803. EXPECT_TRUE(items[1].filename == "");
  8804. EXPECT_TRUE(items[1].content_type == "");
  8805. } else {
  8806. std::string body;
  8807. content_reader([&](const char *data, size_t data_length) {
  8808. body.append(data, data_length);
  8809. return true;
  8810. });
  8811. }
  8812. });
  8813. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8814. auto se = detail::scope_exit([&] {
  8815. svr.stop();
  8816. t.join();
  8817. ASSERT_FALSE(svr.is_running());
  8818. });
  8819. svr.wait_until_ready();
  8820. {
  8821. std::string data(1024 * 1024 * 2, '.');
  8822. std::stringstream buffer;
  8823. buffer << data;
  8824. Client cli("https://localhost:8080");
  8825. cli.enable_server_certificate_verification(false);
  8826. UploadFormDataItems items{
  8827. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8828. {"hello", "world", "", ""},
  8829. };
  8830. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8831. ASSERT_TRUE(res);
  8832. ASSERT_EQ(StatusCode::OK_200, res->status);
  8833. }
  8834. }
  8835. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8836. std::string data(1024 * 1024 * 2, '&');
  8837. std::stringstream buffer;
  8838. buffer << data;
  8839. Client cli("https://localhost:8080");
  8840. UploadFormDataItems items{
  8841. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8842. {"hello", "world", "", ""},
  8843. };
  8844. for (const char &c : " \t\r\n") {
  8845. auto res =
  8846. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8847. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8848. ASSERT_FALSE(res);
  8849. }
  8850. }
  8851. TEST(MultipartFormDataTest, PutFormData) {
  8852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8853. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8854. const ContentReader &content_reader) {
  8855. if (req.is_multipart_form_data()) {
  8856. std::vector<FormData> items;
  8857. content_reader(
  8858. [&](const FormData &file) {
  8859. items.push_back(file);
  8860. return true;
  8861. },
  8862. [&](const char *data, size_t data_length) {
  8863. items.back().content.append(data, data_length);
  8864. return true;
  8865. });
  8866. EXPECT_TRUE(std::string(items[0].name) == "document");
  8867. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8868. EXPECT_TRUE(items[0].filename == "2MB_data");
  8869. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8870. EXPECT_TRUE(items[1].name == "hello");
  8871. EXPECT_TRUE(items[1].content == "world");
  8872. EXPECT_TRUE(items[1].filename == "");
  8873. EXPECT_TRUE(items[1].content_type == "");
  8874. } else {
  8875. std::string body;
  8876. content_reader([&](const char *data, size_t data_length) {
  8877. body.append(data, data_length);
  8878. return true;
  8879. });
  8880. }
  8881. });
  8882. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8883. auto se = detail::scope_exit([&] {
  8884. svr.stop();
  8885. t.join();
  8886. ASSERT_FALSE(svr.is_running());
  8887. });
  8888. svr.wait_until_ready();
  8889. {
  8890. std::string data(1024 * 1024 * 2, '&');
  8891. std::stringstream buffer;
  8892. buffer << data;
  8893. Client cli("https://localhost:8080");
  8894. cli.enable_server_certificate_verification(false);
  8895. UploadFormDataItems items{
  8896. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8897. {"hello", "world", "", ""},
  8898. };
  8899. auto res = cli.Put("/put", items);
  8900. ASSERT_TRUE(res);
  8901. ASSERT_EQ(StatusCode::OK_200, res->status);
  8902. }
  8903. }
  8904. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8906. svr.Put("/put_customboundary",
  8907. [&](const Request &req, const Response & /*res*/,
  8908. const ContentReader &content_reader) {
  8909. if (req.is_multipart_form_data()) {
  8910. std::vector<FormData> items;
  8911. content_reader(
  8912. [&](const FormData &file) {
  8913. items.push_back(file);
  8914. return true;
  8915. },
  8916. [&](const char *data, size_t data_length) {
  8917. items.back().content.append(data, data_length);
  8918. return true;
  8919. });
  8920. EXPECT_TRUE(std::string(items[0].name) == "document");
  8921. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8922. EXPECT_TRUE(items[0].filename == "2MB_data");
  8923. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8924. EXPECT_TRUE(items[1].name == "hello");
  8925. EXPECT_TRUE(items[1].content == "world");
  8926. EXPECT_TRUE(items[1].filename == "");
  8927. EXPECT_TRUE(items[1].content_type == "");
  8928. } else {
  8929. std::string body;
  8930. content_reader([&](const char *data, size_t data_length) {
  8931. body.append(data, data_length);
  8932. return true;
  8933. });
  8934. }
  8935. });
  8936. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8937. auto se = detail::scope_exit([&] {
  8938. svr.stop();
  8939. t.join();
  8940. ASSERT_FALSE(svr.is_running());
  8941. });
  8942. svr.wait_until_ready();
  8943. {
  8944. std::string data(1024 * 1024 * 2, '&');
  8945. std::stringstream buffer;
  8946. buffer << data;
  8947. Client cli("https://localhost:8080");
  8948. cli.enable_server_certificate_verification(false);
  8949. UploadFormDataItems items{
  8950. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8951. {"hello", "world", "", ""},
  8952. };
  8953. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8954. ASSERT_TRUE(res);
  8955. ASSERT_EQ(StatusCode::OK_200, res->status);
  8956. }
  8957. }
  8958. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8959. std::string data(1024 * 1024 * 2, '&');
  8960. std::stringstream buffer;
  8961. buffer << data;
  8962. Client cli("https://localhost:8080");
  8963. cli.enable_server_certificate_verification(false);
  8964. UploadFormDataItems items{
  8965. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8966. {"hello", "world", "", ""},
  8967. };
  8968. for (const char &c : " \t\r\n") {
  8969. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8970. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8971. ASSERT_FALSE(res);
  8972. }
  8973. }
  8974. TEST(MultipartFormDataTest, AlternateFilename) {
  8975. auto handled = false;
  8976. Server svr;
  8977. svr.Post("/test", [&](const Request &req, Response &res) {
  8978. ASSERT_EQ(2u, req.form.files.size());
  8979. ASSERT_EQ(1u, req.form.fields.size());
  8980. // Test files
  8981. const auto &file1 = req.form.get_file("file1");
  8982. ASSERT_EQ("file1", file1.name);
  8983. ASSERT_EQ("A.txt", file1.filename);
  8984. ASSERT_EQ("text/plain", file1.content_type);
  8985. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8986. const auto &file2 = req.form.get_file("file2");
  8987. ASSERT_EQ("file2", file2.name);
  8988. ASSERT_EQ("a.html", file2.filename);
  8989. ASSERT_EQ("text/html", file2.content_type);
  8990. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8991. file2.content);
  8992. // Test text field
  8993. const auto &text = req.form.get_field("text");
  8994. ASSERT_EQ("text default", text);
  8995. res.set_content("ok", "text/plain");
  8996. handled = true;
  8997. });
  8998. thread t = thread([&] { svr.listen(HOST, PORT); });
  8999. auto se = detail::scope_exit([&] {
  9000. svr.stop();
  9001. t.join();
  9002. ASSERT_FALSE(svr.is_running());
  9003. ASSERT_TRUE(handled);
  9004. });
  9005. svr.wait_until_ready();
  9006. auto req = "POST /test HTTP/1.1\r\n"
  9007. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9008. "Content-Length: 399\r\n"
  9009. "\r\n"
  9010. "----------\r\n"
  9011. "Content-Disposition: form-data; name=\"text\"\r\n"
  9012. "\r\n"
  9013. "text default\r\n"
  9014. "----------\r\n"
  9015. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9016. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9017. "Content-Type: text/plain\r\n"
  9018. "\r\n"
  9019. "Content of a.txt.\r\n"
  9020. "\r\n"
  9021. "----------\r\n"
  9022. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9023. "\"a.html\"\r\n"
  9024. "Content-Type: text/html\r\n"
  9025. "\r\n"
  9026. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9027. "\r\n"
  9028. "------------\r\n";
  9029. ASSERT_TRUE(send_request(1, req));
  9030. }
  9031. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9032. auto handled = false;
  9033. Server svr;
  9034. svr.Post("/test", [&](const Request &req, Response &) {
  9035. ASSERT_EQ(2u, req.form.fields.size());
  9036. const auto &text1 = req.form.get_field("text1");
  9037. ASSERT_EQ("text1", text1);
  9038. const auto &text2 = req.form.get_field("text2");
  9039. ASSERT_EQ("text2", text2);
  9040. handled = true;
  9041. });
  9042. thread t = thread([&] { svr.listen(HOST, PORT); });
  9043. auto se = detail::scope_exit([&] {
  9044. svr.stop();
  9045. t.join();
  9046. ASSERT_FALSE(svr.is_running());
  9047. ASSERT_TRUE(handled);
  9048. });
  9049. svr.wait_until_ready();
  9050. auto req = "POST /test HTTP/1.1\r\n"
  9051. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9052. "Content-Length: 146\r\n"
  9053. "\r\n----------\r\n"
  9054. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9055. "\r\n"
  9056. "text1"
  9057. "\r\n----------\r\n"
  9058. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9059. "\r\n"
  9060. "text2"
  9061. "\r\n------------";
  9062. std::string response;
  9063. ASSERT_TRUE(send_request(1, req, &response));
  9064. ASSERT_EQ("200", response.substr(9, 3));
  9065. }
  9066. TEST(MultipartFormDataTest, ContentLength) {
  9067. auto handled = false;
  9068. Server svr;
  9069. svr.Post("/test", [&](const Request &req, Response &) {
  9070. ASSERT_EQ(2u, req.form.fields.size());
  9071. const auto &text1 = req.form.get_field("text1");
  9072. ASSERT_EQ("text1", text1);
  9073. const auto &text2 = req.form.get_field("text2");
  9074. ASSERT_EQ("text2", text2);
  9075. handled = true;
  9076. });
  9077. thread t = thread([&] { svr.listen(HOST, PORT); });
  9078. auto se = detail::scope_exit([&] {
  9079. svr.stop();
  9080. t.join();
  9081. ASSERT_FALSE(svr.is_running());
  9082. ASSERT_TRUE(handled);
  9083. });
  9084. svr.wait_until_ready();
  9085. auto req = "POST /test HTTP/1.1\r\n"
  9086. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9087. "Content-Length: 167\r\n"
  9088. "\r\n----------\r\n"
  9089. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9090. "Content-Length: 5\r\n"
  9091. "\r\n"
  9092. "text1"
  9093. "\r\n----------\r\n"
  9094. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9095. "\r\n"
  9096. "text2"
  9097. "\r\n------------\r\n";
  9098. std::string response;
  9099. ASSERT_TRUE(send_request(1, req, &response));
  9100. ASSERT_EQ("200", response.substr(9, 3));
  9101. }
  9102. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9103. auto handled = false;
  9104. Server svr;
  9105. svr.Post("/test", [&](const Request &req, Response &) {
  9106. ASSERT_EQ(2u, req.form.fields.size());
  9107. const auto &text1 = req.form.get_field("text1");
  9108. ASSERT_EQ("text1", text1);
  9109. // TODO: Add header access for text fields if needed
  9110. const auto &text2 = req.form.get_field("text2");
  9111. ASSERT_EQ("text2", text2);
  9112. // TODO: Header access for text fields needs to be implemented
  9113. // auto &headers = it->second.headers;
  9114. // ASSERT_EQ(3U, headers.size());
  9115. // auto custom_header = headers.find("x-whatever");
  9116. // ASSERT_TRUE(custom_header != headers.end());
  9117. // ASSERT_NE("customvalue", custom_header->second);
  9118. // ASSERT_EQ("CustomValue", custom_header->second);
  9119. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9120. handled = true;
  9121. });
  9122. thread t = thread([&] { svr.listen(HOST, PORT); });
  9123. auto se = detail::scope_exit([&] {
  9124. svr.stop();
  9125. t.join();
  9126. ASSERT_FALSE(svr.is_running());
  9127. ASSERT_TRUE(handled);
  9128. });
  9129. svr.wait_until_ready();
  9130. auto req = "POST /test HTTP/1.1\r\n"
  9131. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9132. "Content-Length: 232\r\n"
  9133. "\r\n----------\r\n"
  9134. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9135. "Content-Length: 5\r\n"
  9136. "X-Test: 1\r\n"
  9137. "\r\n"
  9138. "text1"
  9139. "\r\n----------\r\n"
  9140. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9141. "Content-Type: text/plain\r\n"
  9142. "X-Whatever: CustomValue\r\n"
  9143. "\r\n"
  9144. "text2"
  9145. "\r\n------------\r\n"
  9146. "That should be disregarded. Not even read";
  9147. std::string response;
  9148. ASSERT_TRUE(send_request(1, req, &response));
  9149. ASSERT_EQ("200", response.substr(9, 3));
  9150. }
  9151. #endif
  9152. TEST(MultipartFormDataTest, LargeHeader) {
  9153. auto handled = false;
  9154. Server svr;
  9155. svr.Post("/test", [&](const Request &req, Response &) {
  9156. ASSERT_EQ(1u, req.form.fields.size());
  9157. const auto &text = req.form.get_field("name1");
  9158. ASSERT_EQ("text1", text);
  9159. handled = true;
  9160. });
  9161. thread t = thread([&] { svr.listen(HOST, PORT); });
  9162. auto se = detail::scope_exit([&] {
  9163. svr.stop();
  9164. t.join();
  9165. ASSERT_FALSE(svr.is_running());
  9166. ASSERT_TRUE(handled);
  9167. });
  9168. svr.wait_until_ready();
  9169. auto boundary = std::string("cpp-httplib-multipart-data");
  9170. std::string content = "--" + boundary +
  9171. "\r\n"
  9172. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9173. "\r\n"
  9174. "text1\r\n"
  9175. "--" +
  9176. boundary + "--\r\n";
  9177. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9178. "Content-Type: multipart/form-data;boundary=" +
  9179. boundary +
  9180. "\r\n"
  9181. "Content-Length: " +
  9182. std::to_string(content.size()) +
  9183. "\r\n"
  9184. "Dummy-Header: ";
  9185. std::string header_suffix = "\r\n"
  9186. "\r\n";
  9187. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9188. size_t header_dummy_size =
  9189. read_buff_size -
  9190. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9191. auto header_dummy = std::string(header_dummy_size, '@');
  9192. auto req = header_prefix + header_dummy + header_suffix + content;
  9193. std::string response;
  9194. ASSERT_TRUE(send_request(1, req, &response));
  9195. ASSERT_EQ("200", response.substr(9, 3));
  9196. }
  9197. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9198. static constexpr unsigned int number_of_tasks{1000000};
  9199. std::atomic_uint count{0};
  9200. std::unique_ptr<TaskQueue> task_queue{
  9201. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9202. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9203. auto queued = task_queue->enqueue(
  9204. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9205. EXPECT_TRUE(queued);
  9206. }
  9207. EXPECT_NO_THROW(task_queue->shutdown());
  9208. EXPECT_EQ(number_of_tasks, count.load());
  9209. }
  9210. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9211. static constexpr unsigned int number_of_tasks{1000000};
  9212. static constexpr unsigned int qlimit{2};
  9213. unsigned int queued_count{0};
  9214. std::atomic_uint count{0};
  9215. std::unique_ptr<TaskQueue> task_queue{
  9216. new ThreadPool{/*num_threads=*/1, qlimit}};
  9217. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9218. if (task_queue->enqueue(
  9219. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9220. queued_count++;
  9221. }
  9222. }
  9223. EXPECT_NO_THROW(task_queue->shutdown());
  9224. EXPECT_EQ(queued_count, count.load());
  9225. EXPECT_TRUE(queued_count <= number_of_tasks);
  9226. EXPECT_TRUE(queued_count >= qlimit);
  9227. }
  9228. TEST(TaskQueueTest, MaxQueuedRequests) {
  9229. static constexpr unsigned int qlimit{3};
  9230. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9231. std::condition_variable sem_cv;
  9232. std::mutex sem_mtx;
  9233. int credits = 0;
  9234. bool queued;
  9235. /* Fill up the queue with tasks that will block until we give them credits to
  9236. * complete. */
  9237. for (unsigned int n = 0; n <= qlimit;) {
  9238. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9239. std::unique_lock<std::mutex> lock(sem_mtx);
  9240. while (credits <= 0) {
  9241. sem_cv.wait(lock);
  9242. }
  9243. /* Consume the credit and signal the test code if they are all gone. */
  9244. if (--credits == 0) { sem_cv.notify_one(); }
  9245. });
  9246. if (n < qlimit) {
  9247. /* The first qlimit enqueues must succeed. */
  9248. EXPECT_TRUE(queued);
  9249. } else {
  9250. /* The last one will succeed only when the worker thread
  9251. * starts and dequeues the first blocking task. Although
  9252. * not necessary for the correctness of this test, we sleep for
  9253. * a short while to avoid busy waiting. */
  9254. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9255. }
  9256. if (queued) { n++; }
  9257. }
  9258. /* Further enqueues must fail since the queue is full. */
  9259. for (auto i = 0; i < 4; i++) {
  9260. queued = task_queue->enqueue([] {});
  9261. EXPECT_FALSE(queued);
  9262. }
  9263. /* Give the credits to allow the previous tasks to complete. */
  9264. {
  9265. std::unique_lock<std::mutex> lock(sem_mtx);
  9266. credits += qlimit + 1;
  9267. }
  9268. sem_cv.notify_all();
  9269. /* Wait for all the credits to be consumed. */
  9270. {
  9271. std::unique_lock<std::mutex> lock(sem_mtx);
  9272. while (credits > 0) {
  9273. sem_cv.wait(lock);
  9274. }
  9275. }
  9276. /* Check that we are able again to enqueue at least qlimit tasks. */
  9277. for (unsigned int i = 0; i < qlimit; i++) {
  9278. queued = task_queue->enqueue([] {});
  9279. EXPECT_TRUE(queued);
  9280. }
  9281. EXPECT_NO_THROW(task_queue->shutdown());
  9282. }
  9283. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9284. Server svr;
  9285. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9286. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9287. });
  9288. svr.Get("/hello", [](const Request &req, Response &res) {
  9289. res.set_content(req.get_param_value("key"), "text/plain");
  9290. });
  9291. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9292. auto se = detail::scope_exit([&] {
  9293. svr.stop();
  9294. thread.join();
  9295. ASSERT_FALSE(svr.is_running());
  9296. });
  9297. svr.wait_until_ready();
  9298. {
  9299. Client cli(HOST, PORT);
  9300. cli.set_follow_location(true);
  9301. auto res = cli.Get("/");
  9302. ASSERT_TRUE(res);
  9303. EXPECT_EQ(StatusCode::OK_200, res->status);
  9304. EXPECT_EQ("val&key2=val2", res->body);
  9305. }
  9306. }
  9307. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9308. Server svr;
  9309. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9310. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9311. });
  9312. svr.Get("/hello", [](const Request &req, Response &res) {
  9313. res.set_content(req.get_param_value("key"), "text/plain");
  9314. });
  9315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9316. auto se = detail::scope_exit([&] {
  9317. svr.stop();
  9318. thread.join();
  9319. ASSERT_FALSE(svr.is_running());
  9320. });
  9321. svr.wait_until_ready();
  9322. {
  9323. Client cli(HOST, PORT);
  9324. cli.set_follow_location(true);
  9325. auto res = cli.Get("/");
  9326. ASSERT_TRUE(res);
  9327. EXPECT_EQ(StatusCode::OK_200, res->status);
  9328. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9329. }
  9330. }
  9331. #ifdef CPPHTTPLIB_SSL_ENABLED
  9332. TEST(RedirectTest, Issue2185_Online) {
  9333. SSLClient client("github.com");
  9334. client.set_follow_location(true);
  9335. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9336. "Coollab-Windows.zip");
  9337. ASSERT_TRUE(res);
  9338. EXPECT_EQ(StatusCode::OK_200, res->status);
  9339. EXPECT_EQ(9920427U, res->body.size());
  9340. }
  9341. #endif
  9342. TEST(VulnerabilityTest, CRLFInjection) {
  9343. Server svr;
  9344. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9345. res.set_content("Hello 1", "text/plain");
  9346. });
  9347. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9348. res.set_content("Hello 2", "text/plain");
  9349. });
  9350. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9351. res.set_content("Hello 3", "text/plain");
  9352. });
  9353. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9354. res.set_content("Hello 4", "text/plain");
  9355. });
  9356. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9357. for (const auto &x : req.headers) {
  9358. auto key = x.first;
  9359. EXPECT_STRNE("evil", key.c_str());
  9360. }
  9361. });
  9362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9363. auto se = detail::scope_exit([&] {
  9364. svr.stop();
  9365. thread.join();
  9366. ASSERT_FALSE(svr.is_running());
  9367. });
  9368. svr.wait_until_ready();
  9369. {
  9370. Client cli(HOST, PORT);
  9371. cli.Post("/test1", "A=B",
  9372. "application/x-www-form-urlencoded\r\nevil: hello1");
  9373. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9374. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9375. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9376. }
  9377. }
  9378. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9379. auto server_thread = std::thread([] {
  9380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9381. default_socket_options(srv);
  9382. sockaddr_in addr{};
  9383. addr.sin_family = AF_INET;
  9384. addr.sin_port = htons(PORT + 1);
  9385. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9386. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9387. ::listen(srv, 1);
  9388. sockaddr_in cli_addr{};
  9389. socklen_t cli_len = sizeof(cli_addr);
  9390. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9391. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9392. std::string buf_all;
  9393. char buf[2048];
  9394. ssize_t n;
  9395. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9396. buf_all.append(buf, static_cast<size_t>(n));
  9397. size_t pos;
  9398. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9399. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9400. auto e = request_block.find("\r\n");
  9401. if (e != std::string::npos) {
  9402. auto request_line = request_block.substr(0, e);
  9403. std::string msg =
  9404. "CRLF injection detected in request line: '" + request_line + "'";
  9405. EXPECT_FALSE(true) << msg;
  9406. }
  9407. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9408. ::send(cli,
  9409. #ifdef _WIN32
  9410. static_cast<const char *>(resp.c_str()),
  9411. static_cast<int>(resp.size()),
  9412. #else
  9413. resp.c_str(), resp.size(),
  9414. #endif
  9415. 0);
  9416. buf_all.erase(0, pos + 4);
  9417. }
  9418. }
  9419. detail::close_socket(cli);
  9420. detail::close_socket(srv);
  9421. });
  9422. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9423. auto cli = Client("127.0.0.1", PORT + 1);
  9424. auto headers = Headers{
  9425. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9426. {"Connection", "keep-alive"}};
  9427. auto res = cli.Get("/hi", headers);
  9428. EXPECT_FALSE(res);
  9429. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9430. server_thread.join();
  9431. }
  9432. TEST(PathParamsTest, StaticMatch) {
  9433. const auto pattern = "/users/all";
  9434. detail::PathParamsMatcher matcher(pattern);
  9435. Request request;
  9436. request.path = "/users/all";
  9437. ASSERT_TRUE(matcher.match(request));
  9438. std::unordered_map<std::string, std::string> expected_params = {};
  9439. EXPECT_EQ(request.path_params, expected_params);
  9440. }
  9441. TEST(PathParamsTest, StaticMismatch) {
  9442. const auto pattern = "/users/all";
  9443. detail::PathParamsMatcher matcher(pattern);
  9444. Request request;
  9445. request.path = "/users/1";
  9446. ASSERT_FALSE(matcher.match(request));
  9447. }
  9448. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9449. const auto pattern = "/users/:id/subscriptions";
  9450. detail::PathParamsMatcher matcher(pattern);
  9451. Request request;
  9452. request.path = "/users/42/subscriptions";
  9453. ASSERT_TRUE(matcher.match(request));
  9454. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9455. EXPECT_EQ(request.path_params, expected_params);
  9456. }
  9457. TEST(PathParamsTest, SingleParamInTheEnd) {
  9458. const auto pattern = "/users/:id";
  9459. detail::PathParamsMatcher matcher(pattern);
  9460. Request request;
  9461. request.path = "/users/24";
  9462. ASSERT_TRUE(matcher.match(request));
  9463. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9464. EXPECT_EQ(request.path_params, expected_params);
  9465. }
  9466. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9467. const auto pattern = "/users/:id/";
  9468. detail::PathParamsMatcher matcher(pattern);
  9469. Request request;
  9470. request.path = "/users/42/";
  9471. ASSERT_TRUE(matcher.match(request));
  9472. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9473. EXPECT_EQ(request.path_params, expected_params);
  9474. }
  9475. TEST(PathParamsTest, EmptyParam) {
  9476. const auto pattern = "/users/:id/";
  9477. detail::PathParamsMatcher matcher(pattern);
  9478. Request request;
  9479. request.path = "/users//";
  9480. ASSERT_TRUE(matcher.match(request));
  9481. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9482. EXPECT_EQ(request.path_params, expected_params);
  9483. }
  9484. TEST(PathParamsTest, FragmentMismatch) {
  9485. const auto pattern = "/users/:id/";
  9486. detail::PathParamsMatcher matcher(pattern);
  9487. Request request;
  9488. request.path = "/admins/24/";
  9489. ASSERT_FALSE(matcher.match(request));
  9490. }
  9491. TEST(PathParamsTest, ExtraFragments) {
  9492. const auto pattern = "/users/:id";
  9493. detail::PathParamsMatcher matcher(pattern);
  9494. Request request;
  9495. request.path = "/users/42/subscriptions";
  9496. ASSERT_FALSE(matcher.match(request));
  9497. }
  9498. TEST(PathParamsTest, MissingTrailingParam) {
  9499. const auto pattern = "/users/:id";
  9500. detail::PathParamsMatcher matcher(pattern);
  9501. Request request;
  9502. request.path = "/users";
  9503. ASSERT_FALSE(matcher.match(request));
  9504. }
  9505. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9506. const auto pattern = "/users/:id/subscriptions";
  9507. detail::PathParamsMatcher matcher(pattern);
  9508. Request request;
  9509. request.path = "/users/subscriptions";
  9510. ASSERT_FALSE(matcher.match(request));
  9511. }
  9512. TEST(PathParamsTest, MultipleParams) {
  9513. const auto pattern = "/users/:userid/subscriptions/:subid";
  9514. detail::PathParamsMatcher matcher(pattern);
  9515. Request request;
  9516. request.path = "/users/42/subscriptions/2";
  9517. ASSERT_TRUE(matcher.match(request));
  9518. std::unordered_map<std::string, std::string> expected_params = {
  9519. {"userid", "42"}, {"subid", "2"}};
  9520. EXPECT_EQ(request.path_params, expected_params);
  9521. }
  9522. TEST(PathParamsTest, SequenceOfParams) {
  9523. const auto pattern = "/values/:x/:y/:z";
  9524. detail::PathParamsMatcher matcher(pattern);
  9525. Request request;
  9526. request.path = "/values/1/2/3";
  9527. ASSERT_TRUE(matcher.match(request));
  9528. std::unordered_map<std::string, std::string> expected_params = {
  9529. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9530. EXPECT_EQ(request.path_params, expected_params);
  9531. }
  9532. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9533. const auto pattern = "/prefix:suffix";
  9534. detail::PathParamsMatcher matcher(pattern);
  9535. Request request;
  9536. request.path = "/prefix:suffix";
  9537. ASSERT_TRUE(matcher.match(request));
  9538. const std::unordered_map<std::string, std::string> expected_params = {};
  9539. EXPECT_EQ(request.path_params, expected_params);
  9540. }
  9541. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9542. // If ipv6 regex working, regex match codepath is taken.
  9543. // else port will default to 80 in Client impl
  9544. int clientImplMagicPort = 80;
  9545. int port = 4321;
  9546. // above ports must be different to avoid false negative
  9547. EXPECT_NE(clientImplMagicPort, port);
  9548. std::string ipV6TestURL = "http://[ff06::c3]";
  9549. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9550. CLIENT_PRIVATE_KEY_FILE);
  9551. EXPECT_EQ(cli.port(), port);
  9552. }
  9553. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9554. auto file_path = "./www/dir/index.html";
  9555. auto dir_path = "./www/dir";
  9556. detail::FileStat stat_file(file_path);
  9557. EXPECT_TRUE(stat_file.is_file());
  9558. EXPECT_FALSE(stat_file.is_dir());
  9559. detail::FileStat stat_dir(dir_path);
  9560. EXPECT_FALSE(stat_dir.is_file());
  9561. EXPECT_TRUE(stat_dir.is_dir());
  9562. }
  9563. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9564. // IPv4 with default HTTP port (80)
  9565. EXPECT_EQ("example.com",
  9566. detail::make_host_and_port_string("example.com", 80, false));
  9567. // IPv4 with default HTTPS port (443)
  9568. EXPECT_EQ("example.com",
  9569. detail::make_host_and_port_string("example.com", 443, true));
  9570. // IPv4 with non-default HTTP port
  9571. EXPECT_EQ("example.com:8080",
  9572. detail::make_host_and_port_string("example.com", 8080, false));
  9573. // IPv4 with non-default HTTPS port
  9574. EXPECT_EQ("example.com:8443",
  9575. detail::make_host_and_port_string("example.com", 8443, true));
  9576. // IPv6 with default HTTP port (80)
  9577. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9578. // IPv6 with default HTTPS port (443)
  9579. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9580. // IPv6 with non-default HTTP port
  9581. EXPECT_EQ("[::1]:8080",
  9582. detail::make_host_and_port_string("::1", 8080, false));
  9583. // IPv6 with non-default HTTPS port
  9584. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9585. // IPv6 full address with default port
  9586. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9587. detail::make_host_and_port_string(
  9588. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9589. // IPv6 full address with non-default port
  9590. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9591. detail::make_host_and_port_string(
  9592. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9593. // IPv6 localhost with non-default port
  9594. EXPECT_EQ("[::1]:3000",
  9595. detail::make_host_and_port_string("::1", 3000, false));
  9596. // IPv6 with zone ID (link-local address) with default port
  9597. EXPECT_EQ("[fe80::1%eth0]",
  9598. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9599. // IPv6 with zone ID (link-local address) with non-default port
  9600. EXPECT_EQ("[fe80::1%eth0]:8080",
  9601. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9602. // Edge case: Port 443 with is_ssl=false (should add port)
  9603. EXPECT_EQ("example.com:443",
  9604. detail::make_host_and_port_string("example.com", 443, false));
  9605. // Edge case: Port 80 with is_ssl=true (should add port)
  9606. EXPECT_EQ("example.com:80",
  9607. detail::make_host_and_port_string("example.com", 80, true));
  9608. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9609. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9610. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9611. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9612. // Security fix: Already bracketed IPv6 should not get double brackets
  9613. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9614. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9615. EXPECT_EQ("[::1]:8080",
  9616. detail::make_host_and_port_string("[::1]", 8080, false));
  9617. EXPECT_EQ("[2001:db8::1]:8080",
  9618. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9619. EXPECT_EQ("[fe80::1%eth0]",
  9620. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9621. EXPECT_EQ("[fe80::1%eth0]:8080",
  9622. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9623. // Edge case: Empty host (should return as-is)
  9624. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9625. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9626. // This is a known limitation but shouldn't crash
  9627. EXPECT_EQ("[host:name]",
  9628. detail::make_host_and_port_string("host:name", 80, false));
  9629. // Port number edge cases (no validation, but should not crash)
  9630. EXPECT_EQ("example.com:0",
  9631. detail::make_host_and_port_string("example.com", 0, false));
  9632. EXPECT_EQ("example.com:-1",
  9633. detail::make_host_and_port_string("example.com", -1, false));
  9634. EXPECT_EQ("example.com:65535",
  9635. detail::make_host_and_port_string("example.com", 65535, false));
  9636. EXPECT_EQ("example.com:65536",
  9637. detail::make_host_and_port_string("example.com", 65536, false));
  9638. }
  9639. #ifdef CPPHTTPLIB_SSL_ENABLED
  9640. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9641. httplib::SSLClient cli("roblox.com", 443);
  9642. cli.set_follow_location(true);
  9643. auto res = cli.Get("/");
  9644. ASSERT_TRUE(res);
  9645. EXPECT_EQ(StatusCode::OK_200, res->status);
  9646. }
  9647. #endif
  9648. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9649. Server svr;
  9650. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9651. EXPECT_EQ(res.status, 400);
  9652. });
  9653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9654. auto se = detail::scope_exit([&] {
  9655. svr.stop();
  9656. thread.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. Client cli(HOST, PORT);
  9661. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9662. }
  9663. TEST(InvalidHeaderCharsTest, is_field_name) {
  9664. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9665. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9666. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9667. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9668. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9669. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9670. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9671. EXPECT_FALSE(detail::fields::is_field_name(""));
  9672. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9673. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9674. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9675. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9676. }
  9677. TEST(InvalidHeaderCharsTest, is_field_value) {
  9678. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9679. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9680. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9681. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9682. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9683. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9684. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9685. EXPECT_TRUE(detail::fields::is_field_value(""));
  9686. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9687. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9688. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9689. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9690. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9691. }
  9692. TEST(InvalidHeaderCharsTest, OnServer) {
  9693. Server svr;
  9694. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9695. std::string header = "Not Set";
  9696. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9697. res.set_header(header, "value");
  9698. res.set_content("Page Content Page Content", "text/plain");
  9699. });
  9700. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9701. std::string header = "Not Set";
  9702. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9703. res.set_header("X-Test", header);
  9704. res.set_content("Page Content Page Content", "text/plain");
  9705. });
  9706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9707. auto se = detail::scope_exit([&] {
  9708. svr.stop();
  9709. thread.join();
  9710. ASSERT_FALSE(svr.is_running());
  9711. });
  9712. svr.wait_until_ready();
  9713. Client cli(HOST, PORT);
  9714. {
  9715. auto res = cli.Get(
  9716. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9717. ASSERT_TRUE(res);
  9718. EXPECT_EQ("Page Content Page Content", res->body);
  9719. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9720. }
  9721. {
  9722. auto res = cli.Get(
  9723. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9724. ASSERT_TRUE(res);
  9725. EXPECT_EQ("Page Content Page Content", res->body);
  9726. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9727. }
  9728. }
  9729. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9730. auto handled = false;
  9731. Server svr;
  9732. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9733. thread t = thread([&] { svr.listen(HOST, PORT); });
  9734. auto se = detail::scope_exit([&] {
  9735. svr.stop();
  9736. t.join();
  9737. ASSERT_FALSE(svr.is_running());
  9738. ASSERT_FALSE(handled);
  9739. });
  9740. svr.wait_until_ready();
  9741. auto req = "POST /test HTTP/1.1\r\n"
  9742. "Content-Length: x\r\n"
  9743. "\r\n";
  9744. std::string response;
  9745. ASSERT_TRUE(send_request(1, req, &response));
  9746. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9747. response.substr(0, response.find("\r\n")));
  9748. }
  9749. #ifndef _WIN32
  9750. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9751. static constexpr char reject[] = "Unauthorized";
  9752. static constexpr char accept[] = "Upload accepted";
  9753. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9754. Server svr;
  9755. svr.set_expect_100_continue_handler(
  9756. [](const Request & /*req*/, Response &res) {
  9757. res.status = StatusCode::Unauthorized_401;
  9758. res.set_content(reject, "text/plain");
  9759. return res.status;
  9760. });
  9761. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9762. res.set_content(accept, "text/plain");
  9763. });
  9764. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9765. auto se = detail::scope_exit([&] {
  9766. svr.stop();
  9767. thread.join();
  9768. ASSERT_FALSE(svr.is_running());
  9769. });
  9770. svr.wait_until_ready();
  9771. {
  9772. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9773. curl_easy_init(), &curl_easy_cleanup};
  9774. ASSERT_NE(curl, nullptr);
  9775. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9776. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9777. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9778. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9779. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9780. &curl_slist_free_all};
  9781. ASSERT_NE(list, nullptr);
  9782. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9783. struct read_data {
  9784. size_t read_size;
  9785. size_t total_size;
  9786. } data = {0, total_size};
  9787. using read_callback_t =
  9788. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9789. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9790. void *userdata) -> size_t {
  9791. read_data *data = (read_data *)userdata;
  9792. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9793. std::fill_n(ptr, size * nmemb, 'A');
  9794. data->read_size += size * nmemb;
  9795. return size * nmemb;
  9796. };
  9797. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9798. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9799. std::vector<char> buffer;
  9800. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9801. using write_callback_t =
  9802. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9803. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9804. void *userdata) -> size_t {
  9805. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9806. buffer->reserve(buffer->size() + size * nmemb + 1);
  9807. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9808. return size * nmemb;
  9809. };
  9810. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9811. {
  9812. const auto res = curl_easy_perform(curl.get());
  9813. ASSERT_EQ(res, CURLE_OK);
  9814. }
  9815. {
  9816. auto response_code = long{};
  9817. const auto res =
  9818. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9819. ASSERT_EQ(res, CURLE_OK);
  9820. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9821. }
  9822. {
  9823. auto dl = curl_off_t{};
  9824. const auto res =
  9825. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9826. ASSERT_EQ(res, CURLE_OK);
  9827. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9828. }
  9829. {
  9830. buffer.push_back('\0');
  9831. ASSERT_STRCASEEQ(buffer.data(), reject);
  9832. }
  9833. }
  9834. }
  9835. #endif
  9836. template <typename S, typename C>
  9837. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9838. svr.Get("/stream", [&](const Request &, Response &res) {
  9839. auto data = new std::string("01234567890123456789");
  9840. res.set_content_provider(
  9841. data->size(), "text/plain",
  9842. [&, data](size_t offset, size_t length, DataSink &sink) {
  9843. const size_t DATA_CHUNK_SIZE = 4;
  9844. const auto &d = *data;
  9845. std::this_thread::sleep_for(std::chrono::seconds(1));
  9846. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9847. return true;
  9848. },
  9849. [data](bool success) {
  9850. EXPECT_FALSE(success);
  9851. delete data;
  9852. });
  9853. });
  9854. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9855. auto i = new size_t(0);
  9856. res.set_content_provider(
  9857. "text/plain",
  9858. [i](size_t, DataSink &sink) {
  9859. if (*i < 5) {
  9860. std::this_thread::sleep_for(std::chrono::seconds(1));
  9861. sink.write("abcd", 4);
  9862. (*i)++;
  9863. } else {
  9864. sink.done();
  9865. }
  9866. return true;
  9867. },
  9868. [i](bool success) {
  9869. EXPECT_FALSE(success);
  9870. delete i;
  9871. });
  9872. });
  9873. svr.Get("/chunked", [&](const Request &, Response &res) {
  9874. auto i = new size_t(0);
  9875. res.set_chunked_content_provider(
  9876. "text/plain",
  9877. [i](size_t, DataSink &sink) {
  9878. if (*i < 5) {
  9879. std::this_thread::sleep_for(std::chrono::seconds(1));
  9880. sink.os << "abcd";
  9881. (*i)++;
  9882. } else {
  9883. sink.done();
  9884. }
  9885. return true;
  9886. },
  9887. [i](bool success) {
  9888. EXPECT_FALSE(success);
  9889. delete i;
  9890. });
  9891. });
  9892. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9893. auto se = detail::scope_exit([&] {
  9894. svr.stop();
  9895. listen_thread.join();
  9896. ASSERT_FALSE(svr.is_running());
  9897. });
  9898. svr.wait_until_ready();
  9899. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9900. {
  9901. auto start = std::chrono::steady_clock::now();
  9902. auto res = cli.Get("/stream");
  9903. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9904. std::chrono::steady_clock::now() - start)
  9905. .count();
  9906. ASSERT_FALSE(res);
  9907. EXPECT_EQ(Error::Read, res.error());
  9908. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9909. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9910. }
  9911. {
  9912. auto start = std::chrono::steady_clock::now();
  9913. auto res = cli.Get("/stream_without_length");
  9914. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9915. std::chrono::steady_clock::now() - start)
  9916. .count();
  9917. ASSERT_FALSE(res);
  9918. EXPECT_EQ(Error::Read, res.error());
  9919. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9920. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9921. }
  9922. {
  9923. auto start = std::chrono::steady_clock::now();
  9924. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9925. EXPECT_EQ("abcd", string(data, data_length));
  9926. return true;
  9927. });
  9928. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9929. std::chrono::steady_clock::now() - start)
  9930. .count();
  9931. ASSERT_FALSE(res);
  9932. EXPECT_EQ(Error::Read, res.error());
  9933. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9934. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9935. }
  9936. }
  9937. TEST(MaxTimeoutTest, ContentStream) {
  9938. time_t timeout = 2000;
  9939. time_t threshold = 200;
  9940. Server svr;
  9941. Client cli("localhost", PORT);
  9942. max_timeout_test(svr, cli, timeout, threshold);
  9943. }
  9944. #ifdef CPPHTTPLIB_SSL_ENABLED
  9945. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9946. time_t timeout = 2000;
  9947. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9949. SSLClient cli("localhost", PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. max_timeout_test(svr, cli, timeout, threshold);
  9952. }
  9953. #endif
  9954. class EventDispatcher {
  9955. public:
  9956. EventDispatcher() {}
  9957. bool wait_event(DataSink *sink) {
  9958. unique_lock<mutex> lk(m_);
  9959. int id = id_;
  9960. // Wait with timeout to prevent hanging if client disconnects
  9961. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9962. [&] { return cid_ == id; })) {
  9963. return false; // Timeout occurred
  9964. }
  9965. sink->write(message_.data(), message_.size());
  9966. return true;
  9967. }
  9968. void send_event(const string &message) {
  9969. lock_guard<mutex> lk(m_);
  9970. cid_ = id_++;
  9971. message_ = message;
  9972. cv_.notify_all();
  9973. }
  9974. private:
  9975. mutex m_;
  9976. condition_variable cv_;
  9977. atomic_int id_{0};
  9978. atomic_int cid_{-1};
  9979. string message_;
  9980. };
  9981. TEST(ClientInThreadTest, Issue2068) {
  9982. EventDispatcher ed;
  9983. Server svr;
  9984. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9985. res.set_chunked_content_provider("text/event-stream",
  9986. [&](size_t /*offset*/, DataSink &sink) {
  9987. return ed.wait_event(&sink);
  9988. });
  9989. });
  9990. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9991. svr.wait_until_ready();
  9992. thread event_thread([&] {
  9993. int id = 0;
  9994. while (svr.is_running()) {
  9995. this_thread::sleep_for(chrono::milliseconds(500));
  9996. std::stringstream ss;
  9997. ss << "data: " << id << "\n\n";
  9998. ed.send_event(ss.str());
  9999. id++;
  10000. }
  10001. });
  10002. auto se = detail::scope_exit([&] {
  10003. svr.stop();
  10004. listen_thread.join();
  10005. event_thread.join();
  10006. ASSERT_FALSE(svr.is_running());
  10007. });
  10008. {
  10009. auto client = detail::make_unique<Client>(HOST, PORT);
  10010. client->set_read_timeout(std::chrono::minutes(10));
  10011. std::atomic<bool> stop{false};
  10012. std::thread t([&] {
  10013. client->Get("/event1",
  10014. [&](const char *, size_t) -> bool { return !stop; });
  10015. });
  10016. std::this_thread::sleep_for(std::chrono::seconds(2));
  10017. stop = true;
  10018. client->stop();
  10019. t.join();
  10020. // Reset client after thread has finished
  10021. client.reset();
  10022. }
  10023. }
  10024. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10025. Server svr;
  10026. svr.Get("/", [](const Request &req, Response &res) {
  10027. EXPECT_EQ(2U, req.trailers.size());
  10028. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10029. // Denied
  10030. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10031. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10032. // Accepted
  10033. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10034. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10035. EXPECT_TRUE(req.has_trailer("X-World"));
  10036. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET / HTTP/1.1\r\n"
  10047. "Transfer-Encoding: chunked\r\n"
  10048. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10049. "\r\n"
  10050. "0\r\n"
  10051. "Content-Length: 10\r\n"
  10052. "Host: internal.local\r\n"
  10053. "Content-Type: malicious/content\r\n"
  10054. "Cookie: any\r\n"
  10055. "Set-Cookie: any\r\n"
  10056. "X-Forwarded-For: attacker.com\r\n"
  10057. "X-Real-Ip: 1.1.1.1\r\n"
  10058. "X-Hello: hello\r\n"
  10059. "X-World: world\r\n"
  10060. "\r\n";
  10061. std::string res;
  10062. ASSERT_TRUE(send_request(1, req, &res));
  10063. }
  10064. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10065. Server svr;
  10066. std::string observed_remote_addr;
  10067. std::string observed_xff;
  10068. svr.Get("/ip", [&](const Request &req, Response &res) {
  10069. observed_remote_addr = req.remote_addr;
  10070. observed_xff = req.get_header_value("X-Forwarded-For");
  10071. res.set_content("ok", "text/plain");
  10072. });
  10073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10074. auto se = detail::scope_exit([&] {
  10075. svr.stop();
  10076. t.join();
  10077. ASSERT_FALSE(svr.is_running());
  10078. });
  10079. svr.wait_until_ready();
  10080. Client cli(HOST, PORT);
  10081. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10082. ASSERT_TRUE(res);
  10083. EXPECT_EQ(StatusCode::OK_200, res->status);
  10084. EXPECT_EQ(observed_xff, "203.0.113.66");
  10085. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10086. observed_remote_addr == "127.0.0.1");
  10087. }
  10088. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10089. Server svr;
  10090. svr.set_trusted_proxies({"203.0.113.66"});
  10091. std::string observed_remote_addr;
  10092. std::string observed_xff;
  10093. svr.Get("/ip", [&](const Request &req, Response &res) {
  10094. observed_remote_addr = req.remote_addr;
  10095. observed_xff = req.get_header_value("X-Forwarded-For");
  10096. res.set_content("ok", "text/plain");
  10097. });
  10098. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10099. auto se = detail::scope_exit([&] {
  10100. svr.stop();
  10101. t.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. Client cli(HOST, PORT);
  10106. auto res = cli.Get("/ip");
  10107. ASSERT_TRUE(res);
  10108. EXPECT_EQ(StatusCode::OK_200, res->status);
  10109. EXPECT_EQ(observed_xff, "");
  10110. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10111. observed_remote_addr == "127.0.0.1");
  10112. }
  10113. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10114. Server svr;
  10115. svr.set_trusted_proxies({"203.0.113.66"});
  10116. std::string observed_remote_addr;
  10117. std::string observed_xff;
  10118. svr.Get("/ip", [&](const Request &req, Response &res) {
  10119. observed_remote_addr = req.remote_addr;
  10120. observed_xff = req.get_header_value("X-Forwarded-For");
  10121. res.set_content("ok", "text/plain");
  10122. });
  10123. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10124. auto se = detail::scope_exit([&] {
  10125. svr.stop();
  10126. t.join();
  10127. ASSERT_FALSE(svr.is_running());
  10128. });
  10129. svr.wait_until_ready();
  10130. Client cli(HOST, PORT);
  10131. auto res =
  10132. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10133. ASSERT_TRUE(res);
  10134. EXPECT_EQ(StatusCode::OK_200, res->status);
  10135. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10136. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10137. }
  10138. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10139. Server svr;
  10140. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10141. std::string observed_remote_addr;
  10142. std::string observed_xff;
  10143. svr.Get("/ip", [&](const Request &req, Response &res) {
  10144. observed_remote_addr = req.remote_addr;
  10145. observed_xff = req.get_header_value("X-Forwarded-For");
  10146. res.set_content("ok", "text/plain");
  10147. });
  10148. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. t.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. Client cli(HOST, PORT);
  10156. auto res = cli.Get(
  10157. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10158. ASSERT_TRUE(res);
  10159. EXPECT_EQ(StatusCode::OK_200, res->status);
  10160. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10161. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10162. }
  10163. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10164. Server svr;
  10165. svr.set_trusted_proxies({"192.0.2.45"});
  10166. std::string observed_remote_addr;
  10167. std::string observed_xff;
  10168. svr.Get("/ip", [&](const Request &req, Response &res) {
  10169. observed_remote_addr = req.remote_addr;
  10170. observed_xff = req.get_header_value("X-Forwarded-For");
  10171. res.set_content("ok", "text/plain");
  10172. });
  10173. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10174. auto se = detail::scope_exit([&] {
  10175. svr.stop();
  10176. t.join();
  10177. ASSERT_FALSE(svr.is_running());
  10178. });
  10179. svr.wait_until_ready();
  10180. Client cli(HOST, PORT);
  10181. auto res =
  10182. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10183. ASSERT_TRUE(res);
  10184. EXPECT_EQ(StatusCode::OK_200, res->status);
  10185. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10186. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10187. }
  10188. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10189. Server svr;
  10190. svr.set_trusted_proxies({"192.0.2.45"});
  10191. std::string observed_remote_addr;
  10192. std::string observed_xff;
  10193. svr.Get("/ip", [&](const Request &req, Response &res) {
  10194. observed_remote_addr = req.remote_addr;
  10195. observed_xff = req.get_header_value("X-Forwarded-For");
  10196. res.set_content("ok", "text/plain");
  10197. });
  10198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10199. auto se = detail::scope_exit([&] {
  10200. svr.stop();
  10201. t.join();
  10202. ASSERT_FALSE(svr.is_running());
  10203. });
  10204. svr.wait_until_ready();
  10205. Client cli(HOST, PORT);
  10206. auto res = cli.Get(
  10207. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10208. ASSERT_TRUE(res);
  10209. EXPECT_EQ(StatusCode::OK_200, res->status);
  10210. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10211. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10212. }
  10213. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10214. Server svr;
  10215. svr.set_trusted_proxies({"192.0.2.45"});
  10216. std::string observed_remote_addr;
  10217. std::string observed_xff;
  10218. svr.Get("/ip", [&](const Request &req, Response &res) {
  10219. observed_remote_addr = req.remote_addr;
  10220. observed_xff = req.get_header_value("X-Forwarded-For");
  10221. res.set_content("ok", "text/plain");
  10222. });
  10223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. ASSERT_FALSE(svr.is_running());
  10228. });
  10229. svr.wait_until_ready();
  10230. std::string raw_req =
  10231. "GET /ip HTTP/1.1\r\n"
  10232. "Host: localhost\r\n"
  10233. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10234. "Connection: close\r\n"
  10235. "\r\n";
  10236. std::string out;
  10237. ASSERT_TRUE(send_request(5, raw_req, &out));
  10238. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10239. // Header parser trims surrounding whitespace of the header value
  10240. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10241. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10242. }
  10243. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10244. Server svr;
  10245. svr.Post("/post", [&](const Request &req, Response &res) {
  10246. res.set_content(req.body, "text/plain");
  10247. });
  10248. svr.Put("/put", [&](const Request &req, Response &res) {
  10249. res.set_content(req.body, "text/plain");
  10250. });
  10251. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10252. res.set_content(req.body, "text/plain");
  10253. });
  10254. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10255. res.set_content(req.body, "text/plain");
  10256. });
  10257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10258. auto se = detail::scope_exit([&] {
  10259. svr.stop();
  10260. t.join();
  10261. ASSERT_FALSE(svr.is_running());
  10262. });
  10263. svr.wait_until_ready();
  10264. std::string resp;
  10265. // POST without Content-Length
  10266. ASSERT_TRUE(send_request(5,
  10267. "POST /post HTTP/1.1\r\n"
  10268. "Host: localhost\r\n"
  10269. "Connection: close\r\n"
  10270. "\r\n",
  10271. &resp));
  10272. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10273. // PUT without Content-Length
  10274. resp.clear();
  10275. ASSERT_TRUE(send_request(5,
  10276. "PUT /put HTTP/1.1\r\n"
  10277. "Host: localhost\r\n"
  10278. "Connection: close\r\n"
  10279. "\r\n",
  10280. &resp));
  10281. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10282. // PATCH without Content-Length
  10283. resp.clear();
  10284. ASSERT_TRUE(send_request(5,
  10285. "PATCH /patch HTTP/1.1\r\n"
  10286. "Host: localhost\r\n"
  10287. "Connection: close\r\n"
  10288. "\r\n",
  10289. &resp));
  10290. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10291. // DELETE without Content-Length
  10292. resp.clear();
  10293. ASSERT_TRUE(send_request(5,
  10294. "DELETE /delete HTTP/1.1\r\n"
  10295. "Host: localhost\r\n"
  10296. "Connection: close\r\n"
  10297. "\r\n",
  10298. &resp));
  10299. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10300. }
  10301. //==============================================================================
  10302. // open_stream() Tests
  10303. //==============================================================================
  10304. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10305. std::string result;
  10306. char buf[8192];
  10307. ssize_t n;
  10308. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10309. result.append(buf, static_cast<size_t>(n));
  10310. }
  10311. return result;
  10312. }
  10313. // Mock stream for unit tests
  10314. class MockStream : public Stream {
  10315. public:
  10316. std::string data;
  10317. size_t pos = 0;
  10318. ssize_t error_after = -1; // -1 = no error
  10319. explicit MockStream(const std::string &d, ssize_t err = -1)
  10320. : data(d), error_after(err) {}
  10321. bool is_readable() const override { return true; }
  10322. bool wait_readable() const override { return true; }
  10323. bool wait_writable() const override { return true; }
  10324. ssize_t read(char *ptr, size_t size) override {
  10325. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10326. if (pos >= data.size()) return 0;
  10327. size_t limit =
  10328. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10329. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10330. std::memcpy(ptr, data.data() + pos, to_read);
  10331. pos += to_read;
  10332. return static_cast<ssize_t>(to_read);
  10333. }
  10334. ssize_t write(const char *, size_t) override { return -1; }
  10335. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10336. ip = "127.0.0.1";
  10337. port = 0;
  10338. }
  10339. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10340. ip = "127.0.0.1";
  10341. port = 0;
  10342. }
  10343. socket_t socket() const override { return INVALID_SOCKET; }
  10344. time_t duration() const override { return 0; }
  10345. };
  10346. TEST(StreamHandleTest, Basic) {
  10347. ClientImpl::StreamHandle handle;
  10348. EXPECT_FALSE(handle.is_valid());
  10349. handle.response = detail::make_unique<Response>();
  10350. handle.error = Error::Connection;
  10351. EXPECT_FALSE(handle.is_valid());
  10352. handle.error = Error::Success;
  10353. EXPECT_TRUE(handle.is_valid());
  10354. }
  10355. TEST(BodyReaderTest, Basic) {
  10356. MockStream stream("Hello, World!");
  10357. detail::BodyReader reader;
  10358. reader.stream = &stream;
  10359. reader.content_length = 13;
  10360. char buf[32];
  10361. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10362. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10363. EXPECT_TRUE(reader.eof);
  10364. }
  10365. TEST(BodyReaderTest, NoStream) {
  10366. detail::BodyReader reader;
  10367. char buf[32];
  10368. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10369. EXPECT_EQ(Error::Connection, reader.last_error);
  10370. }
  10371. TEST(BodyReaderTest, Error) {
  10372. MockStream stream("Hello, World!", 5);
  10373. detail::BodyReader reader;
  10374. reader.stream = &stream;
  10375. reader.content_length = 13;
  10376. char buf[32];
  10377. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10378. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10379. EXPECT_EQ(Error::Read, reader.last_error);
  10380. }
  10381. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10382. // Mock-based StreamHandle tests relying on private internals are removed.
  10383. class OpenStreamTest : public ::testing::Test {
  10384. protected:
  10385. void SetUp() override {
  10386. svr_.Get("/hello", [](const Request &, Response &res) {
  10387. res.set_content("Hello World!", "text/plain");
  10388. });
  10389. svr_.Get("/large", [](const Request &, Response &res) {
  10390. res.set_content(std::string(10000, 'X'), "text/plain");
  10391. });
  10392. svr_.Get("/chunked", [](const Request &, Response &res) {
  10393. res.set_chunked_content_provider("text/plain",
  10394. [](size_t offset, DataSink &sink) {
  10395. if (offset < 15) {
  10396. sink.write("chunk", 5);
  10397. return true;
  10398. }
  10399. sink.done();
  10400. return true;
  10401. });
  10402. });
  10403. svr_.Get("/compressible", [](const Request &, Response &res) {
  10404. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10405. DataSink &sink) {
  10406. if (offset < 100 * 1024) {
  10407. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10408. sink.write(chunk.data(), chunk.size());
  10409. return true;
  10410. }
  10411. sink.done();
  10412. return true;
  10413. });
  10414. });
  10415. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10416. [](const Request & /*req*/, Response &res) {
  10417. auto i = new int(0);
  10418. res.set_header("Trailer", "Content-Length, X-Allowed");
  10419. res.set_chunked_content_provider(
  10420. "text/plain",
  10421. [i](size_t /*offset*/, DataSink &sink) {
  10422. switch (*i) {
  10423. case 0: sink.os << "123"; break;
  10424. case 1: sink.os << "456"; break;
  10425. case 2: sink.os << "789"; break;
  10426. case 3: {
  10427. sink.done_with_trailer(
  10428. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10429. } break;
  10430. }
  10431. (*i)++;
  10432. return true;
  10433. },
  10434. [i](bool success) {
  10435. EXPECT_TRUE(success);
  10436. delete i;
  10437. });
  10438. });
  10439. // Echo headers endpoint for header-related tests
  10440. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10441. std::string body;
  10442. for (const auto &h : req.headers) {
  10443. body.append(h.first);
  10444. body.push_back(':');
  10445. body.append(h.second);
  10446. body.push_back('\n');
  10447. }
  10448. res.set_content(body, "text/plain");
  10449. });
  10450. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10451. std::string body;
  10452. for (const auto &h : req.headers) {
  10453. body.append(h.first);
  10454. body.push_back(':');
  10455. body.append(h.second);
  10456. body.push_back('\n');
  10457. }
  10458. res.set_content(body, "text/plain");
  10459. });
  10460. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10461. svr_.wait_until_ready();
  10462. }
  10463. void TearDown() override {
  10464. svr_.stop();
  10465. if (thread_.joinable()) thread_.join();
  10466. }
  10467. Server svr_;
  10468. std::thread thread_;
  10469. };
  10470. TEST_F(OpenStreamTest, Basic) {
  10471. Client cli("127.0.0.1", 8787);
  10472. auto handle = cli.open_stream("GET", "/hello");
  10473. EXPECT_TRUE(handle.is_valid());
  10474. EXPECT_EQ("Hello World!", read_all(handle));
  10475. }
  10476. TEST_F(OpenStreamTest, SmallBuffer) {
  10477. Client cli("127.0.0.1", 8787);
  10478. auto handle = cli.open_stream("GET", "/hello");
  10479. std::string result;
  10480. char buf[4];
  10481. ssize_t n;
  10482. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10483. result.append(buf, static_cast<size_t>(n));
  10484. EXPECT_EQ("Hello World!", result);
  10485. }
  10486. TEST_F(OpenStreamTest, DefaultHeaders) {
  10487. Client cli("127.0.0.1", 8787);
  10488. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10489. {
  10490. auto handle = cli.open_stream("GET", "/echo-headers");
  10491. ASSERT_TRUE(handle.is_valid());
  10492. auto body = read_all(handle);
  10493. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10494. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10495. std::string::npos);
  10496. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10497. }
  10498. // open_stream POST with body and no explicit content_type should NOT add
  10499. // text/plain Content-Type (behavior differs from non-streaming path), but
  10500. // should include Content-Length
  10501. {
  10502. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10503. ASSERT_TRUE(handle.is_valid());
  10504. auto body = read_all(handle);
  10505. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10506. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10507. }
  10508. // open_stream POST with explicit Content-Type should preserve it
  10509. {
  10510. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10511. {{"Content-Type", "application/custom"}},
  10512. "{}", "application/custom");
  10513. ASSERT_TRUE(handle.is_valid());
  10514. auto body = read_all(handle);
  10515. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10516. }
  10517. // User-specified User-Agent must not be overwritten for stream API
  10518. {
  10519. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10520. {{"User-Agent", "MyAgent/1.2"}});
  10521. ASSERT_TRUE(handle.is_valid());
  10522. auto body = read_all(handle);
  10523. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10524. }
  10525. }
  10526. TEST_F(OpenStreamTest, Large) {
  10527. Client cli("127.0.0.1", 8787);
  10528. auto handle = cli.open_stream("GET", "/large");
  10529. EXPECT_EQ(10000u, read_all(handle).size());
  10530. }
  10531. TEST_F(OpenStreamTest, ConnectionError) {
  10532. Client cli("127.0.0.1", 9999);
  10533. auto handle = cli.open_stream("GET", "/hello");
  10534. EXPECT_FALSE(handle.is_valid());
  10535. }
  10536. TEST_F(OpenStreamTest, Chunked) {
  10537. Client cli("127.0.0.1", 8787);
  10538. auto handle = cli.open_stream("GET", "/chunked");
  10539. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10540. "Transfer-Encoding") == "chunked");
  10541. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10542. }
  10543. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10544. Client cli("127.0.0.1", 8787);
  10545. auto handle =
  10546. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10547. ASSERT_TRUE(handle.is_valid());
  10548. // Consume body to allow trailers to be received/parsed
  10549. auto body = read_all(handle);
  10550. // Explicitly parse trailers (ensure trailers are available for assertion)
  10551. handle.parse_trailers_if_needed();
  10552. EXPECT_EQ(std::string("123456789"), body);
  10553. // The response should include a Trailer header declaring both names
  10554. ASSERT_TRUE(handle.response);
  10555. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10556. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10557. handle.response->get_header_value("Trailer"));
  10558. // Prohibited trailer must not be present
  10559. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10560. // Allowed trailer should be present
  10561. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10562. EXPECT_EQ(std::string("yes"),
  10563. handle.response->get_trailer_value("X-Allowed"));
  10564. // Verify trailers are NOT present as regular headers
  10565. EXPECT_EQ(std::string(""),
  10566. handle.response->get_header_value("Content-Length"));
  10567. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10568. }
  10569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10570. TEST_F(OpenStreamTest, Gzip) {
  10571. Client cli("127.0.0.1", 8787);
  10572. auto handle = cli.open_stream("GET", "/compressible", {},
  10573. {{"Accept-Encoding", "gzip"}});
  10574. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10575. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10576. }
  10577. #endif
  10578. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10579. TEST_F(OpenStreamTest, Brotli) {
  10580. Client cli("127.0.0.1", 8787);
  10581. auto handle =
  10582. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10583. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10584. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10585. }
  10586. #endif
  10587. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10588. TEST_F(OpenStreamTest, Zstd) {
  10589. Client cli("127.0.0.1", 8787);
  10590. auto handle = cli.open_stream("GET", "/compressible", {},
  10591. {{"Accept-Encoding", "zstd"}});
  10592. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10593. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10594. }
  10595. #endif
  10596. #ifdef CPPHTTPLIB_SSL_ENABLED
  10597. class SSLOpenStreamTest : public ::testing::Test {
  10598. protected:
  10599. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10600. void SetUp() override {
  10601. svr_.Get("/hello", [](const Request &, Response &res) {
  10602. res.set_content("Hello SSL World!", "text/plain");
  10603. });
  10604. svr_.Get("/chunked", [](const Request &, Response &res) {
  10605. res.set_chunked_content_provider("text/plain",
  10606. [](size_t offset, DataSink &sink) {
  10607. if (offset < 15) {
  10608. sink.write("chunk", 5);
  10609. return true;
  10610. }
  10611. sink.done();
  10612. return true;
  10613. });
  10614. });
  10615. svr_.Post("/echo", [](const Request &req, Response &res) {
  10616. res.set_content(req.body, req.get_header_value("Content-Type"));
  10617. });
  10618. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10619. std::string body = req.body;
  10620. res.set_chunked_content_provider(
  10621. "text/plain", [body](size_t offset, DataSink &sink) {
  10622. if (offset < body.size()) {
  10623. sink.write(body.data() + offset, body.size() - offset);
  10624. }
  10625. sink.done();
  10626. return true;
  10627. });
  10628. });
  10629. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10630. svr_.wait_until_ready();
  10631. }
  10632. void TearDown() override {
  10633. svr_.stop();
  10634. if (thread_.joinable()) thread_.join();
  10635. }
  10636. SSLServer svr_;
  10637. std::thread thread_;
  10638. };
  10639. TEST_F(SSLOpenStreamTest, Basic) {
  10640. SSLClient cli("127.0.0.1", 8788);
  10641. cli.enable_server_certificate_verification(false);
  10642. auto handle = cli.open_stream("GET", "/hello");
  10643. ASSERT_TRUE(handle.is_valid());
  10644. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10645. }
  10646. TEST_F(SSLOpenStreamTest, Chunked) {
  10647. SSLClient cli("127.0.0.1", 8788);
  10648. cli.enable_server_certificate_verification(false);
  10649. auto handle = cli.open_stream("GET", "/chunked");
  10650. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10651. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10652. "Transfer-Encoding") == "chunked");
  10653. auto body = read_all(handle);
  10654. EXPECT_EQ("chunkchunkchunk", body);
  10655. }
  10656. TEST_F(SSLOpenStreamTest, Post) {
  10657. SSLClient cli("127.0.0.1", 8788);
  10658. cli.enable_server_certificate_verification(false);
  10659. auto handle =
  10660. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10661. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10662. EXPECT_EQ(200, handle.response->status);
  10663. auto body = read_all(handle);
  10664. EXPECT_EQ("Hello SSL POST", body);
  10665. }
  10666. TEST_F(SSLOpenStreamTest, PostChunked) {
  10667. SSLClient cli("127.0.0.1", 8788);
  10668. cli.enable_server_certificate_verification(false);
  10669. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10670. "Chunked SSL Data", "text/plain");
  10671. ASSERT_TRUE(handle.is_valid());
  10672. EXPECT_EQ(200, handle.response->status);
  10673. auto body = read_all(handle);
  10674. EXPECT_EQ("Chunked SSL Data", body);
  10675. }
  10676. #endif // CPPHTTPLIB_SSL_ENABLED
  10677. //==============================================================================
  10678. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10679. // results for various scenarios.
  10680. //==============================================================================
  10681. TEST(ParityTest, GetVsOpenStream) {
  10682. Server svr;
  10683. const std::string path = "/parity";
  10684. const std::string content = "Parity test content: hello world";
  10685. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10686. res.set_content(content, "text/plain");
  10687. });
  10688. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10689. auto se = detail::scope_exit([&] {
  10690. svr.stop();
  10691. t.join();
  10692. ASSERT_FALSE(svr.is_running());
  10693. });
  10694. svr.wait_until_ready();
  10695. Client cli(HOST, PORT);
  10696. // Non-stream path
  10697. auto r1 = cli.Get(path);
  10698. ASSERT_TRUE(r1);
  10699. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10700. // Stream path
  10701. auto h = cli.open_stream("GET", path);
  10702. ASSERT_TRUE(h.is_valid());
  10703. EXPECT_EQ(r1->body, read_all(h));
  10704. }
  10705. // Helper to compress data with provided compressor type T
  10706. template <typename Compressor>
  10707. static std::string compress_payload_for_parity(const std::string &in) {
  10708. std::string out;
  10709. Compressor compressor;
  10710. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10711. [&](const char *data, size_t n) {
  10712. out.append(data, n);
  10713. return true;
  10714. });
  10715. EXPECT_TRUE(ok);
  10716. return out;
  10717. }
  10718. // Helper function for compression parity tests
  10719. template <typename Compressor>
  10720. static void test_compression_parity(const std::string &original,
  10721. const std::string &path,
  10722. const std::string &encoding) {
  10723. const std::string compressed =
  10724. compress_payload_for_parity<Compressor>(original);
  10725. Server svr;
  10726. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10727. res.set_content(compressed, "application/octet-stream");
  10728. res.set_header("Content-Encoding", encoding);
  10729. });
  10730. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10731. auto se = detail::scope_exit([&] {
  10732. svr.stop();
  10733. t.join();
  10734. ASSERT_FALSE(svr.is_running());
  10735. });
  10736. svr.wait_until_ready();
  10737. Client cli(HOST, PORT);
  10738. // Non-streaming
  10739. {
  10740. auto res = cli.Get(path);
  10741. ASSERT_TRUE(res);
  10742. EXPECT_EQ(StatusCode::OK_200, res->status);
  10743. EXPECT_EQ(original, res->body);
  10744. }
  10745. // Streaming
  10746. {
  10747. auto h = cli.open_stream("GET", path);
  10748. ASSERT_TRUE(h.is_valid());
  10749. EXPECT_EQ(original, read_all(h));
  10750. }
  10751. }
  10752. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10753. TEST(ParityTest, Gzip) {
  10754. test_compression_parity<detail::gzip_compressor>(
  10755. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10756. }
  10757. #endif
  10758. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10759. TEST(ParityTest, Brotli) {
  10760. test_compression_parity<detail::brotli_compressor>(
  10761. "Hello, brotli parity test payload", "/parity-br", "br");
  10762. }
  10763. #endif
  10764. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10765. TEST(ParityTest, Zstd) {
  10766. test_compression_parity<detail::zstd_compressor>(
  10767. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10768. }
  10769. #endif
  10770. //==============================================================================
  10771. // New Stream API Tests
  10772. //==============================================================================
  10773. inline std::string read_body(httplib::stream::Result &result) {
  10774. std::string body;
  10775. while (result.next()) {
  10776. body.append(result.data(), result.size());
  10777. }
  10778. return body;
  10779. }
  10780. TEST(ClientConnectionTest, Basic) {
  10781. httplib::ClientConnection conn;
  10782. EXPECT_FALSE(conn.is_open());
  10783. conn.sock = 1;
  10784. EXPECT_TRUE(conn.is_open());
  10785. httplib::ClientConnection conn2(std::move(conn));
  10786. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10787. conn2.sock = INVALID_SOCKET;
  10788. }
  10789. // Unified test server for all stream::* tests
  10790. class StreamApiTest : public ::testing::Test {
  10791. protected:
  10792. void SetUp() override {
  10793. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10794. res.set_content("Hello World!", "text/plain");
  10795. });
  10796. svr_.Get("/echo-params",
  10797. [](const httplib::Request &req, httplib::Response &res) {
  10798. std::string r;
  10799. for (const auto &p : req.params) {
  10800. if (!r.empty()) r += "&";
  10801. r += p.first + "=" + p.second;
  10802. }
  10803. res.set_content(r, "text/plain");
  10804. });
  10805. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10806. res.set_content(req.body, req.get_header_value("Content-Type"));
  10807. });
  10808. svr_.Post("/echo-headers",
  10809. [](const httplib::Request &req, httplib::Response &res) {
  10810. std::string r;
  10811. for (const auto &h : req.headers)
  10812. r += h.first + ": " + h.second + "\n";
  10813. res.set_content(r, "text/plain");
  10814. });
  10815. svr_.Post("/echo-params",
  10816. [](const httplib::Request &req, httplib::Response &res) {
  10817. std::string r = "params:";
  10818. for (const auto &p : req.params)
  10819. r += p.first + "=" + p.second + ";";
  10820. res.set_content(r + " body:" + req.body, "text/plain");
  10821. });
  10822. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10823. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10824. });
  10825. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10826. res.set_content("PUT:" + req.body, "text/plain");
  10827. });
  10828. svr_.Patch("/echo",
  10829. [](const httplib::Request &req, httplib::Response &res) {
  10830. res.set_content("PATCH:" + req.body, "text/plain");
  10831. });
  10832. svr_.Delete(
  10833. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10834. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10835. "text/plain");
  10836. });
  10837. svr_.Get("/head-test",
  10838. [](const httplib::Request &, httplib::Response &res) {
  10839. res.set_content("body for HEAD", "text/plain");
  10840. });
  10841. svr_.Options("/options",
  10842. [](const httplib::Request &, httplib::Response &res) {
  10843. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10844. });
  10845. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10846. svr_.wait_until_ready();
  10847. }
  10848. void TearDown() override {
  10849. svr_.stop();
  10850. if (thread_.joinable()) thread_.join();
  10851. }
  10852. httplib::Server svr_;
  10853. std::thread thread_;
  10854. };
  10855. // stream::Get tests
  10856. TEST_F(StreamApiTest, GetBasic) {
  10857. httplib::Client cli(HOST, PORT);
  10858. auto result = httplib::stream::Get(cli, "/hello");
  10859. ASSERT_TRUE(result.is_valid());
  10860. EXPECT_EQ(200, result.status());
  10861. EXPECT_EQ("Hello World!", read_body(result));
  10862. }
  10863. TEST_F(StreamApiTest, GetWithParams) {
  10864. httplib::Client cli(HOST, PORT);
  10865. httplib::Params params{{"foo", "bar"}};
  10866. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10867. ASSERT_TRUE(result.is_valid());
  10868. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10869. }
  10870. TEST_F(StreamApiTest, GetConnectionError) {
  10871. httplib::Client cli(HOST, 9999);
  10872. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10873. }
  10874. TEST_F(StreamApiTest, Get404) {
  10875. httplib::Client cli(HOST, PORT);
  10876. auto result = httplib::stream::Get(cli, "/nonexistent");
  10877. EXPECT_TRUE(result.is_valid());
  10878. EXPECT_EQ(404, result.status());
  10879. }
  10880. // stream::Post tests
  10881. TEST_F(StreamApiTest, PostBasic) {
  10882. httplib::Client cli(HOST, PORT);
  10883. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10884. "application/json");
  10885. ASSERT_TRUE(result.is_valid());
  10886. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10887. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10888. }
  10889. TEST_F(StreamApiTest, PostWithHeaders) {
  10890. httplib::Client cli(HOST, PORT);
  10891. httplib::Headers headers{{"X-Custom", "value"}};
  10892. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10893. "text/plain");
  10894. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10895. }
  10896. TEST_F(StreamApiTest, PostWithParams) {
  10897. httplib::Client cli(HOST, PORT);
  10898. httplib::Params params{{"k", "v"}};
  10899. auto result =
  10900. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10901. auto body = read_body(result);
  10902. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10903. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10904. }
  10905. TEST_F(StreamApiTest, PostLarge) {
  10906. httplib::Client cli(HOST, PORT);
  10907. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10908. size_t total = 0;
  10909. while (result.next()) {
  10910. total += result.size();
  10911. }
  10912. EXPECT_EQ(100u * 1024u, total);
  10913. }
  10914. // stream::Put/Patch tests
  10915. TEST_F(StreamApiTest, PutAndPatch) {
  10916. httplib::Client cli(HOST, PORT);
  10917. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10918. EXPECT_EQ("PUT:test", read_body(put));
  10919. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10920. EXPECT_EQ("PATCH:test", read_body(patch));
  10921. }
  10922. // stream::Delete tests
  10923. TEST_F(StreamApiTest, Delete) {
  10924. httplib::Client cli(HOST, PORT);
  10925. auto del1 = httplib::stream::Delete(cli, "/resource");
  10926. EXPECT_EQ("Deleted", read_body(del1));
  10927. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10928. EXPECT_EQ("Deleted:data", read_body(del2));
  10929. }
  10930. // stream::Head/Options tests
  10931. TEST_F(StreamApiTest, HeadAndOptions) {
  10932. httplib::Client cli(HOST, PORT);
  10933. auto head = httplib::stream::Head(cli, "/head-test");
  10934. EXPECT_TRUE(head.is_valid());
  10935. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10936. auto opts = httplib::stream::Options(cli, "/options");
  10937. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10938. }
  10939. // SSL stream::* tests
  10940. #ifdef CPPHTTPLIB_SSL_ENABLED
  10941. class SSLStreamApiTest : public ::testing::Test {
  10942. protected:
  10943. void SetUp() override {
  10944. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10945. res.set_content("Hello SSL!", "text/plain");
  10946. });
  10947. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10948. res.set_content(req.body, "text/plain");
  10949. });
  10950. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10951. svr_.wait_until_ready();
  10952. }
  10953. void TearDown() override {
  10954. svr_.stop();
  10955. if (thread_.joinable()) thread_.join();
  10956. }
  10957. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10958. std::thread thread_;
  10959. };
  10960. TEST_F(SSLStreamApiTest, GetAndPost) {
  10961. httplib::SSLClient cli("127.0.0.1", 8803);
  10962. cli.enable_server_certificate_verification(false);
  10963. auto get = httplib::stream::Get(cli, "/hello");
  10964. EXPECT_EQ("Hello SSL!", read_body(get));
  10965. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10966. EXPECT_EQ("test", read_body(post));
  10967. }
  10968. #endif
  10969. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10970. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10971. // BodyReader
  10972. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10973. // Test that read timeout during streaming is detected
  10974. // Use a large content-length response where server delays mid-stream
  10975. Server svr;
  10976. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10977. // Send a large response with delay in the middle
  10978. res.set_content_provider(
  10979. 1000, // content_length
  10980. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10981. if (offset < 100) {
  10982. // Send first 100 bytes immediately
  10983. std::string data(100, 'A');
  10984. sink.write(data.c_str(), data.size());
  10985. return true;
  10986. }
  10987. // Then delay longer than client timeout
  10988. std::this_thread::sleep_for(std::chrono::seconds(3));
  10989. std::string data(900, 'B');
  10990. sink.write(data.c_str(), data.size());
  10991. return true;
  10992. });
  10993. });
  10994. auto port = 8091;
  10995. std::thread t([&]() { svr.listen("localhost", port); });
  10996. svr.wait_until_ready();
  10997. Client cli("localhost", port);
  10998. cli.set_read_timeout(1, 0); // 1 second timeout
  10999. auto handle = cli.open_stream("GET", "/slow-stream");
  11000. ASSERT_TRUE(handle.is_valid());
  11001. char buf[256];
  11002. ssize_t total = 0;
  11003. ssize_t n;
  11004. bool got_error = false;
  11005. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11006. total += n;
  11007. }
  11008. if (n < 0) {
  11009. got_error = true;
  11010. // Should be timeout or read error
  11011. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11012. handle.get_read_error() == Error::Read)
  11013. << "Actual error: " << to_string(handle.get_read_error());
  11014. }
  11015. // Either we got an error, or we got less data than expected
  11016. EXPECT_TRUE(got_error || total < 1000)
  11017. << "Expected timeout but got all " << total << " bytes";
  11018. svr.stop();
  11019. t.join();
  11020. }
  11021. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11022. // Test connection closed detection via BodyReader
  11023. Server svr;
  11024. std::atomic<bool> close_now{false};
  11025. svr.Get("/will-close", [&](const Request &, Response &res) {
  11026. res.set_content_provider(
  11027. 10000, // Large content_length that we won't fully send
  11028. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11029. if (offset < 100) {
  11030. std::string data(100, 'X');
  11031. sink.write(data.c_str(), data.size());
  11032. return true;
  11033. }
  11034. // Wait for signal then abort
  11035. while (!close_now) {
  11036. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11037. }
  11038. return false; // Abort - server will close connection
  11039. });
  11040. });
  11041. auto port = 8092;
  11042. std::thread t([&]() { svr.listen("localhost", port); });
  11043. svr.wait_until_ready();
  11044. Client cli("localhost", port);
  11045. auto handle = cli.open_stream("GET", "/will-close");
  11046. ASSERT_TRUE(handle.is_valid());
  11047. char buf[256];
  11048. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11049. EXPECT_GT(n, 0) << "First read should succeed";
  11050. // Signal server to close
  11051. close_now = true;
  11052. // Keep reading until error or EOF
  11053. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11054. // Keep reading
  11055. }
  11056. // Should get an error since content_length wasn't satisfied
  11057. if (n < 0) {
  11058. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11059. handle.get_read_error() == Error::Read)
  11060. << "Actual error: " << to_string(handle.get_read_error());
  11061. }
  11062. svr.stop();
  11063. t.join();
  11064. }
  11065. #ifdef CPPHTTPLIB_SSL_ENABLED
  11066. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11067. // Test that read timeout during SSL streaming is detected
  11068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11069. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11070. res.set_content_provider(
  11071. 1000, "text/plain",
  11072. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11073. if (offset < 100) {
  11074. std::string data(100, 'A');
  11075. sink.write(data.c_str(), data.size());
  11076. return true;
  11077. }
  11078. std::this_thread::sleep_for(std::chrono::seconds(3));
  11079. std::string data(900, 'B');
  11080. sink.write(data.c_str(), data.size());
  11081. return true;
  11082. });
  11083. });
  11084. auto port = 8093;
  11085. std::thread t([&]() { svr.listen("localhost", port); });
  11086. svr.wait_until_ready();
  11087. SSLClient cli("localhost", port);
  11088. cli.enable_server_certificate_verification(false);
  11089. cli.set_read_timeout(1, 0); // 1 second timeout
  11090. auto handle = cli.open_stream("GET", "/slow-stream");
  11091. ASSERT_TRUE(handle.is_valid());
  11092. char buf[256];
  11093. ssize_t total = 0;
  11094. ssize_t n;
  11095. bool got_error = false;
  11096. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11097. total += n;
  11098. }
  11099. if (n < 0) {
  11100. got_error = true;
  11101. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11102. handle.get_read_error() == Error::Read)
  11103. << "Actual error: " << to_string(handle.get_read_error());
  11104. }
  11105. EXPECT_TRUE(got_error || total < 1000)
  11106. << "Expected timeout but got all " << total << " bytes";
  11107. svr.stop();
  11108. t.join();
  11109. }
  11110. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11111. // Test SSL connection closed detection
  11112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11113. std::atomic<bool> close_now{false};
  11114. svr.Get("/will-close", [&](const Request &, Response &res) {
  11115. res.set_content_provider(
  11116. 10000, "text/plain",
  11117. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11118. if (offset < 100) {
  11119. std::string data(100, 'X');
  11120. sink.write(data.c_str(), data.size());
  11121. return true;
  11122. }
  11123. while (!close_now) {
  11124. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11125. }
  11126. return false;
  11127. });
  11128. });
  11129. auto port = 8094;
  11130. std::thread t([&]() { svr.listen("localhost", port); });
  11131. svr.wait_until_ready();
  11132. SSLClient cli("localhost", port);
  11133. cli.enable_server_certificate_verification(false);
  11134. auto handle = cli.open_stream("GET", "/will-close");
  11135. ASSERT_TRUE(handle.is_valid());
  11136. char buf[256];
  11137. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11138. EXPECT_GT(n, 0);
  11139. // Signal server to close
  11140. close_now = true;
  11141. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11142. // Keep reading
  11143. }
  11144. if (n < 0) {
  11145. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11146. handle.get_read_error() == Error::Read)
  11147. << "Actual error: " << to_string(handle.get_read_error());
  11148. }
  11149. svr.stop();
  11150. t.join();
  11151. }
  11152. #endif
  11153. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11154. using namespace httplib;
  11155. // Create a test file
  11156. const char *fname = "etag_testfile.txt";
  11157. const char *content = "etag-content";
  11158. {
  11159. std::ofstream ofs(fname);
  11160. ofs << content;
  11161. ASSERT_TRUE(ofs.good());
  11162. }
  11163. Server svr;
  11164. svr.set_mount_point("/static", ".");
  11165. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11166. svr.wait_until_ready();
  11167. Client cli(HOST, PORT);
  11168. // First request: should get 200 with ETag header
  11169. auto res1 = cli.Get("/static/etag_testfile.txt");
  11170. ASSERT_TRUE(res1);
  11171. ASSERT_EQ(200, res1->status);
  11172. ASSERT_TRUE(res1->has_header("ETag"));
  11173. std::string etag = res1->get_header_value("ETag");
  11174. EXPECT_FALSE(etag.empty());
  11175. // Verify ETag format: W/"hex-hex"
  11176. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11177. EXPECT_EQ('W', etag[0]);
  11178. EXPECT_EQ('/', etag[1]);
  11179. EXPECT_EQ('"', etag[2]);
  11180. EXPECT_EQ('"', etag.back());
  11181. // Exact match: expect 304 Not Modified
  11182. Headers h2 = {{"If-None-Match", etag}};
  11183. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11184. ASSERT_TRUE(res2);
  11185. EXPECT_EQ(304, res2->status);
  11186. // Wildcard match: expect 304 Not Modified
  11187. Headers h3 = {{"If-None-Match", "*"}};
  11188. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11189. ASSERT_TRUE(res3);
  11190. EXPECT_EQ(304, res3->status);
  11191. // Non-matching ETag: expect 200
  11192. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11193. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11194. ASSERT_TRUE(res4);
  11195. EXPECT_EQ(200, res4->status);
  11196. // Multiple ETags with one matching: expect 304
  11197. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11198. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11199. ASSERT_TRUE(res5);
  11200. EXPECT_EQ(304, res5->status);
  11201. svr.stop();
  11202. t.join();
  11203. std::remove(fname);
  11204. }
  11205. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11206. using namespace httplib;
  11207. Server svr;
  11208. svr.set_mount_point("/static", ".");
  11209. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11210. svr.wait_until_ready();
  11211. Client cli(HOST, PORT);
  11212. // Send If-None-Match: * to a non-existent file
  11213. Headers h = {{"If-None-Match", "*"}};
  11214. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11215. ASSERT_TRUE(res);
  11216. EXPECT_EQ(404, res->status);
  11217. svr.stop();
  11218. t.join();
  11219. }
  11220. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11221. using namespace httplib;
  11222. // Create a test file
  11223. const char *fname = "ims_testfile.txt";
  11224. const char *content = "if-modified-since-test";
  11225. {
  11226. std::ofstream ofs(fname);
  11227. ofs << content;
  11228. ASSERT_TRUE(ofs.good());
  11229. }
  11230. Server svr;
  11231. svr.set_mount_point("/static", ".");
  11232. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11233. svr.wait_until_ready();
  11234. Client cli(HOST, PORT);
  11235. // First request: should get 200 with Last-Modified header
  11236. auto res1 = cli.Get("/static/ims_testfile.txt");
  11237. ASSERT_TRUE(res1);
  11238. ASSERT_EQ(200, res1->status);
  11239. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11240. std::string last_modified = res1->get_header_value("Last-Modified");
  11241. EXPECT_FALSE(last_modified.empty());
  11242. // If-Modified-Since with same time: expect 304
  11243. Headers h2 = {{"If-Modified-Since", last_modified}};
  11244. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11245. ASSERT_TRUE(res2);
  11246. EXPECT_EQ(304, res2->status);
  11247. // If-Modified-Since with future time: expect 304
  11248. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11249. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11250. ASSERT_TRUE(res3);
  11251. EXPECT_EQ(304, res3->status);
  11252. // If-Modified-Since with past time: expect 200
  11253. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11254. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11255. ASSERT_TRUE(res4);
  11256. EXPECT_EQ(200, res4->status);
  11257. // If-None-Match takes precedence over If-Modified-Since
  11258. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11259. ASSERT_TRUE(res1->has_header("ETag"));
  11260. std::string etag = res1->get_header_value("ETag");
  11261. Headers h5 = {{"If-None-Match", etag},
  11262. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11263. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11264. ASSERT_TRUE(res5);
  11265. EXPECT_EQ(304, res5->status);
  11266. svr.stop();
  11267. t.join();
  11268. std::remove(fname);
  11269. }
  11270. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11271. using namespace httplib;
  11272. Server svr;
  11273. // Endpoint that returns compressible content
  11274. svr.Get("/compressible", [](const Request &, Response &res) {
  11275. // Return a large enough body to trigger compression
  11276. std::string body(1000, 'a');
  11277. res.set_content(body, "text/plain");
  11278. });
  11279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11280. svr.wait_until_ready();
  11281. Client cli(HOST, PORT);
  11282. // Request with gzip support: should get Vary header when compressed
  11283. cli.set_compress(true);
  11284. auto res1 = cli.Get("/compressible");
  11285. ASSERT_TRUE(res1);
  11286. EXPECT_EQ(200, res1->status);
  11287. // If Content-Encoding is set, Vary should also be set
  11288. if (res1->has_header("Content-Encoding")) {
  11289. EXPECT_TRUE(res1->has_header("Vary"));
  11290. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11291. }
  11292. // Request without Accept-Encoding header: should not have compression
  11293. Headers h_no_compress;
  11294. auto res2 = cli.Get("/compressible", h_no_compress);
  11295. ASSERT_TRUE(res2);
  11296. EXPECT_EQ(200, res2->status);
  11297. // Verify Vary header is present when compression is applied
  11298. // (the exact behavior depends on server configuration)
  11299. svr.stop();
  11300. t.join();
  11301. }
  11302. TEST(ETagTest, IfRangeWithETag) {
  11303. using namespace httplib;
  11304. // Create a test file with known content
  11305. const char *fname = "if_range_testfile.txt";
  11306. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11307. {
  11308. std::ofstream ofs(fname);
  11309. ofs << content;
  11310. ASSERT_TRUE(ofs.good());
  11311. }
  11312. Server svr;
  11313. svr.set_mount_point("/static", ".");
  11314. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11315. svr.wait_until_ready();
  11316. Client cli(HOST, PORT);
  11317. // First request: get ETag
  11318. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11319. ASSERT_TRUE(res1);
  11320. ASSERT_EQ(200, res1->status);
  11321. ASSERT_TRUE(res1->has_header("ETag"));
  11322. std::string etag = res1->get_header_value("ETag");
  11323. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11324. // Since our server generates weak ETags (W/"..."), If-Range with our
  11325. // ETag should NOT result in partial content - it should return full content.
  11326. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11327. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11328. ASSERT_TRUE(res2);
  11329. // Weak ETag in If-Range -> full content (200), not partial (206)
  11330. EXPECT_EQ(200, res2->status);
  11331. EXPECT_EQ(content, res2->body);
  11332. EXPECT_FALSE(res2->has_header("Content-Range"));
  11333. // Range request with non-matching If-Range (ETag): should get 200 (full
  11334. // content)
  11335. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11336. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11337. ASSERT_TRUE(res3);
  11338. EXPECT_EQ(200, res3->status);
  11339. EXPECT_EQ(content, res3->body);
  11340. EXPECT_FALSE(res3->has_header("Content-Range"));
  11341. // Range request with strong ETag (hypothetical - our server doesn't generate
  11342. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11343. // should return full content)
  11344. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11345. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11346. ASSERT_TRUE(res4);
  11347. EXPECT_EQ(200, res4->status);
  11348. EXPECT_EQ(content, res4->body);
  11349. EXPECT_FALSE(res4->has_header("Content-Range"));
  11350. svr.stop();
  11351. t.join();
  11352. std::remove(fname);
  11353. }
  11354. TEST(ETagTest, IfRangeWithDate) {
  11355. using namespace httplib;
  11356. // Create a test file
  11357. const char *fname = "if_range_date_testfile.txt";
  11358. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11359. {
  11360. std::ofstream ofs(fname);
  11361. ofs << content;
  11362. ASSERT_TRUE(ofs.good());
  11363. }
  11364. Server svr;
  11365. svr.set_mount_point("/static", ".");
  11366. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11367. svr.wait_until_ready();
  11368. Client cli(HOST, PORT);
  11369. // First request: get Last-Modified
  11370. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11371. ASSERT_TRUE(res1);
  11372. ASSERT_EQ(200, res1->status);
  11373. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11374. std::string last_modified = res1->get_header_value("Last-Modified");
  11375. // Range request with matching If-Range (date): should get 206
  11376. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11377. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11378. ASSERT_TRUE(res2);
  11379. EXPECT_EQ(206, res2->status);
  11380. EXPECT_EQ("FGHIJ", res2->body);
  11381. // Range request with old If-Range date: should get 200 (full content)
  11382. Headers h3 = {{"Range", "bytes=5-9"},
  11383. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11384. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11385. ASSERT_TRUE(res3);
  11386. EXPECT_EQ(200, res3->status);
  11387. EXPECT_EQ(content, res3->body);
  11388. // Range request with future If-Range date: should get 206
  11389. Headers h4 = {{"Range", "bytes=0-4"},
  11390. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11391. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11392. ASSERT_TRUE(res4);
  11393. EXPECT_EQ(206, res4->status);
  11394. EXPECT_EQ("ABCDE", res4->body);
  11395. svr.stop();
  11396. t.join();
  11397. std::remove(fname);
  11398. }
  11399. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11400. using namespace httplib;
  11401. const char *fname = "etag_malformed.txt";
  11402. const char *content = "malformed-etag";
  11403. {
  11404. std::ofstream ofs(fname);
  11405. ofs << content;
  11406. ASSERT_TRUE(ofs.good());
  11407. }
  11408. Server svr;
  11409. svr.set_mount_point("/static", ".");
  11410. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11411. svr.wait_until_ready();
  11412. Client cli(HOST, PORT);
  11413. // baseline: should get 200 and an ETag
  11414. auto res1 = cli.Get("/static/etag_malformed.txt");
  11415. ASSERT_TRUE(res1);
  11416. ASSERT_EQ(200, res1->status);
  11417. ASSERT_TRUE(res1->has_header("ETag"));
  11418. // Malformed ETag value (missing quotes) should be treated as non-matching
  11419. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11420. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11421. ASSERT_TRUE(res_bad);
  11422. EXPECT_EQ(200, res_bad->status);
  11423. // Whitespace-only header value should be considered invalid / non-matching
  11424. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11425. "Host: localhost\r\n"
  11426. "If-None-Match: \r\n"
  11427. "Connection: close\r\n"
  11428. "\r\n";
  11429. std::string out;
  11430. ASSERT_TRUE(send_request(5, raw_req, &out));
  11431. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11432. svr.stop();
  11433. t.join();
  11434. std::remove(fname);
  11435. }
  11436. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11437. using namespace httplib;
  11438. const char *fname = "ims_invalid_format.txt";
  11439. const char *content = "ims-bad-format";
  11440. {
  11441. std::ofstream ofs(fname);
  11442. ofs << content;
  11443. ASSERT_TRUE(ofs.good());
  11444. }
  11445. Server svr;
  11446. svr.set_mount_point("/static", ".");
  11447. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11448. svr.wait_until_ready();
  11449. Client cli(HOST, PORT);
  11450. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11451. ASSERT_TRUE(res1);
  11452. ASSERT_EQ(200, res1->status);
  11453. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11454. // If-Modified-Since with invalid format should not result in 304
  11455. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11456. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11457. ASSERT_TRUE(res_bad);
  11458. EXPECT_EQ(200, res_bad->status);
  11459. // If-Range with invalid date format should be treated as mismatch -> full
  11460. // content (200)
  11461. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11462. {"If-Range", "invalid-date"}};
  11463. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11464. ASSERT_TRUE(res_ifrange);
  11465. EXPECT_EQ(200, res_ifrange->status);
  11466. svr.stop();
  11467. t.join();
  11468. std::remove(fname);
  11469. }
  11470. TEST(ETagTest, IfRangeWithMalformedETag) {
  11471. using namespace httplib;
  11472. const char *fname = "ifrange_malformed.txt";
  11473. const std::string content = "0123456789";
  11474. {
  11475. std::ofstream ofs(fname);
  11476. ofs << content;
  11477. ASSERT_TRUE(ofs.good());
  11478. }
  11479. Server svr;
  11480. svr.set_mount_point("/static", ".");
  11481. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11482. svr.wait_until_ready();
  11483. Client cli(HOST, PORT);
  11484. // First request: get ETag
  11485. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11486. ASSERT_TRUE(res1);
  11487. ASSERT_EQ(200, res1->status);
  11488. ASSERT_TRUE(res1->has_header("ETag"));
  11489. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11490. // full content (200)
  11491. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11492. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11493. ASSERT_TRUE(res2);
  11494. EXPECT_EQ(200, res2->status);
  11495. EXPECT_EQ(content, res2->body);
  11496. svr.stop();
  11497. t.join();
  11498. std::remove(fname);
  11499. }
  11500. TEST(ETagTest, ExtremeLargeDateValues) {
  11501. using namespace httplib;
  11502. const char *fname = "ims_extreme_date.txt";
  11503. const char *content = "ims-extreme-date";
  11504. {
  11505. std::ofstream ofs(fname);
  11506. ofs << content;
  11507. ASSERT_TRUE(ofs.good());
  11508. }
  11509. Server svr;
  11510. svr.set_mount_point("/static", ".");
  11511. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11512. svr.wait_until_ready();
  11513. Client cli(HOST, PORT);
  11514. auto res1 = cli.Get(std::string("/static/") + fname);
  11515. ASSERT_TRUE(res1);
  11516. ASSERT_EQ(200, res1->status);
  11517. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11518. // Extremely large year that may overflow date parsing routines.
  11519. Headers h_large_date = {
  11520. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11521. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11522. ASSERT_TRUE(res_bad);
  11523. // Expect server to treat this as invalid/mismatch and return full content
  11524. EXPECT_EQ(200, res_bad->status);
  11525. // If-Range with extremely large date should be treated as mismatch -> full
  11526. // content (200)
  11527. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11528. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11529. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11530. ASSERT_TRUE(res_ifrange);
  11531. EXPECT_EQ(200, res_ifrange->status);
  11532. svr.stop();
  11533. t.join();
  11534. std::remove(fname);
  11535. }
  11536. TEST(ETagTest, NegativeFileModificationTime) {
  11537. using namespace httplib;
  11538. const char *fname = "ims_negative_mtime.txt";
  11539. const std::string content = "negative-mtime";
  11540. {
  11541. std::ofstream ofs(fname);
  11542. ofs << content;
  11543. ASSERT_TRUE(ofs.good());
  11544. }
  11545. // Try to set file mtime to a negative value. This may fail on some
  11546. // platforms/filesystems; if it fails, the test will still verify server
  11547. // behaves safely by performing a regular conditional request.
  11548. #if defined(__APPLE__) || defined(__linux__)
  11549. bool set_negative = false;
  11550. do {
  11551. struct timeval times[2];
  11552. // access time: now
  11553. times[0].tv_sec = time(nullptr);
  11554. times[0].tv_usec = 0;
  11555. // modification time: negative (e.g., -1)
  11556. times[1].tv_sec = -1;
  11557. times[1].tv_usec = 0;
  11558. if (utimes(fname, times) == 0) { set_negative = true; }
  11559. } while (0);
  11560. #else
  11561. bool set_negative = false;
  11562. #endif
  11563. Server svr;
  11564. svr.set_mount_point("/static", ".");
  11565. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11566. svr.wait_until_ready();
  11567. Client cli(HOST, PORT);
  11568. auto res1 = cli.Get(std::string("/static/") + fname);
  11569. ASSERT_TRUE(res1);
  11570. ASSERT_EQ(200, res1->status);
  11571. bool has_last_modified = res1->has_header("Last-Modified");
  11572. std::string last_modified;
  11573. if (has_last_modified) {
  11574. last_modified = res1->get_header_value("Last-Modified");
  11575. }
  11576. if (set_negative) {
  11577. // If we successfully set a negative mtime, ensure server returns a
  11578. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11579. // with an old date and ensure server handles it without crash.
  11580. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11581. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11582. ASSERT_TRUE(res2);
  11583. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11584. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11585. } else {
  11586. // Could not set negative mtime on this platform; fall back to verifying
  11587. // that normal invalid/malformed dates are treated safely (non-304).
  11588. Headers h_bad_date = {
  11589. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11590. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11591. ASSERT_TRUE(res_bad);
  11592. EXPECT_EQ(200, res_bad->status);
  11593. }
  11594. svr.stop();
  11595. t.join();
  11596. std::remove(fname);
  11597. }
  11598. //==============================================================================
  11599. // SSE Parsing Tests
  11600. //==============================================================================
  11601. class SSEParsingTest : public ::testing::Test {
  11602. protected:
  11603. // Test helper that mimics SSE parsing behavior
  11604. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11605. int &retry_ms) {
  11606. // Blank line signals end of event
  11607. if (line.empty() || line == "\r") { return true; }
  11608. // Lines starting with ':' are comments (ignored)
  11609. if (!line.empty() && line[0] == ':') { return false; }
  11610. // Find the colon separator
  11611. auto colon_pos = line.find(':');
  11612. if (colon_pos == std::string::npos) {
  11613. // Line with no colon is treated as field name with empty value
  11614. return false;
  11615. }
  11616. std::string field = line.substr(0, colon_pos);
  11617. std::string value;
  11618. // Value starts after colon, skip optional single space
  11619. if (colon_pos + 1 < line.size()) {
  11620. size_t value_start = colon_pos + 1;
  11621. if (line[value_start] == ' ') { value_start++; }
  11622. value = line.substr(value_start);
  11623. // Remove trailing \r if present
  11624. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11625. }
  11626. // Handle known fields
  11627. if (field == "event") {
  11628. msg.event = value;
  11629. } else if (field == "data") {
  11630. // Multiple data lines are concatenated with newlines
  11631. if (!msg.data.empty()) { msg.data += "\n"; }
  11632. msg.data += value;
  11633. } else if (field == "id") {
  11634. // Empty id is valid (clears the last event ID)
  11635. msg.id = value;
  11636. } else if (field == "retry") {
  11637. // Parse retry interval in milliseconds
  11638. try {
  11639. retry_ms = std::stoi(value);
  11640. } catch (...) {
  11641. // Invalid retry value, ignore
  11642. }
  11643. }
  11644. // Unknown fields are ignored per SSE spec
  11645. return false;
  11646. }
  11647. };
  11648. // Test: Single-line data
  11649. TEST_F(SSEParsingTest, SingleLineData) {
  11650. sse::SSEMessage msg;
  11651. int retry_ms = 3000;
  11652. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11653. EXPECT_EQ(msg.data, "hello");
  11654. EXPECT_EQ(msg.event, "message");
  11655. // Blank line ends event
  11656. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11657. }
  11658. // Test: Multi-line data
  11659. TEST_F(SSEParsingTest, MultiLineData) {
  11660. sse::SSEMessage msg;
  11661. int retry_ms = 3000;
  11662. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11663. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11664. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11665. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11666. }
  11667. // Test: Custom event types
  11668. TEST_F(SSEParsingTest, CustomEventType) {
  11669. sse::SSEMessage msg;
  11670. int retry_ms = 3000;
  11671. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11672. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11673. EXPECT_EQ(msg.event, "update");
  11674. EXPECT_EQ(msg.data, "payload");
  11675. }
  11676. // Test: Event ID handling
  11677. TEST_F(SSEParsingTest, EventIdHandling) {
  11678. sse::SSEMessage msg;
  11679. int retry_ms = 3000;
  11680. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11681. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11682. EXPECT_EQ(msg.id, "12345");
  11683. }
  11684. // Test: Empty event ID (clears last event ID)
  11685. TEST_F(SSEParsingTest, EmptyEventId) {
  11686. sse::SSEMessage msg;
  11687. msg.id = "previous";
  11688. int retry_ms = 3000;
  11689. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11690. EXPECT_EQ(msg.id, "");
  11691. }
  11692. // Test: Retry field parsing
  11693. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11694. sse::SSEMessage msg;
  11695. int retry_ms = 3000;
  11696. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11697. EXPECT_EQ(retry_ms, 5000);
  11698. }
  11699. // Test: Invalid retry value
  11700. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11701. sse::SSEMessage msg;
  11702. int retry_ms = 3000;
  11703. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11704. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11705. }
  11706. // Test: Comments (lines starting with :)
  11707. TEST_F(SSEParsingTest, CommentsIgnored) {
  11708. sse::SSEMessage msg;
  11709. int retry_ms = 3000;
  11710. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11711. EXPECT_EQ(msg.data, "");
  11712. EXPECT_EQ(msg.event, "message");
  11713. }
  11714. // Test: Colon in value
  11715. TEST_F(SSEParsingTest, ColonInValue) {
  11716. sse::SSEMessage msg;
  11717. int retry_ms = 3000;
  11718. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11719. EXPECT_EQ(msg.data, "hello:world:test");
  11720. }
  11721. // Test: Line with no colon (field name only)
  11722. TEST_F(SSEParsingTest, FieldNameOnly) {
  11723. sse::SSEMessage msg;
  11724. int retry_ms = 3000;
  11725. // According to SSE spec, this is treated as field name with empty value
  11726. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11727. // Since we don't recognize "data" without colon, data should be empty
  11728. EXPECT_EQ(msg.data, "");
  11729. }
  11730. // Test: Trailing \r handling
  11731. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11732. sse::SSEMessage msg;
  11733. int retry_ms = 3000;
  11734. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11735. EXPECT_EQ(msg.data, "hello");
  11736. }
  11737. // Test: Unknown fields ignored
  11738. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11739. sse::SSEMessage msg;
  11740. int retry_ms = 3000;
  11741. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11742. EXPECT_EQ(msg.data, "");
  11743. EXPECT_EQ(msg.event, "message");
  11744. }
  11745. // Test: Space after colon is optional
  11746. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11747. sse::SSEMessage msg1, msg2;
  11748. int retry_ms = 3000;
  11749. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11750. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11751. EXPECT_EQ(msg1.data, "hello");
  11752. EXPECT_EQ(msg2.data, "hello");
  11753. }
  11754. // Test: SSEMessage clear
  11755. TEST_F(SSEParsingTest, MessageClear) {
  11756. sse::SSEMessage msg;
  11757. msg.event = "custom";
  11758. msg.data = "some data";
  11759. msg.id = "123";
  11760. msg.clear();
  11761. EXPECT_EQ(msg.event, "message");
  11762. EXPECT_EQ(msg.data, "");
  11763. EXPECT_EQ(msg.id, "");
  11764. }
  11765. // Test: Complete event parsing
  11766. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11767. sse::SSEMessage msg;
  11768. int retry_ms = 3000;
  11769. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11770. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11771. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11772. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11773. // Blank line ends event
  11774. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11775. EXPECT_EQ(msg.event, "notification");
  11776. EXPECT_EQ(msg.id, "evt-42");
  11777. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11778. EXPECT_EQ(retry_ms, 1000);
  11779. }
  11780. //==============================================================================
  11781. // Integration Tests with Server
  11782. //==============================================================================
  11783. class SSEIntegrationTest : public ::testing::Test {
  11784. protected:
  11785. void SetUp() override {
  11786. stop_server_.store(false);
  11787. events_.clear();
  11788. server_ = httplib::detail::make_unique<Server>();
  11789. setup_server();
  11790. start_server();
  11791. }
  11792. void TearDown() override {
  11793. stop_server_.store(true);
  11794. event_cv_.notify_all();
  11795. server_->stop();
  11796. if (server_thread_.joinable()) { server_thread_.join(); }
  11797. }
  11798. void setup_server() {
  11799. // Simple SSE endpoint
  11800. server_->Get("/events", [this](const Request &req, Response &res) {
  11801. auto last_id = req.get_header_value("Last-Event-ID");
  11802. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11803. res.set_chunked_content_provider(
  11804. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11805. std::unique_lock<std::mutex> lock(event_mutex_);
  11806. if (event_cv_.wait_for(
  11807. lock, std::chrono::milliseconds(200), [this] {
  11808. return !events_.empty() || stop_server_.load();
  11809. })) {
  11810. if (stop_server_.load()) { return false; }
  11811. if (!events_.empty()) {
  11812. std::string event = events_.front();
  11813. events_.erase(events_.begin());
  11814. sink.write(event.data(), event.size());
  11815. return true;
  11816. }
  11817. }
  11818. return !stop_server_.load();
  11819. });
  11820. });
  11821. // Endpoint that returns error
  11822. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11823. res.status = 500;
  11824. res.set_content("Internal Server Error", "text/plain");
  11825. });
  11826. // Endpoint for custom event types
  11827. server_->Get("/custom-events", [](const Request &, Response &res) {
  11828. res.set_chunked_content_provider(
  11829. "text/event-stream", [](size_t offset, DataSink &sink) {
  11830. if (offset == 0) {
  11831. std::string event = "event: update\ndata: updated\n\n"
  11832. "event: delete\ndata: deleted\n\n";
  11833. sink.write(event.data(), event.size());
  11834. }
  11835. return false; // End stream after sending
  11836. });
  11837. });
  11838. }
  11839. void start_server() {
  11840. port_ = server_->bind_to_any_port(HOST);
  11841. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11842. // Wait for server to start
  11843. while (!server_->is_running()) {
  11844. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11845. }
  11846. }
  11847. int get_port() const { return port_; }
  11848. void send_event(const std::string &event) {
  11849. std::lock_guard<std::mutex> lock(event_mutex_);
  11850. events_.push_back(event);
  11851. event_cv_.notify_all();
  11852. }
  11853. std::unique_ptr<Server> server_;
  11854. std::thread server_thread_;
  11855. std::mutex event_mutex_;
  11856. std::condition_variable event_cv_;
  11857. std::vector<std::string> events_;
  11858. std::atomic<bool> stop_server_{false};
  11859. std::string last_received_event_id_;
  11860. int port_ = 0;
  11861. };
  11862. // Test: Successful connection and on_open callback
  11863. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11864. // Add a simple endpoint that sends one event and closes
  11865. server_->Get("/simple-event", [](const Request &, Response &res) {
  11866. res.set_chunked_content_provider(
  11867. "text/event-stream", [](size_t offset, DataSink &sink) {
  11868. if (offset == 0) {
  11869. std::string event = "data: hello\n\n";
  11870. sink.write(event.data(), event.size());
  11871. }
  11872. return false; // Close stream after sending
  11873. });
  11874. });
  11875. Client client("localhost", get_port());
  11876. sse::SSEClient sse(client, "/simple-event");
  11877. std::atomic<bool> open_called{false};
  11878. std::atomic<bool> message_received{false};
  11879. sse.on_open([&open_called]() { open_called.store(true); });
  11880. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11881. if (msg.data == "hello") { message_received.store(true); }
  11882. });
  11883. sse.set_reconnect_interval(100);
  11884. sse.set_max_reconnect_attempts(1);
  11885. // Start async
  11886. sse.start_async();
  11887. // Wait for message to be processed
  11888. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11889. sse.stop();
  11890. EXPECT_TRUE(open_called.load());
  11891. EXPECT_TRUE(message_received.load());
  11892. }
  11893. // Test: on_message callback
  11894. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11895. // Endpoint that sends multiple events then closes
  11896. server_->Get("/multi-event", [](const Request &, Response &res) {
  11897. res.set_chunked_content_provider(
  11898. "text/event-stream", [](size_t offset, DataSink &sink) {
  11899. if (offset == 0) {
  11900. std::string events = "data: message1\n\ndata: message2\n\n";
  11901. sink.write(events.data(), events.size());
  11902. }
  11903. return false;
  11904. });
  11905. });
  11906. Client client("localhost", get_port());
  11907. sse::SSEClient sse(client, "/multi-event");
  11908. std::vector<std::string> received_messages;
  11909. std::mutex messages_mutex;
  11910. sse.on_message([&](const sse::SSEMessage &msg) {
  11911. std::lock_guard<std::mutex> lock(messages_mutex);
  11912. received_messages.push_back(msg.data);
  11913. });
  11914. sse.set_reconnect_interval(100);
  11915. sse.set_max_reconnect_attempts(1);
  11916. sse.start_async();
  11917. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11918. sse.stop();
  11919. std::lock_guard<std::mutex> lock(messages_mutex);
  11920. EXPECT_GE(received_messages.size(), 2u);
  11921. if (received_messages.size() >= 2) {
  11922. EXPECT_EQ(received_messages[0], "message1");
  11923. EXPECT_EQ(received_messages[1], "message2");
  11924. }
  11925. }
  11926. // Test: on_event for specific types
  11927. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11928. Client client("localhost", get_port());
  11929. sse::SSEClient sse(client, "/custom-events");
  11930. std::atomic<bool> update_received{false};
  11931. std::atomic<bool> delete_received{false};
  11932. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11933. if (msg.data == "updated") { update_received.store(true); }
  11934. });
  11935. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11936. if (msg.data == "deleted") { delete_received.store(true); }
  11937. });
  11938. sse.set_max_reconnect_attempts(1);
  11939. sse.start_async();
  11940. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11941. sse.stop();
  11942. EXPECT_TRUE(update_received.load());
  11943. EXPECT_TRUE(delete_received.load());
  11944. }
  11945. // Test: on_error callback on connection failure
  11946. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11947. // Connect to a non-existent port
  11948. Client client("localhost", 59999);
  11949. sse::SSEClient sse(client, "/events");
  11950. std::atomic<bool> error_called{false};
  11951. Error received_error = Error::Success;
  11952. sse.on_error([&](Error err) {
  11953. error_called.store(true);
  11954. received_error = err;
  11955. });
  11956. sse.set_reconnect_interval(50);
  11957. sse.set_max_reconnect_attempts(1);
  11958. sse.start_async();
  11959. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11960. sse.stop();
  11961. EXPECT_TRUE(error_called.load());
  11962. EXPECT_NE(received_error, Error::Success);
  11963. }
  11964. // Test: Last-Event-ID header sent on reconnect
  11965. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11966. // Endpoint that sends event with ID
  11967. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11968. res.set_chunked_content_provider(
  11969. "text/event-stream", [](size_t offset, DataSink &sink) {
  11970. if (offset == 0) {
  11971. std::string event = "id: evt-123\ndata: test\n\n";
  11972. sink.write(event.data(), event.size());
  11973. }
  11974. return false;
  11975. });
  11976. });
  11977. Client client("localhost", get_port());
  11978. sse::SSEClient sse(client, "/event-with-id");
  11979. std::atomic<bool> id_received{false};
  11980. sse.on_message([&](const sse::SSEMessage &msg) {
  11981. if (!msg.id.empty()) { id_received.store(true); }
  11982. });
  11983. sse.set_reconnect_interval(100);
  11984. sse.set_max_reconnect_attempts(1);
  11985. sse.start_async();
  11986. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11987. sse.stop();
  11988. EXPECT_TRUE(id_received.load());
  11989. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11990. }
  11991. // Test: Manual stop
  11992. TEST_F(SSEIntegrationTest, ManualStop) {
  11993. // Endpoint that sends one event and stays open briefly
  11994. std::atomic<bool> handler_running{true};
  11995. server_->Get("/stay-open", [&handler_running](const Request &,
  11996. Response &res) {
  11997. res.set_chunked_content_provider(
  11998. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11999. if (offset == 0) {
  12000. std::string event = "data: connected\n\n";
  12001. sink.write(event.data(), event.size());
  12002. }
  12003. // Keep connection open while handler_running is true
  12004. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12005. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12006. }
  12007. return false;
  12008. });
  12009. });
  12010. Client client("localhost", get_port());
  12011. sse::SSEClient sse(client, "/stay-open");
  12012. std::atomic<bool> connected{false};
  12013. sse.on_open([&connected]() { connected.store(true); });
  12014. sse.set_reconnect_interval(100);
  12015. sse.set_max_reconnect_attempts(1);
  12016. sse.start_async();
  12017. // Wait for connection to establish
  12018. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12019. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12020. }
  12021. EXPECT_TRUE(connected.load());
  12022. EXPECT_TRUE(sse.is_connected());
  12023. // Signal handler to stop
  12024. handler_running.store(false);
  12025. // Stop SSE client
  12026. sse.stop();
  12027. EXPECT_FALSE(sse.is_connected());
  12028. }
  12029. // Test: SSEClient with custom headers
  12030. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12031. // Setup a server endpoint that checks for custom header
  12032. std::atomic<bool> header_received{false};
  12033. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12034. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12035. header_received.store(true);
  12036. }
  12037. res.set_chunked_content_provider("text/event-stream",
  12038. [](size_t, DataSink &) { return false; });
  12039. });
  12040. Client client("localhost", get_port());
  12041. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12042. sse::SSEClient sse(client, "/header-check", headers);
  12043. sse.set_max_reconnect_attempts(1);
  12044. sse.start_async();
  12045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12046. sse.stop();
  12047. EXPECT_TRUE(header_received.load());
  12048. }
  12049. // Test: Reconnect interval configuration
  12050. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12051. Client client("localhost", get_port());
  12052. sse::SSEClient sse(client, "/events");
  12053. auto &result = sse.set_reconnect_interval(500);
  12054. // Builder pattern should return reference to self
  12055. EXPECT_EQ(&result, &sse);
  12056. }
  12057. // Test: Max reconnect attempts
  12058. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12059. // Connect to non-existent port to force reconnects
  12060. Client client("localhost", 59998);
  12061. sse::SSEClient sse(client, "/events");
  12062. std::atomic<int> error_count{0};
  12063. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12064. sse.set_reconnect_interval(50);
  12065. sse.set_max_reconnect_attempts(2);
  12066. auto start = std::chrono::steady_clock::now();
  12067. sse.start(); // Blocking call
  12068. auto end = std::chrono::steady_clock::now();
  12069. // Should have stopped after 2 failed attempts
  12070. EXPECT_GE(error_count.load(), 2);
  12071. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12072. auto duration =
  12073. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12074. #ifdef _WIN32
  12075. // Windows is much slower for socket connection failures
  12076. EXPECT_LT(duration.count(), 7000);
  12077. #else
  12078. EXPECT_LT(duration.count(), 1000);
  12079. #endif
  12080. }
  12081. // Test: Multi-line data in integration
  12082. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12083. // Endpoint with multi-line data
  12084. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12085. res.set_chunked_content_provider(
  12086. "text/event-stream", [](size_t offset, DataSink &sink) {
  12087. if (offset == 0) {
  12088. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12089. sink.write(event.data(), event.size());
  12090. }
  12091. return false;
  12092. });
  12093. });
  12094. Client client("localhost", get_port());
  12095. sse::SSEClient sse(client, "/multiline-data");
  12096. std::string received_data;
  12097. std::mutex data_mutex;
  12098. sse.on_message([&](const sse::SSEMessage &msg) {
  12099. std::lock_guard<std::mutex> lock(data_mutex);
  12100. received_data = msg.data;
  12101. });
  12102. sse.set_reconnect_interval(100);
  12103. sse.set_max_reconnect_attempts(1);
  12104. sse.start_async();
  12105. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12106. sse.stop();
  12107. std::lock_guard<std::mutex> lock(data_mutex);
  12108. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12109. }
  12110. // Test: Auto-reconnect after server disconnection
  12111. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12112. std::atomic<int> connection_count{0};
  12113. std::atomic<int> message_count{0};
  12114. // Endpoint that sends one event and closes, forcing reconnect
  12115. server_->Get("/reconnect-test",
  12116. [&connection_count](const Request &, Response &res) {
  12117. connection_count.fetch_add(1);
  12118. res.set_chunked_content_provider(
  12119. "text/event-stream", [](size_t offset, DataSink &sink) {
  12120. if (offset == 0) {
  12121. std::string event = "data: hello\n\n";
  12122. sink.write(event.data(), event.size());
  12123. }
  12124. return false; // Close connection after sending
  12125. });
  12126. });
  12127. Client client("localhost", get_port());
  12128. sse::SSEClient sse(client, "/reconnect-test");
  12129. sse.on_message([&message_count](const sse::SSEMessage &) {
  12130. message_count.fetch_add(1);
  12131. });
  12132. sse.set_reconnect_interval(100);
  12133. sse.set_max_reconnect_attempts(3);
  12134. sse.start_async();
  12135. // Wait long enough for multiple reconnects
  12136. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12137. sse.stop();
  12138. // Should have connected multiple times (initial + reconnects)
  12139. EXPECT_GE(connection_count.load(), 2);
  12140. // Should have received messages from multiple connections
  12141. EXPECT_GE(message_count.load(), 2);
  12142. }
  12143. // Test: Last-Event-ID sent on reconnect
  12144. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12145. std::atomic<int> connection_count{0};
  12146. std::vector<std::string> received_last_event_ids;
  12147. std::mutex id_mutex;
  12148. // Endpoint that checks Last-Event-ID header and sends event with ID
  12149. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12150. int conn = connection_count.fetch_add(1);
  12151. // Capture the Last-Event-ID header from each connection
  12152. {
  12153. std::lock_guard<std::mutex> lock(id_mutex);
  12154. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12155. }
  12156. res.set_chunked_content_provider(
  12157. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12158. if (offset == 0) {
  12159. std::string event =
  12160. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12161. sink.write(event.data(), event.size());
  12162. }
  12163. return false;
  12164. });
  12165. });
  12166. Client client("localhost", get_port());
  12167. sse::SSEClient sse(client, "/reconnect-with-id");
  12168. sse.set_reconnect_interval(100);
  12169. sse.set_max_reconnect_attempts(3);
  12170. sse.start_async();
  12171. // Wait for at least 2 connections
  12172. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12173. sse.stop();
  12174. // Verify behavior
  12175. std::lock_guard<std::mutex> lock(id_mutex);
  12176. EXPECT_GE(received_last_event_ids.size(), 2u);
  12177. // First connection should have no Last-Event-ID
  12178. if (!received_last_event_ids.empty()) {
  12179. EXPECT_EQ(received_last_event_ids[0], "");
  12180. }
  12181. // Second connection should have Last-Event-ID from first connection
  12182. if (received_last_event_ids.size() >= 2) {
  12183. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12184. }
  12185. }
  12186. TEST(Issue2318Test, EmptyHostString) {
  12187. {
  12188. httplib::Client cli_empty("", PORT);
  12189. auto res = cli_empty.Get("/");
  12190. ASSERT_FALSE(res);
  12191. EXPECT_EQ(httplib::Error::Connection, res.error());
  12192. }
  12193. {
  12194. httplib::Client cli(" ", PORT);
  12195. auto res = cli.Get("/");
  12196. ASSERT_FALSE(res);
  12197. EXPECT_EQ(httplib::Error::Connection, res.error());
  12198. }
  12199. }
  12200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12201. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12202. Server svr;
  12203. // Set a small payload limit (1KB)
  12204. svr.set_payload_max_length(1024);
  12205. svr.Post("/test", [&](const Request &req, Response &res) {
  12206. res.set_content("Body size: " + std::to_string(req.body.size()),
  12207. "text/plain");
  12208. });
  12209. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. listen_thread.join();
  12213. });
  12214. svr.wait_until_ready();
  12215. // Create data that compresses well but exceeds limit when decompressed
  12216. // 8KB of repeated null bytes compresses to a very small size
  12217. std::string original_data(8 * 1024, '\0');
  12218. // Compress the data using gzip
  12219. std::string compressed_data;
  12220. detail::gzip_compressor compressor;
  12221. compressor.compress(original_data.data(), original_data.size(), true,
  12222. [&](const char *data, size_t size) {
  12223. compressed_data.append(data, size);
  12224. return true;
  12225. });
  12226. // Verify compression worked (compressed should be much smaller)
  12227. ASSERT_LT(compressed_data.size(), original_data.size());
  12228. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12229. // Send compressed data with Content-Encoding: gzip
  12230. Client cli(HOST, PORT);
  12231. Headers headers = {{"Content-Encoding", "gzip"}};
  12232. auto res =
  12233. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12234. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12235. ASSERT_TRUE(res);
  12236. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12237. }
  12238. #endif