test.cc 391 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <future>
  18. #include <limits>
  19. #include <memory>
  20. #include <sstream>
  21. #include <stdexcept>
  22. #include <thread>
  23. #include <type_traits>
  24. #include <vector>
  25. #define SERVER_CERT_FILE "./cert.pem"
  26. #define SERVER_CERT2_FILE "./cert2.pem"
  27. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  28. #define CA_CERT_FILE "./ca-bundle.crt"
  29. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  30. #define CLIENT_CA_CERT_DIR "."
  31. #define CLIENT_CERT_FILE "./client.cert.pem"
  32. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  33. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  35. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  36. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  38. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  39. using namespace std;
  40. using namespace httplib;
  41. const char *HOST = "localhost";
  42. const int PORT = 1234;
  43. const string LONG_QUERY_VALUE = string(25000, '@');
  44. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  45. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  46. const string TOO_LONG_QUERY_URL =
  47. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  48. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  49. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  50. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  51. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  52. return file.name == key;
  53. });
  54. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  55. return *it;
  56. #else
  57. if (it != items.end()) { return *it; }
  58. throw std::runtime_error("invalid multipart form data name error");
  59. #endif
  60. }
  61. static void read_file(const std::string &path, std::string &out) {
  62. std::ifstream fs(path, std::ios_base::binary);
  63. if (!fs) throw std::runtime_error("File not found: " + path);
  64. fs.seekg(0, std::ios_base::end);
  65. auto size = fs.tellg();
  66. fs.seekg(0);
  67. out.resize(static_cast<size_t>(size));
  68. fs.read(&out[0], static_cast<std::streamsize>(size));
  69. }
  70. void performance_test(const char *host) {
  71. auto port = 1234;
  72. Server svr;
  73. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  74. res.set_content("Benchmark Response", "text/plain");
  75. });
  76. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  77. auto se = detail::scope_exit([&] {
  78. svr.stop();
  79. listen_thread.join();
  80. ASSERT_FALSE(svr.is_running());
  81. });
  82. svr.wait_until_ready();
  83. Client cli(host, port);
  84. // Warm-up request to establish connection and resolve DNS
  85. auto warmup_res = cli.Get("/benchmark");
  86. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  87. // Run multiple trials and collect timings
  88. const int num_trials = 20;
  89. std::vector<int64_t> timings;
  90. timings.reserve(num_trials);
  91. for (int i = 0; i < num_trials; i++) {
  92. auto start = std::chrono::high_resolution_clock::now();
  93. auto res = cli.Get("/benchmark");
  94. auto end = std::chrono::high_resolution_clock::now();
  95. auto elapsed =
  96. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  97. .count();
  98. // Assertions after timing measurement to avoid overhead
  99. ASSERT_TRUE(res);
  100. EXPECT_EQ(StatusCode::OK_200, res->status);
  101. timings.push_back(elapsed);
  102. }
  103. // Calculate 25th percentile (lower quartile)
  104. std::sort(timings.begin(), timings.end());
  105. auto p25 = timings[num_trials / 4];
  106. // Format timings for output
  107. std::ostringstream timings_str;
  108. timings_str << "[";
  109. for (size_t i = 0; i < timings.size(); i++) {
  110. if (i > 0) timings_str << ", ";
  111. timings_str << timings[i];
  112. }
  113. timings_str << "]";
  114. // Localhost HTTP GET should be fast even in CI environments
  115. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  116. << "ms (Issue #1777). Timings: " << timings_str.str();
  117. }
  118. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  119. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  120. class UnixSocketTest : public ::testing::Test {
  121. protected:
  122. void TearDown() override { std::remove(pathname_.c_str()); }
  123. void client_GET(const std::string &addr) {
  124. httplib::Client cli{addr};
  125. cli.set_address_family(AF_UNIX);
  126. ASSERT_TRUE(cli.is_valid());
  127. const auto &result = cli.Get(pattern_);
  128. ASSERT_TRUE(result) << "error: " << result.error();
  129. const auto &resp = result.value();
  130. EXPECT_EQ(resp.status, StatusCode::OK_200);
  131. EXPECT_EQ(resp.body, content_);
  132. }
  133. const std::string pathname_{"./httplib-server.sock"};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. }
  154. #if defined(__linux__) || \
  155. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  156. TEST_F(UnixSocketTest, PeerPid) {
  157. httplib::Server svr;
  158. std::string remote_port_val;
  159. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. remote_port_val = std::to_string(req.remote_port);
  162. });
  163. std::thread t{[&] {
  164. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  165. }};
  166. auto se = detail::scope_exit([&] {
  167. svr.stop();
  168. t.join();
  169. ASSERT_FALSE(svr.is_running());
  170. });
  171. svr.wait_until_ready();
  172. ASSERT_TRUE(svr.is_running());
  173. client_GET(pathname_);
  174. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  175. }
  176. #endif
  177. #ifdef __linux__
  178. TEST_F(UnixSocketTest, abstract) {
  179. constexpr char svr_path[]{"\x00httplib-server.sock"};
  180. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  181. httplib::Server svr;
  182. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  183. res.set_content(content_, "text/plain");
  184. });
  185. std::thread t{[&] {
  186. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  187. }};
  188. auto se = detail::scope_exit([&] {
  189. svr.stop();
  190. t.join();
  191. ASSERT_FALSE(svr.is_running());
  192. });
  193. svr.wait_until_ready();
  194. ASSERT_TRUE(svr.is_running());
  195. client_GET(abstract_addr);
  196. }
  197. #endif
  198. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  199. httplib::Server svr;
  200. std::string received_host_header;
  201. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  202. // Capture the Host header sent by the client
  203. auto host_iter = req.headers.find("Host");
  204. if (host_iter != req.headers.end()) {
  205. received_host_header = host_iter->second;
  206. }
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. // Test that Host header is automatically set to "localhost" for Unix socket
  220. // connections
  221. httplib::Client cli{pathname_};
  222. cli.set_address_family(AF_UNIX);
  223. ASSERT_TRUE(cli.is_valid());
  224. const auto &result = cli.Get(pattern_);
  225. ASSERT_TRUE(result) << "error: " << result.error();
  226. const auto &resp = result.value();
  227. EXPECT_EQ(resp.status, StatusCode::OK_200);
  228. EXPECT_EQ(resp.body, content_);
  229. // Verify that Host header was automatically set to "localhost"
  230. EXPECT_EQ(received_host_header, "localhost");
  231. }
  232. #ifndef _WIN32
  233. TEST(SocketStream, wait_writable_UNIX) {
  234. int fds[2];
  235. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  236. const auto asSocketStream = [&](socket_t fd,
  237. std::function<bool(Stream &)> func) {
  238. return detail::process_client_socket(
  239. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  240. };
  241. asSocketStream(fds[0], [&](Stream &s0) {
  242. EXPECT_EQ(s0.socket(), fds[0]);
  243. EXPECT_TRUE(s0.wait_writable());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.wait_writable());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(PORT + 1);
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  261. ASSERT_EQ(0, listen(s, 1));
  262. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  263. ASSERT_EQ(0, close(s));
  264. }};
  265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  266. std::thread cli{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, close(s));
  271. }};
  272. cli.join();
  273. svr.join();
  274. ASSERT_NE(disconnected_svr_sock, -1);
  275. const auto asSocketStream = [&](socket_t fd,
  276. std::function<bool(Stream &)> func) {
  277. return detail::process_client_socket(
  278. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  279. };
  280. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  281. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  282. EXPECT_FALSE(ss.wait_writable());
  283. return true;
  284. });
  285. ASSERT_EQ(0, close(disconnected_svr_sock));
  286. }
  287. #endif // #ifndef _WIN32
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. u8"descrip=Gastos áéíóúñÑ 6");
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  317. string unescapedCharacters = "-_.!~*'()";
  318. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  319. }
  320. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  321. string reservedCharacters = ";,/?:@&=+$";
  322. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  323. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  324. }
  325. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  326. string chineseCharacters = u8"中国語";
  327. string russianCharacters = u8"дом";
  328. string brazilianCharacters = u8"óculos";
  329. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  330. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  331. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  332. "%D0%B4%D0%BE%D0%BC");
  333. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  334. }
  335. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  336. string unescapedCharacters = "-_.!~*'()";
  337. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  338. }
  339. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  340. string reservedCharacters = ";,/?:@&=+$";
  341. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  342. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  343. }
  344. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  345. string chineseCharacters = u8"中国語";
  346. string russianCharacters = u8"дом";
  347. string brazilianCharacters = u8"óculos";
  348. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  349. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  350. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  351. "%D0%B4%D0%BE%D0%BC");
  352. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  353. }
  354. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  355. // Issue #2082 use case: encoding path component with ampersand
  356. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  357. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  358. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  359. }
  360. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$#";
  366. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  367. }
  368. TEST(EncodeUriTest, TestUTF8Characters) {
  369. string chineseCharacters = u8"中国語";
  370. string russianCharacters = u8"дом";
  371. string brazilianCharacters = u8"óculos";
  372. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  373. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  374. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  375. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  376. }
  377. TEST(EncodeUriTest, TestCompleteUri) {
  378. string uri =
  379. "https://example.com/path/to/resource?query=value&param=test#fragment";
  380. EXPECT_EQ(
  381. httplib::encode_uri(uri),
  382. "https://example.com/path/to/resource?query=value&param=test#fragment");
  383. }
  384. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  385. string uri =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. EXPECT_EQ(httplib::encode_uri(uri),
  388. "https://example.com/path%20with%20spaces/"
  389. "file%20name.html?q=hello%20world");
  390. }
  391. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  392. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  393. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  394. }
  395. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  400. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  401. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  402. string encodedBrazilian = "%C3%B3culos";
  403. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  404. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  405. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  406. }
  407. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  408. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  409. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  410. "Piri Tommy Villiers - on & on");
  411. }
  412. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  413. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  414. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  415. }
  416. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  418. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  419. }
  420. TEST(DecodeUriTest, TestUTF8Characters) {
  421. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  422. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  423. string encodedBrazilian = "%C3%B3culos";
  424. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  425. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  426. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  427. }
  428. TEST(DecodeUriTest, TestCompleteUri) {
  429. string encodedUri = "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world";
  431. EXPECT_EQ(
  432. httplib::decode_uri(encodedUri),
  433. "https://example.com/path with spaces/file name.html?q=hello world");
  434. }
  435. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  436. string original =
  437. "https://example.com/path with spaces/file name.html?q=hello world";
  438. string encoded = httplib::encode_uri(original);
  439. string decoded = httplib::decode_uri(encoded);
  440. EXPECT_EQ(decoded, original);
  441. }
  442. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  443. string original = "Piri Tommy Villiers - on & on";
  444. string encoded = httplib::encode_uri_component(original);
  445. string decoded = httplib::decode_uri_component(encoded);
  446. EXPECT_EQ(decoded, original);
  447. }
  448. TEST(TrimTests, TrimStringTests) {
  449. EXPECT_EQ("abc", detail::trim_copy("abc"));
  450. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  451. EXPECT_TRUE(detail::trim_copy("").empty());
  452. }
  453. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  454. // Simple case without quality values
  455. std::vector<std::string> result1;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html,application/json,text/plain", result1));
  458. EXPECT_EQ(result1.size(), 3U);
  459. EXPECT_EQ(result1[0], "text/html");
  460. EXPECT_EQ(result1[1], "application/json");
  461. EXPECT_EQ(result1[2], "text/plain");
  462. // With quality values
  463. std::vector<std::string> result2;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  466. EXPECT_EQ(result2.size(), 3U);
  467. EXPECT_EQ(result2[0], "application/json"); // highest q value
  468. EXPECT_EQ(result2[1], "text/html");
  469. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  470. }
  471. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  472. // Mixed with and without quality values
  473. std::vector<std::string> result;
  474. EXPECT_TRUE(detail::parse_accept_header(
  475. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  476. EXPECT_EQ(result.size(), 3U);
  477. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  478. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  479. EXPECT_EQ(result[2], "application/json"); // q=0.5
  480. }
  481. TEST(ParseAcceptHeaderTest, EdgeCases) {
  482. // Empty header
  483. std::vector<std::string> empty_result;
  484. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  485. EXPECT_TRUE(empty_result.empty());
  486. // Single type
  487. std::vector<std::string> single_result;
  488. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  489. EXPECT_EQ(single_result.size(), 1U);
  490. EXPECT_EQ(single_result[0], "application/json");
  491. // Wildcard types
  492. std::vector<std::string> wildcard_result;
  493. EXPECT_TRUE(detail::parse_accept_header(
  494. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  495. EXPECT_EQ(wildcard_result.size(), 3U);
  496. EXPECT_EQ(wildcard_result[0], "application/json");
  497. EXPECT_EQ(wildcard_result[1], "text/*");
  498. EXPECT_EQ(wildcard_result[2], "*/*");
  499. }
  500. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  501. // Common browser Accept header
  502. std::vector<std::string> browser_result;
  503. EXPECT_TRUE(
  504. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  505. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  506. browser_result));
  507. EXPECT_EQ(browser_result.size(), 6U);
  508. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  509. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  510. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  513. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  514. // API client header
  515. std::vector<std::string> api_result;
  516. EXPECT_TRUE(detail::parse_accept_header(
  517. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  518. api_result));
  519. EXPECT_EQ(api_result.size(), 3U);
  520. EXPECT_EQ(api_result[0], "application/json");
  521. EXPECT_EQ(api_result[1], "application/xml");
  522. EXPECT_EQ(api_result[2], "text/plain");
  523. }
  524. TEST(ParseAcceptHeaderTest, SpecialCases) {
  525. // Quality value with 3 decimal places
  526. std::vector<std::string> decimal_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  529. EXPECT_EQ(decimal_result.size(), 2U);
  530. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  531. EXPECT_EQ(decimal_result[1], "text/html");
  532. // Zero quality (should still be included but with lowest priority)
  533. std::vector<std::string> zero_q_result;
  534. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  535. zero_q_result));
  536. EXPECT_EQ(zero_q_result.size(), 2U);
  537. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  538. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  539. // No spaces around commas
  540. std::vector<std::string> no_space_result;
  541. EXPECT_TRUE(detail::parse_accept_header(
  542. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  543. no_space_result));
  544. EXPECT_EQ(no_space_result.size(), 3U);
  545. EXPECT_EQ(no_space_result[0], "text/html");
  546. EXPECT_EQ(no_space_result[1], "application/json");
  547. EXPECT_EQ(no_space_result[2], "text/plain");
  548. }
  549. TEST(ParseAcceptHeaderTest, InvalidCases) {
  550. std::vector<std::string> result;
  551. // Invalid quality value (> 1.0)
  552. EXPECT_FALSE(
  553. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  554. // Invalid quality value (< 0.0)
  555. EXPECT_FALSE(
  556. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  557. // Invalid quality value (not a number)
  558. EXPECT_FALSE(detail::parse_accept_header(
  559. "text/html;q=invalid,application/json", result));
  560. // Empty quality value
  561. EXPECT_FALSE(
  562. detail::parse_accept_header("text/html;q=,application/json", result));
  563. // Invalid media type format (no slash and not wildcard)
  564. EXPECT_FALSE(
  565. detail::parse_accept_header("invalidtype,application/json", result));
  566. // Empty media type
  567. result.clear();
  568. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  569. // Only commas
  570. result.clear();
  571. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  572. // Valid cases should still work
  573. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  574. EXPECT_EQ(result.size(), 1U);
  575. EXPECT_EQ(result[0], "*/*");
  576. EXPECT_TRUE(detail::parse_accept_header("*", result));
  577. EXPECT_EQ(result.size(), 1U);
  578. EXPECT_EQ(result[0], "*");
  579. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  580. EXPECT_EQ(result.size(), 1U);
  581. EXPECT_EQ(result[0], "text/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  584. Server svr;
  585. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  586. EXPECT_EQ(req.accept_content_types.size(), 3U);
  587. EXPECT_EQ(req.accept_content_types[0], "application/json");
  588. EXPECT_EQ(req.accept_content_types[1], "text/html");
  589. EXPECT_EQ(req.accept_content_types[2], "*/*");
  590. res.set_content("ok", "text/plain");
  591. });
  592. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  593. EXPECT_TRUE(false);
  594. res.set_content("bad request", "text/plain");
  595. });
  596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  597. auto se = detail::scope_exit([&] {
  598. svr.stop();
  599. listen_thread.join();
  600. ASSERT_FALSE(svr.is_running());
  601. });
  602. svr.wait_until_ready();
  603. Client cli("localhost", PORT);
  604. {
  605. auto res =
  606. cli.Get("/accept_ok",
  607. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  608. ASSERT_TRUE(res);
  609. EXPECT_EQ(StatusCode::OK_200, res->status);
  610. }
  611. {
  612. auto res = cli.Get("/accept_bad_request",
  613. {{"Accept", "text/html;q=abc,application/json"}});
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  616. }
  617. }
  618. TEST(DivideTest, DivideStringTests) {
  619. auto divide = [](const std::string &str, char d) {
  620. std::string lhs;
  621. std::string rhs;
  622. detail::divide(str, d,
  623. [&](const char *lhs_data, std::size_t lhs_size,
  624. const char *rhs_data, std::size_t rhs_size) {
  625. lhs.assign(lhs_data, lhs_size);
  626. rhs.assign(rhs_data, rhs_size);
  627. });
  628. return std::make_pair(std::move(lhs), std::move(rhs));
  629. };
  630. {
  631. const auto res = divide("", '=');
  632. EXPECT_EQ(res.first, "");
  633. EXPECT_EQ(res.second, "");
  634. }
  635. {
  636. const auto res = divide("=", '=');
  637. EXPECT_EQ(res.first, "");
  638. EXPECT_EQ(res.second, "");
  639. }
  640. {
  641. const auto res = divide(" ", '=');
  642. EXPECT_EQ(res.first, " ");
  643. EXPECT_EQ(res.second, "");
  644. }
  645. {
  646. const auto res = divide("a", '=');
  647. EXPECT_EQ(res.first, "a");
  648. EXPECT_EQ(res.second, "");
  649. }
  650. {
  651. const auto res = divide("a=", '=');
  652. EXPECT_EQ(res.first, "a");
  653. EXPECT_EQ(res.second, "");
  654. }
  655. {
  656. const auto res = divide("=b", '=');
  657. EXPECT_EQ(res.first, "");
  658. EXPECT_EQ(res.second, "b");
  659. }
  660. {
  661. const auto res = divide("a=b", '=');
  662. EXPECT_EQ(res.first, "a");
  663. EXPECT_EQ(res.second, "b");
  664. }
  665. {
  666. const auto res = divide("a=b=", '=');
  667. EXPECT_EQ(res.first, "a");
  668. EXPECT_EQ(res.second, "b=");
  669. }
  670. {
  671. const auto res = divide("a=b=c", '=');
  672. EXPECT_EQ(res.first, "a");
  673. EXPECT_EQ(res.second, "b=c");
  674. }
  675. }
  676. TEST(SplitTest, ParseQueryString) {
  677. string s = "key1=val1&key2=val2&key3=val3";
  678. Params dic;
  679. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  680. [&](const char *b, const char *e) {
  681. string key, val;
  682. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  683. if (key.empty()) {
  684. key.assign(b2, e2);
  685. } else {
  686. val.assign(b2, e2);
  687. }
  688. });
  689. dic.emplace(key, val);
  690. });
  691. EXPECT_EQ("val1", dic.find("key1")->second);
  692. EXPECT_EQ("val2", dic.find("key2")->second);
  693. EXPECT_EQ("val3", dic.find("key3")->second);
  694. }
  695. TEST(SplitTest, ParseInvalidQueryTests) {
  696. {
  697. string s = " ";
  698. Params dict;
  699. detail::parse_query_text(s, dict);
  700. EXPECT_TRUE(dict.empty());
  701. }
  702. {
  703. string s = " = =";
  704. Params dict;
  705. detail::parse_query_text(s, dict);
  706. EXPECT_TRUE(dict.empty());
  707. }
  708. }
  709. TEST(ParseQueryTest, ParseQueryString) {
  710. {
  711. std::string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::parse_query_text(s, dic);
  714. EXPECT_EQ("val1", dic.find("key1")->second);
  715. EXPECT_EQ("val2", dic.find("key2")->second);
  716. EXPECT_EQ("val3", dic.find("key3")->second);
  717. }
  718. {
  719. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  720. Params dic;
  721. detail::parse_query_text(s, dic);
  722. EXPECT_EQ("", dic.find("key1")->second);
  723. EXPECT_EQ("val1", dic.find("key2")->second);
  724. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  725. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  726. }
  727. }
  728. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  729. Params dic;
  730. EXPECT_EQ(detail::params_to_query_str(dic), "");
  731. dic.emplace("key1", "val1");
  732. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  733. dic.emplace("key2", "val2");
  734. dic.emplace("key3", "val3");
  735. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  736. }
  737. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  738. string content_type = "multipart/form-data; boundary=something";
  739. string boundary;
  740. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  741. EXPECT_TRUE(ret);
  742. EXPECT_EQ(boundary, "something");
  743. }
  744. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  745. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  746. string boundary;
  747. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  748. EXPECT_TRUE(ret);
  749. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  750. }
  751. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  752. string content_type =
  753. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  754. string boundary;
  755. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  756. EXPECT_TRUE(ret);
  757. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  758. }
  759. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  760. string content_type =
  761. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  762. string boundary;
  763. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  764. EXPECT_TRUE(ret);
  765. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  766. }
  767. TEST(GetHeaderValueTest, DefaultValue) {
  768. Headers headers = {{"Dummy", "Dummy"}};
  769. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  770. EXPECT_STREQ("text/plain", val);
  771. }
  772. TEST(GetHeaderValueTest, DefaultValueInt) {
  773. Headers headers = {{"Dummy", "Dummy"}};
  774. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  775. EXPECT_EQ(100ull, val);
  776. }
  777. TEST(GetHeaderValueTest, RegularValue) {
  778. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  779. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  780. EXPECT_STREQ("text/html", val);
  781. }
  782. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  783. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  784. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  785. EXPECT_STREQ("text/html", val);
  786. }
  787. TEST(GetHeaderValueTest, SetContent) {
  788. Response res;
  789. res.set_content("html", "text/html");
  790. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  791. res.set_content("text", "text/plain");
  792. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  793. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  794. }
  795. TEST(GetHeaderValueTest, RegularValueInt) {
  796. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  798. EXPECT_EQ(100ull, val);
  799. }
  800. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  801. Headers headers = {{"Content-Length", "x"}};
  802. auto is_invalid_value = false;
  803. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  804. is_invalid_value);
  805. EXPECT_EQ(0ull, val);
  806. EXPECT_TRUE(is_invalid_value);
  807. }
  808. TEST(GetHeaderValueTest, Range) {
  809. {
  810. Headers headers = {make_range_header({{1, -1}})};
  811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  812. EXPECT_STREQ("bytes=1-", val);
  813. }
  814. {
  815. Headers headers = {make_range_header({{-1, 1}})};
  816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  817. EXPECT_STREQ("bytes=-1", val);
  818. }
  819. {
  820. Headers headers = {make_range_header({{1, 10}})};
  821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  822. EXPECT_STREQ("bytes=1-10", val);
  823. }
  824. {
  825. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  827. EXPECT_STREQ("bytes=1-10, 100-", val);
  828. }
  829. {
  830. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  832. EXPECT_STREQ("bytes=1-10, 100-200", val);
  833. }
  834. {
  835. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  837. EXPECT_STREQ("bytes=0-0, -1", val);
  838. }
  839. }
  840. TEST(ParseHeaderValueTest, Range) {
  841. {
  842. Ranges ranges;
  843. auto ret = detail::parse_range_header("bytes=1-", ranges);
  844. EXPECT_TRUE(ret);
  845. EXPECT_EQ(1u, ranges.size());
  846. EXPECT_EQ(1u, ranges[0].first);
  847. EXPECT_EQ(-1, ranges[0].second);
  848. }
  849. {
  850. Ranges ranges;
  851. auto ret = detail::parse_range_header("bytes=-1", ranges);
  852. EXPECT_TRUE(ret);
  853. EXPECT_EQ(1u, ranges.size());
  854. EXPECT_EQ(-1, ranges[0].first);
  855. EXPECT_EQ(1u, ranges[0].second);
  856. }
  857. {
  858. Ranges ranges;
  859. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  860. EXPECT_TRUE(ret);
  861. EXPECT_EQ(1u, ranges.size());
  862. EXPECT_EQ(1u, ranges[0].first);
  863. EXPECT_EQ(10u, ranges[0].second);
  864. }
  865. {
  866. Ranges ranges;
  867. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  868. EXPECT_FALSE(ret);
  869. }
  870. {
  871. Ranges ranges;
  872. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  873. EXPECT_TRUE(ret);
  874. EXPECT_EQ(2u, ranges.size());
  875. EXPECT_EQ(1u, ranges[0].first);
  876. EXPECT_EQ(10u, ranges[0].second);
  877. EXPECT_EQ(100u, ranges[1].first);
  878. EXPECT_EQ(-1, ranges[1].second);
  879. }
  880. {
  881. Ranges ranges;
  882. auto ret =
  883. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  884. EXPECT_TRUE(ret);
  885. EXPECT_EQ(3u, ranges.size());
  886. EXPECT_EQ(1u, ranges[0].first);
  887. EXPECT_EQ(10u, ranges[0].second);
  888. EXPECT_EQ(100u, ranges[1].first);
  889. EXPECT_EQ(200u, ranges[1].second);
  890. EXPECT_EQ(300u, ranges[2].first);
  891. EXPECT_EQ(400u, ranges[2].second);
  892. }
  893. {
  894. Ranges ranges;
  895. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  896. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  897. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  908. EXPECT_TRUE(ranges.empty());
  909. }
  910. }
  911. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  912. Request req;
  913. req.set_header("Accept-Encoding", "gzip");
  914. Response res;
  915. res.set_header("Content-Type", "text/plain");
  916. auto ret = detail::encoding_type(req, res);
  917. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  918. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  919. #else
  920. EXPECT_TRUE(ret == detail::EncodingType::None);
  921. #endif
  922. }
  923. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  924. Request req;
  925. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  926. Response res;
  927. res.set_header("Content-Type", "text/plain");
  928. auto ret = detail::encoding_type(req, res);
  929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  930. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  931. #elif CPPHTTPLIB_ZLIB_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  933. #elif CPPHTTPLIB_ZSTD_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  935. #else
  936. EXPECT_TRUE(ret == detail::EncodingType::None);
  937. #endif
  938. }
  939. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding",
  942. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  943. Response res;
  944. res.set_header("Content-Type", "text/plain");
  945. auto ret = detail::encoding_type(req, res);
  946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  947. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  948. #elif CPPHTTPLIB_ZLIB_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  950. #elif CPPHTTPLIB_ZSTD_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  952. #else
  953. EXPECT_TRUE(ret == detail::EncodingType::None);
  954. #endif
  955. }
  956. TEST(BufferStreamTest, read) {
  957. detail::BufferStream strm1;
  958. Stream &strm = strm1;
  959. EXPECT_EQ(5, strm.write("hello"));
  960. char buf[512];
  961. EXPECT_EQ(2, strm.read(buf, 2));
  962. EXPECT_EQ('h', buf[0]);
  963. EXPECT_EQ('e', buf[1]);
  964. EXPECT_EQ(2, strm.read(buf, 2));
  965. EXPECT_EQ('l', buf[0]);
  966. EXPECT_EQ('l', buf[1]);
  967. EXPECT_EQ(1, strm.read(buf, 1));
  968. EXPECT_EQ('o', buf[0]);
  969. EXPECT_EQ(0, strm.read(buf, 1));
  970. }
  971. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  972. auto host = "www.httpwatch.com";
  973. auto ip = hosted_at(host);
  974. EXPECT_EQ("23.96.13.243", ip);
  975. std::vector<std::string> addrs;
  976. hosted_at(host, addrs);
  977. EXPECT_EQ(1u, addrs.size());
  978. }
  979. #if 0 // It depends on each test environment...
  980. TEST(HostnameToIPConversionTest, YouTube_Online) {
  981. auto host = "www.youtube.com";
  982. std::vector<std::string> addrs;
  983. hosted_at(host, addrs);
  984. EXPECT_EQ(20u, addrs.size());
  985. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  986. EXPECT_TRUE(it != addrs.end());
  987. }
  988. #endif
  989. class ChunkedEncodingTest : public ::testing::Test {
  990. protected:
  991. ChunkedEncodingTest()
  992. : cli_(HOST, PORT)
  993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  994. ,
  995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  996. #endif
  997. {
  998. cli_.set_connection_timeout(2);
  999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1000. cli_.enable_server_certificate_verification(false);
  1001. #endif
  1002. }
  1003. virtual void SetUp() {
  1004. read_file("./image.jpg", image_data_);
  1005. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1006. res.set_content("Hello World!", "text/plain");
  1007. });
  1008. svr_.Get(
  1009. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1010. res.set_chunked_content_provider(
  1011. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1012. size_t remaining = image_data_.size() - offset;
  1013. if (remaining == 0) {
  1014. sink.done();
  1015. } else {
  1016. constexpr size_t CHUNK_SIZE = 1024;
  1017. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1018. sink.write(&image_data_[offset], send_size);
  1019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1020. }
  1021. return true;
  1022. });
  1023. });
  1024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1025. svr_.wait_until_ready();
  1026. }
  1027. virtual void TearDown() {
  1028. svr_.stop();
  1029. if (!request_threads_.empty()) {
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. for (auto &t : request_threads_) {
  1032. t.join();
  1033. }
  1034. }
  1035. t_.join();
  1036. }
  1037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1038. SSLClient cli_;
  1039. SSLServer svr_;
  1040. #else
  1041. Client cli_;
  1042. Server svr_;
  1043. #endif
  1044. thread t_;
  1045. std::vector<thread> request_threads_;
  1046. std::string image_data_;
  1047. };
  1048. TEST_F(ChunkedEncodingTest, NormalGet) {
  1049. auto res = cli_.Get("/chunked");
  1050. ASSERT_TRUE(res);
  1051. std::string out;
  1052. read_file("./image.jpg", out);
  1053. EXPECT_EQ(StatusCode::OK_200, res->status);
  1054. EXPECT_EQ(out, res->body);
  1055. }
  1056. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1057. std::string body;
  1058. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1059. body.append(data, data_length);
  1060. return true;
  1061. });
  1062. ASSERT_TRUE(res);
  1063. std::string out;
  1064. read_file("./image.jpg", out);
  1065. EXPECT_EQ(StatusCode::OK_200, res->status);
  1066. EXPECT_EQ(out, body);
  1067. }
  1068. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1069. std::string body;
  1070. auto res = cli_.Get(
  1071. "/chunked",
  1072. [&](const Response &response) {
  1073. EXPECT_EQ(StatusCode::OK_200, response.status);
  1074. return true;
  1075. },
  1076. [&](const char *data, size_t data_length) {
  1077. body.append(data, data_length);
  1078. return true;
  1079. });
  1080. ASSERT_TRUE(res);
  1081. std::string out;
  1082. read_file("./image.jpg", out);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. EXPECT_EQ(out, body);
  1085. }
  1086. TEST(RangeTest, FromHTTPBin_Online) {
  1087. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1088. auto host = "httpbin.org";
  1089. auto path = std::string{"/range/32"};
  1090. #else
  1091. auto host = "nghttp2.org";
  1092. auto path = std::string{"/httpbin/range/32"};
  1093. #endif
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(5);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{1, -1}})};
  1110. auto res = cli.Get(path, headers);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto res = cli.Get(path, headers);
  1118. ASSERT_TRUE(res);
  1119. EXPECT_EQ("bcdefghijk", res->body);
  1120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 31}})};
  1124. auto res = cli.Get(path, headers);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1127. EXPECT_EQ(StatusCode::OK_200, res->status);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{0, -1}})};
  1131. auto res = cli.Get(path, headers);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{0, 32}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1141. }
  1142. }
  1143. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1144. auto host = "unresolvableaddress.local";
  1145. auto path = std::string{"/"};
  1146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1147. auto port = 443;
  1148. SSLClient cli(host, port);
  1149. #else
  1150. auto port = 80;
  1151. Client cli(host, port);
  1152. #endif
  1153. cli.set_connection_timeout(1);
  1154. {
  1155. auto res = cli.Get(path);
  1156. ASSERT_FALSE(res);
  1157. }
  1158. std::this_thread::sleep_for(std::chrono::seconds(8));
  1159. }
  1160. TEST(ConnectionErrorTest, InvalidHost) {
  1161. auto host = "-abcde.com";
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. auto port = 443;
  1164. SSLClient cli(host, port);
  1165. #else
  1166. auto port = 80;
  1167. Client cli(host, port);
  1168. #endif
  1169. cli.set_connection_timeout(std::chrono::seconds(2));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Connection, res.error());
  1173. }
  1174. TEST(ConnectionErrorTest, InvalidHost2) {
  1175. auto host = "httpbin.org/";
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. SSLClient cli(host);
  1178. #else
  1179. Client cli(host);
  1180. #endif
  1181. cli.set_connection_timeout(std::chrono::seconds(2));
  1182. auto res = cli.Get("/");
  1183. ASSERT_TRUE(!res);
  1184. EXPECT_EQ(Error::Connection, res.error());
  1185. }
  1186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1187. auto host = "httpbin.org/";
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. SSLClient cli(host);
  1190. #else
  1191. Client cli(host);
  1192. #endif
  1193. cli.set_connection_timeout(std::chrono::seconds(2));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(!res);
  1196. stringstream s;
  1197. s << "error code: " << res.error();
  1198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1199. }
  1200. TEST(ConnectionErrorTest, InvalidPort) {
  1201. auto host = "localhost";
  1202. auto port = 44380;
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host, port);
  1205. #else
  1206. Client cli(host, port);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_TRUE(Error::Connection == res.error() ||
  1212. Error::ConnectionTimeout == res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, Timeout_Online) {
  1215. auto host = "google.com";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. auto port = 44380;
  1218. SSLClient cli(host, port);
  1219. #else
  1220. auto port = 8080;
  1221. Client cli(host, port);
  1222. #endif
  1223. cli.set_connection_timeout(std::chrono::seconds(2));
  1224. // only probe one address type so that the error reason
  1225. // correlates to the timed-out IPv4, not the unsupported
  1226. // IPv6 connection attempt
  1227. cli.set_address_family(AF_INET);
  1228. auto res = cli.Get("/");
  1229. ASSERT_TRUE(!res);
  1230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1231. }
  1232. TEST(CancelTest, NoCancel_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpbin.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1249. ASSERT_TRUE(res);
  1250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1251. EXPECT_EQ(StatusCode::OK_200, res->status);
  1252. }
  1253. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1254. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1255. auto host = "httpbin.org";
  1256. auto path = std::string{"/range/32"};
  1257. #else
  1258. auto host = "nghttp2.org";
  1259. auto path = std::string{"/httpbin/range/32"};
  1260. #endif
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Canceled, res.error());
  1272. }
  1273. TEST(CancelTest, WithCancelLargePayload_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpbin.org";
  1276. auto path = std::string{"/range/65536"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/65536"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. uint32_t count = 0;
  1290. auto res =
  1291. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, NoCancelPost) {
  1296. Server svr;
  1297. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return true; });
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ("Hello World!", res->body);
  1314. EXPECT_EQ(StatusCode::OK_200, res->status);
  1315. }
  1316. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1317. Server svr;
  1318. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return false; });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, WithCancelLargePayloadPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content(LARGE_DATA, "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, NoCancelPut) {
  1357. Server svr;
  1358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content("Hello World!", "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return true; });
  1373. ASSERT_TRUE(res);
  1374. EXPECT_EQ("Hello World!", res->body);
  1375. EXPECT_EQ(StatusCode::OK_200, res->status);
  1376. }
  1377. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1378. Server svr;
  1379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, WithCancelLargePayloadPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content(LARGE_DATA, "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, NoCancelPatch) {
  1418. Server svr;
  1419. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content("Hello World!", "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return true; });
  1434. ASSERT_TRUE(res);
  1435. EXPECT_EQ("Hello World!", res->body);
  1436. EXPECT_EQ(StatusCode::OK_200, res->status);
  1437. }
  1438. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1439. Server svr;
  1440. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content("Hello World!", "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content(LARGE_DATA, "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return false; });
  1475. ASSERT_TRUE(!res);
  1476. EXPECT_EQ(Error::Canceled, res.error());
  1477. }
  1478. TEST(CancelTest, NoCancelDelete) {
  1479. Server svr;
  1480. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return true; });
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ("Hello World!", res->body);
  1497. EXPECT_EQ(StatusCode::OK_200, res->status);
  1498. }
  1499. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1500. Server svr;
  1501. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content("Hello World!", "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content(LARGE_DATA, "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return false; });
  1536. ASSERT_TRUE(!res);
  1537. EXPECT_EQ(Error::Canceled, res.error());
  1538. }
  1539. static std::string remove_whitespace(const std::string &input) {
  1540. std::string output;
  1541. output.reserve(input.size());
  1542. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1543. [](unsigned char c) { return !std::isspace(c); });
  1544. return output;
  1545. }
  1546. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1547. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1548. auto host = "httpbin.org";
  1549. auto path = std::string{"/basic-auth/hello/world"};
  1550. #else
  1551. auto host = "nghttp2.org";
  1552. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1553. #endif
  1554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1555. auto port = 443;
  1556. SSLClient cli(host, port);
  1557. #else
  1558. auto port = 80;
  1559. Client cli(host, port);
  1560. #endif
  1561. {
  1562. auto res = cli.Get(path);
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1565. }
  1566. {
  1567. auto res =
  1568. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1571. remove_whitespace(res->body));
  1572. EXPECT_EQ(StatusCode::OK_200, res->status);
  1573. }
  1574. {
  1575. cli.set_basic_auth("hello", "world");
  1576. auto res = cli.Get(path);
  1577. ASSERT_TRUE(res);
  1578. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1579. remove_whitespace(res->body));
  1580. EXPECT_EQ(StatusCode::OK_200, res->status);
  1581. }
  1582. {
  1583. cli.set_basic_auth("hello", "bad");
  1584. auto res = cli.Get(path);
  1585. ASSERT_TRUE(res);
  1586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1587. }
  1588. {
  1589. cli.set_basic_auth("bad", "world");
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. }
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1597. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1598. auto host = "httpbin.org";
  1599. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1600. auto paths = std::vector<std::string>{
  1601. "/digest-auth/auth/hello/world/MD5",
  1602. "/digest-auth/auth/hello/world/SHA-256",
  1603. "/digest-auth/auth/hello/world/SHA-512",
  1604. "/digest-auth/auth-int/hello/world/MD5",
  1605. };
  1606. #else
  1607. auto host = "nghttp2.org";
  1608. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1609. auto paths = std::vector<std::string>{
  1610. "/httpbin/digest-auth/auth/hello/world/MD5",
  1611. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1612. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1613. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1614. };
  1615. #endif
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. {
  1619. auto res = cli.Get(unauth_path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_digest_auth("hello", "world");
  1625. for (const auto &path : paths) {
  1626. auto res = cli.Get(path.c_str());
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. cli.set_digest_auth("hello", "bad");
  1633. for (const auto &path : paths) {
  1634. auto res = cli.Get(path.c_str());
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1637. }
  1638. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1639. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1640. // cli.set_digest_auth("bad", "world");
  1641. // for (const auto& path : paths) {
  1642. // auto res = cli.Get(path.c_str());
  1643. // ASSERT_TRUE(res);
  1644. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1645. // }
  1646. }
  1647. }
  1648. #endif
  1649. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1650. auto host = "google.com";
  1651. auto another_host = "example.com";
  1652. auto wrong_ip = "0.0.0.0";
  1653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. }
  1663. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1664. auto host = "google.com";
  1665. auto wrong_ip = "0.0.0.0";
  1666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1667. SSLClient cli(host);
  1668. #else
  1669. Client cli(host);
  1670. #endif
  1671. cli.set_hostname_addr_map({{host, wrong_ip}});
  1672. auto res = cli.Get("/");
  1673. ASSERT_TRUE(!res);
  1674. EXPECT_EQ(Error::Connection, res.error());
  1675. }
  1676. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1677. auto host = "nghttp2.org";
  1678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1679. SSLClient cli(host);
  1680. #else
  1681. Client cli(host);
  1682. #endif
  1683. cli.set_follow_location(true);
  1684. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(RedirectTest, Redirect_Online) {
  1689. auto host = "nghttp2.org";
  1690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1691. SSLClient cli(host);
  1692. #else
  1693. Client cli(host);
  1694. #endif
  1695. cli.set_follow_location(true);
  1696. auto res = cli.Get("/httpbin/redirect/3");
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(RelativeRedirectTest, Redirect_Online) {
  1701. auto host = "nghttp2.org";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_follow_location(true);
  1708. auto res = cli.Get("/httpbin/relative-redirect/3");
  1709. ASSERT_TRUE(res);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. }
  1712. TEST(TooManyRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/redirect/21");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1723. }
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. TEST(YahooRedirectTest, Redirect_Online) {
  1726. Client cli("yahoo.com");
  1727. auto res = cli.Get("/");
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1730. cli.set_follow_location(true);
  1731. res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(StatusCode::OK_200, res->status);
  1734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1735. }
  1736. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1737. #define REDIR_HOST "httpbingo.org"
  1738. #define REDIR_PATH "/redirect-to"
  1739. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1740. SSLClient cli(REDIR_HOST);
  1741. cli.set_follow_location(true);
  1742. auto res =
  1743. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1748. SSLClient cli(REDIR_HOST);
  1749. cli.set_follow_location(true);
  1750. Params params;
  1751. params.emplace("url", "http://example.com");
  1752. params.emplace("status_code", "302");
  1753. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1758. SSLClient cli(REDIR_HOST);
  1759. cli.set_follow_location(true);
  1760. Params params;
  1761. params.emplace("url", "http://example.com");
  1762. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::OK_200, res->status);
  1765. }
  1766. TEST(UrlWithSpace, Redirect_Online) {
  1767. SSLClient cli("edge.forgecdn.net");
  1768. cli.set_follow_location(true);
  1769. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1773. }
  1774. #endif
  1775. #if !defined(_WIN32) && !defined(_WIN64)
  1776. TEST(ReceiveSignals, Signal) {
  1777. auto setupSignalHandlers = []() {
  1778. struct sigaction act;
  1779. sigemptyset(&act.sa_mask);
  1780. act.sa_flags = SA_SIGINFO;
  1781. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1782. switch (sig) {
  1783. case SIGINT:
  1784. default: break;
  1785. }
  1786. };
  1787. ::sigaction(SIGINT, &act, nullptr);
  1788. };
  1789. Server svr;
  1790. int port = 0;
  1791. auto thread = std::thread([&]() {
  1792. setupSignalHandlers();
  1793. port = svr.bind_to_any_port("localhost");
  1794. svr.listen_after_bind();
  1795. });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. thread.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. svr.wait_until_ready();
  1802. ASSERT_TRUE(svr.is_running());
  1803. pthread_kill(thread.native_handle(), SIGINT);
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1805. ASSERT_TRUE(svr.is_running());
  1806. }
  1807. #endif
  1808. TEST(RedirectToDifferentPort, Redirect) {
  1809. Server svr1;
  1810. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1811. res.set_content("Hello World!", "text/plain");
  1812. });
  1813. int svr1_port = 0;
  1814. auto thread1 = std::thread([&]() {
  1815. svr1_port = svr1.bind_to_any_port("localhost");
  1816. svr1.listen_after_bind();
  1817. });
  1818. Server svr2;
  1819. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1820. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1821. });
  1822. int svr2_port = 0;
  1823. auto thread2 = std::thread([&]() {
  1824. svr2_port = svr2.bind_to_any_port("localhost");
  1825. svr2.listen_after_bind();
  1826. });
  1827. auto se = detail::scope_exit([&] {
  1828. svr2.stop();
  1829. thread2.join();
  1830. svr1.stop();
  1831. thread1.join();
  1832. ASSERT_FALSE(svr2.is_running());
  1833. ASSERT_FALSE(svr1.is_running());
  1834. });
  1835. svr1.wait_until_ready();
  1836. svr2.wait_until_ready();
  1837. Client cli("localhost", svr2_port);
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/2");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("Hello World!", res->body);
  1843. }
  1844. TEST(RedirectFromPageWithContent, Redirect) {
  1845. Server svr;
  1846. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("___", "text/plain");
  1848. res.set_redirect("/2");
  1849. });
  1850. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. th.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli("localhost", PORT);
  1862. cli.set_follow_location(true);
  1863. std::string body;
  1864. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1865. body.append(data, data_length);
  1866. return true;
  1867. });
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", body);
  1871. }
  1872. {
  1873. Client cli("localhost", PORT);
  1874. std::string body;
  1875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1876. body.append(data, data_length);
  1877. return true;
  1878. });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(StatusCode::Found_302, res->status);
  1881. EXPECT_EQ("___", body);
  1882. }
  1883. }
  1884. TEST(RedirectFromPageWithContentIP6, 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. res.set_redirect("http://[::1]:1234/2");
  1890. });
  1891. svr.Get("/2", [&](const Request &req, Response &res) {
  1892. auto host_header = req.headers.find("Host");
  1893. ASSERT_TRUE(host_header != req.headers.end());
  1894. EXPECT_EQ("[::1]:1234", host_header->second);
  1895. res.set_content("Hello World!", "text/plain");
  1896. });
  1897. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. th.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1904. // actually starts anything, so the condition !svr.is_running() will
  1905. // always remain true, and the loop never stops.
  1906. // This basically counts how many milliseconds have passed since the
  1907. // call to svr.listen(), and if after 5 seconds nothing started yet
  1908. // aborts the test.
  1909. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1911. ASSERT_LT(milliseconds, 5000U);
  1912. }
  1913. {
  1914. Client cli("http://[::1]:1234");
  1915. cli.set_follow_location(true);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ("Hello World!", body);
  1924. }
  1925. {
  1926. Client cli("http://[::1]:1234");
  1927. std::string body;
  1928. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1929. body.append(data, data_length);
  1930. return true;
  1931. });
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::Found_302, res->status);
  1934. EXPECT_EQ("___", body);
  1935. }
  1936. }
  1937. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1938. Server svr;
  1939. svr.Get("/foo", [](const Request &req, Response &res) {
  1940. auto a = req.params.find("a");
  1941. if (a != req.params.end()) {
  1942. res.set_content((*a).second, "text/plain");
  1943. res.status = StatusCode::OK_200;
  1944. } else {
  1945. res.status = StatusCode::BadRequest_400;
  1946. }
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. cli.set_path_encode(false);
  1958. auto res = cli.Get("/foo?a=explicitly+encoded");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // This expects it back with a space, as the `+` won't have been
  1962. // url-encoded, and server-side the params get decoded turning `+`
  1963. // into spaces.
  1964. EXPECT_EQ("explicitly encoded", res->body);
  1965. }
  1966. }
  1967. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1968. Server svr;
  1969. svr.Get("/", [](const Request &req, Response &) {
  1970. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_path_encode(false);
  1982. auto res = cli.Get("/?something=%0A");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. }
  1987. TEST(BindServerTest, DISABLED_BindDualStack) {
  1988. Server svr;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("Hello World!", "text/plain");
  1991. });
  1992. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1993. auto se = detail::scope_exit([&] {
  1994. svr.stop();
  1995. thread.join();
  1996. ASSERT_FALSE(svr.is_running());
  1997. });
  1998. svr.wait_until_ready();
  1999. {
  2000. Client cli("127.0.0.1", PORT);
  2001. auto res = cli.Get("/1");
  2002. ASSERT_TRUE(res);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ("Hello World!", res->body);
  2005. }
  2006. {
  2007. Client cli("::1", PORT);
  2008. auto res = cli.Get("/1");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", res->body);
  2012. }
  2013. }
  2014. TEST(BindServerTest, BindAndListenSeparately) {
  2015. Server svr;
  2016. int port = svr.bind_to_any_port("0.0.0.0");
  2017. ASSERT_TRUE(svr.is_valid());
  2018. ASSERT_TRUE(port > 0);
  2019. svr.stop();
  2020. }
  2021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2022. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2024. CLIENT_CA_CERT_DIR);
  2025. int port = svr.bind_to_any_port("0.0.0.0");
  2026. ASSERT_TRUE(svr.is_valid());
  2027. ASSERT_TRUE(port > 0);
  2028. svr.stop();
  2029. }
  2030. #endif
  2031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2032. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2033. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2034. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2035. int port = svr.bind_to_any_port("0.0.0.0");
  2036. ASSERT_TRUE(svr.is_valid());
  2037. ASSERT_TRUE(port > 0);
  2038. svr.stop();
  2039. }
  2040. #endif
  2041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2042. X509 *readCertificate(const std::string &strFileName) {
  2043. std::ifstream inStream(strFileName);
  2044. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2045. std::istreambuf_iterator<char>());
  2046. if (strCertPEM.empty()) return (nullptr);
  2047. BIO *pbCert = BIO_new(BIO_s_mem());
  2048. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2049. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2050. BIO_free(pbCert);
  2051. return (pCert);
  2052. }
  2053. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2054. std::ifstream inStream(strFileName);
  2055. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2056. std::istreambuf_iterator<char>());
  2057. if (strPrivateKeyPEM.empty()) return (nullptr);
  2058. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2059. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2060. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2061. BIO_free(pbPrivKey);
  2062. return (pPrivateKey);
  2063. }
  2064. TEST(BindServerTest, UpdateCerts) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2070. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2071. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2072. ASSERT_TRUE(cert != nullptr);
  2073. ASSERT_TRUE(ca_cert != nullptr);
  2074. ASSERT_TRUE(key != nullptr);
  2075. X509_STORE *cert_store = X509_STORE_new();
  2076. X509_STORE_add_cert(cert_store, ca_cert);
  2077. svr.update_certs(cert, key, cert_store);
  2078. ASSERT_TRUE(svr.is_valid());
  2079. svr.stop();
  2080. X509_free(cert);
  2081. X509_free(ca_cert);
  2082. EVP_PKEY_free(key);
  2083. }
  2084. #endif
  2085. TEST(ErrorHandlerTest, ContentLength) {
  2086. Server svr;
  2087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2088. res.status = StatusCode::OK_200;
  2089. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2090. "text/html"); // <= Content-Length still 13
  2091. });
  2092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!\n", "text/plain");
  2094. res.status = 524;
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. {
  2104. Client cli(HOST, PORT);
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::OK_200, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. }
  2113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2114. TEST(ExceptionTest, WithoutExceptionHandler) {
  2115. Server svr;
  2116. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2117. throw std::runtime_error("exception...");
  2118. });
  2119. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2120. throw std::runtime_error("exception\r\n...");
  2121. });
  2122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2123. auto se = detail::scope_exit([&] {
  2124. svr.stop();
  2125. listen_thread.join();
  2126. ASSERT_FALSE(svr.is_running());
  2127. });
  2128. svr.wait_until_ready();
  2129. Client cli("localhost", PORT);
  2130. {
  2131. auto res = cli.Get("/exception");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2135. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2136. }
  2137. {
  2138. auto res = cli.Get("/unknown");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2141. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2142. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2143. }
  2144. }
  2145. TEST(ExceptionTest, WithExceptionHandler) {
  2146. Server svr;
  2147. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2148. std::exception_ptr ep) {
  2149. EXPECT_FALSE(ep == nullptr);
  2150. try {
  2151. std::rethrow_exception(ep);
  2152. } catch (std::exception &e) {
  2153. EXPECT_EQ("abc", std::string(e.what()));
  2154. } catch (...) {}
  2155. res.status = StatusCode::InternalServerError_500;
  2156. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2157. "text/html"); // <= Content-Length still 13 at this point
  2158. });
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!\n", "text/plain");
  2161. throw std::runtime_error("abc");
  2162. });
  2163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. for (size_t i = 0; i < 10; i++) {
  2171. Client cli(HOST, PORT);
  2172. for (size_t j = 0; j < 100; j++) {
  2173. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2179. }
  2180. cli.set_keep_alive(true);
  2181. for (size_t j = 0; j < 100; j++) {
  2182. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2186. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2187. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2188. }
  2189. }
  2190. }
  2191. TEST(ExceptionTest, AndErrorHandler) {
  2192. Server svr;
  2193. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2194. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2195. });
  2196. svr.set_exception_handler(
  2197. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. res.set_content(e.what(), "text/html");
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. });
  2206. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2207. throw std::runtime_error("EXCEPTION");
  2208. });
  2209. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2210. res.set_content("ERROR", "text/html");
  2211. res.status = StatusCode::InternalServerError_500;
  2212. });
  2213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2214. auto se = detail::scope_exit([&] {
  2215. svr.stop();
  2216. thread.join();
  2217. ASSERT_FALSE(svr.is_running());
  2218. });
  2219. svr.wait_until_ready();
  2220. Client cli(HOST, PORT);
  2221. {
  2222. auto res = cli.Get("/exception");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2225. EXPECT_EQ("EXCEPTION", res->body);
  2226. }
  2227. {
  2228. auto res = cli.Get("/error");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2231. EXPECT_EQ("ERROR", res->body);
  2232. }
  2233. {
  2234. auto res = cli.Get("/invalid");
  2235. ASSERT_TRUE(res);
  2236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2237. EXPECT_EQ("NOT_FOUND", res->body);
  2238. }
  2239. }
  2240. #endif
  2241. TEST(NoContentTest, ContentLength) {
  2242. Server svr;
  2243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2244. res.status = StatusCode::NoContent_204;
  2245. });
  2246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2247. auto se = detail::scope_exit([&] {
  2248. svr.stop();
  2249. thread.join();
  2250. ASSERT_FALSE(svr.is_running());
  2251. });
  2252. svr.wait_until_ready();
  2253. {
  2254. Client cli(HOST, PORT);
  2255. auto res = cli.Get("/hi");
  2256. ASSERT_TRUE(res);
  2257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2259. }
  2260. }
  2261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2264. ASSERT_TRUE(svr.is_valid());
  2265. #else
  2266. Server svr;
  2267. #endif
  2268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2269. if (req.path == "/routing_handler") {
  2270. res.set_header("PRE_ROUTING", "on");
  2271. res.set_content("Routing Handler", "text/plain");
  2272. return httplib::Server::HandlerResponse::Handled;
  2273. }
  2274. return httplib::Server::HandlerResponse::Unhandled;
  2275. });
  2276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2277. res.set_content("Error", "text/html");
  2278. });
  2279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2280. if (req.path == "/routing_handler") {
  2281. res.set_header("POST_ROUTING", "on");
  2282. }
  2283. });
  2284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!\n", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. {
  2295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2296. SSLClient cli(HOST, PORT);
  2297. cli.enable_server_certificate_verification(false);
  2298. #else
  2299. Client cli(HOST, PORT);
  2300. #endif
  2301. auto res = cli.Get("/routing_handler");
  2302. ASSERT_TRUE(res);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ("Routing Handler", res->body);
  2305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2309. }
  2310. {
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli(HOST, PORT);
  2313. cli.enable_server_certificate_verification(false);
  2314. #else
  2315. Client cli(HOST, PORT);
  2316. #endif
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!\n", res->body);
  2321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2323. }
  2324. {
  2325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2326. SSLClient cli(HOST, PORT);
  2327. cli.enable_server_certificate_verification(false);
  2328. #else
  2329. Client cli(HOST, PORT);
  2330. #endif
  2331. auto res = cli.Get("/aaa");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2334. EXPECT_EQ("Error", res->body);
  2335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2337. }
  2338. }
  2339. TEST(RequestHandlerTest, PreRequestHandler) {
  2340. auto route_path = "/user/:user";
  2341. Server svr;
  2342. svr.Get("/hi", [](const Request &, Response &res) {
  2343. res.set_content("hi", "text/plain");
  2344. });
  2345. svr.Get(route_path, [](const Request &req, Response &res) {
  2346. res.set_content(req.path_params.at("user"), "text/plain");
  2347. });
  2348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2349. if (req.matched_route == route_path) {
  2350. auto user = req.path_params.at("user");
  2351. if (user != "john") {
  2352. res.status = StatusCode::Forbidden_403;
  2353. res.set_content("error", "text/html");
  2354. return Server::HandlerResponse::Handled;
  2355. }
  2356. }
  2357. return Server::HandlerResponse::Unhandled;
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. {
  2368. auto res = cli.Get("/hi");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. EXPECT_EQ("hi", res->body);
  2372. }
  2373. {
  2374. auto res = cli.Get("/user/john");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("john", res->body);
  2378. }
  2379. {
  2380. auto res = cli.Get("/user/invalid-user");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2383. EXPECT_EQ("error", res->body);
  2384. }
  2385. }
  2386. TEST(InvalidFormatTest, StatusCode) {
  2387. Server svr;
  2388. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2389. res.set_content("Hello World!\n", "text/plain");
  2390. res.status = 9999; // Status should be a three-digit code...
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. {
  2400. Client cli(HOST, PORT);
  2401. auto res = cli.Get("/hi");
  2402. ASSERT_FALSE(res);
  2403. }
  2404. }
  2405. TEST(URLFragmentTest, WithFragment) {
  2406. Server svr;
  2407. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2408. EXPECT_TRUE(req.target == "/hi");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. {
  2418. Client cli(HOST, PORT);
  2419. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2420. EXPECT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. res = cli.Get("/hi%23key1=val1=key2=val2");
  2423. EXPECT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2425. }
  2426. }
  2427. TEST(HeaderWriter, SetHeaderWriter) {
  2428. Server svr;
  2429. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2430. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2431. return detail::write_headers(strm, hdrs);
  2432. });
  2433. svr.Get("/hi", [](const Request &req, Response &res) {
  2434. auto it = req.headers.find("CustomClientHeader");
  2435. EXPECT_TRUE(it != req.headers.end());
  2436. EXPECT_EQ(it->second, "CustomClientValue");
  2437. res.set_content("Hello World!\n", "text/plain");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2449. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2450. return detail::write_headers(strm, hdrs);
  2451. });
  2452. auto res = cli.Get("/hi");
  2453. EXPECT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::OK_200, res->status);
  2455. auto it = res->headers.find("CustomServerHeader");
  2456. EXPECT_TRUE(it != res->headers.end());
  2457. EXPECT_EQ(it->second, "CustomServerValue");
  2458. }
  2459. }
  2460. class ServerTest : public ::testing::Test {
  2461. protected:
  2462. ServerTest()
  2463. : cli_(HOST, PORT)
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. ,
  2466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2467. #endif
  2468. {
  2469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2470. cli_.enable_server_certificate_verification(false);
  2471. #endif
  2472. }
  2473. virtual void SetUp() {
  2474. svr_.set_mount_point("/", "./www");
  2475. svr_.set_mount_point("/mount", "./www2");
  2476. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2477. svr_.Get("/hi",
  2478. [&](const Request & /*req*/, Response &res) {
  2479. res.set_content("Hello World!", "text/plain");
  2480. })
  2481. .Get("/file_content",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_file_content("./www/dir/test.html");
  2484. })
  2485. .Get("/file_content_with_content_type",
  2486. [&](const Request & /*req*/, Response &res) {
  2487. res.set_file_content("./www/file", "text/plain");
  2488. })
  2489. .Get("/invalid_file_content",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_file_content("./www/dir/invalid_file_path");
  2492. })
  2493. .Get("/http_response_splitting",
  2494. [&](const Request & /*req*/, Response &res) {
  2495. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2496. EXPECT_EQ(0U, res.headers.size());
  2497. EXPECT_FALSE(res.has_header("a"));
  2498. res.set_header("a", "1\nSet-Cookie: a=1");
  2499. EXPECT_EQ(0U, res.headers.size());
  2500. EXPECT_FALSE(res.has_header("a"));
  2501. res.set_header("a", "1\rSet-Cookie: a=1");
  2502. EXPECT_EQ(0U, res.headers.size());
  2503. EXPECT_FALSE(res.has_header("a"));
  2504. res.set_header("a\r\nb", "0");
  2505. EXPECT_EQ(0U, res.headers.size());
  2506. EXPECT_FALSE(res.has_header("a"));
  2507. res.set_header("a\rb", "0");
  2508. EXPECT_EQ(0U, res.headers.size());
  2509. EXPECT_FALSE(res.has_header("a"));
  2510. res.set_header("a\nb", "0");
  2511. EXPECT_EQ(0U, res.headers.size());
  2512. EXPECT_FALSE(res.has_header("a"));
  2513. res.set_redirect("1\r\nSet-Cookie: a=1");
  2514. EXPECT_EQ(0U, res.headers.size());
  2515. EXPECT_FALSE(res.has_header("Location"));
  2516. })
  2517. .Get("/slow",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. std::this_thread::sleep_for(std::chrono::seconds(2));
  2520. res.set_content("slow", "text/plain");
  2521. })
  2522. #if 0
  2523. .Post("/slowpost",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. std::this_thread::sleep_for(std::chrono::seconds(2));
  2526. res.set_content("slow", "text/plain");
  2527. })
  2528. #endif
  2529. .Get("/remote_addr",
  2530. [&](const Request &req, Response &res) {
  2531. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2532. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2533. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2534. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2535. res.set_content(req.remote_addr, "text/plain");
  2536. })
  2537. .Get("/local_addr",
  2538. [&](const Request &req, Response &res) {
  2539. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2540. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2541. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2542. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2543. auto local_addr = req.local_addr;
  2544. auto local_port = std::to_string(req.local_port);
  2545. res.set_content(local_addr.append(":").append(local_port),
  2546. "text/plain");
  2547. })
  2548. .Get("/endwith%",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. })
  2552. .Get("/a\\+\\+b",
  2553. [&](const Request &req, Response &res) {
  2554. ASSERT_TRUE(req.has_param("a +b"));
  2555. auto val = req.get_param_value("a +b");
  2556. res.set_content(val, "text/plain");
  2557. })
  2558. .Get("/", [&](const Request & /*req*/,
  2559. Response &res) { res.set_redirect("/hi"); })
  2560. .Post("/1",
  2561. [](const Request & /*req*/, Response &res) {
  2562. res.set_redirect("/2", StatusCode::SeeOther_303);
  2563. })
  2564. .Get("/2",
  2565. [](const Request & /*req*/, Response &res) {
  2566. res.set_content("redirected.", "text/plain");
  2567. res.status = StatusCode::OK_200;
  2568. })
  2569. .Post("/person",
  2570. [&](const Request &req, Response &res) {
  2571. if (req.has_param("name") && req.has_param("note")) {
  2572. persons_[req.get_param_value("name")] =
  2573. req.get_param_value("note");
  2574. } else {
  2575. res.status = StatusCode::BadRequest_400;
  2576. }
  2577. })
  2578. .Put("/person",
  2579. [&](const Request &req, Response &res) {
  2580. if (req.has_param("name") && req.has_param("note")) {
  2581. persons_[req.get_param_value("name")] =
  2582. req.get_param_value("note");
  2583. } else {
  2584. res.status = StatusCode::BadRequest_400;
  2585. }
  2586. })
  2587. .Get("/person/(.*)",
  2588. [&](const Request &req, Response &res) {
  2589. string name = req.matches[1];
  2590. if (persons_.find(name) != persons_.end()) {
  2591. auto note = persons_[name];
  2592. res.set_content(note, "text/plain");
  2593. } else {
  2594. res.status = StatusCode::NotFound_404;
  2595. }
  2596. })
  2597. .Delete("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name")) {
  2600. string name = req.get_param_value("name");
  2601. if (persons_.find(name) != persons_.end()) {
  2602. persons_.erase(name);
  2603. res.set_content("DELETED", "text/plain");
  2604. } else {
  2605. res.status = StatusCode::NotFound_404;
  2606. }
  2607. } else {
  2608. res.status = StatusCode::BadRequest_400;
  2609. }
  2610. })
  2611. .Post("/x-www-form-urlencoded-json",
  2612. [&](const Request &req, Response &res) {
  2613. auto json = req.get_param_value("json");
  2614. ASSERT_EQ(JSON_DATA, json);
  2615. res.set_content(json, "appliation/json");
  2616. res.status = StatusCode::OK_200;
  2617. })
  2618. .Get("/streamed-chunked",
  2619. [&](const Request & /*req*/, Response &res) {
  2620. res.set_chunked_content_provider(
  2621. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2622. sink.os << "123";
  2623. sink.os << "456";
  2624. sink.os << "789";
  2625. sink.done();
  2626. return true;
  2627. });
  2628. })
  2629. .Get("/streamed-chunked-with-prohibited-trailer",
  2630. [&](const Request & /*req*/, Response &res) {
  2631. auto i = new int(0);
  2632. // Declare both a prohibited trailer (Content-Length) and an
  2633. // allowed one
  2634. res.set_header("Trailer", "Content-Length, X-Allowed");
  2635. res.set_chunked_content_provider(
  2636. "text/plain",
  2637. [i](size_t /*offset*/, DataSink &sink) {
  2638. switch (*i) {
  2639. case 0: sink.os << "123"; break;
  2640. case 1: sink.os << "456"; break;
  2641. case 2: sink.os << "789"; break;
  2642. case 3: {
  2643. sink.done_with_trailer(
  2644. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2645. } break;
  2646. }
  2647. (*i)++;
  2648. return true;
  2649. },
  2650. [i](bool success) {
  2651. EXPECT_TRUE(success);
  2652. delete i;
  2653. });
  2654. })
  2655. .Get("/streamed-chunked2",
  2656. [&](const Request & /*req*/, Response &res) {
  2657. auto i = new int(0);
  2658. res.set_chunked_content_provider(
  2659. "text/plain",
  2660. [i](size_t /*offset*/, DataSink &sink) {
  2661. switch (*i) {
  2662. case 0: sink.os << "123"; break;
  2663. case 1: sink.os << "456"; break;
  2664. case 2: sink.os << "789"; break;
  2665. case 3: sink.done(); break;
  2666. }
  2667. (*i)++;
  2668. return true;
  2669. },
  2670. [i](bool success) {
  2671. EXPECT_TRUE(success);
  2672. delete i;
  2673. });
  2674. })
  2675. .Get("/streamed-chunked-with-trailer",
  2676. [&](const Request & /*req*/, Response &res) {
  2677. auto i = new int(0);
  2678. res.set_header("Trailer", "Dummy1, Dummy2");
  2679. res.set_chunked_content_provider(
  2680. "text/plain",
  2681. [i](size_t /*offset*/, DataSink &sink) {
  2682. switch (*i) {
  2683. case 0: sink.os << "123"; break;
  2684. case 1: sink.os << "456"; break;
  2685. case 2: sink.os << "789"; break;
  2686. case 3: {
  2687. sink.done_with_trailer(
  2688. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2689. } break;
  2690. }
  2691. (*i)++;
  2692. return true;
  2693. },
  2694. [i](bool success) {
  2695. EXPECT_TRUE(success);
  2696. delete i;
  2697. });
  2698. })
  2699. .Get("/streamed",
  2700. [&](const Request & /*req*/, Response &res) {
  2701. res.set_content_provider(
  2702. 6, "text/plain",
  2703. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2704. sink.os << (offset < 3 ? "a" : "b");
  2705. return true;
  2706. });
  2707. })
  2708. .Get("/streamed-with-range",
  2709. [&](const Request &req, Response &res) {
  2710. auto data = new std::string("abcdefg");
  2711. res.set_content_provider(
  2712. data->size(), "text/plain",
  2713. [data](size_t offset, size_t length, DataSink &sink) {
  2714. size_t DATA_CHUNK_SIZE = 4;
  2715. const auto &d = *data;
  2716. auto out_len =
  2717. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2718. auto ret =
  2719. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2720. EXPECT_TRUE(ret);
  2721. return true;
  2722. },
  2723. [data, &req](bool success) {
  2724. EXPECT_EQ(success, !req.has_param("error"));
  2725. delete data;
  2726. });
  2727. })
  2728. .Get("/streamed-cancel",
  2729. [&](const Request & /*req*/, Response &res) {
  2730. res.set_content_provider(
  2731. size_t(-1), "text/plain",
  2732. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2733. sink.os << "data_chunk";
  2734. return true;
  2735. });
  2736. })
  2737. .Get("/regex-with-delimiter",
  2738. [&](const Request &req, Response & /*res*/) {
  2739. ASSERT_TRUE(req.has_param("key"));
  2740. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2741. })
  2742. .Get("/with-range",
  2743. [&](const Request & /*req*/, Response &res) {
  2744. res.set_content("abcdefg", "text/plain");
  2745. })
  2746. .Get("/test-start-time",
  2747. [&](const Request &req, Response & /*res*/) {
  2748. EXPECT_NE(req.start_time_,
  2749. std::chrono::steady_clock::time_point::min());
  2750. })
  2751. .Get("/with-range-customized-response",
  2752. [&](const Request & /*req*/, Response &res) {
  2753. res.status = StatusCode::BadRequest_400;
  2754. res.set_content(JSON_DATA, "application/json");
  2755. })
  2756. .Post("/chunked",
  2757. [&](const Request &req, Response & /*res*/) {
  2758. EXPECT_EQ(req.body, "dechunked post body");
  2759. })
  2760. .Post("/large-chunked",
  2761. [&](const Request &req, Response & /*res*/) {
  2762. std::string expected(6 * 30 * 1024u, 'a');
  2763. EXPECT_EQ(req.body, expected);
  2764. })
  2765. .Post("/multipart",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2768. req.form.get_field_count("text2") +
  2769. req.form.get_field_count("file3") +
  2770. req.form.get_field_count("file4"));
  2771. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2772. req.form.get_file_count("file2"));
  2773. ASSERT_TRUE(!req.form.has_file("???"));
  2774. ASSERT_TRUE(!req.form.has_field("???"));
  2775. ASSERT_TRUE(req.body.empty());
  2776. {
  2777. const auto &text = req.form.get_field("text1");
  2778. EXPECT_EQ("text default", text);
  2779. }
  2780. {
  2781. const auto &text = req.form.get_field("text2");
  2782. EXPECT_EQ("aωb", text);
  2783. }
  2784. {
  2785. const auto &file = req.form.get_file("file1");
  2786. EXPECT_EQ("hello.txt", file.filename);
  2787. EXPECT_EQ("text/plain", file.content_type);
  2788. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2789. }
  2790. {
  2791. const auto &file = req.form.get_file("file2");
  2792. EXPECT_EQ("world.json", file.filename);
  2793. EXPECT_EQ("application/json", file.content_type);
  2794. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2795. }
  2796. {
  2797. const auto &text = req.form.get_field("file3");
  2798. EXPECT_EQ(0u, text.size());
  2799. }
  2800. {
  2801. const auto &text = req.form.get_field("file4");
  2802. EXPECT_EQ(0u, text.size());
  2803. }
  2804. })
  2805. .Post("/multipart/multi_file_values",
  2806. [&](const Request &req, Response & /*res*/) {
  2807. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2808. req.form.get_field_count("multi_text1"));
  2809. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2810. ASSERT_TRUE(!req.form.has_file("???"));
  2811. ASSERT_TRUE(!req.form.has_field("???"));
  2812. ASSERT_TRUE(req.body.empty());
  2813. {
  2814. const auto &text = req.form.get_field("text");
  2815. EXPECT_EQ("default text", text);
  2816. }
  2817. {
  2818. const auto &text1_values = req.form.get_fields("multi_text1");
  2819. EXPECT_EQ(2u, text1_values.size());
  2820. EXPECT_EQ("aaaaa", text1_values[0]);
  2821. EXPECT_EQ("bbbbb", text1_values[1]);
  2822. }
  2823. {
  2824. const auto &file1_values = req.form.get_files("multi_file1");
  2825. EXPECT_EQ(2u, file1_values.size());
  2826. auto file1 = file1_values[0];
  2827. EXPECT_EQ(file1.filename, "hello.txt");
  2828. EXPECT_EQ(file1.content_type, "text/plain");
  2829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2830. auto file2 = file1_values[1];
  2831. EXPECT_EQ(file2.filename, "world.json");
  2832. EXPECT_EQ(file2.content_type, "application/json");
  2833. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2834. }
  2835. })
  2836. .Post("/empty",
  2837. [&](const Request &req, Response &res) {
  2838. EXPECT_EQ(req.body, "");
  2839. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2840. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2841. res.set_content("empty", "text/plain");
  2842. })
  2843. .Post("/empty-no-content-type",
  2844. [&](const Request &req, Response &res) {
  2845. EXPECT_EQ(req.body, "");
  2846. EXPECT_FALSE(req.has_header("Content-Type"));
  2847. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2848. res.set_content("empty-no-content-type", "text/plain");
  2849. })
  2850. .Post("/path-only",
  2851. [&](const Request &req, Response &res) {
  2852. EXPECT_EQ(req.body, "");
  2853. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2855. res.set_content("path-only", "text/plain");
  2856. })
  2857. .Post("/path-headers-only",
  2858. [&](const Request &req, Response &res) {
  2859. EXPECT_EQ(req.body, "");
  2860. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2862. EXPECT_EQ("world", req.get_header_value("hello"));
  2863. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2864. res.set_content("path-headers-only", "text/plain");
  2865. })
  2866. .Post("/post-large",
  2867. [&](const Request &req, Response &res) {
  2868. EXPECT_EQ(req.body, LARGE_DATA);
  2869. res.set_content(req.body, "text/plain");
  2870. })
  2871. .Post("/post-loopback",
  2872. [&](const Request &, Response &res,
  2873. ContentReader const &content_reader) {
  2874. std::string body;
  2875. content_reader([&](const char *data, size_t data_length) {
  2876. body.append(data, data_length);
  2877. return true;
  2878. });
  2879. res.set_content(body, "text/plain");
  2880. })
  2881. .Put("/put-loopback",
  2882. [&](const Request &, Response &res,
  2883. ContentReader const &content_reader) {
  2884. std::string body;
  2885. content_reader([&](const char *data, size_t data_length) {
  2886. body.append(data, data_length);
  2887. return true;
  2888. });
  2889. res.set_content(body, "text/plain");
  2890. })
  2891. .Patch("/patch-loopback",
  2892. [&](const Request &, Response &res,
  2893. ContentReader const &content_reader) {
  2894. std::string body;
  2895. content_reader([&](const char *data, size_t data_length) {
  2896. body.append(data, data_length);
  2897. return true;
  2898. });
  2899. res.set_content(body, "text/plain");
  2900. })
  2901. .Put("/empty-no-content-type",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "");
  2904. EXPECT_FALSE(req.has_header("Content-Type"));
  2905. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2906. res.set_content("empty-no-content-type", "text/plain");
  2907. })
  2908. .Put("/put",
  2909. [&](const Request &req, Response &res) {
  2910. EXPECT_EQ(req.body, "PUT");
  2911. res.set_content(req.body, "text/plain");
  2912. })
  2913. .Put("/put-large",
  2914. [&](const Request &req, Response &res) {
  2915. EXPECT_EQ(req.body, LARGE_DATA);
  2916. res.set_content(req.body, "text/plain");
  2917. })
  2918. .Patch("/patch",
  2919. [&](const Request &req, Response &res) {
  2920. EXPECT_EQ(req.body, "PATCH");
  2921. res.set_content(req.body, "text/plain");
  2922. })
  2923. .Delete("/delete",
  2924. [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("DELETE", "text/plain");
  2926. })
  2927. .Delete("/delete-body",
  2928. [&](const Request &req, Response &res) {
  2929. EXPECT_EQ(req.body, "content");
  2930. res.set_content(req.body, "text/plain");
  2931. })
  2932. .Options(R"(\*)",
  2933. [&](const Request & /*req*/, Response &res) {
  2934. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2935. })
  2936. .Get("/request-target",
  2937. [&](const Request &req, Response & /*res*/) {
  2938. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2939. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2940. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2941. })
  2942. .Get("/long-query-value",
  2943. [&](const Request &req, Response & /*res*/) {
  2944. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2945. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2946. })
  2947. .Get("/too-long-query-value",
  2948. [&](const Request &req, Response & /*res*/) {
  2949. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2950. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2951. })
  2952. .Get("/array-param",
  2953. [&](const Request &req, Response & /*res*/) {
  2954. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2955. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2956. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2957. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2958. })
  2959. .Post("/validate-no-multiple-headers",
  2960. [&](const Request &req, Response & /*res*/) {
  2961. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2962. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2963. })
  2964. .Post("/content_receiver",
  2965. [&](const Request &req, Response &res,
  2966. const ContentReader &content_reader) {
  2967. if (req.is_multipart_form_data()) {
  2968. std::vector<FormData> items;
  2969. content_reader(
  2970. [&](const FormData &file) {
  2971. items.push_back(file);
  2972. return true;
  2973. },
  2974. [&](const char *data, size_t data_length) {
  2975. items.back().content.append(data, data_length);
  2976. return true;
  2977. });
  2978. EXPECT_EQ(5u, items.size());
  2979. {
  2980. const auto &file = get_file_value(items, "text1");
  2981. EXPECT_TRUE(file.filename.empty());
  2982. EXPECT_EQ("text default", file.content);
  2983. }
  2984. {
  2985. const auto &file = get_file_value(items, "text2");
  2986. EXPECT_TRUE(file.filename.empty());
  2987. EXPECT_EQ("aωb", file.content);
  2988. }
  2989. {
  2990. const auto &file = get_file_value(items, "file1");
  2991. EXPECT_EQ("hello.txt", file.filename);
  2992. EXPECT_EQ("text/plain", file.content_type);
  2993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2994. }
  2995. {
  2996. const auto &file = get_file_value(items, "file2");
  2997. EXPECT_EQ("world.json", file.filename);
  2998. EXPECT_EQ("application/json", file.content_type);
  2999. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3000. }
  3001. {
  3002. const auto &file = get_file_value(items, "file3");
  3003. EXPECT_TRUE(file.filename.empty());
  3004. EXPECT_EQ("application/octet-stream", file.content_type);
  3005. EXPECT_EQ(0u, file.content.size());
  3006. }
  3007. } else {
  3008. std::string body;
  3009. content_reader([&](const char *data, size_t data_length) {
  3010. EXPECT_EQ(7U, data_length);
  3011. body.append(data, data_length);
  3012. return true;
  3013. });
  3014. EXPECT_EQ(body, "content");
  3015. res.set_content(body, "text/plain");
  3016. }
  3017. })
  3018. .Put("/content_receiver",
  3019. [&](const Request & /*req*/, Response &res,
  3020. const ContentReader &content_reader) {
  3021. std::string body;
  3022. content_reader([&](const char *data, size_t data_length) {
  3023. body.append(data, data_length);
  3024. return true;
  3025. });
  3026. EXPECT_EQ(body, "content");
  3027. res.set_content(body, "text/plain");
  3028. })
  3029. .Patch("/content_receiver",
  3030. [&](const Request & /*req*/, Response &res,
  3031. const ContentReader &content_reader) {
  3032. std::string body;
  3033. content_reader([&](const char *data, size_t data_length) {
  3034. body.append(data, data_length);
  3035. return true;
  3036. });
  3037. EXPECT_EQ(body, "content");
  3038. res.set_content(body, "text/plain");
  3039. })
  3040. .Post("/query-string-and-body",
  3041. [&](const Request &req, Response & /*res*/) {
  3042. ASSERT_TRUE(req.has_param("key"));
  3043. EXPECT_EQ(req.get_param_value("key"), "value");
  3044. EXPECT_EQ(req.body, "content");
  3045. })
  3046. .Get("/last-request",
  3047. [&](const Request &req, Response & /*res*/) {
  3048. EXPECT_EQ("close", req.get_header_value("Connection"));
  3049. })
  3050. .Get(R"(/redirect/(\d+))",
  3051. [&](const Request &req, Response &res) {
  3052. auto num = std::stoi(req.matches[1]) + 1;
  3053. std::string url = "/redirect/" + std::to_string(num);
  3054. res.set_redirect(url);
  3055. })
  3056. .Post("/binary",
  3057. [&](const Request &req, Response &res) {
  3058. EXPECT_EQ(4U, req.body.size());
  3059. EXPECT_EQ("application/octet-stream",
  3060. req.get_header_value("Content-Type"));
  3061. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3062. res.set_content(req.body, "application/octet-stream");
  3063. })
  3064. .Put("/binary",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(4U, req.body.size());
  3067. EXPECT_EQ("application/octet-stream",
  3068. req.get_header_value("Content-Type"));
  3069. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3070. res.set_content(req.body, "application/octet-stream");
  3071. })
  3072. .Patch("/binary",
  3073. [&](const Request &req, Response &res) {
  3074. EXPECT_EQ(4U, req.body.size());
  3075. EXPECT_EQ("application/octet-stream",
  3076. req.get_header_value("Content-Type"));
  3077. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3078. res.set_content(req.body, "application/octet-stream");
  3079. })
  3080. .Delete("/binary",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(4U, req.body.size());
  3083. EXPECT_EQ("application/octet-stream",
  3084. req.get_header_value("Content-Type"));
  3085. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3086. res.set_content(req.body, "application/octet-stream");
  3087. })
  3088. .Get("/issue1772",
  3089. [&](const Request & /*req*/, Response &res) {
  3090. res.status = 401;
  3091. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3092. })
  3093. .Delete("/issue609",
  3094. [](const httplib::Request &, httplib::Response &res,
  3095. const httplib::ContentReader &) {
  3096. res.set_content("ok", "text/plain");
  3097. })
  3098. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3099. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3100. .Get("/compress",
  3101. [&](const Request & /*req*/, Response &res) {
  3102. res.set_content(
  3103. "12345678901234567890123456789012345678901234567890123456789"
  3104. "01234567890123456789012345678901234567890",
  3105. "text/plain");
  3106. })
  3107. .Get("/nocompress",
  3108. [&](const Request & /*req*/, Response &res) {
  3109. res.set_content(
  3110. "12345678901234567890123456789012345678901234567890123456789"
  3111. "01234567890123456789012345678901234567890",
  3112. "application/octet-stream");
  3113. })
  3114. .Post("/compress-multipart",
  3115. [&](const Request &req, Response & /*res*/) {
  3116. EXPECT_EQ(2u, req.form.fields.size());
  3117. ASSERT_TRUE(!req.form.has_field("???"));
  3118. {
  3119. const auto &text = req.form.get_field("key1");
  3120. EXPECT_EQ("test", text);
  3121. }
  3122. {
  3123. const auto &text = req.form.get_field("key2");
  3124. EXPECT_EQ("--abcdefg123", text);
  3125. }
  3126. })
  3127. #endif
  3128. ;
  3129. persons_["john"] = "programmer";
  3130. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3131. svr_.wait_until_ready();
  3132. }
  3133. virtual void TearDown() {
  3134. svr_.stop();
  3135. if (!request_threads_.empty()) {
  3136. std::this_thread::sleep_for(std::chrono::seconds(1));
  3137. for (auto &t : request_threads_) {
  3138. t.join();
  3139. }
  3140. }
  3141. t_.join();
  3142. }
  3143. map<string, string> persons_;
  3144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3145. SSLClient cli_;
  3146. SSLServer svr_;
  3147. #else
  3148. Client cli_;
  3149. Server svr_;
  3150. #endif
  3151. thread t_;
  3152. std::vector<thread> request_threads_;
  3153. };
  3154. TEST_F(ServerTest, GetMethod200) {
  3155. auto res = cli_.Get("/hi");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ("HTTP/1.1", res->version);
  3158. EXPECT_EQ(StatusCode::OK_200, res->status);
  3159. EXPECT_EQ("OK", res->reason);
  3160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3161. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3162. EXPECT_EQ("Hello World!", res->body);
  3163. }
  3164. TEST_F(ServerTest, GetEmptyFile) {
  3165. auto res = cli_.Get("/empty_file");
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3169. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3170. EXPECT_EQ("", res->body);
  3171. }
  3172. TEST_F(ServerTest, GetFileContent) {
  3173. auto res = cli_.Get("/file_content");
  3174. ASSERT_TRUE(res);
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3177. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3178. EXPECT_EQ("test.html", res->body);
  3179. }
  3180. TEST_F(ServerTest, GetFileContentWithRange) {
  3181. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3182. ASSERT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3184. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3185. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3186. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3187. EXPECT_EQ("est", res->body);
  3188. }
  3189. TEST_F(ServerTest, GetFileContentWithContentType) {
  3190. auto res = cli_.Get("/file_content_with_content_type");
  3191. ASSERT_TRUE(res);
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3194. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3195. EXPECT_EQ("file\n", res->body);
  3196. }
  3197. TEST_F(ServerTest, GetInvalidFileContent) {
  3198. auto res = cli_.Get("/invalid_file_content");
  3199. ASSERT_TRUE(res);
  3200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3201. }
  3202. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3203. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_EQ("HTTP/1.1", res->version);
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3208. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3209. EXPECT_EQ("Hello World!", res->body);
  3210. }
  3211. TEST_F(ServerTest, GetMethod302) {
  3212. auto res = cli_.Get("/");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::Found_302, res->status);
  3215. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3216. }
  3217. TEST_F(ServerTest, GetMethod302Redirect) {
  3218. cli_.set_follow_location(true);
  3219. auto res = cli_.Get("/");
  3220. ASSERT_TRUE(res);
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("Hello World!", res->body);
  3223. EXPECT_EQ("/hi", res->location);
  3224. }
  3225. TEST_F(ServerTest, GetMethod404) {
  3226. auto res = cli_.Get("/invalid");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, HeadMethod200) {
  3231. auto res = cli_.Head("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::OK_200, res->status);
  3234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3235. EXPECT_TRUE(res->body.empty());
  3236. }
  3237. TEST_F(ServerTest, HeadMethod200Static) {
  3238. auto res = cli_.Head("/mount/dir/index.html");
  3239. ASSERT_TRUE(res);
  3240. EXPECT_EQ(StatusCode::OK_200, res->status);
  3241. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3242. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3243. EXPECT_TRUE(res->body.empty());
  3244. }
  3245. TEST_F(ServerTest, HeadMethod404) {
  3246. auto res = cli_.Head("/invalid");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3249. EXPECT_TRUE(res->body.empty());
  3250. }
  3251. TEST_F(ServerTest, GetMethodPersonJohn) {
  3252. auto res = cli_.Get("/person/john");
  3253. ASSERT_TRUE(res);
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3256. EXPECT_EQ("programmer", res->body);
  3257. }
  3258. TEST_F(ServerTest, PostMethod1) {
  3259. auto res = cli_.Get("/person/john1");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3262. res = cli_.Post("/person", "name=john1&note=coder",
  3263. "application/x-www-form-urlencoded");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::OK_200, res->status);
  3266. res = cli_.Get("/person/john1");
  3267. ASSERT_TRUE(res);
  3268. ASSERT_EQ(StatusCode::OK_200, res->status);
  3269. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3270. ASSERT_EQ("coder", res->body);
  3271. }
  3272. TEST_F(ServerTest, PostMethod2) {
  3273. auto res = cli_.Get("/person/john2");
  3274. ASSERT_TRUE(res);
  3275. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3276. Params params;
  3277. params.emplace("name", "john2");
  3278. params.emplace("note", "coder");
  3279. res = cli_.Post("/person", params);
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::OK_200, res->status);
  3282. res = cli_.Get("/person/john2");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::OK_200, res->status);
  3285. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3286. ASSERT_EQ("coder", res->body);
  3287. }
  3288. TEST_F(ServerTest, PutMethod3) {
  3289. auto res = cli_.Get("/person/john3");
  3290. ASSERT_TRUE(res);
  3291. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3292. Params params;
  3293. params.emplace("name", "john3");
  3294. params.emplace("note", "coder");
  3295. res = cli_.Put("/person", params);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. res = cli_.Get("/person/john3");
  3299. ASSERT_TRUE(res);
  3300. ASSERT_EQ(StatusCode::OK_200, res->status);
  3301. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3302. ASSERT_EQ("coder", res->body);
  3303. }
  3304. TEST_F(ServerTest, DeleteMethod1) {
  3305. auto res = cli_.Get("/person/john4");
  3306. ASSERT_TRUE(res);
  3307. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3308. Params params;
  3309. params.emplace("name", "john4");
  3310. params.emplace("note", "coder");
  3311. res = cli_.Post("/person", params);
  3312. ASSERT_TRUE(res);
  3313. ASSERT_EQ(StatusCode::OK_200, res->status);
  3314. res = cli_.Get("/person/john4");
  3315. ASSERT_TRUE(res);
  3316. ASSERT_EQ(StatusCode::OK_200, res->status);
  3317. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3318. ASSERT_EQ("coder", res->body);
  3319. Params delete_params;
  3320. delete_params.emplace("name", "john4");
  3321. res = cli_.Delete("/person", delete_params);
  3322. ASSERT_TRUE(res);
  3323. ASSERT_EQ(StatusCode::OK_200, res->status);
  3324. ASSERT_EQ("DELETED", res->body);
  3325. res = cli_.Get("/person/john4");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3328. }
  3329. TEST_F(ServerTest, DeleteMethod2) {
  3330. auto res = cli_.Get("/person/john5");
  3331. ASSERT_TRUE(res);
  3332. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3333. Params params;
  3334. params.emplace("name", "john5");
  3335. params.emplace("note", "developer");
  3336. res = cli_.Post("/person", params);
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::OK_200, res->status);
  3339. res = cli_.Get("/person/john5");
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3343. ASSERT_EQ("developer", res->body);
  3344. Params delete_params;
  3345. delete_params.emplace("name", "john5");
  3346. Headers headers;
  3347. headers.emplace("Custom-Header", "test-value");
  3348. res = cli_.Delete("/person", headers, delete_params);
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. ASSERT_EQ("DELETED", res->body);
  3352. res = cli_.Get("/person/john5");
  3353. ASSERT_TRUE(res);
  3354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3355. }
  3356. TEST_F(ServerTest, DeleteMethod3) {
  3357. auto res = cli_.Get("/person/john6");
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3360. Params params;
  3361. params.emplace("name", "john6");
  3362. params.emplace("note", "tester");
  3363. res = cli_.Post("/person", params);
  3364. ASSERT_TRUE(res);
  3365. ASSERT_EQ(StatusCode::OK_200, res->status);
  3366. res = cli_.Get("/person/john6");
  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("tester", res->body);
  3371. Params delete_params;
  3372. delete_params.emplace("name", "john6");
  3373. Headers headers;
  3374. headers.emplace("Custom-Header", "test-value");
  3375. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("DELETED", res->body);
  3379. res = cli_.Get("/person/john6");
  3380. ASSERT_TRUE(res);
  3381. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3382. }
  3383. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3384. Params params;
  3385. params.emplace("json", JSON_DATA);
  3386. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::OK_200, res->status);
  3389. ASSERT_EQ(JSON_DATA, res->body);
  3390. }
  3391. TEST_F(ServerTest, PostEmptyContent) {
  3392. auto res = cli_.Post("/empty", "", "text/plain");
  3393. ASSERT_TRUE(res);
  3394. ASSERT_EQ(StatusCode::OK_200, res->status);
  3395. ASSERT_EQ("empty", res->body);
  3396. }
  3397. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3398. auto res = cli_.Post("/empty-no-content-type");
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("empty-no-content-type", res->body);
  3402. }
  3403. TEST_F(ServerTest, PostPathOnly) {
  3404. auto res = cli_.Post("/path-only");
  3405. ASSERT_TRUE(res);
  3406. ASSERT_EQ(StatusCode::OK_200, res->status);
  3407. ASSERT_EQ("path-only", res->body);
  3408. }
  3409. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3410. auto res = cli_.Post("/path-headers-only",
  3411. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("path-headers-only", res->body);
  3415. }
  3416. TEST_F(ServerTest, PostLarge) {
  3417. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3418. ASSERT_TRUE(res);
  3419. ASSERT_EQ(StatusCode::OK_200, res->status);
  3420. EXPECT_EQ(LARGE_DATA, res->body);
  3421. }
  3422. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3423. auto res = cli_.Put("/empty-no-content-type");
  3424. ASSERT_TRUE(res);
  3425. ASSERT_EQ(StatusCode::OK_200, res->status);
  3426. ASSERT_EQ("empty-no-content-type", res->body);
  3427. }
  3428. TEST_F(ServerTest, GetMethodDir) {
  3429. auto res = cli_.Get("/dir/");
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3433. auto body = R"(<html>
  3434. <head>
  3435. </head>
  3436. <body>
  3437. <a href="/dir/test.html">Test</a>
  3438. <a href="/hi">hi</a>
  3439. </body>
  3440. </html>
  3441. )";
  3442. EXPECT_EQ(body, res->body);
  3443. }
  3444. TEST_F(ServerTest, GetMethodDirTest) {
  3445. auto res = cli_.Get("/dir/test.html");
  3446. ASSERT_TRUE(res);
  3447. EXPECT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3449. EXPECT_EQ("test.html", res->body);
  3450. }
  3451. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3452. auto res = cli_.Get("/dir/../dir/test.html");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3456. EXPECT_EQ("test.html", res->body);
  3457. }
  3458. TEST_F(ServerTest, GetMethodInvalidPath) {
  3459. auto res = cli_.Get("/dir/../test.html");
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3462. }
  3463. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3464. auto res = cli_.Get("/../www/dir/test.html");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3467. }
  3468. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3469. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3472. }
  3473. TEST_F(ServerTest, GetMethodDirMountTest) {
  3474. auto res = cli_.Get("/mount/dir/test.html");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ("test.html", res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3481. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3488. auto res = cli_.Get("/mount/dir/../test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3491. }
  3492. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3493. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3494. ASSERT_TRUE(res);
  3495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3496. }
  3497. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3498. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3501. }
  3502. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3503. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3506. }
  3507. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3508. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3509. ASSERT_TRUE(res);
  3510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3511. }
  3512. TEST_F(ServerTest, PostMethod303) {
  3513. auto res = cli_.Post("/1", "body", "text/plain");
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3516. EXPECT_EQ("/2", res->get_header_value("Location"));
  3517. }
  3518. TEST_F(ServerTest, PostMethod303Redirect) {
  3519. cli_.set_follow_location(true);
  3520. auto res = cli_.Post("/1", "body", "text/plain");
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. EXPECT_EQ("redirected.", res->body);
  3524. EXPECT_EQ("/2", res->location);
  3525. }
  3526. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3527. auto res = cli_.Get("/dir/test.abcde");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("abcde", res->body);
  3532. }
  3533. TEST_F(ServerTest, StaticFileRange) {
  3534. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3537. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3539. EXPECT_EQ(true, res->has_header("Content-Range"));
  3540. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3541. EXPECT_EQ(std::string("cd"), res->body);
  3542. }
  3543. TEST_F(ServerTest, StaticFileRanges) {
  3544. auto res =
  3545. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3548. EXPECT_TRUE(
  3549. res->get_header_value("Content-Type")
  3550. .find(
  3551. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3552. 0);
  3553. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3554. }
  3555. TEST_F(ServerTest, StaticFileRangeHead) {
  3556. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3559. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3560. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3561. EXPECT_EQ(true, res->has_header("Content-Range"));
  3562. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3563. }
  3564. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3565. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3569. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3570. EXPECT_EQ(true, res->has_header("Content-Range"));
  3571. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3572. res->get_header_value("Content-Range"));
  3573. EXPECT_EQ("LAST\n", res->body);
  3574. }
  3575. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3576. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3580. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3581. EXPECT_EQ(true, res->has_header("Content-Range"));
  3582. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3583. }
  3584. TEST_F(ServerTest, StaticFileBigFile) {
  3585. auto res = cli_.Get("/dir/1MB.txt");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3589. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3590. }
  3591. TEST_F(ServerTest, InvalidBaseDirMount) {
  3592. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3593. }
  3594. TEST_F(ServerTest, Binary) {
  3595. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3596. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3597. "application/octet-stream");
  3598. ASSERT_TRUE(res);
  3599. ASSERT_EQ(StatusCode::OK_200, res->status);
  3600. ASSERT_EQ(4U, res->body.size());
  3601. res = cli_.Put("/binary", binary.data(), binary.size(),
  3602. "application/octet-stream");
  3603. ASSERT_TRUE(res);
  3604. ASSERT_EQ(StatusCode::OK_200, res->status);
  3605. ASSERT_EQ(4U, res->body.size());
  3606. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3607. "application/octet-stream");
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ(4U, res->body.size());
  3611. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3612. "application/octet-stream");
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::OK_200, res->status);
  3615. ASSERT_EQ(4U, res->body.size());
  3616. }
  3617. TEST_F(ServerTest, BinaryString) {
  3618. auto binary = std::string("\x00\x01\x02\x03", 4);
  3619. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3620. ASSERT_TRUE(res);
  3621. ASSERT_EQ(StatusCode::OK_200, res->status);
  3622. ASSERT_EQ(4U, res->body.size());
  3623. res = cli_.Put("/binary", binary, "application/octet-stream");
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ(4U, res->body.size());
  3627. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3628. ASSERT_TRUE(res);
  3629. ASSERT_EQ(StatusCode::OK_200, res->status);
  3630. ASSERT_EQ(4U, res->body.size());
  3631. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. ASSERT_EQ(4U, res->body.size());
  3635. }
  3636. TEST_F(ServerTest, EmptyRequest) {
  3637. auto res = cli_.Get("");
  3638. ASSERT_TRUE(!res);
  3639. EXPECT_EQ(Error::Connection, res.error());
  3640. }
  3641. TEST_F(ServerTest, LongRequest) {
  3642. std::string request;
  3643. for (size_t i = 0; i < 545; i++) {
  3644. request += "/TooLongRequest";
  3645. }
  3646. request += "OK";
  3647. auto res = cli_.Get(request.c_str());
  3648. ASSERT_TRUE(res);
  3649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3650. }
  3651. TEST_F(ServerTest, TooLongRequest) {
  3652. std::string request;
  3653. for (size_t i = 0; i < 546; i++) {
  3654. request += "/TooLongRequest";
  3655. }
  3656. request += "_NG";
  3657. auto start = std::chrono::high_resolution_clock::now();
  3658. cli_.set_keep_alive(true);
  3659. auto res = cli_.Get(request.c_str());
  3660. auto end = std::chrono::high_resolution_clock::now();
  3661. auto elapsed =
  3662. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3663. .count();
  3664. ASSERT_TRUE(res);
  3665. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3666. EXPECT_LE(elapsed, 100);
  3667. EXPECT_EQ("close", res->get_header_value("Connection"));
  3668. EXPECT_FALSE(cli_.is_socket_open());
  3669. }
  3670. TEST_F(ServerTest, AlmostTooLongRequest) {
  3671. // test for #2046 - URI length check shouldn't include other content on req
  3672. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3673. // leading /, space, HTTP/1.1)
  3674. std::string request =
  3675. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3676. auto res = cli_.Get(request.c_str());
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3679. }
  3680. TEST_F(ServerTest, LongHeader) {
  3681. Request req;
  3682. req.method = "GET";
  3683. req.path = "/hi";
  3684. std::string host_and_port;
  3685. host_and_port += HOST;
  3686. host_and_port += ":";
  3687. host_and_port += std::to_string(PORT);
  3688. req.headers.emplace("Host", host_and_port.c_str());
  3689. req.headers.emplace("Accept", "*/*");
  3690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3691. req.headers.emplace(
  3692. "Header-Name",
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3721. "@@@@@@@@@@@@@@@@");
  3722. auto res = std::make_shared<Response>();
  3723. auto error = Error::Success;
  3724. auto ret = cli_.send(req, *res, error);
  3725. ASSERT_TRUE(ret);
  3726. EXPECT_EQ(StatusCode::OK_200, res->status);
  3727. }
  3728. TEST_F(ServerTest, LongQueryValue) {
  3729. auto start = std::chrono::high_resolution_clock::now();
  3730. cli_.set_keep_alive(true);
  3731. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3732. auto end = std::chrono::high_resolution_clock::now();
  3733. auto elapsed =
  3734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3735. .count();
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3738. EXPECT_LE(elapsed, 100);
  3739. EXPECT_EQ("close", res->get_header_value("Connection"));
  3740. EXPECT_FALSE(cli_.is_socket_open());
  3741. }
  3742. TEST_F(ServerTest, TooLongQueryValue) {
  3743. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3744. ASSERT_FALSE(res);
  3745. EXPECT_EQ(Error::Read, res.error());
  3746. }
  3747. TEST_F(ServerTest, TooLongHeader) {
  3748. Request req;
  3749. req.method = "GET";
  3750. req.path = "/hi";
  3751. std::string host_and_port;
  3752. host_and_port += HOST;
  3753. host_and_port += ":";
  3754. host_and_port += std::to_string(PORT);
  3755. req.headers.emplace("Host", host_and_port.c_str());
  3756. req.headers.emplace("Accept", "*/*");
  3757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3758. req.headers.emplace(
  3759. "Header-Name",
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@");
  3789. auto res = std::make_shared<Response>();
  3790. auto error = Error::Success;
  3791. auto ret = cli_.send(req, *res, error);
  3792. ASSERT_TRUE(ret);
  3793. EXPECT_EQ(StatusCode::OK_200, res->status);
  3794. }
  3795. TEST_F(ServerTest, HeaderCountAtLimit) {
  3796. // Test with headers just under the 100 limit
  3797. httplib::Headers headers;
  3798. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3799. // This should keep us just under the 100 header limit
  3800. for (int i = 0; i < 95; i++) {
  3801. std::string name = "X-Test-Header-" + std::to_string(i);
  3802. std::string value = "value" + std::to_string(i);
  3803. headers.emplace(name, value);
  3804. }
  3805. // This should work fine as we're under the limit
  3806. auto res = cli_.Get("/hi", headers);
  3807. EXPECT_TRUE(res);
  3808. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3809. }
  3810. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3811. // Test with many headers to exceed the 100 limit
  3812. httplib::Headers headers;
  3813. // Add 150 headers to definitely exceed the 100 limit
  3814. for (int i = 0; i < 150; i++) {
  3815. std::string name = "X-Test-Header-" + std::to_string(i);
  3816. std::string value = "value" + std::to_string(i);
  3817. headers.emplace(name, value);
  3818. }
  3819. // This should fail due to exceeding header count limit
  3820. cli_.set_keep_alive(true);
  3821. auto res = cli_.Get("/hi", headers);
  3822. // The request should either fail or return 400 Bad Request
  3823. if (res) {
  3824. // If we get a response, it should be 400 Bad Request
  3825. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3826. } else {
  3827. // Or the request should fail entirely
  3828. EXPECT_FALSE(res);
  3829. }
  3830. EXPECT_EQ("close", res->get_header_value("Connection"));
  3831. EXPECT_FALSE(cli_.is_socket_open());
  3832. }
  3833. TEST_F(ServerTest, PercentEncoding) {
  3834. auto res = cli_.Get("/e%6edwith%");
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. }
  3838. TEST_F(ServerTest, PercentEncodingUnicode) {
  3839. auto res = cli_.Get("/e%u006edwith%");
  3840. ASSERT_TRUE(res);
  3841. EXPECT_EQ(StatusCode::OK_200, res->status);
  3842. }
  3843. TEST_F(ServerTest, InvalidPercentEncoding) {
  3844. auto res = cli_.Get("/%endwith%");
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3847. }
  3848. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3849. auto res = cli_.Get("/%uendwith%");
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3852. }
  3853. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3854. auto res = cli_.Get("/hello?aaa=bbb%");
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3857. }
  3858. TEST_F(ServerTest, PlusSignEncoding) {
  3859. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::OK_200, res->status);
  3862. EXPECT_EQ("a +b", res->body);
  3863. }
  3864. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3865. // This test simulates a potential DoS attack using many headers
  3866. // to verify our security fix prevents memory exhaustion
  3867. httplib::Headers attack_headers;
  3868. // Attempt to add many headers like an attacker would (200 headers to far
  3869. // exceed limit)
  3870. for (int i = 0; i < 200; i++) {
  3871. std::string name = "X-Attack-Header-" + std::to_string(i);
  3872. std::string value = "attack_payload_" + std::to_string(i);
  3873. attack_headers.emplace(name, value);
  3874. }
  3875. // Try to POST with excessive headers
  3876. cli_.set_keep_alive(true);
  3877. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3878. // Should either fail or return 400 Bad Request due to security limit
  3879. if (res) {
  3880. // If we get a response, it should be 400 Bad Request
  3881. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3882. } else {
  3883. // Request failed, which is the expected behavior for DoS protection
  3884. EXPECT_FALSE(res);
  3885. }
  3886. EXPECT_EQ("close", res->get_header_value("Connection"));
  3887. EXPECT_FALSE(cli_.is_socket_open());
  3888. }
  3889. TEST_F(ServerTest, MultipartFormData) {
  3890. UploadFormDataItems items = {
  3891. {"text1", "text default", "", ""},
  3892. {"text2", "aωb", "", ""},
  3893. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3894. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3895. {"file3", "", "", "application/octet-stream"},
  3896. {"file4", "", "", " application/json tmp-string "}};
  3897. auto res = cli_.Post("/multipart", items);
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::OK_200, res->status);
  3900. }
  3901. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3902. UploadFormDataItems items = {
  3903. {"text", "default text", "", ""},
  3904. {"multi_text1", "aaaaa", "", ""},
  3905. {"multi_text1", "bbbbb", "", ""},
  3906. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3907. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3908. "application/json"},
  3909. };
  3910. auto res = cli_.Post("/multipart/multi_file_values", items);
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3915. auto res = cli_.Get("/hi");
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3919. EXPECT_EQ("Hello World!", res->body);
  3920. }
  3921. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3922. Request req;
  3923. req.method = "POST";
  3924. req.path = "/chunked";
  3925. std::string host_and_port;
  3926. host_and_port += HOST;
  3927. host_and_port += ":";
  3928. host_and_port += std::to_string(PORT);
  3929. req.headers.emplace("Host", host_and_port.c_str());
  3930. req.headers.emplace("Accept", "*/*");
  3931. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3932. req.headers.emplace("Content-Type", "text/plain");
  3933. req.headers.emplace("Content-Length", "0");
  3934. req.headers.emplace(
  3935. "Transfer-Encoding",
  3936. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3937. // Client does not chunk, so make a chunked body manually.
  3938. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3939. auto res = std::make_shared<Response>();
  3940. auto error = Error::Success;
  3941. auto ret = cli_.send(req, *res, error);
  3942. ASSERT_TRUE(ret);
  3943. EXPECT_EQ(StatusCode::OK_200, res->status);
  3944. }
  3945. TEST_F(ServerTest, GetStreamed2) {
  3946. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3949. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3950. EXPECT_EQ(true, res->has_header("Content-Range"));
  3951. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3952. EXPECT_EQ(std::string("ab"), res->body);
  3953. }
  3954. TEST_F(ServerTest, GetStreamed) {
  3955. auto res = cli_.Get("/streamed");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3959. EXPECT_EQ(std::string("aaabbb"), res->body);
  3960. }
  3961. TEST_F(ServerTest, GetStreamedWithRange1) {
  3962. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3963. ASSERT_TRUE(res);
  3964. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3965. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3966. EXPECT_EQ(true, res->has_header("Content-Range"));
  3967. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3968. EXPECT_EQ(std::string("def"), res->body);
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithRange2) {
  3971. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3974. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3975. EXPECT_EQ(true, res->has_header("Content-Range"));
  3976. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3977. EXPECT_EQ(std::string("bcdefg"), res->body);
  3978. }
  3979. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3980. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3981. ASSERT_TRUE(res);
  3982. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3983. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3984. EXPECT_EQ(true, res->has_header("Content-Range"));
  3985. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3986. EXPECT_EQ(std::string("efg"), res->body);
  3987. }
  3988. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3989. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3990. ASSERT_TRUE(res);
  3991. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3992. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ(false, res->has_header("Content-Range"));
  3994. EXPECT_EQ(0U, res->body.size());
  3995. }
  3996. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3997. auto res = cli_.Get("/streamed-with-range",
  3998. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3999. "92233720368547758079223372036854775807"}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4002. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(false, res->has_header("Content-Range"));
  4004. EXPECT_EQ(0U, res->body.size());
  4005. }
  4006. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4007. auto res = cli_.Get(
  4008. "/with-range",
  4009. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4010. {"Accept-Encoding", ""}});
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4013. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4014. EXPECT_EQ(true, res->has_header("Content-Range"));
  4015. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4016. EXPECT_EQ(std::string("abcdefg"), res->body);
  4017. }
  4018. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4019. auto res = cli_.Get("/with-range", {
  4020. {"Range", "bytes=0-"},
  4021. {"Accept-Encoding", ""},
  4022. });
  4023. ASSERT_TRUE(res);
  4024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4025. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4026. EXPECT_EQ(true, res->has_header("Content-Range"));
  4027. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4028. EXPECT_EQ(std::string("abcdefg"), res->body);
  4029. }
  4030. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4031. auto res =
  4032. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4033. ASSERT_TRUE(res);
  4034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4035. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4036. EXPECT_EQ(false, res->has_header("Content-Range"));
  4037. EXPECT_EQ(267U, res->body.size());
  4038. // Check that both range contents are present
  4039. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4040. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4041. // Check that Content-Range headers are present for both ranges
  4042. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4043. std::string::npos);
  4044. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4045. std::string::npos);
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4048. Ranges ranges;
  4049. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4050. ranges.emplace_back(0, -1);
  4051. }
  4052. auto res =
  4053. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4056. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4057. EXPECT_EQ(false, res->has_header("Content-Range"));
  4058. EXPECT_EQ(0U, res->body.size());
  4059. }
  4060. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4061. auto res =
  4062. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ(5U, res->body.size());
  4066. // Check that overlapping ranges are coalesced into a single range
  4067. EXPECT_EQ("bcdef", res->body);
  4068. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4069. // Should be single range, not multipart
  4070. EXPECT_TRUE(res->has_header("Content-Range"));
  4071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4072. }
  4073. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4074. auto res =
  4075. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ(268U, res->body.size());
  4079. // Check that both range contents are present
  4080. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4081. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4082. // Check that Content-Range headers are present for both ranges
  4083. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4084. std::string::npos);
  4085. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4086. std::string::npos);
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(269U, res->body.size());
  4094. // Check that both duplicate range contents are present
  4095. size_t first_abc = res->body.find("abc\r\n");
  4096. EXPECT_TRUE(first_abc != std::string::npos);
  4097. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4098. EXPECT_TRUE(second_abc != std::string::npos);
  4099. // Check that Content-Range headers are present for both ranges
  4100. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4101. EXPECT_TRUE(first_range != std::string::npos);
  4102. size_t second_range =
  4103. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4104. EXPECT_TRUE(second_range != std::string::npos);
  4105. }
  4106. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4107. auto res = cli_.Get("/streamed-with-range?error",
  4108. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4109. ASSERT_TRUE(res);
  4110. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4111. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4112. EXPECT_EQ(false, res->has_header("Content-Range"));
  4113. EXPECT_EQ(0U, res->body.size());
  4114. }
  4115. TEST_F(ServerTest, GetStreamedEndless) {
  4116. uint64_t offset = 0;
  4117. auto res = cli_.Get("/streamed-cancel",
  4118. [&](const char * /*data*/, uint64_t data_length) {
  4119. if (offset < 100) {
  4120. offset += data_length;
  4121. return true;
  4122. }
  4123. return false;
  4124. });
  4125. ASSERT_TRUE(!res);
  4126. EXPECT_EQ(Error::Canceled, res.error());
  4127. }
  4128. TEST_F(ServerTest, ClientStop) {
  4129. std::atomic_size_t count{4};
  4130. std::vector<std::thread> threads;
  4131. for (auto i = count.load(); i != 0; --i) {
  4132. threads.emplace_back([&]() {
  4133. auto res = cli_.Get("/streamed-cancel",
  4134. [&](const char *, uint64_t) { return true; });
  4135. --count;
  4136. ASSERT_TRUE(!res);
  4137. EXPECT_TRUE(res.error() == Error::Canceled ||
  4138. res.error() == Error::Read || res.error() == Error::Write);
  4139. });
  4140. }
  4141. std::this_thread::sleep_for(std::chrono::seconds(2));
  4142. while (count != 0) {
  4143. cli_.stop();
  4144. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4145. }
  4146. for (auto &t : threads) {
  4147. t.join();
  4148. }
  4149. }
  4150. TEST_F(ServerTest, GetWithRange1) {
  4151. auto res = cli_.Get("/with-range", {
  4152. make_range_header({{3, 5}}),
  4153. {"Accept-Encoding", ""},
  4154. });
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4157. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4158. EXPECT_EQ(true, res->has_header("Content-Range"));
  4159. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4160. EXPECT_EQ(std::string("def"), res->body);
  4161. }
  4162. TEST_F(ServerTest, GetWithRange2) {
  4163. auto res = cli_.Get("/with-range", {
  4164. make_range_header({{1, -1}}),
  4165. {"Accept-Encoding", ""},
  4166. });
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4169. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4170. EXPECT_EQ(true, res->has_header("Content-Range"));
  4171. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4172. EXPECT_EQ(std::string("bcdefg"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetWithRange3) {
  4175. auto res = cli_.Get("/with-range", {
  4176. make_range_header({{0, 0}}),
  4177. {"Accept-Encoding", ""},
  4178. });
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4181. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4182. EXPECT_EQ(true, res->has_header("Content-Range"));
  4183. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4184. EXPECT_EQ(std::string("a"), res->body);
  4185. }
  4186. TEST_F(ServerTest, GetWithRange4) {
  4187. auto res = cli_.Get("/with-range", {
  4188. make_range_header({{-1, 2}}),
  4189. {"Accept-Encoding", ""},
  4190. });
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4196. EXPECT_EQ(std::string("fg"), res->body);
  4197. }
  4198. TEST_F(ServerTest, GetWithRange5) {
  4199. auto res = cli_.Get("/with-range", {
  4200. make_range_header({{0, 5}}),
  4201. {"Accept-Encoding", ""},
  4202. });
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4205. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(true, res->has_header("Content-Range"));
  4207. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4208. EXPECT_EQ(std::string("abcdef"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4211. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4214. }
  4215. TEST_F(ServerTest, GetWithRangeMultipart) {
  4216. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4219. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4220. EXPECT_EQ(false, res->has_header("Content-Range"));
  4221. EXPECT_EQ(267U, res->body.size());
  4222. }
  4223. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4224. auto res =
  4225. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4228. }
  4229. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4230. auto res = cli_.Get("/with-range-customized-response",
  4231. {{make_range_header({{1, 2}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4234. EXPECT_EQ(true, res->has_header("Content-Length"));
  4235. EXPECT_EQ(false, res->has_header("Content-Range"));
  4236. EXPECT_EQ(JSON_DATA, res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4239. auto res = cli_.Get("/with-range-customized-response",
  4240. {{make_range_header({{1, 2}, {4, 5}})}});
  4241. ASSERT_TRUE(res);
  4242. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4243. EXPECT_EQ(true, res->has_header("Content-Length"));
  4244. EXPECT_EQ(false, res->has_header("Content-Range"));
  4245. EXPECT_EQ(JSON_DATA, res->body);
  4246. }
  4247. TEST_F(ServerTest, Issue1772) {
  4248. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4251. }
  4252. TEST_F(ServerTest, Issue609) {
  4253. auto res = cli_.Delete("/issue609");
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::OK_200, res->status);
  4256. EXPECT_EQ(std::string("ok"), res->body);
  4257. }
  4258. TEST_F(ServerTest, GetStreamedChunked) {
  4259. auto res = cli_.Get("/streamed-chunked");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ(std::string("123456789"), res->body);
  4263. }
  4264. TEST_F(ServerTest, GetStreamedChunked2) {
  4265. auto res = cli_.Get("/streamed-chunked2");
  4266. ASSERT_TRUE(res);
  4267. EXPECT_EQ(StatusCode::OK_200, res->status);
  4268. EXPECT_EQ(std::string("123456789"), res->body);
  4269. }
  4270. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4271. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ(std::string("123456789"), res->body);
  4275. EXPECT_TRUE(res->has_header("Trailer"));
  4276. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4277. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4278. // Trailers are now stored separately from headers (security fix)
  4279. EXPECT_EQ(2U, res->trailers.size());
  4280. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4281. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4282. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4283. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4284. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4285. // Verify trailers are NOT in headers (security verification)
  4286. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4287. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4288. }
  4289. TEST_F(ServerTest, LargeChunkedPost) {
  4290. Request req;
  4291. req.method = "POST";
  4292. req.path = "/large-chunked";
  4293. std::string host_and_port;
  4294. host_and_port += HOST;
  4295. host_and_port += ":";
  4296. host_and_port += std::to_string(PORT);
  4297. req.headers.emplace("Host", host_and_port.c_str());
  4298. req.headers.emplace("Accept", "*/*");
  4299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4300. req.headers.emplace("Content-Type", "text/plain");
  4301. req.headers.emplace("Content-Length", "0");
  4302. req.headers.emplace("Transfer-Encoding", "chunked");
  4303. std::string long_string(30 * 1024u, 'a');
  4304. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4305. // Attempt to make a large enough post to exceed OS buffers, to test that
  4306. // the server handles short reads if the full chunk data isn't available.
  4307. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4308. auto res = std::make_shared<Response>();
  4309. auto error = Error::Success;
  4310. auto ret = cli_.send(req, *res, error);
  4311. ASSERT_TRUE(ret);
  4312. EXPECT_EQ(StatusCode::OK_200, res->status);
  4313. }
  4314. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4315. auto res = cli_.Get("/remote_addr");
  4316. ASSERT_TRUE(res);
  4317. EXPECT_EQ(StatusCode::OK_200, res->status);
  4318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4319. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4320. }
  4321. TEST_F(ServerTest, GetMethodLocalAddr) {
  4322. auto res = cli_.Get("/local_addr");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4326. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4327. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4328. }
  4329. TEST_F(ServerTest, HTTPResponseSplitting) {
  4330. auto res = cli_.Get("/http_response_splitting");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. }
  4334. TEST_F(ServerTest, SlowRequest) {
  4335. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4336. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4337. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4338. }
  4339. #if 0
  4340. TEST_F(ServerTest, SlowPost) {
  4341. char buffer[64 * 1024];
  4342. memset(buffer, 0x42, sizeof(buffer));
  4343. auto res = cli_.Post(
  4344. "/slowpost", 64 * 1024 * 1024,
  4345. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4346. auto ret = sink.write(buffer, sizeof(buffer));
  4347. EXPECT_TRUE(ret);
  4348. return true;
  4349. },
  4350. "text/plain");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. TEST_F(ServerTest, SlowPostFail) {
  4355. char buffer[64 * 1024];
  4356. memset(buffer, 0x42, sizeof(buffer));
  4357. cli_.set_write_timeout(std::chrono::seconds(0));
  4358. auto res = cli_.Post(
  4359. "/slowpost", 64 * 1024 * 1024,
  4360. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4361. sink.write(buffer, sizeof(buffer));
  4362. return true;
  4363. },
  4364. "text/plain");
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_EQ(Error::Write, res.error());
  4367. }
  4368. #endif
  4369. TEST_F(ServerTest, Put) {
  4370. auto res = cli_.Put("/put", "PUT", "text/plain");
  4371. ASSERT_TRUE(res);
  4372. EXPECT_EQ(StatusCode::OK_200, res->status);
  4373. EXPECT_EQ("PUT", res->body);
  4374. }
  4375. TEST_F(ServerTest, PutWithContentProvider) {
  4376. auto res = cli_.Put(
  4377. "/put", 3,
  4378. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4379. sink.os << "PUT";
  4380. return true;
  4381. },
  4382. "text/plain");
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. EXPECT_EQ("PUT", res->body);
  4386. }
  4387. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4388. auto res = cli_.Post(
  4389. "/post", 42,
  4390. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4391. return false;
  4392. },
  4393. "text/plain");
  4394. ASSERT_TRUE(!res);
  4395. EXPECT_EQ(Error::Canceled, res.error());
  4396. }
  4397. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4398. auto res = cli_.Put(
  4399. "/put",
  4400. [](size_t /*offset*/, DataSink &sink) {
  4401. sink.os << "PUT";
  4402. sink.done();
  4403. return true;
  4404. },
  4405. "text/plain");
  4406. ASSERT_TRUE(res);
  4407. EXPECT_EQ(StatusCode::OK_200, res->status);
  4408. EXPECT_EQ("PUT", res->body);
  4409. }
  4410. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4411. auto res = cli_.Post(
  4412. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4413. "text/plain");
  4414. ASSERT_TRUE(!res);
  4415. EXPECT_EQ(Error::Canceled, res.error());
  4416. }
  4417. TEST_F(ServerTest, PostLoopBack) {
  4418. std::string body;
  4419. auto res = cli_.Post(
  4420. "/post-loopback", 9,
  4421. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4422. EXPECT_EQ(9u, length);
  4423. sink.write("123", 3);
  4424. sink.write("456", 3);
  4425. sink.write("789", 3);
  4426. return true;
  4427. },
  4428. "text/plain",
  4429. [&body](const char *data, size_t data_length) {
  4430. body.append(data, data_length);
  4431. return true;
  4432. });
  4433. ASSERT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. EXPECT_EQ("123456789", body);
  4436. }
  4437. TEST_F(ServerTest, PutLoopBack) {
  4438. std::string body;
  4439. auto res = cli_.Put(
  4440. "/put-loopback", 9,
  4441. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4442. EXPECT_EQ(9u, length);
  4443. sink.write("123", 3);
  4444. sink.write("456", 3);
  4445. sink.write("789", 3);
  4446. return true;
  4447. },
  4448. "text/plain",
  4449. [&body](const char *data, size_t data_length) {
  4450. body.append(data, data_length);
  4451. return true;
  4452. });
  4453. ASSERT_TRUE(res);
  4454. EXPECT_EQ(StatusCode::OK_200, res->status);
  4455. EXPECT_EQ("123456789", body);
  4456. }
  4457. TEST_F(ServerTest, PatchLoopBack) {
  4458. std::string body;
  4459. auto res = cli_.Patch(
  4460. "/patch-loopback", 9,
  4461. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4462. EXPECT_EQ(9u, length);
  4463. sink.write("123", 3);
  4464. sink.write("456", 3);
  4465. sink.write("789", 3);
  4466. return true;
  4467. },
  4468. "text/plain",
  4469. [&body](const char *data, size_t data_length) {
  4470. body.append(data, data_length);
  4471. return true;
  4472. });
  4473. ASSERT_TRUE(res);
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ("123456789", body);
  4476. }
  4477. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4478. std::string body;
  4479. auto res = cli_.Post(
  4480. "/post-loopback",
  4481. [](size_t /*offset*/, DataSink &sink) {
  4482. sink.write("123", 3);
  4483. sink.write("456", 3);
  4484. sink.write("789", 3);
  4485. sink.done();
  4486. return true;
  4487. },
  4488. "text/plain",
  4489. [&body](const char *data, size_t data_length) {
  4490. body.append(data, data_length);
  4491. return true;
  4492. });
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ("123456789", body);
  4496. }
  4497. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4498. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4499. cli_.set_compress(true);
  4500. auto res = cli_.Put(
  4501. "/put", 3,
  4502. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4503. sink.os << "PUT";
  4504. return true;
  4505. },
  4506. "text/plain");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. EXPECT_EQ("PUT", res->body);
  4510. }
  4511. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4512. cli_.set_compress(true);
  4513. auto res = cli_.Post(
  4514. "/post", 42,
  4515. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4516. return false;
  4517. },
  4518. "text/plain");
  4519. ASSERT_TRUE(!res);
  4520. EXPECT_EQ(Error::Canceled, res.error());
  4521. }
  4522. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4523. cli_.set_compress(true);
  4524. auto res = cli_.Put(
  4525. "/put",
  4526. [](size_t /*offset*/, DataSink &sink) {
  4527. sink.os << "PUT";
  4528. sink.done();
  4529. return true;
  4530. },
  4531. "text/plain");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. EXPECT_EQ("PUT", res->body);
  4535. }
  4536. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4537. cli_.set_compress(true);
  4538. auto res = cli_.Post(
  4539. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4540. "text/plain");
  4541. ASSERT_TRUE(!res);
  4542. EXPECT_EQ(Error::Canceled, res.error());
  4543. }
  4544. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4545. cli_.set_compress(true);
  4546. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::OK_200, res->status);
  4549. EXPECT_EQ(LARGE_DATA, res->body);
  4550. }
  4551. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4553. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4554. Client cli(s.c_str());
  4555. cli.enable_server_certificate_verification(false);
  4556. #else
  4557. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4558. Client cli(s.c_str());
  4559. #endif
  4560. cli.set_compress(true);
  4561. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. EXPECT_EQ(LARGE_DATA, res->body);
  4565. // The compressed size should be less than a 10th of the original. May vary
  4566. // depending on the zlib library.
  4567. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4568. static_cast<uint64_t>(10 * 1024 * 1024));
  4569. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4570. }
  4571. TEST_F(ServerTest, PutContentWithDeflate) {
  4572. cli_.set_compress(false);
  4573. Headers headers;
  4574. headers.emplace("Content-Encoding", "deflate");
  4575. // PUT in deflate format:
  4576. auto res = cli_.Put("/put", headers,
  4577. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. EXPECT_EQ("PUT", res->body);
  4581. }
  4582. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4583. Headers headers;
  4584. headers.emplace("Accept-Encoding", "gzip, deflate");
  4585. auto res = cli_.Get("/streamed-chunked", headers);
  4586. ASSERT_TRUE(res);
  4587. EXPECT_EQ(StatusCode::OK_200, res->status);
  4588. EXPECT_EQ(std::string("123456789"), res->body);
  4589. }
  4590. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4591. Headers headers;
  4592. headers.emplace("Accept-Encoding", "gzip, deflate");
  4593. auto res = cli_.Get("/streamed-chunked2", headers);
  4594. ASSERT_TRUE(res);
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ(std::string("123456789"), res->body);
  4597. }
  4598. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4599. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. TEST(GzipDecompressor, ChunkedDecompression) {
  4604. std::string data;
  4605. for (size_t i = 0; i < 32 * 1024; ++i) {
  4606. data.push_back(static_cast<char>('a' + i % 26));
  4607. }
  4608. std::string compressed_data;
  4609. {
  4610. httplib::detail::gzip_compressor compressor;
  4611. bool result = compressor.compress(
  4612. data.data(), data.size(),
  4613. /*last=*/true,
  4614. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4615. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4616. compressed_data_size);
  4617. return true;
  4618. });
  4619. ASSERT_TRUE(result);
  4620. }
  4621. std::string decompressed_data;
  4622. {
  4623. httplib::detail::gzip_decompressor decompressor;
  4624. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4625. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4626. size_t chunk_size = 130;
  4627. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4628. chunk_begin += chunk_size) {
  4629. size_t current_chunk_size =
  4630. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4631. bool result = decompressor.decompress(
  4632. compressed_data.data() + chunk_begin, current_chunk_size,
  4633. [&](const char *decompressed_data_chunk,
  4634. size_t decompressed_data_chunk_size) {
  4635. decompressed_data.insert(decompressed_data.size(),
  4636. decompressed_data_chunk,
  4637. decompressed_data_chunk_size);
  4638. return true;
  4639. });
  4640. ASSERT_TRUE(result);
  4641. }
  4642. }
  4643. ASSERT_EQ(data, decompressed_data);
  4644. }
  4645. TEST(GzipDecompressor, DeflateDecompression) {
  4646. std::string original_text = "Raw deflate without gzip";
  4647. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4651. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4652. std::string decompressed_data;
  4653. {
  4654. httplib::detail::gzip_decompressor decompressor;
  4655. bool result = decompressor.decompress(
  4656. compressed_data.data(), compressed_data.size(),
  4657. [&](const char *decompressed_data_chunk,
  4658. size_t decompressed_data_chunk_size) {
  4659. decompressed_data.insert(decompressed_data.size(),
  4660. decompressed_data_chunk,
  4661. decompressed_data_chunk_size);
  4662. return true;
  4663. });
  4664. ASSERT_TRUE(result);
  4665. }
  4666. ASSERT_EQ(original_text, decompressed_data);
  4667. }
  4668. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4669. std::string original_text = "Raw deflate without gzip";
  4670. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4671. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4672. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4673. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4674. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4675. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4676. std::string decompressed_data;
  4677. {
  4678. httplib::detail::gzip_decompressor decompressor;
  4679. bool result = decompressor.decompress(
  4680. compressed_data.data(), compressed_data.size(),
  4681. [&](const char *decompressed_data_chunk,
  4682. size_t decompressed_data_chunk_size) {
  4683. decompressed_data.insert(decompressed_data.size(),
  4684. decompressed_data_chunk,
  4685. decompressed_data_chunk_size);
  4686. return true;
  4687. });
  4688. ASSERT_TRUE(result);
  4689. }
  4690. ASSERT_EQ(original_text, decompressed_data);
  4691. }
  4692. #ifdef _WIN32
  4693. TEST(GzipDecompressor, LargeRandomData) {
  4694. // prepare large random data that is difficult to be compressed and is
  4695. // expected to have large size even when compressed
  4696. std::random_device seed_gen;
  4697. std::mt19937 random(seed_gen());
  4698. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4699. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4700. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4701. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4702. // compress data over 4GiB
  4703. std::string compressed_data;
  4704. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4705. httplib::detail::gzip_compressor compressor;
  4706. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4707. data.size() * sizeof(std::uint32_t), true,
  4708. [&](const char *data, size_t size) {
  4709. compressed_data.insert(
  4710. compressed_data.size(), data, size);
  4711. return true;
  4712. });
  4713. ASSERT_TRUE(result);
  4714. // FIXME: compressed data size is expected to be greater than 4GiB,
  4715. // but there is no guarantee
  4716. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4717. // decompress data over 4GiB
  4718. std::string decompressed_data;
  4719. decompressed_data.reserve(data_size);
  4720. httplib::detail::gzip_decompressor decompressor;
  4721. result = decompressor.decompress(
  4722. compressed_data.data(), compressed_data.size(),
  4723. [&](const char *data, size_t size) {
  4724. decompressed_data.insert(decompressed_data.size(), data, size);
  4725. return true;
  4726. });
  4727. ASSERT_TRUE(result);
  4728. // compare
  4729. ASSERT_EQ(data_size, decompressed_data.size());
  4730. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4731. 0);
  4732. }
  4733. #endif
  4734. #endif
  4735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4736. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4737. Headers headers;
  4738. headers.emplace("Accept-Encoding", "br");
  4739. auto res = cli_.Get("/streamed-chunked", headers);
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. EXPECT_EQ(std::string("123456789"), res->body);
  4743. }
  4744. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4745. Headers headers;
  4746. headers.emplace("Accept-Encoding", "br");
  4747. auto res = cli_.Get("/streamed-chunked2", headers);
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::OK_200, res->status);
  4750. EXPECT_EQ(std::string("123456789"), res->body);
  4751. }
  4752. #endif
  4753. TEST_F(ServerTest, Patch) {
  4754. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4755. ASSERT_TRUE(res);
  4756. EXPECT_EQ(StatusCode::OK_200, res->status);
  4757. EXPECT_EQ("PATCH", res->body);
  4758. }
  4759. TEST_F(ServerTest, Delete) {
  4760. auto res = cli_.Delete("/delete");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("DELETE", res->body);
  4764. }
  4765. TEST_F(ServerTest, DeleteContentReceiver) {
  4766. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. EXPECT_EQ("content", res->body);
  4770. }
  4771. TEST_F(ServerTest, Options) {
  4772. auto res = cli_.Options("*");
  4773. ASSERT_TRUE(res);
  4774. EXPECT_EQ(StatusCode::OK_200, res->status);
  4775. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4776. EXPECT_TRUE(res->body.empty());
  4777. }
  4778. TEST_F(ServerTest, URL) {
  4779. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4780. ASSERT_TRUE(res);
  4781. EXPECT_EQ(StatusCode::OK_200, res->status);
  4782. }
  4783. TEST_F(ServerTest, ArrayParam) {
  4784. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4785. ASSERT_TRUE(res);
  4786. EXPECT_EQ(StatusCode::OK_200, res->status);
  4787. }
  4788. TEST_F(ServerTest, NoMultipleHeaders) {
  4789. Headers headers = {{"Content-Length", "5"}};
  4790. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4791. "text/plain");
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. }
  4795. TEST_F(ServerTest, PostContentReceiver) {
  4796. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4797. ASSERT_TRUE(res);
  4798. ASSERT_EQ(StatusCode::OK_200, res->status);
  4799. ASSERT_EQ("content", res->body);
  4800. }
  4801. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4802. UploadFormDataItems items = {
  4803. {"text1", "text default", "", ""},
  4804. {"text2", "aωb", "", ""},
  4805. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4806. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4807. {"file3", "", "", "application/octet-stream"},
  4808. };
  4809. auto res = cli_.Post("/content_receiver", items);
  4810. ASSERT_TRUE(res);
  4811. EXPECT_EQ(StatusCode::OK_200, res->status);
  4812. }
  4813. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4814. UploadFormDataItems items = {
  4815. {"text1", "text default", "", ""},
  4816. {"text2", "aωb", "", ""},
  4817. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4818. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4819. {"file3", "", "", "application/octet-stream"},
  4820. };
  4821. auto boundary = std::string("+++++");
  4822. std::string body;
  4823. for (const auto &item : items) {
  4824. body += "--" + boundary + "\r\n";
  4825. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4826. if (!item.filename.empty()) {
  4827. body += "; filename=\"" + item.filename + "\"";
  4828. }
  4829. body += "\r\n";
  4830. if (!item.content_type.empty()) {
  4831. body += "Content-Type: " + item.content_type + "\r\n";
  4832. }
  4833. body += "\r\n";
  4834. body += item.content + "\r\n";
  4835. }
  4836. body += "--" + boundary + "--\r\n";
  4837. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4838. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::OK_200, res->status);
  4841. }
  4842. TEST_F(ServerTest, PostContentReceiverGzip) {
  4843. cli_.set_compress(true);
  4844. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4845. ASSERT_TRUE(res);
  4846. ASSERT_EQ(StatusCode::OK_200, res->status);
  4847. ASSERT_EQ("content", res->body);
  4848. }
  4849. TEST_F(ServerTest, PutContentReceiver) {
  4850. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4851. ASSERT_TRUE(res);
  4852. ASSERT_EQ(StatusCode::OK_200, res->status);
  4853. ASSERT_EQ("content", res->body);
  4854. }
  4855. TEST_F(ServerTest, PatchContentReceiver) {
  4856. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4857. ASSERT_TRUE(res);
  4858. ASSERT_EQ(StatusCode::OK_200, res->status);
  4859. ASSERT_EQ("content", res->body);
  4860. }
  4861. template <typename ClientType>
  4862. void TestWithHeadersAndContentReceiver(
  4863. ClientType &cli,
  4864. std::function<Result(ClientType &, const std::string &, const Headers &,
  4865. const std::string &, const std::string &,
  4866. ContentReceiver, DownloadProgress)>
  4867. request_func) {
  4868. Headers headers;
  4869. headers.emplace("X-Custom-Header", "test-value");
  4870. std::string received_body;
  4871. auto res = request_func(
  4872. cli, "/content_receiver", headers, "content", "application/json",
  4873. [&](const char *data, size_t data_length) {
  4874. received_body.append(data, data_length);
  4875. return true;
  4876. },
  4877. nullptr);
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. EXPECT_EQ("content", received_body);
  4881. }
  4882. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4884. using ClientT = SSLClient;
  4885. #else
  4886. using ClientT = Client;
  4887. #endif
  4888. TestWithHeadersAndContentReceiver<ClientT>(
  4889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4890. const std::string &body, const std::string &content_type,
  4891. ContentReceiver receiver, DownloadProgress progress) {
  4892. return cli.Post(path, headers, body, content_type, receiver, progress);
  4893. });
  4894. }
  4895. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4896. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4897. using ClientT = SSLClient;
  4898. #else
  4899. using ClientT = Client;
  4900. #endif
  4901. TestWithHeadersAndContentReceiver<ClientT>(
  4902. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4903. const std::string &body, const std::string &content_type,
  4904. ContentReceiver receiver, DownloadProgress progress) {
  4905. return cli.Put(path, headers, body, content_type, receiver, progress);
  4906. });
  4907. }
  4908. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4910. using ClientT = SSLClient;
  4911. #else
  4912. using ClientT = Client;
  4913. #endif
  4914. TestWithHeadersAndContentReceiver<ClientT>(
  4915. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4916. const std::string &body, const std::string &content_type,
  4917. ContentReceiver receiver, DownloadProgress progress) {
  4918. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4919. });
  4920. }
  4921. template <typename ClientType>
  4922. void TestWithHeadersAndContentReceiverWithProgress(
  4923. ClientType &cli,
  4924. std::function<Result(ClientType &, const std::string &, const Headers &,
  4925. const std::string &, const std::string &,
  4926. ContentReceiver, DownloadProgress)>
  4927. request_func) {
  4928. Headers headers;
  4929. headers.emplace("X-Test-Header", "progress-test");
  4930. std::string received_body;
  4931. auto progress_called = false;
  4932. auto res = request_func(
  4933. cli, "/content_receiver", headers, "content", "text/plain",
  4934. [&](const char *data, size_t data_length) {
  4935. received_body.append(data, data_length);
  4936. return true;
  4937. },
  4938. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4939. progress_called = true;
  4940. return true;
  4941. });
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. EXPECT_EQ("content", received_body);
  4945. EXPECT_TRUE(progress_called);
  4946. }
  4947. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4949. using ClientT = SSLClient;
  4950. #else
  4951. using ClientT = Client;
  4952. #endif
  4953. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4954. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4955. const std::string &body, const std::string &content_type,
  4956. ContentReceiver receiver, DownloadProgress progress) {
  4957. return cli.Post(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4961. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4962. using ClientT = SSLClient;
  4963. #else
  4964. using ClientT = Client;
  4965. #endif
  4966. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4967. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4968. const std::string &body, const std::string &content_type,
  4969. ContentReceiver receiver, DownloadProgress progress) {
  4970. return cli.Put(path, headers, body, content_type, receiver, progress);
  4971. });
  4972. }
  4973. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4975. using ClientT = SSLClient;
  4976. #else
  4977. using ClientT = Client;
  4978. #endif
  4979. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4980. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4981. const std::string &body, const std::string &content_type,
  4982. ContentReceiver receiver, DownloadProgress progress) {
  4983. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4984. });
  4985. }
  4986. template <typename ClientType>
  4987. void TestWithHeadersAndContentReceiverError(
  4988. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4989. const Headers &, const std::string &,
  4990. const std::string &, ContentReceiver)>
  4991. request_func) {
  4992. Headers headers;
  4993. headers.emplace("X-Error-Test", "true");
  4994. std::string received_body;
  4995. auto receiver_failed = false;
  4996. auto res =
  4997. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4998. [&](const char *data, size_t data_length) {
  4999. received_body.append(data, data_length);
  5000. receiver_failed = true;
  5001. return false;
  5002. });
  5003. ASSERT_FALSE(res);
  5004. EXPECT_TRUE(receiver_failed);
  5005. }
  5006. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5008. using ClientT = SSLClient;
  5009. #else
  5010. using ClientT = Client;
  5011. #endif
  5012. TestWithHeadersAndContentReceiverError<ClientT>(
  5013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5014. const std::string &body, const std::string &content_type,
  5015. ContentReceiver receiver) {
  5016. return cli.Post(path, headers, body, content_type, receiver);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5021. using ClientT = SSLClient;
  5022. #else
  5023. using ClientT = Client;
  5024. #endif
  5025. TestWithHeadersAndContentReceiverError<ClientT>(
  5026. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5027. const std::string &body, const std::string &content_type,
  5028. ContentReceiver receiver) {
  5029. return cli.Put(path, headers, body, content_type, receiver);
  5030. });
  5031. }
  5032. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5034. using ClientT = SSLClient;
  5035. #else
  5036. using ClientT = Client;
  5037. #endif
  5038. TestWithHeadersAndContentReceiverError<ClientT>(
  5039. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5040. const std::string &body, const std::string &content_type,
  5041. ContentReceiver receiver) {
  5042. return cli.Patch(path, headers, body, content_type, receiver);
  5043. });
  5044. }
  5045. TEST_F(ServerTest, PostQueryStringAndBody) {
  5046. auto res =
  5047. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5048. ASSERT_TRUE(res);
  5049. ASSERT_EQ(StatusCode::OK_200, res->status);
  5050. }
  5051. TEST_F(ServerTest, HTTP2Magic) {
  5052. Request req;
  5053. req.method = "PRI";
  5054. req.path = "*";
  5055. req.body = "SM";
  5056. auto res = std::make_shared<Response>();
  5057. auto error = Error::Success;
  5058. auto ret = cli_.send(req, *res, error);
  5059. ASSERT_TRUE(ret);
  5060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5061. }
  5062. TEST_F(ServerTest, KeepAlive) {
  5063. auto res = cli_.Get("/hi");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5067. EXPECT_EQ("Hello World!", res->body);
  5068. res = cli_.Get("/hi");
  5069. ASSERT_TRUE(res);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5072. EXPECT_EQ("Hello World!", res->body);
  5073. res = cli_.Get("/hi");
  5074. ASSERT_TRUE(res);
  5075. EXPECT_EQ(StatusCode::OK_200, res->status);
  5076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5077. EXPECT_EQ("Hello World!", res->body);
  5078. res = cli_.Get("/not-exist");
  5079. ASSERT_TRUE(res);
  5080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5081. res = cli_.Post("/empty", "", "text/plain");
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5085. EXPECT_EQ("empty", res->body);
  5086. EXPECT_EQ("close", res->get_header_value("Connection"));
  5087. res = cli_.Post(
  5088. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5089. "text/plain");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5093. EXPECT_EQ("empty", res->body);
  5094. cli_.set_keep_alive(false);
  5095. res = cli_.Get("/last-request");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("close", res->get_header_value("Connection"));
  5099. }
  5100. TEST_F(ServerTest, TooManyRedirect) {
  5101. cli_.set_follow_location(true);
  5102. auto res = cli_.Get("/redirect/0");
  5103. ASSERT_TRUE(!res);
  5104. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5105. }
  5106. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5107. Request req;
  5108. req.method = "FOOBAR";
  5109. req.path = "/hi";
  5110. cli_.set_keep_alive(true);
  5111. auto res = cli_.send(req);
  5112. ASSERT_TRUE(res);
  5113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. EXPECT_FALSE(cli_.is_socket_open());
  5116. }
  5117. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5119. TEST_F(ServerTest, Gzip) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "gzip, deflate");
  5122. auto res = cli_.Get("/compress", headers);
  5123. ASSERT_TRUE(res);
  5124. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5127. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5128. "7890123456789012345678901234567890",
  5129. res->body);
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. }
  5132. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5133. Headers headers;
  5134. headers.emplace("Accept-Encoding", "");
  5135. auto res = cli_.Get("/compress", headers);
  5136. ASSERT_TRUE(res);
  5137. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5139. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5140. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5141. "7890123456789012345678901234567890",
  5142. res->body);
  5143. EXPECT_EQ(StatusCode::OK_200, res->status);
  5144. }
  5145. TEST_F(ServerTest, GzipWithContentReceiver) {
  5146. Headers headers;
  5147. headers.emplace("Accept-Encoding", "gzip, deflate");
  5148. std::string body;
  5149. auto res = cli_.Get("/compress", headers,
  5150. [&](const char *data, uint64_t data_length) {
  5151. EXPECT_EQ(100U, data_length);
  5152. body.append(data, data_length);
  5153. return true;
  5154. });
  5155. ASSERT_TRUE(res);
  5156. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5158. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5159. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5160. "7890123456789012345678901234567890",
  5161. body);
  5162. EXPECT_EQ(StatusCode::OK_200, res->status);
  5163. }
  5164. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5165. Headers headers;
  5166. headers.emplace("Accept-Encoding", "gzip, deflate");
  5167. cli_.set_decompress(false);
  5168. auto res = cli_.Get("/compress", headers);
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5173. EXPECT_EQ(33U, res->body.size());
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. }
  5176. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5177. Headers headers;
  5178. headers.emplace("Accept-Encoding", "");
  5179. std::string body;
  5180. auto res = cli_.Get("/compress", headers,
  5181. [&](const char *data, uint64_t data_length) {
  5182. EXPECT_EQ(100U, data_length);
  5183. body.append(data, data_length);
  5184. return true;
  5185. });
  5186. ASSERT_TRUE(res);
  5187. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5189. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5190. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5191. "7890123456789012345678901234567890",
  5192. body);
  5193. EXPECT_EQ(StatusCode::OK_200, res->status);
  5194. }
  5195. TEST_F(ServerTest, NoGzip) {
  5196. Headers headers;
  5197. headers.emplace("Accept-Encoding", "gzip, deflate");
  5198. auto res = cli_.Get("/nocompress", headers);
  5199. ASSERT_TRUE(res);
  5200. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5201. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5202. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5203. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5204. "7890123456789012345678901234567890",
  5205. res->body);
  5206. EXPECT_EQ(StatusCode::OK_200, res->status);
  5207. }
  5208. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5209. Headers headers;
  5210. headers.emplace("Accept-Encoding", "gzip, deflate");
  5211. std::string body;
  5212. auto res = cli_.Get("/nocompress", headers,
  5213. [&](const char *data, uint64_t data_length) {
  5214. EXPECT_EQ(100U, data_length);
  5215. body.append(data, data_length);
  5216. return true;
  5217. });
  5218. ASSERT_TRUE(res);
  5219. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5220. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5221. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5222. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5223. "7890123456789012345678901234567890",
  5224. body);
  5225. EXPECT_EQ(StatusCode::OK_200, res->status);
  5226. }
  5227. TEST_F(ServerTest, MultipartFormDataGzip) {
  5228. UploadFormDataItems items = {
  5229. {"key1", "test", "", ""},
  5230. {"key2", "--abcdefg123", "", ""},
  5231. };
  5232. cli_.set_compress(true);
  5233. auto res = cli_.Post("/compress-multipart", items);
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. }
  5237. #endif
  5238. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5239. TEST_F(ServerTest, Brotli) {
  5240. Headers headers;
  5241. headers.emplace("Accept-Encoding", "br");
  5242. auto res = cli_.Get("/compress", headers);
  5243. ASSERT_TRUE(res);
  5244. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5246. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5247. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5248. "7890123456789012345678901234567890",
  5249. res->body);
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. }
  5252. #endif
  5253. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5254. TEST_F(ServerTest, Zstd) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "zstd");
  5257. auto res = cli_.Get("/compress", headers);
  5258. ASSERT_TRUE(res);
  5259. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5261. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5262. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5263. "7890123456789012345678901234567890",
  5264. res->body);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5281. Headers headers;
  5282. headers.emplace("Accept-Encoding", "zstd");
  5283. std::string body;
  5284. auto res = cli_.Get("/compress", headers,
  5285. [&](const char *data, uint64_t data_length) {
  5286. EXPECT_EQ(100U, data_length);
  5287. body.append(data, data_length);
  5288. return true;
  5289. });
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5293. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5294. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5295. "7890123456789012345678901234567890",
  5296. body);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5300. Headers headers;
  5301. headers.emplace("Accept-Encoding", "zstd");
  5302. cli_.set_decompress(false);
  5303. auto res = cli_.Get("/compress", headers);
  5304. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5305. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5306. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5307. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5311. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. ASSERT_EQ(26U, res->body.size());
  5314. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5315. 0);
  5316. }
  5317. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5318. Headers headers;
  5319. headers.emplace("Accept-Encoding", "");
  5320. std::string body;
  5321. auto res = cli_.Get("/compress", headers,
  5322. [&](const char *data, uint64_t data_length) {
  5323. EXPECT_EQ(100U, data_length);
  5324. body.append(data, data_length);
  5325. return true;
  5326. });
  5327. ASSERT_TRUE(res);
  5328. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5330. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5331. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5332. "7890123456789012345678901234567890",
  5333. body);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. }
  5336. TEST_F(ServerTest, NoZstd) {
  5337. Headers headers;
  5338. headers.emplace("Accept-Encoding", "zstd");
  5339. auto res = cli_.Get("/nocompress", headers);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5342. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5343. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5344. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5345. "7890123456789012345678901234567890",
  5346. res->body);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. }
  5349. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5350. Headers headers;
  5351. headers.emplace("Accept-Encoding", "zstd");
  5352. std::string body;
  5353. auto res = cli_.Get("/nocompress", headers,
  5354. [&](const char *data, uint64_t data_length) {
  5355. EXPECT_EQ(100U, data_length);
  5356. body.append(data, data_length);
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5361. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5362. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5363. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5364. "7890123456789012345678901234567890",
  5365. body);
  5366. EXPECT_EQ(StatusCode::OK_200, res->status);
  5367. }
  5368. // TODO: How to enable zstd ??
  5369. TEST_F(ServerTest, MultipartFormDataZstd) {
  5370. UploadFormDataItems items = {
  5371. {"key1", "test", "", ""},
  5372. {"key2", "--abcdefg123", "", ""},
  5373. };
  5374. Headers headers;
  5375. headers.emplace("Accept-Encoding", "zstd");
  5376. cli_.set_compress(true);
  5377. auto res = cli_.Post("/compress-multipart", headers, items);
  5378. ASSERT_TRUE(res);
  5379. EXPECT_EQ(StatusCode::OK_200, res->status);
  5380. }
  5381. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5382. Headers headers;
  5383. headers.emplace("Accept-Encoding", "zstd");
  5384. cli_.set_compress(true);
  5385. auto res = cli_.Put(
  5386. "/put", headers, 3,
  5387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5388. sink.os << "PUT";
  5389. return true;
  5390. },
  5391. "text/plain");
  5392. ASSERT_TRUE(res);
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. EXPECT_EQ("PUT", res->body);
  5395. }
  5396. // Pre-compression logging tests
  5397. TEST_F(ServerTest, PreCompressionLogging) {
  5398. // Test data for compression (matches the actual /compress endpoint content)
  5399. const std::string test_content =
  5400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5401. "3456789012345678901234567890";
  5402. // Variables to capture logging data
  5403. std::string pre_compression_body;
  5404. std::string pre_compression_content_type;
  5405. std::string pre_compression_content_encoding;
  5406. std::string post_compression_body;
  5407. std::string post_compression_content_type;
  5408. std::string post_compression_content_encoding;
  5409. // Set up pre-compression logger
  5410. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5411. const Response &res) {
  5412. pre_compression_body = res.body;
  5413. pre_compression_content_type = res.get_header_value("Content-Type");
  5414. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5415. });
  5416. // Set up post-compression logger
  5417. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5418. post_compression_body = res.body;
  5419. post_compression_content_type = res.get_header_value("Content-Type");
  5420. post_compression_content_encoding =
  5421. res.get_header_value("Content-Encoding");
  5422. });
  5423. // Test with gzip compression
  5424. Headers headers;
  5425. headers.emplace("Accept-Encoding", "gzip");
  5426. auto res = cli_.Get("/compress", headers);
  5427. // Verify response was compressed
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5431. // Verify pre-compression logger captured uncompressed content
  5432. EXPECT_EQ(test_content, pre_compression_body);
  5433. EXPECT_EQ("text/plain", pre_compression_content_type);
  5434. EXPECT_TRUE(pre_compression_content_encoding
  5435. .empty()); // No encoding header before compression
  5436. // Verify post-compression logger captured compressed content
  5437. EXPECT_NE(test_content,
  5438. post_compression_body); // Should be different after compression
  5439. EXPECT_EQ("text/plain", post_compression_content_type);
  5440. EXPECT_EQ("gzip", post_compression_content_encoding);
  5441. // Verify compressed content is smaller
  5442. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5443. }
  5444. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5445. const std::string test_content =
  5446. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5447. "3456789012345678901234567890";
  5448. std::string pre_compression_body;
  5449. std::string post_compression_body;
  5450. svr_.set_pre_compression_logger(
  5451. [&](const Request & /*req*/, const Response &res) {
  5452. pre_compression_body = res.body;
  5453. });
  5454. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5455. post_compression_body = res.body;
  5456. });
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "br");
  5459. auto res = cli_.Get("/compress", headers);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5463. // Verify pre-compression content is uncompressed
  5464. EXPECT_EQ(test_content, pre_compression_body);
  5465. // Verify post-compression content is compressed
  5466. EXPECT_NE(test_content, post_compression_body);
  5467. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5468. }
  5469. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5470. const std::string test_content =
  5471. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5472. "3456789012345678901234567890";
  5473. std::string pre_compression_body;
  5474. std::string post_compression_body;
  5475. svr_.set_pre_compression_logger(
  5476. [&](const Request & /*req*/, const Response &res) {
  5477. pre_compression_body = res.body;
  5478. });
  5479. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5480. post_compression_body = res.body;
  5481. });
  5482. // Request without compression (use /nocompress endpoint)
  5483. Headers headers;
  5484. auto res = cli_.Get("/nocompress", headers);
  5485. ASSERT_TRUE(res);
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5488. // Pre-compression logger should not be called when no compression is applied
  5489. EXPECT_TRUE(
  5490. pre_compression_body.empty()); // Pre-compression logger not called
  5491. EXPECT_EQ(
  5492. test_content,
  5493. post_compression_body); // Post-compression logger captures final content
  5494. }
  5495. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5496. const std::string test_content =
  5497. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5498. "3456789012345678901234567890";
  5499. std::string pre_compression_body;
  5500. bool pre_logger_called = false;
  5501. // Set only pre-compression logger
  5502. svr_.set_pre_compression_logger(
  5503. [&](const Request & /*req*/, const Response &res) {
  5504. pre_compression_body = res.body;
  5505. pre_logger_called = true;
  5506. });
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "gzip");
  5509. auto res = cli_.Get("/compress", headers);
  5510. ASSERT_TRUE(res);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5513. // Verify pre-compression logger was called
  5514. EXPECT_TRUE(pre_logger_called);
  5515. EXPECT_EQ(test_content, pre_compression_body);
  5516. }
  5517. TEST(ZstdDecompressor, ChunkedDecompression) {
  5518. std::string data;
  5519. for (size_t i = 0; i < 32 * 1024; ++i) {
  5520. data.push_back(static_cast<char>('a' + i % 26));
  5521. }
  5522. std::string compressed_data;
  5523. {
  5524. httplib::detail::zstd_compressor compressor;
  5525. bool result = compressor.compress(
  5526. data.data(), data.size(),
  5527. /*last=*/true,
  5528. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5529. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5530. compressed_data_size);
  5531. return true;
  5532. });
  5533. ASSERT_TRUE(result);
  5534. }
  5535. std::string decompressed_data;
  5536. {
  5537. httplib::detail::zstd_decompressor decompressor;
  5538. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5539. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5540. size_t chunk_size = 130;
  5541. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5542. chunk_begin += chunk_size) {
  5543. size_t current_chunk_size =
  5544. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5545. bool result = decompressor.decompress(
  5546. compressed_data.data() + chunk_begin, current_chunk_size,
  5547. [&](const char *decompressed_data_chunk,
  5548. size_t decompressed_data_chunk_size) {
  5549. decompressed_data.insert(decompressed_data.size(),
  5550. decompressed_data_chunk,
  5551. decompressed_data_chunk_size);
  5552. return true;
  5553. });
  5554. ASSERT_TRUE(result);
  5555. }
  5556. }
  5557. ASSERT_EQ(data, decompressed_data);
  5558. }
  5559. TEST(ZstdDecompressor, Decompress) {
  5560. std::string original_text = "Compressed with ZSTD";
  5561. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5562. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5563. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5564. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5565. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5566. std::string decompressed_data;
  5567. {
  5568. httplib::detail::zstd_decompressor decompressor;
  5569. bool result = decompressor.decompress(
  5570. compressed_data.data(), compressed_data.size(),
  5571. [&](const char *decompressed_data_chunk,
  5572. size_t decompressed_data_chunk_size) {
  5573. decompressed_data.insert(decompressed_data.size(),
  5574. decompressed_data_chunk,
  5575. decompressed_data_chunk_size);
  5576. return true;
  5577. });
  5578. ASSERT_TRUE(result);
  5579. }
  5580. ASSERT_EQ(original_text, decompressed_data);
  5581. }
  5582. #endif
  5583. // Sends a raw request to a server listening at HOST:PORT.
  5584. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5585. std::string *resp = nullptr) {
  5586. auto error = Error::Success;
  5587. auto client_sock = detail::create_client_socket(
  5588. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5589. /*connection_timeout_sec=*/5, 0,
  5590. /*read_timeout_sec=*/5, 0,
  5591. /*write_timeout_sec=*/5, 0, std::string(), error);
  5592. if (client_sock == INVALID_SOCKET) { return false; }
  5593. auto ret = detail::process_client_socket(
  5594. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5595. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5596. if (req.size() !=
  5597. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5598. return false;
  5599. }
  5600. char buf[512];
  5601. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5602. while (line_reader.getline()) {
  5603. if (resp) { *resp += line_reader.ptr(); }
  5604. }
  5605. return true;
  5606. });
  5607. detail::close_socket(client_sock);
  5608. return ret;
  5609. }
  5610. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5611. Server svr;
  5612. std::string header_value;
  5613. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5614. header_value = req.get_header_value("foo");
  5615. res.set_content("ok", "text/plain");
  5616. });
  5617. thread t = thread([&] { svr.listen(HOST, PORT); });
  5618. auto se = detail::scope_exit([&] {
  5619. svr.stop();
  5620. t.join();
  5621. ASSERT_FALSE(svr.is_running());
  5622. });
  5623. svr.wait_until_ready();
  5624. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5625. // like characters are not treated the same - use vertical tab and escape.
  5626. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5627. "foo: \t \v bar \x1B\t \r\n"
  5628. "Connection: close\r\n"
  5629. "\r\n";
  5630. std::string res;
  5631. ASSERT_TRUE(send_request(5, req, &res));
  5632. EXPECT_EQ(header_value, "");
  5633. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5634. }
  5635. // Sends a raw request and verifies that there isn't a crash or exception.
  5636. static void test_raw_request(const std::string &req,
  5637. std::string *out = nullptr) {
  5638. Server svr;
  5639. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5640. res.set_content("ok", "text/plain");
  5641. });
  5642. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. svr.Get("/header_field_value_check",
  5646. [&](const Request & /*req*/, Response &res) {
  5647. res.set_content("ok", "text/plain");
  5648. });
  5649. // Server read timeout must be longer than the client read timeout for the
  5650. // bug to reproduce, probably to force the server to process a request
  5651. // without a trailing blank line.
  5652. const time_t client_read_timeout_sec = 1;
  5653. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5654. bool listen_thread_ok = false;
  5655. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5656. auto se = detail::scope_exit([&] {
  5657. svr.stop();
  5658. t.join();
  5659. ASSERT_FALSE(svr.is_running());
  5660. EXPECT_TRUE(listen_thread_ok);
  5661. });
  5662. svr.wait_until_ready();
  5663. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5664. }
  5665. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5666. // A certain header line causes an exception if the header property is parsed
  5667. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5668. test_raw_request(
  5669. "GET /hi HTTP/1.1\r\n"
  5670. " : "
  5671. " "
  5672. " ");
  5673. }
  5674. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5675. // A certain header line causes an exception if the header property *name* is
  5676. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5677. // greedy matcher and requires backtracking when there are a lot of ":"
  5678. // characters.
  5679. // This occurs with libc++ but not libstdc++.
  5680. test_raw_request(
  5681. "GET /hi HTTP/1.1\r\n"
  5682. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5683. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5684. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5685. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5686. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5687. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5688. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5689. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5690. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5691. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5692. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5693. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5694. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5695. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5696. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5697. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5698. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5699. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5700. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5701. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5702. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5703. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5704. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5705. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5706. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5707. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5708. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5709. "&&&%%%");
  5710. }
  5711. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5712. // Make sure this doesn't crash the server.
  5713. // In a previous version of the header line regex, the "\r" rendered the line
  5714. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5715. // a new position where the leading white space ended and the field value
  5716. // began.
  5717. // The crash occurs with libc++ but not libstdc++.
  5718. test_raw_request("GET /hi HTTP/1.1\r\n"
  5719. "a:" +
  5720. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5721. "\r\n"
  5722. "\r\n");
  5723. }
  5724. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5725. std::string out;
  5726. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5727. "Content-Type: text/plain\r\n"
  5728. "Transfer-Encoding: chunked\r\n"
  5729. "\r\n"
  5730. "nothex\r\n",
  5731. &out);
  5732. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5733. }
  5734. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5735. std::string out;
  5736. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5737. "Content-Type: text/plain\r\n"
  5738. "Transfer-Encoding: chunked\r\n"
  5739. "\r\n"
  5740. "3\r\n"
  5741. "xyz\r\n"
  5742. "NaN\r\n",
  5743. &out);
  5744. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5745. }
  5746. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5747. std::string out;
  5748. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5749. "Content-Type: text/plain\r\n"
  5750. "Transfer-Encoding: chunked\r\n"
  5751. "\r\n"
  5752. // Length is too large for 64 bits.
  5753. "1ffffffffffffffff\r\n"
  5754. "xyz\r\n",
  5755. &out);
  5756. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5757. }
  5758. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5759. test_raw_request("GET /hi HTTP/1.1\r\n"
  5760. "Content-Type: text/plain\r\n\r");
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5763. std::string out;
  5764. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5765. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5766. }
  5767. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5768. std::string out;
  5769. std::string request(
  5770. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5771. test_raw_request(request, &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5775. std::string out;
  5776. std::string request(
  5777. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5778. test_raw_request(request, &out);
  5779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5780. }
  5781. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5782. std::string out;
  5783. std::string request(
  5784. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5785. test_raw_request(request, &out);
  5786. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5787. }
  5788. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5789. std::string out;
  5790. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5791. "Test: \r\n\r\n",
  5792. &out);
  5793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5794. }
  5795. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5796. Server svr;
  5797. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5798. res.set_header("Cache-Control", "no-cache");
  5799. res.set_chunked_content_provider(
  5800. "text/event-stream", [](size_t offset, DataSink &sink) {
  5801. std::string s = "data:";
  5802. s += std::to_string(offset);
  5803. s += "\n\n";
  5804. auto ret = sink.write(s.data(), s.size());
  5805. EXPECT_TRUE(ret);
  5806. std::this_thread::sleep_for(std::chrono::seconds(1));
  5807. return true;
  5808. });
  5809. });
  5810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5811. svr.wait_until_ready();
  5812. Client client(HOST, PORT);
  5813. const Headers headers = {{"Accept", "text/event-stream"}};
  5814. auto get_thread = std::thread([&client, &headers]() {
  5815. auto res = client.Get(
  5816. "/events", headers,
  5817. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5818. });
  5819. auto se = detail::scope_exit([&] {
  5820. svr.stop();
  5821. get_thread.join();
  5822. listen_thread.join();
  5823. ASSERT_FALSE(svr.is_running());
  5824. });
  5825. // Give GET time to get a few messages.
  5826. std::this_thread::sleep_for(std::chrono::seconds(2));
  5827. }
  5828. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5829. httplib::Server svr;
  5830. svr.Post("/hi",
  5831. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5832. res.status = StatusCode::OK_200;
  5833. });
  5834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5835. svr.wait_until_ready();
  5836. Client cli(HOST, PORT);
  5837. auto res = cli.Post("/hi", "data", "text/plain");
  5838. ASSERT_TRUE(res);
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. svr.stop();
  5841. thread.join();
  5842. ASSERT_FALSE(svr.is_running());
  5843. res = cli.Post("/hi", "data", "text/plain");
  5844. ASSERT_FALSE(res);
  5845. }
  5846. TEST(ServerStopTest, ListenFailure) {
  5847. Server svr;
  5848. auto t = thread([&]() {
  5849. auto ret = svr.listen("????", PORT);
  5850. EXPECT_FALSE(ret);
  5851. });
  5852. svr.wait_until_ready();
  5853. svr.stop();
  5854. t.join();
  5855. }
  5856. TEST(ServerStopTest, Decommision) {
  5857. Server svr;
  5858. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5859. for (int i = 0; i < 4; i++) {
  5860. auto is_even = !(i % 2);
  5861. std::thread t{[&] {
  5862. try {
  5863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5864. if (is_even) {
  5865. throw std::runtime_error("Some thing that happens to go wrong.");
  5866. }
  5867. svr.listen(HOST, PORT);
  5868. } catch (...) { svr.decommission(); }
  5869. }};
  5870. svr.wait_until_ready();
  5871. // Server is up
  5872. {
  5873. Client cli(HOST, PORT);
  5874. auto res = cli.Get("/hi");
  5875. if (is_even) {
  5876. EXPECT_FALSE(res);
  5877. } else {
  5878. EXPECT_TRUE(res);
  5879. EXPECT_EQ("hi...", res->body);
  5880. }
  5881. }
  5882. svr.stop();
  5883. t.join();
  5884. // Server is down...
  5885. {
  5886. Client cli(HOST, PORT);
  5887. auto res = cli.Get("/hi");
  5888. EXPECT_FALSE(res);
  5889. }
  5890. }
  5891. }
  5892. // Helper function for string body upload progress tests
  5893. template <typename SetupHandler, typename ClientCall>
  5894. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5895. ClientCall &&client_call,
  5896. const string &body) {
  5897. Server svr;
  5898. setup_handler(svr);
  5899. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5900. auto se = detail::scope_exit([&] {
  5901. svr.stop();
  5902. t.join();
  5903. });
  5904. svr.wait_until_ready();
  5905. Client cli(HOST, PORT);
  5906. vector<uint64_t> progress_values;
  5907. bool progress_called = false;
  5908. auto res =
  5909. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5910. progress_values.push_back(current);
  5911. progress_called = true;
  5912. return true;
  5913. });
  5914. ASSERT_TRUE(res);
  5915. EXPECT_EQ(200, res->status);
  5916. EXPECT_TRUE(progress_called);
  5917. }
  5918. TEST(UploadProgressTest, PostStringBodyBasic) {
  5919. TestStringBodyUploadProgress(
  5920. [](Server &svr) {
  5921. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5922. res.set_content("received", "text/plain");
  5923. });
  5924. },
  5925. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5926. return cli.Post("/test", body, "text/plain", progress_callback);
  5927. },
  5928. "test data for upload progress");
  5929. }
  5930. TEST(UploadProgressTest, PutStringBodyBasic) {
  5931. TestStringBodyUploadProgress(
  5932. [](Server &svr) {
  5933. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5934. res.set_content("put received", "text/plain");
  5935. });
  5936. },
  5937. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5938. return cli.Put("/test", body, "text/plain", progress_callback);
  5939. },
  5940. "put test data for upload progress");
  5941. }
  5942. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5943. TestStringBodyUploadProgress(
  5944. [](Server &svr) {
  5945. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5946. res.set_content("patch received", "text/plain");
  5947. });
  5948. },
  5949. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5950. return cli.Patch("/test", body, "text/plain", progress_callback);
  5951. },
  5952. "patch test data for upload progress");
  5953. }
  5954. // Helper function for content provider upload progress tests
  5955. template <typename SetupHandler, typename ClientCall>
  5956. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5957. ClientCall &&client_call) {
  5958. Server svr;
  5959. setup_handler(svr);
  5960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. });
  5965. svr.wait_until_ready();
  5966. Client cli(HOST, PORT);
  5967. vector<uint64_t> progress_values;
  5968. auto res =
  5969. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5970. progress_values.push_back(current);
  5971. return true;
  5972. });
  5973. ASSERT_TRUE(res);
  5974. EXPECT_EQ(200, res->status);
  5975. EXPECT_FALSE(progress_values.empty());
  5976. }
  5977. TEST(UploadProgressTest, PostContentProviderProgress) {
  5978. TestContentProviderUploadProgress(
  5979. [](Server &svr) {
  5980. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5981. res.set_content("provider received", "text/plain");
  5982. });
  5983. },
  5984. [](Client &cli, UploadProgress progress_callback) {
  5985. return cli.Post(
  5986. "/test", 10,
  5987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5988. sink.os << "test data";
  5989. return true;
  5990. },
  5991. "text/plain", progress_callback);
  5992. });
  5993. }
  5994. // Helper function for multipart upload progress tests
  5995. template <typename SetupHandler, typename ClientCall>
  5996. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5997. ClientCall &&client_call,
  5998. const string &endpoint) {
  5999. Server svr;
  6000. setup_handler(svr);
  6001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6002. auto se = detail::scope_exit([&] {
  6003. svr.stop();
  6004. t.join();
  6005. });
  6006. svr.wait_until_ready();
  6007. Client cli(HOST, PORT);
  6008. vector<uint64_t> progress_values;
  6009. UploadFormDataItems items = {
  6010. {"field1", "value1", "", ""},
  6011. {"field2", "longer value for progress tracking test", "", ""},
  6012. {"file1", "file content data for upload progress", "test.txt",
  6013. "text/plain"}};
  6014. auto res = client_call(cli, endpoint, items,
  6015. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6016. progress_values.push_back(current);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(200, res->status);
  6021. EXPECT_FALSE(progress_values.empty());
  6022. }
  6023. TEST(UploadProgressTest, PostMultipartProgress) {
  6024. TestMultipartUploadProgress(
  6025. [](Server &svr) {
  6026. svr.Post("/multipart", [](const Request &req, Response &res) {
  6027. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6028. res.set_content("multipart received", "text/plain");
  6029. });
  6030. },
  6031. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6032. UploadProgress progress_callback) {
  6033. return cli.Post(endpoint, items, progress_callback);
  6034. },
  6035. "/multipart");
  6036. }
  6037. // Helper function for basic download progress tests
  6038. template <typename SetupHandler, typename ClientCall>
  6039. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6040. ClientCall &&client_call, const string &endpoint,
  6041. size_t expected_content_size) {
  6042. Server svr;
  6043. setup_handler(svr);
  6044. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6045. auto se = detail::scope_exit([&] {
  6046. svr.stop();
  6047. t.join();
  6048. });
  6049. svr.wait_until_ready();
  6050. Client cli(HOST, PORT);
  6051. vector<uint64_t> progress_values;
  6052. auto res = client_call(cli, endpoint,
  6053. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6054. progress_values.push_back(current);
  6055. return true;
  6056. });
  6057. ASSERT_TRUE(res);
  6058. EXPECT_EQ(200, res->status);
  6059. EXPECT_FALSE(progress_values.empty());
  6060. EXPECT_EQ(expected_content_size, res->body.size());
  6061. }
  6062. TEST(DownloadProgressTest, GetBasic) {
  6063. TestBasicDownloadProgress(
  6064. [](Server &svr) {
  6065. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6066. string content(1000, 'D');
  6067. res.set_content(content, "text/plain");
  6068. });
  6069. },
  6070. [](Client &cli, const string &endpoint,
  6071. DownloadProgress progress_callback) {
  6072. return cli.Get(endpoint, progress_callback);
  6073. },
  6074. "/download", 1000u);
  6075. }
  6076. // Helper function for content receiver download progress tests
  6077. template <typename SetupHandler, typename ClientCall>
  6078. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6079. ClientCall &&client_call,
  6080. const string &endpoint,
  6081. size_t expected_content_size) {
  6082. Server svr;
  6083. setup_handler(svr);
  6084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6085. auto se = detail::scope_exit([&] {
  6086. svr.stop();
  6087. t.join();
  6088. });
  6089. svr.wait_until_ready();
  6090. Client cli(HOST, PORT);
  6091. vector<uint64_t> progress_values;
  6092. string received_body;
  6093. auto res = client_call(
  6094. cli, endpoint,
  6095. [&](const char *data, size_t data_length) -> bool {
  6096. received_body.append(data, data_length);
  6097. return true;
  6098. },
  6099. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6100. progress_values.push_back(current);
  6101. return true;
  6102. });
  6103. ASSERT_TRUE(res);
  6104. EXPECT_EQ(200, res->status);
  6105. EXPECT_FALSE(progress_values.empty());
  6106. EXPECT_EQ(expected_content_size, received_body.size());
  6107. EXPECT_TRUE(res->body.empty());
  6108. }
  6109. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6110. TestContentReceiverDownloadProgress(
  6111. [](Server &svr) {
  6112. svr.Get("/download-receiver",
  6113. [](const Request & /*req*/, Response &res) {
  6114. string content(2000, 'R');
  6115. res.set_content(content, "text/plain");
  6116. });
  6117. },
  6118. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6119. DownloadProgress progress_callback) {
  6120. return cli.Get(endpoint, content_receiver, progress_callback);
  6121. },
  6122. "/download-receiver", 2000u);
  6123. }
  6124. TEST(StreamingTest, NoContentLengthStreaming) {
  6125. Server svr;
  6126. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6127. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6128. if (offset < 6) {
  6129. sink.os << (offset < 3 ? "a" : "b");
  6130. } else {
  6131. sink.done();
  6132. }
  6133. return true;
  6134. });
  6135. });
  6136. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6137. auto listen_se = detail::scope_exit([&] {
  6138. svr.stop();
  6139. listen_thread.join();
  6140. ASSERT_FALSE(svr.is_running());
  6141. });
  6142. svr.wait_until_ready();
  6143. Client client(HOST, PORT);
  6144. auto get_thread = std::thread([&client]() {
  6145. std::string s;
  6146. auto res =
  6147. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6148. s += std::string(data, len);
  6149. return true;
  6150. });
  6151. ASSERT_TRUE(res);
  6152. EXPECT_EQ(StatusCode::OK_200, res->status);
  6153. EXPECT_EQ("aaabbb", s);
  6154. });
  6155. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6156. // Give GET time to get a few messages.
  6157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6158. }
  6159. TEST(MountTest, Unmount) {
  6160. Server svr;
  6161. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6162. auto se = detail::scope_exit([&] {
  6163. svr.stop();
  6164. listen_thread.join();
  6165. ASSERT_FALSE(svr.is_running());
  6166. });
  6167. svr.wait_until_ready();
  6168. Client cli("localhost", PORT);
  6169. svr.set_mount_point("/mount2", "./www2");
  6170. auto res = cli.Get("/");
  6171. ASSERT_TRUE(res);
  6172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6173. res = cli.Get("/mount2/dir/test.html");
  6174. ASSERT_TRUE(res);
  6175. EXPECT_EQ(StatusCode::OK_200, res->status);
  6176. svr.set_mount_point("/", "./www");
  6177. res = cli.Get("/dir/");
  6178. ASSERT_TRUE(res);
  6179. EXPECT_EQ(StatusCode::OK_200, res->status);
  6180. svr.remove_mount_point("/");
  6181. res = cli.Get("/dir/");
  6182. ASSERT_TRUE(res);
  6183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6184. svr.remove_mount_point("/mount2");
  6185. res = cli.Get("/mount2/dir/test.html");
  6186. ASSERT_TRUE(res);
  6187. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6188. }
  6189. TEST(MountTest, Redicect) {
  6190. Server svr;
  6191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6192. auto se = detail::scope_exit([&] {
  6193. svr.stop();
  6194. listen_thread.join();
  6195. ASSERT_FALSE(svr.is_running());
  6196. });
  6197. svr.set_mount_point("/", "./www");
  6198. svr.wait_until_ready();
  6199. Client cli("localhost", PORT);
  6200. auto res = cli.Get("/dir/");
  6201. ASSERT_TRUE(res);
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. res = cli.Get("/dir");
  6204. ASSERT_TRUE(res);
  6205. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6206. res = cli.Get("/file");
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli.Get("/file/");
  6210. ASSERT_TRUE(res);
  6211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6212. cli.set_follow_location(true);
  6213. res = cli.Get("/dir");
  6214. ASSERT_TRUE(res);
  6215. EXPECT_EQ(StatusCode::OK_200, res->status);
  6216. }
  6217. TEST(MountTest, MultibytesPathName) {
  6218. Server svr;
  6219. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.set_mount_point("/", "./www");
  6226. svr.wait_until_ready();
  6227. Client cli("localhost", PORT);
  6228. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6229. ASSERT_TRUE(res);
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6232. }
  6233. TEST(KeepAliveTest, ReadTimeout) {
  6234. Server svr;
  6235. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6236. std::this_thread::sleep_for(std::chrono::seconds(2));
  6237. res.set_content("a", "text/plain");
  6238. });
  6239. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6240. res.set_content("b", "text/plain");
  6241. });
  6242. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6243. auto se = detail::scope_exit([&] {
  6244. svr.stop();
  6245. listen_thread.join();
  6246. ASSERT_FALSE(svr.is_running());
  6247. });
  6248. svr.wait_until_ready();
  6249. Client cli("localhost", PORT);
  6250. cli.set_keep_alive(true);
  6251. cli.set_read_timeout(std::chrono::seconds(1));
  6252. auto resa = cli.Get("/a");
  6253. ASSERT_FALSE(resa);
  6254. EXPECT_EQ(Error::Read, resa.error());
  6255. auto resb = cli.Get("/b");
  6256. ASSERT_TRUE(resb);
  6257. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6258. EXPECT_EQ("b", resb->body);
  6259. }
  6260. TEST(KeepAliveTest, MaxCount) {
  6261. size_t keep_alive_max_count = 3;
  6262. Server svr;
  6263. svr.set_keep_alive_max_count(keep_alive_max_count);
  6264. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6265. res.set_content("Hello World!", "text/plain");
  6266. });
  6267. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6268. auto se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. listen_thread.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. });
  6273. svr.wait_until_ready();
  6274. Client cli(HOST, PORT);
  6275. cli.set_keep_alive(true);
  6276. for (size_t i = 0; i < 5; i++) {
  6277. auto result = cli.Get("/hi");
  6278. ASSERT_TRUE(result);
  6279. EXPECT_EQ(StatusCode::OK_200, result->status);
  6280. if (i == keep_alive_max_count - 1) {
  6281. EXPECT_EQ("close", result->get_header_value("Connection"));
  6282. } else {
  6283. EXPECT_FALSE(result->has_header("Connection"));
  6284. }
  6285. }
  6286. }
  6287. TEST(KeepAliveTest, Issue1041) {
  6288. Server svr;
  6289. svr.set_keep_alive_timeout(3);
  6290. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6291. res.set_content("Hello World!", "text/plain");
  6292. });
  6293. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6294. auto se = detail::scope_exit([&] {
  6295. svr.stop();
  6296. listen_thread.join();
  6297. ASSERT_FALSE(svr.is_running());
  6298. });
  6299. svr.wait_until_ready();
  6300. Client cli(HOST, PORT);
  6301. cli.set_keep_alive(true);
  6302. auto result = cli.Get("/hi");
  6303. ASSERT_TRUE(result);
  6304. EXPECT_EQ(StatusCode::OK_200, result->status);
  6305. std::this_thread::sleep_for(std::chrono::seconds(5));
  6306. result = cli.Get("/hi");
  6307. ASSERT_TRUE(result);
  6308. EXPECT_EQ(StatusCode::OK_200, result->status);
  6309. }
  6310. TEST(KeepAliveTest, Issue1959) {
  6311. Server svr;
  6312. svr.set_keep_alive_timeout(5);
  6313. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6314. res.set_content("a", "text/plain");
  6315. });
  6316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. if (!svr.is_running()) return;
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. Client cli("localhost", PORT);
  6325. cli.set_keep_alive(true);
  6326. using namespace std::chrono;
  6327. auto start = steady_clock::now();
  6328. cli.Get("/a");
  6329. svr.stop();
  6330. listen_thread.join();
  6331. auto end = steady_clock::now();
  6332. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6333. EXPECT_LT(elapsed, 5000);
  6334. }
  6335. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6336. TEST(KeepAliveTest, SSLClientReconnection) {
  6337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6338. ASSERT_TRUE(svr.is_valid());
  6339. svr.set_keep_alive_timeout(1);
  6340. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6341. res.set_content("Hello World!", "text/plain");
  6342. });
  6343. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6344. auto se = detail::scope_exit([&] {
  6345. svr.stop();
  6346. listen_thread.join();
  6347. ASSERT_FALSE(svr.is_running());
  6348. });
  6349. svr.wait_until_ready();
  6350. SSLClient cli(HOST, PORT);
  6351. cli.enable_server_certificate_verification(false);
  6352. cli.set_keep_alive(true);
  6353. auto result = cli.Get("/hi");
  6354. ASSERT_TRUE(result);
  6355. EXPECT_EQ(StatusCode::OK_200, result->status);
  6356. result = cli.Get("/hi");
  6357. ASSERT_TRUE(result);
  6358. EXPECT_EQ(StatusCode::OK_200, result->status);
  6359. std::this_thread::sleep_for(std::chrono::seconds(2));
  6360. // Recoonect
  6361. result = cli.Get("/hi");
  6362. ASSERT_TRUE(result);
  6363. EXPECT_EQ(StatusCode::OK_200, result->status);
  6364. result = cli.Get("/hi");
  6365. ASSERT_TRUE(result);
  6366. EXPECT_EQ(StatusCode::OK_200, result->status);
  6367. }
  6368. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6370. ASSERT_TRUE(svr.is_valid());
  6371. svr.set_keep_alive_timeout(1);
  6372. std::string content = "reconnect";
  6373. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6374. res.set_content("Hello World!", "text/plain");
  6375. });
  6376. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. ASSERT_FALSE(svr.is_running());
  6381. });
  6382. svr.wait_until_ready();
  6383. SSLClient cli(HOST, PORT);
  6384. cli.enable_server_certificate_verification(false);
  6385. cli.set_keep_alive(true);
  6386. auto result = cli.Post(
  6387. "/hi", content.size(),
  6388. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6389. sink.write(content.c_str(), content.size());
  6390. return true;
  6391. },
  6392. "text/plain");
  6393. ASSERT_TRUE(result);
  6394. EXPECT_EQ(200, result->status);
  6395. std::this_thread::sleep_for(std::chrono::seconds(2));
  6396. // Recoonect
  6397. result = cli.Post(
  6398. "/hi", content.size(),
  6399. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6400. sink.write(content.c_str(), content.size());
  6401. return true;
  6402. },
  6403. "text/plain");
  6404. ASSERT_TRUE(result);
  6405. EXPECT_EQ(200, result->status);
  6406. result = cli.Post(
  6407. "/hi", content.size(),
  6408. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6409. sink.write(content.c_str(), content.size());
  6410. return true;
  6411. },
  6412. "text/plain");
  6413. ASSERT_TRUE(result);
  6414. EXPECT_EQ(200, result->status);
  6415. }
  6416. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6417. {
  6418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6419. ASSERT_TRUE(svr.is_valid());
  6420. svr.Get("/sni", [&](const Request &req, Response &res) {
  6421. std::string expected;
  6422. if (req.ssl) {
  6423. if (const char *sni =
  6424. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6425. expected = sni;
  6426. }
  6427. }
  6428. EXPECT_EQ(expected, req.get_param_value("expected"));
  6429. res.set_content("ok", "text/plain");
  6430. });
  6431. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6432. auto se = detail::scope_exit([&] {
  6433. svr.stop();
  6434. listen_thread.join();
  6435. ASSERT_FALSE(svr.is_running());
  6436. });
  6437. svr.wait_until_ready();
  6438. {
  6439. SSLClient cli("localhost", PORT);
  6440. cli.enable_server_certificate_verification(false);
  6441. auto res = cli.Get("/sni?expected=localhost");
  6442. ASSERT_TRUE(res);
  6443. }
  6444. {
  6445. SSLClient cli("::1", PORT);
  6446. cli.enable_server_certificate_verification(false);
  6447. auto res = cli.Get("/sni?expected=");
  6448. // NOTE: This may fail if the server is listening on IPv4 only
  6449. // (e.g., when localhost resolves to 127.0.0.1 only)
  6450. if (res) {
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. } else {
  6453. EXPECT_EQ(Error::Connection, res.error());
  6454. }
  6455. }
  6456. }
  6457. }
  6458. #endif
  6459. TEST(ClientProblemDetectionTest, ContentProvider) {
  6460. Server svr;
  6461. size_t content_length = 1024 * 1024;
  6462. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6463. res.set_content_provider(
  6464. content_length, "text/plain",
  6465. [&](size_t offset, size_t length, DataSink &sink) {
  6466. auto out_len = std::min(length, static_cast<size_t>(1024));
  6467. std::string out(out_len, '@');
  6468. sink.write(out.data(), out_len);
  6469. return offset < 4096;
  6470. },
  6471. [](bool success) { ASSERT_FALSE(success); });
  6472. });
  6473. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6474. res.set_content_provider(
  6475. 0, "text/plain",
  6476. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6477. EXPECT_TRUE(false);
  6478. return true;
  6479. },
  6480. [](bool success) { ASSERT_FALSE(success); });
  6481. });
  6482. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6483. auto se = detail::scope_exit([&] {
  6484. svr.stop();
  6485. listen_thread.join();
  6486. ASSERT_FALSE(svr.is_running());
  6487. });
  6488. svr.wait_until_ready();
  6489. Client cli("localhost", PORT);
  6490. {
  6491. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6492. size_t /*data_length*/) { return false; });
  6493. ASSERT_FALSE(res);
  6494. }
  6495. {
  6496. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6497. size_t /*data_length*/) { return false; });
  6498. ASSERT_TRUE(res);
  6499. }
  6500. }
  6501. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6502. Server svr;
  6503. svr.set_error_handler([](Request const &, Response &res) -> void {
  6504. res.set_chunked_content_provider(
  6505. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6506. sink.os << "hello";
  6507. sink.os << "world";
  6508. sink.done();
  6509. return true;
  6510. });
  6511. });
  6512. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6513. auto se = detail::scope_exit([&] {
  6514. svr.stop();
  6515. listen_thread.join();
  6516. ASSERT_FALSE(svr.is_running());
  6517. });
  6518. svr.wait_until_ready();
  6519. Client cli("localhost", PORT);
  6520. auto res = cli.Get("/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. EXPECT_EQ("helloworld", res->body);
  6524. }
  6525. TEST(LongPollingTest, ClientCloseDetection) {
  6526. Server svr;
  6527. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6528. res.set_chunked_content_provider(
  6529. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6530. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6531. sink.os << "hello";
  6532. auto count = 10;
  6533. while (count > 0 && sink.is_writable()) {
  6534. this_thread::sleep_for(chrono::milliseconds(10));
  6535. count--;
  6536. }
  6537. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6538. return true;
  6539. });
  6540. });
  6541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.wait_until_ready();
  6548. Client cli("localhost", PORT);
  6549. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6550. EXPECT_EQ("hello", string(data, data_length));
  6551. return false; // close the socket immediately.
  6552. });
  6553. ASSERT_FALSE(res);
  6554. }
  6555. TEST(GetWithParametersTest, GetWithParameters) {
  6556. Server svr;
  6557. svr.Get("/", [&](const Request &req, Response &) {
  6558. EXPECT_EQ("world", req.get_param_value("hello"));
  6559. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6560. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6561. });
  6562. svr.Get("/params", [&](const Request &req, Response &) {
  6563. EXPECT_EQ("world", req.get_param_value("hello"));
  6564. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6565. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6566. });
  6567. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6568. EXPECT_EQ("resource-id", req.matches[1]);
  6569. EXPECT_EQ("foo", req.get_param_value("param1"));
  6570. EXPECT_EQ("bar", req.get_param_value("param2"));
  6571. });
  6572. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6573. EXPECT_EQ("user-id", req.path_params.at("id"));
  6574. EXPECT_EQ("foo", req.get_param_value("param1"));
  6575. EXPECT_EQ("bar", req.get_param_value("param2"));
  6576. });
  6577. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6578. auto se = detail::scope_exit([&] {
  6579. svr.stop();
  6580. listen_thread.join();
  6581. ASSERT_FALSE(svr.is_running());
  6582. });
  6583. svr.wait_until_ready();
  6584. {
  6585. Client cli(HOST, PORT);
  6586. Params params;
  6587. params.emplace("hello", "world");
  6588. params.emplace("hello2", "world2");
  6589. params.emplace("hello3", "world3");
  6590. auto res = cli.Get("/", params, Headers{});
  6591. ASSERT_TRUE(res);
  6592. EXPECT_EQ(StatusCode::OK_200, res->status);
  6593. }
  6594. {
  6595. Client cli(HOST, PORT);
  6596. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6597. ASSERT_TRUE(res);
  6598. EXPECT_EQ(StatusCode::OK_200, res->status);
  6599. }
  6600. {
  6601. Client cli(HOST, PORT);
  6602. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. }
  6606. {
  6607. Client cli(HOST, PORT);
  6608. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6609. ASSERT_TRUE(res);
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. }
  6612. }
  6613. TEST(GetWithParametersTest, GetWithParameters2) {
  6614. Server svr;
  6615. svr.Get("/", [&](const Request &req, Response &res) {
  6616. auto text = req.get_param_value("hello");
  6617. res.set_content(text, "text/plain");
  6618. });
  6619. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6620. auto se = detail::scope_exit([&] {
  6621. svr.stop();
  6622. listen_thread.join();
  6623. ASSERT_FALSE(svr.is_running());
  6624. });
  6625. svr.wait_until_ready();
  6626. Client cli("localhost", PORT);
  6627. Params params;
  6628. params.emplace("hello", "world");
  6629. std::string body;
  6630. auto res = cli.Get("/", params, Headers{},
  6631. [&](const char *data, size_t data_length) {
  6632. body.append(data, data_length);
  6633. return true;
  6634. });
  6635. ASSERT_TRUE(res);
  6636. EXPECT_EQ(StatusCode::OK_200, res->status);
  6637. EXPECT_EQ("world", body);
  6638. }
  6639. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6640. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6641. auto host = "httpbin.org";
  6642. auto path = std::string{"/range/32"};
  6643. #else
  6644. auto host = "nghttp2.org";
  6645. auto path = std::string{"/httpbin/range/32"};
  6646. #endif
  6647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6648. SSLClient cli(host);
  6649. #else
  6650. Client cli(host);
  6651. #endif
  6652. cli.set_default_headers({make_range_header({{1, 10}})});
  6653. cli.set_connection_timeout(5);
  6654. {
  6655. auto res = cli.Get(path);
  6656. ASSERT_TRUE(res);
  6657. EXPECT_EQ("bcdefghijk", res->body);
  6658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6659. }
  6660. {
  6661. auto res = cli.Get(path);
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ("bcdefghijk", res->body);
  6664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6665. }
  6666. }
  6667. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6668. Server svr;
  6669. svr.set_default_headers({{"Hello", "World"}});
  6670. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6671. res.set_content("ok", "text/plain");
  6672. });
  6673. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6674. auto se = detail::scope_exit([&] {
  6675. svr.stop();
  6676. listen_thread.join();
  6677. ASSERT_FALSE(svr.is_running());
  6678. });
  6679. svr.wait_until_ready();
  6680. Client cli("localhost", PORT);
  6681. auto res = cli.Get("/");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. EXPECT_EQ("ok", res->body);
  6685. EXPECT_EQ("World", res->get_header_value("Hello"));
  6686. }
  6687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6688. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6690. ASSERT_TRUE(svr.is_valid());
  6691. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6692. std::this_thread::sleep_for(std::chrono::seconds(2));
  6693. res.set_content("a", "text/plain");
  6694. });
  6695. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6696. res.set_content("b", "text/plain");
  6697. });
  6698. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6699. auto se = detail::scope_exit([&] {
  6700. svr.stop();
  6701. listen_thread.join();
  6702. ASSERT_FALSE(svr.is_running());
  6703. });
  6704. svr.wait_until_ready();
  6705. SSLClient cli("localhost", PORT);
  6706. cli.enable_server_certificate_verification(false);
  6707. cli.set_keep_alive(true);
  6708. cli.set_read_timeout(std::chrono::seconds(1));
  6709. auto resa = cli.Get("/a");
  6710. ASSERT_TRUE(!resa);
  6711. EXPECT_EQ(Error::Read, resa.error());
  6712. auto resb = cli.Get("/b");
  6713. ASSERT_TRUE(resb);
  6714. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6715. EXPECT_EQ("b", resb->body);
  6716. }
  6717. #endif
  6718. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6719. protected:
  6720. ServerTestWithAI_PASSIVE()
  6721. : cli_(HOST, PORT)
  6722. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6723. ,
  6724. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6725. #endif
  6726. {
  6727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6728. cli_.enable_server_certificate_verification(false);
  6729. #endif
  6730. }
  6731. virtual void SetUp() {
  6732. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6733. res.set_content("Hello World!", "text/plain");
  6734. });
  6735. t_ = thread(
  6736. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6737. svr_.wait_until_ready();
  6738. }
  6739. virtual void TearDown() {
  6740. svr_.stop();
  6741. t_.join();
  6742. }
  6743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6744. SSLClient cli_;
  6745. SSLServer svr_;
  6746. #else
  6747. Client cli_;
  6748. Server svr_;
  6749. #endif
  6750. thread t_;
  6751. };
  6752. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6753. auto res = cli_.Get("/hi");
  6754. ASSERT_TRUE(res);
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6757. EXPECT_EQ("Hello World!", res->body);
  6758. }
  6759. class ServerUpDownTest : public ::testing::Test {
  6760. protected:
  6761. ServerUpDownTest() : cli_(HOST, PORT) {}
  6762. virtual void SetUp() {
  6763. t_ = thread([&]() {
  6764. svr_.bind_to_any_port(HOST);
  6765. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6766. ASSERT_TRUE(svr_.listen_after_bind());
  6767. });
  6768. svr_.wait_until_ready();
  6769. }
  6770. virtual void TearDown() {
  6771. svr_.stop();
  6772. t_.join();
  6773. }
  6774. Client cli_;
  6775. Server svr_;
  6776. thread t_;
  6777. };
  6778. TEST_F(ServerUpDownTest, QuickStartStop) {
  6779. // Should not crash, especially when run with
  6780. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6781. }
  6782. class PayloadMaxLengthTest : public ::testing::Test {
  6783. protected:
  6784. PayloadMaxLengthTest()
  6785. : cli_(HOST, PORT)
  6786. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6787. ,
  6788. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6789. #endif
  6790. {
  6791. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6792. cli_.enable_server_certificate_verification(false);
  6793. #endif
  6794. }
  6795. virtual void SetUp() {
  6796. svr_.set_payload_max_length(8);
  6797. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6798. res.set_content("test", "text/plain");
  6799. });
  6800. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6801. svr_.wait_until_ready();
  6802. }
  6803. virtual void TearDown() {
  6804. svr_.stop();
  6805. t_.join();
  6806. }
  6807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6808. SSLClient cli_;
  6809. SSLServer svr_;
  6810. #else
  6811. Client cli_;
  6812. Server svr_;
  6813. #endif
  6814. thread t_;
  6815. };
  6816. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6817. auto res = cli_.Post("/test", "123456789", "text/plain");
  6818. ASSERT_TRUE(res);
  6819. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6820. res = cli_.Post("/test", "12345678", "text/plain");
  6821. ASSERT_TRUE(res);
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. }
  6824. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6825. // Test chunked encoding with payload exceeding the 8-byte limit
  6826. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6827. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6828. ASSERT_TRUE(res);
  6829. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6830. }
  6831. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6832. // Test chunked encoding with payload within the 8-byte limit
  6833. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6834. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. }
  6838. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6839. // Test using send_request to send chunked data exceeding payload limit
  6840. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6841. "Host: " +
  6842. std::string(HOST) + ":" + std::to_string(PORT) +
  6843. "\r\n"
  6844. "Transfer-Encoding: chunked\r\n"
  6845. "Connection: close\r\n"
  6846. "\r\n"
  6847. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6848. "0123456789\r\n"
  6849. "0\r\n" // End chunk
  6850. "\r\n";
  6851. std::string response;
  6852. bool result = send_request(1, chunked_request, &response);
  6853. if (!result) {
  6854. // If send_request fails, it might be because the server closed the
  6855. // connection due to payload limit enforcement, which is acceptable
  6856. SUCCEED()
  6857. << "Server rejected oversized chunked request (connection closed)";
  6858. } else {
  6859. // If we got a response, check if it's an error response or connection was
  6860. // closed early Short response length indicates connection was closed due to
  6861. // payload limit
  6862. if (response.length() <= 10) {
  6863. SUCCEED() << "Server closed connection for oversized chunked request";
  6864. } else {
  6865. // Check for error status codes
  6866. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6867. response.find("Payload Too Large") != std::string::npos ||
  6868. response.find("400") != std::string::npos);
  6869. }
  6870. }
  6871. }
  6872. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6873. // Test request without Content-Length header exceeding payload limit
  6874. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6875. "Host: " +
  6876. std::string(HOST) + ":" +
  6877. std::to_string(PORT) +
  6878. "\r\n"
  6879. "Connection: close\r\n"
  6880. "\r\n";
  6881. // Add payload exceeding the 8-byte limit
  6882. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6883. request_without_content_length += large_payload;
  6884. std::string response;
  6885. bool result = send_request(1, request_without_content_length, &response);
  6886. if (!result) {
  6887. // If send_request fails, server likely closed connection due to payload
  6888. // limit
  6889. SUCCEED() << "Server rejected oversized request without Content-Length "
  6890. "(connection closed)";
  6891. } else {
  6892. // Check if server responded with error or closed connection early
  6893. if (response.length() <= 10) {
  6894. SUCCEED() << "Server closed connection for oversized request without "
  6895. "Content-Length";
  6896. } else {
  6897. // Check for error status codes
  6898. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6899. response.find("Payload Too Large") != std::string::npos ||
  6900. response.find("400") != std::string::npos);
  6901. }
  6902. }
  6903. }
  6904. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6905. // Test request without Content-Length header within payload limit
  6906. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6907. "Host: " +
  6908. std::string(HOST) + ":" +
  6909. std::to_string(PORT) +
  6910. "\r\n"
  6911. "Connection: close\r\n"
  6912. "\r\n";
  6913. // Add payload within the 8-byte limit
  6914. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6915. request_without_content_length += small_payload;
  6916. std::string response;
  6917. bool result = send_request(1, request_without_content_length, &response);
  6918. // For requests without Content-Length, the server may have different behavior
  6919. // The key is that it should not reject due to payload limit for small
  6920. // payloads
  6921. if (result) {
  6922. // Check for any HTTP response (success or error, but not connection closed)
  6923. if (response.length() > 10) {
  6924. SUCCEED()
  6925. << "Server processed request without Content-Length within limit";
  6926. } else {
  6927. // Short response might indicate connection closed, which is acceptable
  6928. SUCCEED() << "Server closed connection for request without "
  6929. "Content-Length (acceptable behavior)";
  6930. }
  6931. } else {
  6932. // Connection failure might be due to protocol requirements
  6933. SUCCEED() << "Connection issue with request without Content-Length "
  6934. "(environment-specific)";
  6935. }
  6936. }
  6937. class LargePayloadMaxLengthTest : public ::testing::Test {
  6938. protected:
  6939. LargePayloadMaxLengthTest()
  6940. : cli_(HOST, PORT)
  6941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6942. ,
  6943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6944. #endif
  6945. {
  6946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6947. cli_.enable_server_certificate_verification(false);
  6948. #endif
  6949. }
  6950. virtual void SetUp() {
  6951. // Set 10MB payload limit
  6952. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6953. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6954. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6955. res.set_content("Large payload test", "text/plain");
  6956. });
  6957. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6958. svr_.wait_until_ready();
  6959. }
  6960. virtual void TearDown() {
  6961. svr_.stop();
  6962. t_.join();
  6963. }
  6964. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6965. SSLClient cli_;
  6966. SSLServer svr_;
  6967. #else
  6968. Client cli_;
  6969. Server svr_;
  6970. #endif
  6971. thread t_;
  6972. };
  6973. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6974. // Test chunked encoding with payload within 10MB limit
  6975. std::string medium_payload(5 * 1024 * 1024,
  6976. 'A'); // 5MB payload, within 10MB limit
  6977. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6978. ASSERT_TRUE(res);
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. }
  6981. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6982. // Test chunked encoding with payload exceeding 10MB limit
  6983. std::string large_payload(12 * 1024 * 1024,
  6984. 'B'); // 12MB payload, exceeds 10MB limit
  6985. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6986. ASSERT_TRUE(res);
  6987. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6988. }
  6989. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6990. // Test request without Content-Length header within 10MB limit
  6991. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6992. "Host: " +
  6993. std::string(HOST) + ":" +
  6994. std::to_string(PORT) +
  6995. "\r\n"
  6996. "Connection: close\r\n"
  6997. "\r\n";
  6998. // Add 1MB payload (within 10MB limit)
  6999. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7000. request_without_content_length += medium_payload;
  7001. std::string response;
  7002. bool result = send_request(5, request_without_content_length, &response);
  7003. if (result) {
  7004. // Should get a proper HTTP response for payloads within limit
  7005. if (response.length() > 10) {
  7006. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7007. "10MB limit";
  7008. } else {
  7009. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7010. "Content-Length)";
  7011. }
  7012. } else {
  7013. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7014. }
  7015. }
  7016. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7017. // Test request without Content-Length header exceeding 10MB limit
  7018. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7019. "Host: " +
  7020. std::string(HOST) + ":" +
  7021. std::to_string(PORT) +
  7022. "\r\n"
  7023. "Connection: close\r\n"
  7024. "\r\n";
  7025. // Add 12MB payload (exceeds 10MB limit)
  7026. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7027. request_without_content_length += large_payload;
  7028. std::string response;
  7029. bool result = send_request(10, request_without_content_length, &response);
  7030. if (!result) {
  7031. // Server should close connection due to payload limit
  7032. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7033. "(connection closed)";
  7034. } else {
  7035. // Check for error response
  7036. if (response.length() <= 10) {
  7037. SUCCEED()
  7038. << "Server closed connection for 12MB request exceeding 10MB limit";
  7039. } else {
  7040. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7041. response.find("Payload Too Large") != std::string::npos ||
  7042. response.find("400") != std::string::npos);
  7043. }
  7044. }
  7045. }
  7046. TEST(HostAndPortPropertiesTest, NoSSL) {
  7047. httplib::Client cli("www.google.com", 1234);
  7048. ASSERT_EQ("www.google.com", cli.host());
  7049. ASSERT_EQ(1234, cli.port());
  7050. }
  7051. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7052. httplib::Client cli("www.google.com:1234");
  7053. ASSERT_EQ("www.google.com", cli.host());
  7054. ASSERT_EQ(1234, cli.port());
  7055. }
  7056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7057. TEST(HostAndPortPropertiesTest, SSL) {
  7058. httplib::SSLClient cli("www.google.com");
  7059. ASSERT_EQ("www.google.com", cli.host());
  7060. ASSERT_EQ(443, cli.port());
  7061. }
  7062. #endif
  7063. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7064. TEST(SSLClientTest, UpdateCAStore) {
  7065. httplib::SSLClient httplib_client("www.google.com");
  7066. auto ca_store_1 = X509_STORE_new();
  7067. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7068. nullptr);
  7069. httplib_client.set_ca_cert_store(ca_store_1);
  7070. auto ca_store_2 = X509_STORE_new();
  7071. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7072. nullptr);
  7073. httplib_client.set_ca_cert_store(ca_store_2);
  7074. }
  7075. TEST(SSLClientTest, ServerNameIndication_Online) {
  7076. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7077. auto host = "httpbin.org";
  7078. auto path = std::string{"/get"};
  7079. #else
  7080. auto host = "nghttp2.org";
  7081. auto path = std::string{"/httpbin/get"};
  7082. #endif
  7083. SSLClient cli(host, 443);
  7084. auto res = cli.Get(path);
  7085. ASSERT_TRUE(res);
  7086. ASSERT_EQ(StatusCode::OK_200, res->status);
  7087. }
  7088. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7089. // Use a site that will cause SSL verification failure due to self-signed cert
  7090. SSLClient cli("self-signed.badssl.com", 443);
  7091. cli.enable_server_certificate_verification(true);
  7092. auto res = cli.Get("/");
  7093. ASSERT_TRUE(!res);
  7094. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7095. // For SSL server verification errors, ssl_error should be 0, only
  7096. // ssl_openssl_error should be set
  7097. EXPECT_EQ(0, res.ssl_error());
  7098. // Verify OpenSSL error is captured for SSLServerVerification
  7099. // This occurs when SSL_get_verify_result() returns a verification failure
  7100. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7101. res.ssl_openssl_error());
  7102. }
  7103. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7104. // Use a site where hostname doesn't match the certificate
  7105. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7106. SSLClient cli("wrong.host.badssl.com", 443);
  7107. cli.enable_server_certificate_verification(true);
  7108. cli.enable_server_hostname_verification(true);
  7109. auto res = cli.Get("/");
  7110. ASSERT_TRUE(!res);
  7111. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7112. // For SSL hostname verification errors, ssl_error should be 0, only
  7113. // ssl_openssl_error should be set
  7114. EXPECT_EQ(0, res.ssl_error());
  7115. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7116. // This occurs when verify_host() fails due to hostname mismatch
  7117. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7118. res.ssl_openssl_error());
  7119. }
  7120. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7121. Client cli("https://google.com");
  7122. auto res = cli.Get("/");
  7123. ASSERT_TRUE(res);
  7124. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7125. }
  7126. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7127. SSLClient cli("google.com");
  7128. cli.set_ca_cert_path(CA_CERT_FILE);
  7129. auto res = cli.Get("/");
  7130. ASSERT_TRUE(res);
  7131. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7132. }
  7133. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7134. SSLClient cli("google.com");
  7135. cli.enable_server_certificate_verification(true);
  7136. cli.set_ca_cert_path("hello");
  7137. auto res = cli.Get("/");
  7138. ASSERT_TRUE(!res);
  7139. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7140. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7141. // should be set
  7142. EXPECT_EQ(0, res.ssl_error());
  7143. // Verify OpenSSL error is captured for SSLLoadingCerts
  7144. // This error occurs when SSL_CTX_load_verify_locations() fails
  7145. // > openssl errstr 0x80000002
  7146. // error:80000002:system library::No such file or directory
  7147. // > openssl errstr 0xA000126
  7148. // error:0A000126:SSL routines::unexpected eof while reading
  7149. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7150. res.ssl_openssl_error() == 0xA000126);
  7151. }
  7152. TEST(SSLClientTest, ServerCertificateVerification4) {
  7153. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7154. ASSERT_TRUE(svr.is_valid());
  7155. svr.Get("/test", [&](const Request &, Response &res) {
  7156. res.set_content("test", "text/plain");
  7157. svr.stop();
  7158. ASSERT_TRUE(true);
  7159. });
  7160. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7161. auto se = detail::scope_exit([&] {
  7162. t.join();
  7163. ASSERT_FALSE(svr.is_running());
  7164. });
  7165. svr.wait_until_ready();
  7166. SSLClient cli("127.0.0.1", PORT);
  7167. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7168. cli.enable_server_certificate_verification(true);
  7169. cli.set_connection_timeout(30);
  7170. auto res = cli.Get("/test");
  7171. ASSERT_TRUE(res);
  7172. ASSERT_EQ(StatusCode::OK_200, res->status);
  7173. }
  7174. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7175. std::string cert;
  7176. read_file(CA_CERT_FILE, cert);
  7177. SSLClient cli("google.com");
  7178. cli.load_ca_cert_store(cert.data(), cert.size());
  7179. const auto res = cli.Get("/");
  7180. ASSERT_TRUE(res);
  7181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7182. }
  7183. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7184. // clang-format off
  7185. static constexpr char cert[] =
  7186. "GlobalSign Root CA\n"
  7187. "==================\n"
  7188. "-----BEGIN CERTIFICATE-----\n"
  7189. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7190. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7191. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7192. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7193. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7194. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7195. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7196. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7197. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7198. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7199. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7200. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7201. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7202. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7203. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7204. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7205. "-----END CERTIFICATE-----\n";
  7206. // clang-format on
  7207. SSLClient cli("google.com");
  7208. cli.load_ca_cert_store(cert, sizeof(cert));
  7209. const auto res = cli.Get("/");
  7210. ASSERT_TRUE(res);
  7211. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7212. }
  7213. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7214. SSLClient cli("www.youtube.com");
  7215. cli.set_ca_cert_path(CA_CERT_FILE);
  7216. cli.enable_server_certificate_verification(true);
  7217. cli.set_follow_location(true);
  7218. auto res = cli.Get("/");
  7219. ASSERT_TRUE(res);
  7220. ASSERT_EQ(StatusCode::OK_200, res->status);
  7221. }
  7222. TEST(SSLClientTest, Issue2004_Online) {
  7223. Client client("https://google.com");
  7224. client.set_follow_location(true);
  7225. auto res = client.Get("/");
  7226. ASSERT_TRUE(res);
  7227. ASSERT_EQ(StatusCode::OK_200, res->status);
  7228. auto body = res->body;
  7229. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7230. }
  7231. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7232. // Create SSLClient with invalid cert/key to make is_valid() return false
  7233. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7234. "nonexistent_key.pem");
  7235. // is_valid() should be false due to cert loading failure
  7236. ASSERT_FALSE(cli.is_valid());
  7237. auto res = cli.Get("/");
  7238. ASSERT_FALSE(res);
  7239. EXPECT_EQ(Error::SSLConnection, res.error());
  7240. }
  7241. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7242. // Test for Issue #2251: SSL error not properly reported when client cert
  7243. // and key paths are swapped or mismatched
  7244. // This simulates the scenario where user accidentally swaps the cert and key
  7245. // files
  7246. // Using client cert file as private key and vice versa (completely wrong)
  7247. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7248. // Should fail validation due to cert/key mismatch
  7249. ASSERT_FALSE(cli.is_valid());
  7250. // Attempt to make a request should fail with proper error
  7251. auto res = cli.Get("/");
  7252. ASSERT_FALSE(res);
  7253. EXPECT_EQ(Error::SSLConnection, res.error());
  7254. // SSL error should be recorded in the Result object (this is the key fix for
  7255. // Issue #2251)
  7256. auto openssl_error = res.ssl_openssl_error();
  7257. EXPECT_NE(0u, openssl_error);
  7258. }
  7259. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7260. // Another variant: using valid file paths but with mismatched cert/key pair
  7261. // This tests the case where files exist but contain incompatible key material
  7262. // Using client cert with wrong key (cert2 key)
  7263. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7264. // Should fail validation
  7265. ASSERT_FALSE(cli.is_valid());
  7266. auto res = cli.Get("/");
  7267. ASSERT_FALSE(res);
  7268. // Must report error properly, not appear as success
  7269. EXPECT_EQ(Error::SSLConnection, res.error());
  7270. // OpenSSL error should be captured in Result
  7271. EXPECT_NE(0u, res.ssl_openssl_error());
  7272. }
  7273. #if 0
  7274. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7275. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7276. ASSERT_TRUE(cli != nullptr);
  7277. cli->set_address_family(AF_INET6);
  7278. cli->set_interface("en0");
  7279. auto res = cli->Get("/get");
  7280. ASSERT_TRUE(res);
  7281. ASSERT_EQ(StatusCode::OK_200, res->status);
  7282. }
  7283. #endif
  7284. void ClientCertPresent(
  7285. const std::string &client_cert_file,
  7286. const std::string &client_private_key_file,
  7287. const std::string &client_encrypted_private_key_pass = std::string()) {
  7288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7289. CLIENT_CA_CERT_DIR);
  7290. ASSERT_TRUE(svr.is_valid());
  7291. svr.Get("/test", [&](const Request &req, Response &res) {
  7292. res.set_content("test", "text/plain");
  7293. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7294. ASSERT_TRUE(peer_cert != nullptr);
  7295. auto subject_name = X509_get_subject_name(peer_cert);
  7296. ASSERT_TRUE(subject_name != nullptr);
  7297. std::string common_name;
  7298. {
  7299. char name[BUFSIZ];
  7300. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7301. name, sizeof(name));
  7302. common_name.assign(name, static_cast<size_t>(name_len));
  7303. }
  7304. EXPECT_EQ("Common Name", common_name);
  7305. X509_free(peer_cert);
  7306. });
  7307. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7308. auto se = detail::scope_exit([&] {
  7309. svr.stop();
  7310. t.join();
  7311. ASSERT_FALSE(svr.is_running());
  7312. });
  7313. svr.wait_until_ready();
  7314. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7315. client_encrypted_private_key_pass);
  7316. cli.enable_server_certificate_verification(false);
  7317. cli.set_connection_timeout(30);
  7318. auto res = cli.Get("/test");
  7319. ASSERT_TRUE(res);
  7320. ASSERT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST(SSLClientServerTest, ClientCertPresent) {
  7323. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7324. }
  7325. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7326. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7327. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7328. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7329. }
  7330. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7331. void MemoryClientCertPresent(
  7332. const std::string &client_cert_file,
  7333. const std::string &client_private_key_file,
  7334. const std::string &client_encrypted_private_key_pass = std::string()) {
  7335. auto f = fopen(SERVER_CERT_FILE, "r+");
  7336. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7337. fclose(f);
  7338. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7339. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7340. fclose(f);
  7341. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7342. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7343. auto client_ca_cert_store = X509_STORE_new();
  7344. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7345. X509_free(client_cert);
  7346. fclose(f);
  7347. f = fopen(client_cert_file.c_str(), "r+");
  7348. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7349. fclose(f);
  7350. f = fopen(client_private_key_file.c_str(), "r+");
  7351. auto client_private_key = PEM_read_PrivateKey(
  7352. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7353. fclose(f);
  7354. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7355. ASSERT_TRUE(svr.is_valid());
  7356. svr.Get("/test", [&](const Request &req, Response &res) {
  7357. res.set_content("test", "text/plain");
  7358. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7359. ASSERT_TRUE(peer_cert != nullptr);
  7360. auto subject_name = X509_get_subject_name(peer_cert);
  7361. ASSERT_TRUE(subject_name != nullptr);
  7362. std::string common_name;
  7363. {
  7364. char name[BUFSIZ];
  7365. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7366. name, sizeof(name));
  7367. common_name.assign(name, static_cast<size_t>(name_len));
  7368. }
  7369. EXPECT_EQ("Common Name", common_name);
  7370. X509_free(peer_cert);
  7371. });
  7372. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7373. auto se = detail::scope_exit([&] {
  7374. svr.stop();
  7375. t.join();
  7376. ASSERT_FALSE(svr.is_running());
  7377. });
  7378. svr.wait_until_ready();
  7379. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7380. client_encrypted_private_key_pass);
  7381. cli.enable_server_certificate_verification(false);
  7382. cli.set_connection_timeout(30);
  7383. auto res = cli.Get("/test");
  7384. ASSERT_TRUE(res);
  7385. ASSERT_EQ(StatusCode::OK_200, res->status);
  7386. X509_free(server_cert);
  7387. EVP_PKEY_free(server_private_key);
  7388. X509_free(client_cert);
  7389. EVP_PKEY_free(client_private_key);
  7390. }
  7391. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7392. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7393. }
  7394. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7395. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7396. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7397. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7398. }
  7399. #endif
  7400. TEST(SSLClientServerTest, ClientCertMissing) {
  7401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7402. CLIENT_CA_CERT_DIR);
  7403. ASSERT_TRUE(svr.is_valid());
  7404. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7406. auto se = detail::scope_exit([&] {
  7407. svr.stop();
  7408. t.join();
  7409. ASSERT_FALSE(svr.is_running());
  7410. });
  7411. svr.wait_until_ready();
  7412. SSLClient cli(HOST, PORT);
  7413. cli.set_connection_timeout(30);
  7414. auto res = cli.Get("/test");
  7415. ASSERT_TRUE(!res);
  7416. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7417. // For SSL server verification errors, ssl_error should be 0, only
  7418. // ssl_openssl_error should be set
  7419. EXPECT_EQ(0, res.ssl_error());
  7420. // Verify OpenSSL error is captured for SSLServerVerification
  7421. // Note: This test may have different error codes depending on the exact
  7422. // verification failure
  7423. EXPECT_NE(0UL, res.ssl_openssl_error());
  7424. }
  7425. TEST(SSLClientServerTest, TrustDirOptional) {
  7426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7427. ASSERT_TRUE(svr.is_valid());
  7428. svr.Get("/test", [&](const Request &, Response &res) {
  7429. res.set_content("test", "text/plain");
  7430. });
  7431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7432. auto se = detail::scope_exit([&] {
  7433. svr.stop();
  7434. t.join();
  7435. ASSERT_FALSE(svr.is_running());
  7436. });
  7437. svr.wait_until_ready();
  7438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7439. cli.enable_server_certificate_verification(false);
  7440. cli.set_connection_timeout(30);
  7441. auto res = cli.Get("/test");
  7442. ASSERT_TRUE(res);
  7443. ASSERT_EQ(StatusCode::OK_200, res->status);
  7444. }
  7445. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7446. class NoListenSSLServer : public SSLServer {
  7447. public:
  7448. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7449. const char *client_ca_cert_file_path,
  7450. const char *client_ca_cert_dir_path = nullptr)
  7451. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7452. client_ca_cert_dir_path),
  7453. stop_(false) {}
  7454. std::atomic_bool stop_;
  7455. private:
  7456. bool process_and_close_socket(socket_t /*sock*/) override {
  7457. // Don't create SSL context
  7458. while (!stop_.load()) {
  7459. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7460. }
  7461. return true;
  7462. }
  7463. };
  7464. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7465. CLIENT_CA_CERT_FILE);
  7466. ASSERT_TRUE(svr.is_valid());
  7467. svr.Get("/test", [&](const Request &, Response &res) {
  7468. res.set_content("test", "text/plain");
  7469. });
  7470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7471. auto se = detail::scope_exit([&] {
  7472. svr.stop_ = true;
  7473. svr.stop();
  7474. t.join();
  7475. ASSERT_FALSE(svr.is_running());
  7476. });
  7477. svr.wait_until_ready();
  7478. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7479. cli.enable_server_certificate_verification(false);
  7480. cli.set_connection_timeout(1);
  7481. auto res = cli.Get("/test");
  7482. ASSERT_TRUE(!res);
  7483. EXPECT_EQ(Error::SSLConnection, res.error());
  7484. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7485. }
  7486. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7487. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7488. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7489. SSL_CTX_set_options(&ssl_ctx,
  7490. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7491. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7492. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7493. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7494. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7495. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7496. "ECDHE-DSS-AES128-SHA256:"
  7497. "ECDHE-RSA-AES256-SHA256:"
  7498. "ECDHE-DSS-AES256-SHA256:";
  7499. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7500. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7501. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7502. SSL_FILETYPE_PEM) != 1) {
  7503. return false;
  7504. }
  7505. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7506. CLIENT_CA_CERT_DIR);
  7507. SSL_CTX_set_verify(
  7508. &ssl_ctx,
  7509. SSL_VERIFY_PEER |
  7510. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7511. nullptr);
  7512. return true;
  7513. };
  7514. SSLServer svr(setup_ssl_ctx_callback);
  7515. ASSERT_TRUE(svr.is_valid());
  7516. svr.Get("/test", [&](const Request &req, Response &res) {
  7517. res.set_content("test", "text/plain");
  7518. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7519. ASSERT_TRUE(peer_cert != nullptr);
  7520. auto subject_name = X509_get_subject_name(peer_cert);
  7521. ASSERT_TRUE(subject_name != nullptr);
  7522. std::string common_name;
  7523. {
  7524. char name[BUFSIZ];
  7525. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7526. name, sizeof(name));
  7527. common_name.assign(name, static_cast<size_t>(name_len));
  7528. }
  7529. EXPECT_EQ("Common Name", common_name);
  7530. X509_free(peer_cert);
  7531. });
  7532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7533. auto se = detail::scope_exit([&] {
  7534. svr.stop();
  7535. t.join();
  7536. ASSERT_FALSE(svr.is_running());
  7537. });
  7538. svr.wait_until_ready();
  7539. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7540. cli.enable_server_certificate_verification(false);
  7541. cli.set_connection_timeout(30);
  7542. auto res = cli.Get("/test");
  7543. ASSERT_TRUE(res);
  7544. ASSERT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7548. ASSERT_TRUE(svr.is_valid());
  7549. // Set up a handler to verify client certificate is present
  7550. bool client_cert_verified = false;
  7551. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7552. // Verify that client certificate was provided
  7553. client_cert_verified = true;
  7554. res.set_content("success", "text/plain");
  7555. });
  7556. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7557. auto se = detail::scope_exit([&] {
  7558. svr.stop();
  7559. t.join();
  7560. ASSERT_FALSE(svr.is_running());
  7561. });
  7562. svr.wait_until_ready();
  7563. // Client with certificate
  7564. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7565. cli.enable_server_certificate_verification(false);
  7566. cli.set_connection_timeout(30);
  7567. auto res = cli.Get("/test");
  7568. ASSERT_TRUE(res);
  7569. ASSERT_EQ(StatusCode::OK_200, res->status);
  7570. ASSERT_TRUE(client_cert_verified);
  7571. EXPECT_EQ("success", res->body);
  7572. }
  7573. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7574. // Test that when client CA cert file is provided,
  7575. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7576. // Create a server with client authentication
  7577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7578. ASSERT_TRUE(svr.is_valid());
  7579. // We can't directly access the SSL_CTX from SSLServer to verify,
  7580. // but we can test that the server properly requests client certificates
  7581. // and accepts valid ones from the specified CA
  7582. bool handler_called = false;
  7583. svr.Get("/test", [&](const Request &req, Response &res) {
  7584. handler_called = true;
  7585. // Verify that a client certificate was provided
  7586. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7587. ASSERT_TRUE(peer_cert != nullptr);
  7588. // Get the issuer name
  7589. auto issuer_name = X509_get_issuer_name(peer_cert);
  7590. ASSERT_TRUE(issuer_name != nullptr);
  7591. char issuer_buf[256];
  7592. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7593. // The client certificate should be issued by our test CA
  7594. std::string issuer_str(issuer_buf);
  7595. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7596. X509_free(peer_cert);
  7597. res.set_content("authenticated", "text/plain");
  7598. });
  7599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. t.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. });
  7605. svr.wait_until_ready();
  7606. // Connect with a client certificate issued by the CA
  7607. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7608. cli.enable_server_certificate_verification(false);
  7609. cli.set_connection_timeout(30);
  7610. auto res = cli.Get("/test");
  7611. ASSERT_TRUE(res);
  7612. ASSERT_EQ(StatusCode::OK_200, res->status);
  7613. ASSERT_TRUE(handler_called);
  7614. EXPECT_EQ("authenticated", res->body);
  7615. }
  7616. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7617. // Test 1: Valid CA file - no error should be recorded
  7618. {
  7619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7620. CLIENT_CA_CERT_FILE);
  7621. ASSERT_TRUE(svr.is_valid());
  7622. // With valid setup, last_ssl_error should be 0
  7623. EXPECT_EQ(0, svr.ssl_last_error());
  7624. }
  7625. // Test 2: Invalid CA file content
  7626. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7627. {
  7628. // Create a temporary file with completely invalid content
  7629. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7630. {
  7631. std::ofstream ofs(temp_invalid_ca);
  7632. ofs << "This is not a certificate file at all\n";
  7633. ofs << "Just plain text content\n";
  7634. }
  7635. // Create server with invalid CA file
  7636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7637. // Clean up temporary file
  7638. std::remove(temp_invalid_ca);
  7639. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7640. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7641. // Note: SSL_CTX_load_verify_locations typically fails first,
  7642. // but our error handling code path is still exercised
  7643. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7644. }
  7645. }
  7646. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7647. // Test SSL server using X509_STORE constructor with client CA certificates
  7648. // This test verifies that Phase 2 implementation correctly extracts CA names
  7649. // from an X509_STORE and sets them in the SSL context
  7650. // Load the CA certificate into memory
  7651. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7652. ASSERT_NE(nullptr, bio);
  7653. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7654. BIO_free(bio);
  7655. ASSERT_NE(nullptr, ca_cert);
  7656. // Create an X509_STORE and add the CA certificate
  7657. auto store = X509_STORE_new();
  7658. ASSERT_NE(nullptr, store);
  7659. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7660. // Load server certificate and private key
  7661. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7662. ASSERT_NE(nullptr, cert_bio);
  7663. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7664. BIO_free(cert_bio);
  7665. ASSERT_NE(nullptr, server_cert);
  7666. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7667. ASSERT_NE(nullptr, key_bio);
  7668. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7669. BIO_free(key_bio);
  7670. ASSERT_NE(nullptr, server_key);
  7671. // Create SSLServer with X509_STORE constructor
  7672. // Note: X509_STORE ownership is transferred to SSL_CTX
  7673. SSLServer svr(server_cert, server_key, store);
  7674. ASSERT_TRUE(svr.is_valid());
  7675. // No SSL error should be recorded for valid setup
  7676. EXPECT_EQ(0, svr.ssl_last_error());
  7677. // Set up server endpoints
  7678. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7679. res.set_content("ok", "text/plain");
  7680. });
  7681. // Start server in a thread
  7682. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7683. svr.wait_until_ready();
  7684. // Connect with client certificate (using constructor with paths)
  7685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7686. cli.enable_server_certificate_verification(false);
  7687. auto res = cli.Get("/test-x509store");
  7688. ASSERT_TRUE(res);
  7689. EXPECT_EQ(200, res->status);
  7690. EXPECT_EQ("ok", res->body);
  7691. // Clean up
  7692. X509_free(server_cert);
  7693. EVP_PKEY_free(server_key);
  7694. X509_free(ca_cert);
  7695. svr.stop();
  7696. server_thread.join();
  7697. }
  7698. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7699. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7700. // prepare large data
  7701. std::random_device seed_gen;
  7702. std::mt19937 random(seed_gen());
  7703. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7704. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7705. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7706. // server
  7707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7708. ASSERT_TRUE(svr.is_valid());
  7709. svr.Post("/binary", [&](const Request &req, Response &res) {
  7710. EXPECT_EQ(large_size_byte, req.body.size());
  7711. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7712. res.set_content(req.body, "application/octet-stream");
  7713. });
  7714. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7715. auto se = detail::scope_exit([&] {
  7716. svr.stop();
  7717. listen_thread.join();
  7718. ASSERT_FALSE(svr.is_running());
  7719. });
  7720. svr.wait_until_ready();
  7721. // client POST
  7722. SSLClient cli("localhost", PORT);
  7723. cli.enable_server_certificate_verification(false);
  7724. cli.set_read_timeout(std::chrono::seconds(100));
  7725. cli.set_write_timeout(std::chrono::seconds(100));
  7726. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7727. large_size_byte, "application/octet-stream");
  7728. // compare
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. EXPECT_EQ(large_size_byte, res->body.size());
  7731. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7732. }
  7733. #endif
  7734. #ifdef _WIN32
  7735. TEST(CleanupTest, WSACleanup) {
  7736. int ret = WSACleanup();
  7737. ASSERT_EQ(0, ret);
  7738. }
  7739. #endif
  7740. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7741. TEST(NoSSLSupport, SimpleInterface) {
  7742. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7743. }
  7744. #endif
  7745. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7746. TEST(InvalidScheme, SimpleInterface) {
  7747. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7748. }
  7749. #endif
  7750. TEST(NoScheme, SimpleInterface) {
  7751. Client cli("yahoo.com:80");
  7752. ASSERT_TRUE(cli.is_valid());
  7753. }
  7754. TEST(SendAPI, SimpleInterface_Online) {
  7755. Client cli("http://yahoo.com");
  7756. Request req;
  7757. req.method = "GET";
  7758. req.path = "/";
  7759. auto res = cli.send(req);
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7762. }
  7763. TEST(SendAPI, WithParamsInRequest) {
  7764. Server svr;
  7765. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7766. EXPECT_TRUE(req.has_param("test"));
  7767. EXPECT_EQ("test_value", req.get_param_value("test"));
  7768. });
  7769. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7770. auto se = detail::scope_exit([&] {
  7771. svr.stop();
  7772. t.join();
  7773. ASSERT_FALSE(svr.is_running());
  7774. });
  7775. svr.wait_until_ready();
  7776. Client cli(HOST, PORT);
  7777. {
  7778. Request req;
  7779. req.method = "GET";
  7780. req.path = "/";
  7781. req.params.emplace("test", "test_value");
  7782. auto res = cli.send(req);
  7783. ASSERT_TRUE(res);
  7784. }
  7785. {
  7786. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7787. ASSERT_TRUE(res);
  7788. }
  7789. }
  7790. TEST(ClientImplMethods, GetSocketTest) {
  7791. httplib::Server svr;
  7792. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7793. res.status = StatusCode::OK_200;
  7794. });
  7795. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7796. auto se = detail::scope_exit([&] {
  7797. svr.stop();
  7798. thread.join();
  7799. ASSERT_FALSE(svr.is_running());
  7800. });
  7801. svr.wait_until_ready();
  7802. {
  7803. httplib::Client cli("http://127.0.0.1:3333");
  7804. cli.set_keep_alive(true);
  7805. // Use the behavior of cpp-httplib of opening the connection
  7806. // only when the first request happens. If that changes,
  7807. // this test would be obsolete.
  7808. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7809. // This also implicitly tests the server. But other tests would fail much
  7810. // earlier than this one to be considered.
  7811. auto res = cli.Get("/");
  7812. ASSERT_TRUE(res);
  7813. EXPECT_EQ(StatusCode::OK_200, res->status);
  7814. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7815. }
  7816. }
  7817. // Disabled due to out-of-memory problem on GitHub Actions
  7818. #ifdef _WIN64
  7819. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7820. // allocate content size larger than 2GB in memory
  7821. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7822. char *content = (char *)malloc(content_size);
  7823. ASSERT_TRUE(content);
  7824. Server svr;
  7825. svr.Get("/foo",
  7826. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7827. res.set_content(content, content_size, "application/octet-stream");
  7828. });
  7829. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7830. auto se = detail::scope_exit([&] {
  7831. svr.stop();
  7832. listen_thread.join();
  7833. if (content) free(content);
  7834. ASSERT_FALSE(svr.is_running());
  7835. });
  7836. svr.wait_until_ready();
  7837. Client cli(HOST, PORT);
  7838. auto res = cli.Get("/foo");
  7839. ASSERT_TRUE(res);
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ(content_size, res->body.length());
  7842. }
  7843. #endif
  7844. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7845. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7846. Client cli("http://yahoo.com");
  7847. auto res = cli.Get("/");
  7848. ASSERT_TRUE(res);
  7849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7850. cli.set_follow_location(true);
  7851. res = cli.Get("/");
  7852. ASSERT_TRUE(res);
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7855. }
  7856. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7857. Client cli("https://yahoo.com");
  7858. auto res = cli.Get("/");
  7859. ASSERT_TRUE(res);
  7860. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7861. cli.set_follow_location(true);
  7862. res = cli.Get("/");
  7863. ASSERT_TRUE(res);
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7866. }
  7867. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7868. Client cli("https://yahoo.com");
  7869. auto res = cli.Get("/");
  7870. ASSERT_TRUE(res);
  7871. ASSERT_FALSE(!res);
  7872. ASSERT_TRUE(res);
  7873. ASSERT_FALSE(res == nullptr);
  7874. ASSERT_TRUE(res != nullptr);
  7875. EXPECT_EQ(Error::Success, res.error());
  7876. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7877. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7878. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7879. cli.set_follow_location(true);
  7880. res = cli.Get("/");
  7881. ASSERT_TRUE(res);
  7882. EXPECT_EQ(Error::Success, res.error());
  7883. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7884. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7887. }
  7888. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7889. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7890. Client cli("https://cdnjs.cloudflare.com");
  7891. auto res =
  7892. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7893. ASSERT_TRUE(res);
  7894. EXPECT_EQ(StatusCode::OK_200, res->status);
  7895. EXPECT_EQ(287630U, res->body.size());
  7896. EXPECT_EQ("application/javascript; charset=utf-8",
  7897. res->get_header_value("Content-Type"));
  7898. }
  7899. #endif
  7900. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7901. #undef REDIR_HOST // Silence compiler warning
  7902. #define REDIR_HOST "https://httpbingo.org"
  7903. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7904. Client cli(REDIR_HOST);
  7905. cli.set_follow_location(true);
  7906. auto res =
  7907. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7908. ASSERT_TRUE(res);
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7912. Client cli(REDIR_HOST);
  7913. cli.set_follow_location(true);
  7914. Params params;
  7915. params.emplace("url", "http://example.com");
  7916. params.emplace("status_code", "302");
  7917. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7918. ASSERT_TRUE(res);
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. }
  7921. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7922. Client cli(REDIR_HOST);
  7923. cli.set_follow_location(true);
  7924. Params params;
  7925. params.emplace("url", "http://example.com");
  7926. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7927. ASSERT_TRUE(res);
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. }
  7930. TEST(HttpToHttpsRedirectTest, CertFile) {
  7931. Server svr;
  7932. ASSERT_TRUE(svr.is_valid());
  7933. svr.Get("/index", [&](const Request &, Response &res) {
  7934. res.set_redirect("https://127.0.0.1:1235/index");
  7935. svr.stop();
  7936. });
  7937. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7938. ASSERT_TRUE(ssl_svr.is_valid());
  7939. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7940. res.set_content("test", "text/plain");
  7941. ssl_svr.stop();
  7942. });
  7943. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7944. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7945. auto se = detail::scope_exit([&] {
  7946. t2.join();
  7947. t.join();
  7948. ASSERT_FALSE(svr.is_running());
  7949. });
  7950. svr.wait_until_ready();
  7951. ssl_svr.wait_until_ready();
  7952. Client cli("127.0.0.1", PORT);
  7953. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7954. cli.enable_server_certificate_verification(true);
  7955. cli.set_follow_location(true);
  7956. cli.set_connection_timeout(30);
  7957. auto res = cli.Get("/index");
  7958. ASSERT_TRUE(res);
  7959. ASSERT_EQ(StatusCode::OK_200, res->status);
  7960. }
  7961. TEST(SSLClientRedirectTest, CertFile) {
  7962. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7963. ASSERT_TRUE(ssl_svr1.is_valid());
  7964. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7965. res.set_redirect("https://127.0.0.1:1235/index");
  7966. ssl_svr1.stop();
  7967. });
  7968. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7969. ASSERT_TRUE(ssl_svr2.is_valid());
  7970. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7971. res.set_content("test", "text/plain");
  7972. ssl_svr2.stop();
  7973. });
  7974. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7975. thread t2 =
  7976. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7977. auto se = detail::scope_exit([&] {
  7978. t2.join();
  7979. t.join();
  7980. ASSERT_FALSE(ssl_svr1.is_running());
  7981. });
  7982. ssl_svr1.wait_until_ready();
  7983. ssl_svr2.wait_until_ready();
  7984. SSLClient cli("127.0.0.1", PORT);
  7985. std::string cert;
  7986. read_file(SERVER_CERT2_FILE, cert);
  7987. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7988. cli.enable_server_certificate_verification(true);
  7989. cli.set_follow_location(true);
  7990. cli.set_connection_timeout(30);
  7991. auto res = cli.Get("/index");
  7992. ASSERT_TRUE(res);
  7993. ASSERT_EQ(StatusCode::OK_200, res->status);
  7994. }
  7995. TEST(MultipartFormDataTest, LargeData) {
  7996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7997. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7998. const ContentReader &content_reader) {
  7999. if (req.is_multipart_form_data()) {
  8000. std::vector<FormData> items;
  8001. content_reader(
  8002. [&](const FormData &file) {
  8003. items.push_back(file);
  8004. return true;
  8005. },
  8006. [&](const char *data, size_t data_length) {
  8007. items.back().content.append(data, data_length);
  8008. return true;
  8009. });
  8010. EXPECT_TRUE(std::string(items[0].name) == "document");
  8011. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8012. EXPECT_TRUE(items[0].filename == "2MB_data");
  8013. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8014. EXPECT_TRUE(items[1].name == "hello");
  8015. EXPECT_TRUE(items[1].content == "world");
  8016. EXPECT_TRUE(items[1].filename == "");
  8017. EXPECT_TRUE(items[1].content_type == "");
  8018. } else {
  8019. std::string body;
  8020. content_reader([&](const char *data, size_t data_length) {
  8021. body.append(data, data_length);
  8022. return true;
  8023. });
  8024. }
  8025. });
  8026. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8027. auto se = detail::scope_exit([&] {
  8028. svr.stop();
  8029. t.join();
  8030. ASSERT_FALSE(svr.is_running());
  8031. });
  8032. svr.wait_until_ready();
  8033. {
  8034. std::string data(1024 * 1024 * 2, '.');
  8035. std::stringstream buffer;
  8036. buffer << data;
  8037. Client cli("https://localhost:8080");
  8038. cli.enable_server_certificate_verification(false);
  8039. UploadFormDataItems items{
  8040. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8041. {"hello", "world", "", ""},
  8042. };
  8043. auto res = cli.Post("/post", items);
  8044. ASSERT_TRUE(res);
  8045. ASSERT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. }
  8048. TEST(MultipartFormDataTest, DataProviderItems) {
  8049. std::random_device seed_gen;
  8050. std::mt19937 random(seed_gen());
  8051. std::string rand1;
  8052. rand1.resize(1000);
  8053. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8054. std::string rand2;
  8055. rand2.resize(3000);
  8056. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8058. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8059. const ContentReader &content_reader) {
  8060. ASSERT_FALSE(req.is_multipart_form_data());
  8061. std::string body;
  8062. content_reader([&](const char *data, size_t data_length) {
  8063. body.append(data, data_length);
  8064. return true;
  8065. });
  8066. EXPECT_EQ(body, "");
  8067. });
  8068. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8069. const ContentReader &content_reader) {
  8070. ASSERT_TRUE(req.is_multipart_form_data());
  8071. std::vector<FormData> items;
  8072. content_reader(
  8073. [&](const FormData &file) {
  8074. items.push_back(file);
  8075. return true;
  8076. },
  8077. [&](const char *data, size_t data_length) {
  8078. items.back().content.append(data, data_length);
  8079. return true;
  8080. });
  8081. ASSERT_TRUE(items.size() == 2);
  8082. EXPECT_EQ(std::string(items[0].name), "name1");
  8083. EXPECT_EQ(items[0].content, "Testing123");
  8084. EXPECT_EQ(items[0].filename, "filename1");
  8085. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8086. EXPECT_EQ(items[1].name, "name2");
  8087. EXPECT_EQ(items[1].content, "Testing456");
  8088. EXPECT_EQ(items[1].filename, "");
  8089. EXPECT_EQ(items[1].content_type, "");
  8090. });
  8091. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8092. const ContentReader &content_reader) {
  8093. ASSERT_TRUE(req.is_multipart_form_data());
  8094. std::vector<FormData> items;
  8095. content_reader(
  8096. [&](const FormData &file) {
  8097. items.push_back(file);
  8098. return true;
  8099. },
  8100. [&](const char *data, size_t data_length) {
  8101. items.back().content.append(data, data_length);
  8102. return true;
  8103. });
  8104. ASSERT_TRUE(items.size() == 2);
  8105. EXPECT_EQ(items[0].name, "name3");
  8106. EXPECT_EQ(items[0].content, rand1);
  8107. EXPECT_EQ(items[0].filename, "filename3");
  8108. EXPECT_EQ(items[0].content_type, "");
  8109. EXPECT_EQ(items[1].name, "name4");
  8110. EXPECT_EQ(items[1].content, rand2);
  8111. EXPECT_EQ(items[1].filename, "filename4");
  8112. EXPECT_EQ(items[1].content_type, "");
  8113. });
  8114. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8115. const ContentReader &content_reader) {
  8116. ASSERT_TRUE(req.is_multipart_form_data());
  8117. std::vector<FormData> items;
  8118. content_reader(
  8119. [&](const FormData &file) {
  8120. items.push_back(file);
  8121. return true;
  8122. },
  8123. [&](const char *data, size_t data_length) {
  8124. items.back().content.append(data, data_length);
  8125. return true;
  8126. });
  8127. ASSERT_TRUE(items.size() == 4);
  8128. EXPECT_EQ(std::string(items[0].name), "name1");
  8129. EXPECT_EQ(items[0].content, "Testing123");
  8130. EXPECT_EQ(items[0].filename, "filename1");
  8131. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8132. EXPECT_EQ(items[1].name, "name2");
  8133. EXPECT_EQ(items[1].content, "Testing456");
  8134. EXPECT_EQ(items[1].filename, "");
  8135. EXPECT_EQ(items[1].content_type, "");
  8136. EXPECT_EQ(items[2].name, "name3");
  8137. EXPECT_EQ(items[2].content, rand1);
  8138. EXPECT_EQ(items[2].filename, "filename3");
  8139. EXPECT_EQ(items[2].content_type, "");
  8140. EXPECT_EQ(items[3].name, "name4");
  8141. EXPECT_EQ(items[3].content, rand2);
  8142. EXPECT_EQ(items[3].filename, "filename4");
  8143. EXPECT_EQ(items[3].content_type, "");
  8144. });
  8145. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. t.join();
  8149. ASSERT_FALSE(svr.is_running());
  8150. });
  8151. svr.wait_until_ready();
  8152. {
  8153. Client cli("https://localhost:8080");
  8154. cli.enable_server_certificate_verification(false);
  8155. UploadFormDataItems items{
  8156. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8157. {"name2", "Testing456", "", ""}, // not a file
  8158. };
  8159. {
  8160. auto res = cli.Post("/post-none", {}, {}, {});
  8161. ASSERT_TRUE(res);
  8162. ASSERT_EQ(StatusCode::OK_200, res->status);
  8163. }
  8164. FormDataProviderItems providers;
  8165. {
  8166. auto res =
  8167. cli.Post("/post-items", {}, items, providers); // empty providers
  8168. ASSERT_TRUE(res);
  8169. ASSERT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. providers.push_back({"name3",
  8172. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8173. // test the offset is given correctly at each step
  8174. if (!offset)
  8175. sink.os.write(rand1.data(), 30);
  8176. else if (offset == 30)
  8177. sink.os.write(rand1.data() + 30, 300);
  8178. else if (offset == 330)
  8179. sink.os.write(rand1.data() + 330, 670);
  8180. else if (offset == rand1.size())
  8181. sink.done();
  8182. return true;
  8183. },
  8184. "filename3",
  8185. {}});
  8186. providers.push_back({"name4",
  8187. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8188. // test the offset is given correctly at each step
  8189. if (!offset)
  8190. sink.os.write(rand2.data(), 2000);
  8191. else if (offset == 2000)
  8192. sink.os.write(rand2.data() + 2000, 1);
  8193. else if (offset == 2001)
  8194. sink.os.write(rand2.data() + 2001, 999);
  8195. else if (offset == rand2.size())
  8196. sink.done();
  8197. return true;
  8198. },
  8199. "filename4",
  8200. {}});
  8201. {
  8202. auto res = cli.Post("/post-providers", {}, {}, providers);
  8203. ASSERT_TRUE(res);
  8204. ASSERT_EQ(StatusCode::OK_200, res->status);
  8205. }
  8206. {
  8207. auto res = cli.Post("/post-both", {}, items, providers);
  8208. ASSERT_TRUE(res);
  8209. ASSERT_EQ(StatusCode::OK_200, res->status);
  8210. }
  8211. }
  8212. }
  8213. TEST(MultipartFormDataTest, BadHeader) {
  8214. Server svr;
  8215. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8216. res.set_content("ok", "text/plain");
  8217. });
  8218. thread t = thread([&] { svr.listen(HOST, PORT); });
  8219. auto se = detail::scope_exit([&] {
  8220. svr.stop();
  8221. t.join();
  8222. ASSERT_FALSE(svr.is_running());
  8223. });
  8224. svr.wait_until_ready();
  8225. const std::string body =
  8226. "This is the preamble. It is to be ignored, though it\r\n"
  8227. "is a handy place for composition agents to include an\r\n"
  8228. "explanatory note to non-MIME conformant readers.\r\n"
  8229. "\r\n"
  8230. "\r\n"
  8231. "--simple boundary\r\n"
  8232. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8233. ": BAD...\r\n"
  8234. "\r\n"
  8235. "value1\r\n"
  8236. "--simple boundary\r\n"
  8237. "Content-Disposition: form-data; name=\"field2\"; "
  8238. "filename=\"example.txt\"\r\n"
  8239. "\r\n"
  8240. "value2\r\n"
  8241. "--simple boundary--\r\n"
  8242. "This is the epilogue. It is also to be ignored.\r\n";
  8243. std::string content_type =
  8244. R"(multipart/form-data; boundary="simple boundary")";
  8245. Client cli(HOST, PORT);
  8246. auto res = cli.Post("/post", body, content_type.c_str());
  8247. ASSERT_TRUE(res);
  8248. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8249. }
  8250. TEST(MultipartFormDataTest, WithPreamble) {
  8251. Server svr;
  8252. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8253. res.set_content("ok", "text/plain");
  8254. });
  8255. thread t = thread([&] { svr.listen(HOST, PORT); });
  8256. auto se = detail::scope_exit([&] {
  8257. svr.stop();
  8258. t.join();
  8259. ASSERT_FALSE(svr.is_running());
  8260. });
  8261. svr.wait_until_ready();
  8262. const std::string body =
  8263. "This is the preamble. It is to be ignored, though it\r\n"
  8264. "is a handy place for composition agents to include an\r\n"
  8265. "explanatory note to non-MIME conformant readers.\r\n"
  8266. "\r\n"
  8267. "\r\n"
  8268. "--simple boundary\r\n"
  8269. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8270. "\r\n"
  8271. "value1\r\n"
  8272. "--simple boundary\r\n"
  8273. "Content-Disposition: form-data; name=\"field2\"; "
  8274. "filename=\"example.txt\"\r\n"
  8275. "\r\n"
  8276. "value2\r\n"
  8277. "--simple boundary--\r\n"
  8278. "This is the epilogue. It is also to be ignored.\r\n";
  8279. std::string content_type =
  8280. R"(multipart/form-data; boundary="simple boundary")";
  8281. Client cli(HOST, PORT);
  8282. auto res = cli.Post("/post", body, content_type.c_str());
  8283. ASSERT_TRUE(res);
  8284. EXPECT_EQ(StatusCode::OK_200, res->status);
  8285. }
  8286. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8288. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8289. const ContentReader &content_reader) {
  8290. if (req.is_multipart_form_data()) {
  8291. std::vector<FormData> items;
  8292. content_reader(
  8293. [&](const FormData &file) {
  8294. items.push_back(file);
  8295. return true;
  8296. },
  8297. [&](const char *data, size_t data_length) {
  8298. items.back().content.append(data, data_length);
  8299. return true;
  8300. });
  8301. EXPECT_TRUE(std::string(items[0].name) == "document");
  8302. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8303. EXPECT_TRUE(items[0].filename == "2MB_data");
  8304. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8305. EXPECT_TRUE(items[1].name == "hello");
  8306. EXPECT_TRUE(items[1].content == "world");
  8307. EXPECT_TRUE(items[1].filename == "");
  8308. EXPECT_TRUE(items[1].content_type == "");
  8309. } else {
  8310. std::string body;
  8311. content_reader([&](const char *data, size_t data_length) {
  8312. body.append(data, data_length);
  8313. return true;
  8314. });
  8315. }
  8316. });
  8317. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8318. auto se = detail::scope_exit([&] {
  8319. svr.stop();
  8320. t.join();
  8321. ASSERT_FALSE(svr.is_running());
  8322. });
  8323. svr.wait_until_ready();
  8324. {
  8325. std::string data(1024 * 1024 * 2, '.');
  8326. std::stringstream buffer;
  8327. buffer << data;
  8328. Client cli("https://localhost:8080");
  8329. cli.enable_server_certificate_verification(false);
  8330. UploadFormDataItems items{
  8331. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8332. {"hello", "world", "", ""},
  8333. };
  8334. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8335. ASSERT_TRUE(res);
  8336. ASSERT_EQ(StatusCode::OK_200, res->status);
  8337. }
  8338. }
  8339. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8340. std::string data(1024 * 1024 * 2, '&');
  8341. std::stringstream buffer;
  8342. buffer << data;
  8343. Client cli("https://localhost:8080");
  8344. UploadFormDataItems items{
  8345. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8346. {"hello", "world", "", ""},
  8347. };
  8348. for (const char &c : " \t\r\n") {
  8349. auto res =
  8350. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8351. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8352. ASSERT_FALSE(res);
  8353. }
  8354. }
  8355. TEST(MultipartFormDataTest, PutFormData) {
  8356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8357. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8358. const ContentReader &content_reader) {
  8359. if (req.is_multipart_form_data()) {
  8360. std::vector<FormData> items;
  8361. content_reader(
  8362. [&](const FormData &file) {
  8363. items.push_back(file);
  8364. return true;
  8365. },
  8366. [&](const char *data, size_t data_length) {
  8367. items.back().content.append(data, data_length);
  8368. return true;
  8369. });
  8370. EXPECT_TRUE(std::string(items[0].name) == "document");
  8371. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8372. EXPECT_TRUE(items[0].filename == "2MB_data");
  8373. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8374. EXPECT_TRUE(items[1].name == "hello");
  8375. EXPECT_TRUE(items[1].content == "world");
  8376. EXPECT_TRUE(items[1].filename == "");
  8377. EXPECT_TRUE(items[1].content_type == "");
  8378. } else {
  8379. std::string body;
  8380. content_reader([&](const char *data, size_t data_length) {
  8381. body.append(data, data_length);
  8382. return true;
  8383. });
  8384. }
  8385. });
  8386. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8387. auto se = detail::scope_exit([&] {
  8388. svr.stop();
  8389. t.join();
  8390. ASSERT_FALSE(svr.is_running());
  8391. });
  8392. svr.wait_until_ready();
  8393. {
  8394. std::string data(1024 * 1024 * 2, '&');
  8395. std::stringstream buffer;
  8396. buffer << data;
  8397. Client cli("https://localhost:8080");
  8398. cli.enable_server_certificate_verification(false);
  8399. UploadFormDataItems items{
  8400. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8401. {"hello", "world", "", ""},
  8402. };
  8403. auto res = cli.Put("/put", items);
  8404. ASSERT_TRUE(res);
  8405. ASSERT_EQ(StatusCode::OK_200, res->status);
  8406. }
  8407. }
  8408. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8410. svr.Put("/put_customboundary",
  8411. [&](const Request &req, const Response & /*res*/,
  8412. const ContentReader &content_reader) {
  8413. if (req.is_multipart_form_data()) {
  8414. std::vector<FormData> items;
  8415. content_reader(
  8416. [&](const FormData &file) {
  8417. items.push_back(file);
  8418. return true;
  8419. },
  8420. [&](const char *data, size_t data_length) {
  8421. items.back().content.append(data, data_length);
  8422. return true;
  8423. });
  8424. EXPECT_TRUE(std::string(items[0].name) == "document");
  8425. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8426. EXPECT_TRUE(items[0].filename == "2MB_data");
  8427. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8428. EXPECT_TRUE(items[1].name == "hello");
  8429. EXPECT_TRUE(items[1].content == "world");
  8430. EXPECT_TRUE(items[1].filename == "");
  8431. EXPECT_TRUE(items[1].content_type == "");
  8432. } else {
  8433. std::string body;
  8434. content_reader([&](const char *data, size_t data_length) {
  8435. body.append(data, data_length);
  8436. return true;
  8437. });
  8438. }
  8439. });
  8440. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8441. auto se = detail::scope_exit([&] {
  8442. svr.stop();
  8443. t.join();
  8444. ASSERT_FALSE(svr.is_running());
  8445. });
  8446. svr.wait_until_ready();
  8447. {
  8448. std::string data(1024 * 1024 * 2, '&');
  8449. std::stringstream buffer;
  8450. buffer << data;
  8451. Client cli("https://localhost:8080");
  8452. cli.enable_server_certificate_verification(false);
  8453. UploadFormDataItems items{
  8454. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8455. {"hello", "world", "", ""},
  8456. };
  8457. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8458. ASSERT_TRUE(res);
  8459. ASSERT_EQ(StatusCode::OK_200, res->status);
  8460. }
  8461. }
  8462. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8463. std::string data(1024 * 1024 * 2, '&');
  8464. std::stringstream buffer;
  8465. buffer << data;
  8466. Client cli("https://localhost:8080");
  8467. cli.enable_server_certificate_verification(false);
  8468. UploadFormDataItems items{
  8469. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8470. {"hello", "world", "", ""},
  8471. };
  8472. for (const char &c : " \t\r\n") {
  8473. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8474. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8475. ASSERT_FALSE(res);
  8476. }
  8477. }
  8478. TEST(MultipartFormDataTest, AlternateFilename) {
  8479. auto handled = false;
  8480. Server svr;
  8481. svr.Post("/test", [&](const Request &req, Response &res) {
  8482. ASSERT_EQ(2u, req.form.files.size());
  8483. ASSERT_EQ(1u, req.form.fields.size());
  8484. // Test files
  8485. const auto &file1 = req.form.get_file("file1");
  8486. ASSERT_EQ("file1", file1.name);
  8487. ASSERT_EQ("A.txt", file1.filename);
  8488. ASSERT_EQ("text/plain", file1.content_type);
  8489. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8490. const auto &file2 = req.form.get_file("file2");
  8491. ASSERT_EQ("file2", file2.name);
  8492. ASSERT_EQ("a.html", file2.filename);
  8493. ASSERT_EQ("text/html", file2.content_type);
  8494. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8495. file2.content);
  8496. // Test text field
  8497. const auto &text = req.form.get_field("text");
  8498. ASSERT_EQ("text default", text);
  8499. res.set_content("ok", "text/plain");
  8500. handled = true;
  8501. });
  8502. thread t = thread([&] { svr.listen(HOST, PORT); });
  8503. auto se = detail::scope_exit([&] {
  8504. svr.stop();
  8505. t.join();
  8506. ASSERT_FALSE(svr.is_running());
  8507. ASSERT_TRUE(handled);
  8508. });
  8509. svr.wait_until_ready();
  8510. auto req = "POST /test HTTP/1.1\r\n"
  8511. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8512. "Content-Length: 399\r\n"
  8513. "\r\n"
  8514. "----------\r\n"
  8515. "Content-Disposition: form-data; name=\"text\"\r\n"
  8516. "\r\n"
  8517. "text default\r\n"
  8518. "----------\r\n"
  8519. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8520. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8521. "Content-Type: text/plain\r\n"
  8522. "\r\n"
  8523. "Content of a.txt.\r\n"
  8524. "\r\n"
  8525. "----------\r\n"
  8526. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8527. "\"a.html\"\r\n"
  8528. "Content-Type: text/html\r\n"
  8529. "\r\n"
  8530. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8531. "\r\n"
  8532. "------------\r\n";
  8533. ASSERT_TRUE(send_request(1, req));
  8534. }
  8535. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8536. auto handled = false;
  8537. Server svr;
  8538. svr.Post("/test", [&](const Request &req, Response &) {
  8539. ASSERT_EQ(2u, req.form.fields.size());
  8540. const auto &text1 = req.form.get_field("text1");
  8541. ASSERT_EQ("text1", text1);
  8542. const auto &text2 = req.form.get_field("text2");
  8543. ASSERT_EQ("text2", text2);
  8544. handled = true;
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. ASSERT_TRUE(handled);
  8552. });
  8553. svr.wait_until_ready();
  8554. auto req = "POST /test HTTP/1.1\r\n"
  8555. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8556. "Content-Length: 146\r\n"
  8557. "\r\n----------\r\n"
  8558. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8559. "\r\n"
  8560. "text1"
  8561. "\r\n----------\r\n"
  8562. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8563. "\r\n"
  8564. "text2"
  8565. "\r\n------------";
  8566. std::string response;
  8567. ASSERT_TRUE(send_request(1, req, &response));
  8568. ASSERT_EQ("200", response.substr(9, 3));
  8569. }
  8570. TEST(MultipartFormDataTest, ContentLength) {
  8571. auto handled = false;
  8572. Server svr;
  8573. svr.Post("/test", [&](const Request &req, Response &) {
  8574. ASSERT_EQ(2u, req.form.fields.size());
  8575. const auto &text1 = req.form.get_field("text1");
  8576. ASSERT_EQ("text1", text1);
  8577. const auto &text2 = req.form.get_field("text2");
  8578. ASSERT_EQ("text2", text2);
  8579. handled = true;
  8580. });
  8581. thread t = thread([&] { svr.listen(HOST, PORT); });
  8582. auto se = detail::scope_exit([&] {
  8583. svr.stop();
  8584. t.join();
  8585. ASSERT_FALSE(svr.is_running());
  8586. ASSERT_TRUE(handled);
  8587. });
  8588. svr.wait_until_ready();
  8589. auto req = "POST /test HTTP/1.1\r\n"
  8590. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8591. "Content-Length: 167\r\n"
  8592. "\r\n----------\r\n"
  8593. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8594. "Content-Length: 5\r\n"
  8595. "\r\n"
  8596. "text1"
  8597. "\r\n----------\r\n"
  8598. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8599. "\r\n"
  8600. "text2"
  8601. "\r\n------------\r\n";
  8602. std::string response;
  8603. ASSERT_TRUE(send_request(1, req, &response));
  8604. ASSERT_EQ("200", response.substr(9, 3));
  8605. }
  8606. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8607. auto handled = false;
  8608. Server svr;
  8609. svr.Post("/test", [&](const Request &req, Response &) {
  8610. ASSERT_EQ(2u, req.form.fields.size());
  8611. const auto &text1 = req.form.get_field("text1");
  8612. ASSERT_EQ("text1", text1);
  8613. // TODO: Add header access for text fields if needed
  8614. const auto &text2 = req.form.get_field("text2");
  8615. ASSERT_EQ("text2", text2);
  8616. // TODO: Header access for text fields needs to be implemented
  8617. // auto &headers = it->second.headers;
  8618. // ASSERT_EQ(3U, headers.size());
  8619. // auto custom_header = headers.find("x-whatever");
  8620. // ASSERT_TRUE(custom_header != headers.end());
  8621. // ASSERT_NE("customvalue", custom_header->second);
  8622. // ASSERT_EQ("CustomValue", custom_header->second);
  8623. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8624. handled = true;
  8625. });
  8626. thread t = thread([&] { svr.listen(HOST, PORT); });
  8627. auto se = detail::scope_exit([&] {
  8628. svr.stop();
  8629. t.join();
  8630. ASSERT_FALSE(svr.is_running());
  8631. ASSERT_TRUE(handled);
  8632. });
  8633. svr.wait_until_ready();
  8634. auto req = "POST /test HTTP/1.1\r\n"
  8635. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8636. "Content-Length: 232\r\n"
  8637. "\r\n----------\r\n"
  8638. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8639. "Content-Length: 5\r\n"
  8640. "X-Test: 1\r\n"
  8641. "\r\n"
  8642. "text1"
  8643. "\r\n----------\r\n"
  8644. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8645. "Content-Type: text/plain\r\n"
  8646. "X-Whatever: CustomValue\r\n"
  8647. "\r\n"
  8648. "text2"
  8649. "\r\n------------\r\n"
  8650. "That should be disregarded. Not even read";
  8651. std::string response;
  8652. ASSERT_TRUE(send_request(1, req, &response));
  8653. ASSERT_EQ("200", response.substr(9, 3));
  8654. }
  8655. #endif
  8656. TEST(MultipartFormDataTest, LargeHeader) {
  8657. auto handled = false;
  8658. Server svr;
  8659. svr.Post("/test", [&](const Request &req, Response &) {
  8660. ASSERT_EQ(1u, req.form.fields.size());
  8661. const auto &text = req.form.get_field("name1");
  8662. ASSERT_EQ("text1", text);
  8663. handled = true;
  8664. });
  8665. thread t = thread([&] { svr.listen(HOST, PORT); });
  8666. auto se = detail::scope_exit([&] {
  8667. svr.stop();
  8668. t.join();
  8669. ASSERT_FALSE(svr.is_running());
  8670. ASSERT_TRUE(handled);
  8671. });
  8672. svr.wait_until_ready();
  8673. auto boundary = std::string("cpp-httplib-multipart-data");
  8674. std::string content = "--" + boundary +
  8675. "\r\n"
  8676. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8677. "\r\n"
  8678. "text1\r\n"
  8679. "--" +
  8680. boundary + "--\r\n";
  8681. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8682. "Content-Type: multipart/form-data;boundary=" +
  8683. boundary +
  8684. "\r\n"
  8685. "Content-Length: " +
  8686. std::to_string(content.size()) +
  8687. "\r\n"
  8688. "Dummy-Header: ";
  8689. std::string header_suffix = "\r\n"
  8690. "\r\n";
  8691. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8692. size_t header_dummy_size =
  8693. read_buff_size -
  8694. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8695. auto header_dummy = std::string(header_dummy_size, '@');
  8696. auto req = header_prefix + header_dummy + header_suffix + content;
  8697. std::string response;
  8698. ASSERT_TRUE(send_request(1, req, &response));
  8699. ASSERT_EQ("200", response.substr(9, 3));
  8700. }
  8701. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8702. static constexpr unsigned int number_of_tasks{1000000};
  8703. std::atomic_uint count{0};
  8704. std::unique_ptr<TaskQueue> task_queue{
  8705. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8706. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8707. auto queued = task_queue->enqueue(
  8708. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8709. EXPECT_TRUE(queued);
  8710. }
  8711. EXPECT_NO_THROW(task_queue->shutdown());
  8712. EXPECT_EQ(number_of_tasks, count.load());
  8713. }
  8714. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8715. static constexpr unsigned int number_of_tasks{1000000};
  8716. static constexpr unsigned int qlimit{2};
  8717. unsigned int queued_count{0};
  8718. std::atomic_uint count{0};
  8719. std::unique_ptr<TaskQueue> task_queue{
  8720. new ThreadPool{/*num_threads=*/1, qlimit}};
  8721. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8722. if (task_queue->enqueue(
  8723. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8724. queued_count++;
  8725. }
  8726. }
  8727. EXPECT_NO_THROW(task_queue->shutdown());
  8728. EXPECT_EQ(queued_count, count.load());
  8729. EXPECT_TRUE(queued_count <= number_of_tasks);
  8730. EXPECT_TRUE(queued_count >= qlimit);
  8731. }
  8732. TEST(TaskQueueTest, MaxQueuedRequests) {
  8733. static constexpr unsigned int qlimit{3};
  8734. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8735. std::condition_variable sem_cv;
  8736. std::mutex sem_mtx;
  8737. int credits = 0;
  8738. bool queued;
  8739. /* Fill up the queue with tasks that will block until we give them credits to
  8740. * complete. */
  8741. for (unsigned int n = 0; n <= qlimit;) {
  8742. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8743. std::unique_lock<std::mutex> lock(sem_mtx);
  8744. while (credits <= 0) {
  8745. sem_cv.wait(lock);
  8746. }
  8747. /* Consume the credit and signal the test code if they are all gone. */
  8748. if (--credits == 0) { sem_cv.notify_one(); }
  8749. });
  8750. if (n < qlimit) {
  8751. /* The first qlimit enqueues must succeed. */
  8752. EXPECT_TRUE(queued);
  8753. } else {
  8754. /* The last one will succeed only when the worker thread
  8755. * starts and dequeues the first blocking task. Although
  8756. * not necessary for the correctness of this test, we sleep for
  8757. * a short while to avoid busy waiting. */
  8758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8759. }
  8760. if (queued) { n++; }
  8761. }
  8762. /* Further enqueues must fail since the queue is full. */
  8763. for (auto i = 0; i < 4; i++) {
  8764. queued = task_queue->enqueue([] {});
  8765. EXPECT_FALSE(queued);
  8766. }
  8767. /* Give the credits to allow the previous tasks to complete. */
  8768. {
  8769. std::unique_lock<std::mutex> lock(sem_mtx);
  8770. credits += qlimit + 1;
  8771. }
  8772. sem_cv.notify_all();
  8773. /* Wait for all the credits to be consumed. */
  8774. {
  8775. std::unique_lock<std::mutex> lock(sem_mtx);
  8776. while (credits > 0) {
  8777. sem_cv.wait(lock);
  8778. }
  8779. }
  8780. /* Check that we are able again to enqueue at least qlimit tasks. */
  8781. for (unsigned int i = 0; i < qlimit; i++) {
  8782. queued = task_queue->enqueue([] {});
  8783. EXPECT_TRUE(queued);
  8784. }
  8785. EXPECT_NO_THROW(task_queue->shutdown());
  8786. }
  8787. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8788. Server svr;
  8789. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8790. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8791. });
  8792. svr.Get("/hello", [](const Request &req, Response &res) {
  8793. res.set_content(req.get_param_value("key"), "text/plain");
  8794. });
  8795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. thread.join();
  8799. ASSERT_FALSE(svr.is_running());
  8800. });
  8801. svr.wait_until_ready();
  8802. {
  8803. Client cli(HOST, PORT);
  8804. cli.set_follow_location(true);
  8805. auto res = cli.Get("/");
  8806. ASSERT_TRUE(res);
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. EXPECT_EQ("val&key2=val2", res->body);
  8809. }
  8810. }
  8811. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8812. Server svr;
  8813. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8814. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8815. });
  8816. svr.Get("/hello", [](const Request &req, Response &res) {
  8817. res.set_content(req.get_param_value("key"), "text/plain");
  8818. });
  8819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8820. auto se = detail::scope_exit([&] {
  8821. svr.stop();
  8822. thread.join();
  8823. ASSERT_FALSE(svr.is_running());
  8824. });
  8825. svr.wait_until_ready();
  8826. {
  8827. Client cli(HOST, PORT);
  8828. cli.set_follow_location(true);
  8829. auto res = cli.Get("/");
  8830. ASSERT_TRUE(res);
  8831. EXPECT_EQ(StatusCode::OK_200, res->status);
  8832. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8833. }
  8834. }
  8835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8836. TEST(RedirectTest, Issue2185_Online) {
  8837. SSLClient client("github.com");
  8838. client.set_follow_location(true);
  8839. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8840. "Coollab-Windows.zip");
  8841. ASSERT_TRUE(res);
  8842. EXPECT_EQ(StatusCode::OK_200, res->status);
  8843. EXPECT_EQ(9920427U, res->body.size());
  8844. }
  8845. #endif
  8846. TEST(VulnerabilityTest, CRLFInjection) {
  8847. Server svr;
  8848. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8849. res.set_content("Hello 1", "text/plain");
  8850. });
  8851. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8852. res.set_content("Hello 2", "text/plain");
  8853. });
  8854. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8855. res.set_content("Hello 3", "text/plain");
  8856. });
  8857. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8858. res.set_content("Hello 4", "text/plain");
  8859. });
  8860. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8861. for (const auto &x : req.headers) {
  8862. auto key = x.first;
  8863. EXPECT_STRNE("evil", key.c_str());
  8864. }
  8865. });
  8866. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8867. auto se = detail::scope_exit([&] {
  8868. svr.stop();
  8869. thread.join();
  8870. ASSERT_FALSE(svr.is_running());
  8871. });
  8872. svr.wait_until_ready();
  8873. {
  8874. Client cli(HOST, PORT);
  8875. cli.Post("/test1", "A=B",
  8876. "application/x-www-form-urlencoded\r\nevil: hello1");
  8877. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8878. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8879. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8880. }
  8881. }
  8882. TEST(PathParamsTest, StaticMatch) {
  8883. const auto pattern = "/users/all";
  8884. detail::PathParamsMatcher matcher(pattern);
  8885. Request request;
  8886. request.path = "/users/all";
  8887. ASSERT_TRUE(matcher.match(request));
  8888. std::unordered_map<std::string, std::string> expected_params = {};
  8889. EXPECT_EQ(request.path_params, expected_params);
  8890. }
  8891. TEST(PathParamsTest, StaticMismatch) {
  8892. const auto pattern = "/users/all";
  8893. detail::PathParamsMatcher matcher(pattern);
  8894. Request request;
  8895. request.path = "/users/1";
  8896. ASSERT_FALSE(matcher.match(request));
  8897. }
  8898. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8899. const auto pattern = "/users/:id/subscriptions";
  8900. detail::PathParamsMatcher matcher(pattern);
  8901. Request request;
  8902. request.path = "/users/42/subscriptions";
  8903. ASSERT_TRUE(matcher.match(request));
  8904. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8905. EXPECT_EQ(request.path_params, expected_params);
  8906. }
  8907. TEST(PathParamsTest, SingleParamInTheEnd) {
  8908. const auto pattern = "/users/:id";
  8909. detail::PathParamsMatcher matcher(pattern);
  8910. Request request;
  8911. request.path = "/users/24";
  8912. ASSERT_TRUE(matcher.match(request));
  8913. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8914. EXPECT_EQ(request.path_params, expected_params);
  8915. }
  8916. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8917. const auto pattern = "/users/:id/";
  8918. detail::PathParamsMatcher matcher(pattern);
  8919. Request request;
  8920. request.path = "/users/42/";
  8921. ASSERT_TRUE(matcher.match(request));
  8922. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8923. EXPECT_EQ(request.path_params, expected_params);
  8924. }
  8925. TEST(PathParamsTest, EmptyParam) {
  8926. const auto pattern = "/users/:id/";
  8927. detail::PathParamsMatcher matcher(pattern);
  8928. Request request;
  8929. request.path = "/users//";
  8930. ASSERT_TRUE(matcher.match(request));
  8931. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8932. EXPECT_EQ(request.path_params, expected_params);
  8933. }
  8934. TEST(PathParamsTest, FragmentMismatch) {
  8935. const auto pattern = "/users/:id/";
  8936. detail::PathParamsMatcher matcher(pattern);
  8937. Request request;
  8938. request.path = "/admins/24/";
  8939. ASSERT_FALSE(matcher.match(request));
  8940. }
  8941. TEST(PathParamsTest, ExtraFragments) {
  8942. const auto pattern = "/users/:id";
  8943. detail::PathParamsMatcher matcher(pattern);
  8944. Request request;
  8945. request.path = "/users/42/subscriptions";
  8946. ASSERT_FALSE(matcher.match(request));
  8947. }
  8948. TEST(PathParamsTest, MissingTrailingParam) {
  8949. const auto pattern = "/users/:id";
  8950. detail::PathParamsMatcher matcher(pattern);
  8951. Request request;
  8952. request.path = "/users";
  8953. ASSERT_FALSE(matcher.match(request));
  8954. }
  8955. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8956. const auto pattern = "/users/:id/subscriptions";
  8957. detail::PathParamsMatcher matcher(pattern);
  8958. Request request;
  8959. request.path = "/users/subscriptions";
  8960. ASSERT_FALSE(matcher.match(request));
  8961. }
  8962. TEST(PathParamsTest, MultipleParams) {
  8963. const auto pattern = "/users/:userid/subscriptions/:subid";
  8964. detail::PathParamsMatcher matcher(pattern);
  8965. Request request;
  8966. request.path = "/users/42/subscriptions/2";
  8967. ASSERT_TRUE(matcher.match(request));
  8968. std::unordered_map<std::string, std::string> expected_params = {
  8969. {"userid", "42"}, {"subid", "2"}};
  8970. EXPECT_EQ(request.path_params, expected_params);
  8971. }
  8972. TEST(PathParamsTest, SequenceOfParams) {
  8973. const auto pattern = "/values/:x/:y/:z";
  8974. detail::PathParamsMatcher matcher(pattern);
  8975. Request request;
  8976. request.path = "/values/1/2/3";
  8977. ASSERT_TRUE(matcher.match(request));
  8978. std::unordered_map<std::string, std::string> expected_params = {
  8979. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8980. EXPECT_EQ(request.path_params, expected_params);
  8981. }
  8982. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8983. const auto pattern = "/prefix:suffix";
  8984. detail::PathParamsMatcher matcher(pattern);
  8985. Request request;
  8986. request.path = "/prefix:suffix";
  8987. ASSERT_TRUE(matcher.match(request));
  8988. const std::unordered_map<std::string, std::string> expected_params = {};
  8989. EXPECT_EQ(request.path_params, expected_params);
  8990. }
  8991. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8992. // If ipv6 regex working, regex match codepath is taken.
  8993. // else port will default to 80 in Client impl
  8994. int clientImplMagicPort = 80;
  8995. int port = 4321;
  8996. // above ports must be different to avoid false negative
  8997. EXPECT_NE(clientImplMagicPort, port);
  8998. std::string ipV6TestURL = "http://[ff06::c3]";
  8999. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9000. CLIENT_PRIVATE_KEY_FILE);
  9001. EXPECT_EQ(cli.port(), port);
  9002. }
  9003. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9004. auto file_path = "./www/dir/index.html";
  9005. auto dir_path = "./www/dir";
  9006. detail::FileStat stat_file(file_path);
  9007. EXPECT_TRUE(stat_file.is_file());
  9008. EXPECT_FALSE(stat_file.is_dir());
  9009. detail::FileStat stat_dir(dir_path);
  9010. EXPECT_FALSE(stat_dir.is_file());
  9011. EXPECT_TRUE(stat_dir.is_dir());
  9012. }
  9013. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9014. // IPv4 with default HTTP port (80)
  9015. EXPECT_EQ("example.com",
  9016. detail::make_host_and_port_string("example.com", 80, false));
  9017. // IPv4 with default HTTPS port (443)
  9018. EXPECT_EQ("example.com",
  9019. detail::make_host_and_port_string("example.com", 443, true));
  9020. // IPv4 with non-default HTTP port
  9021. EXPECT_EQ("example.com:8080",
  9022. detail::make_host_and_port_string("example.com", 8080, false));
  9023. // IPv4 with non-default HTTPS port
  9024. EXPECT_EQ("example.com:8443",
  9025. detail::make_host_and_port_string("example.com", 8443, true));
  9026. // IPv6 with default HTTP port (80)
  9027. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9028. // IPv6 with default HTTPS port (443)
  9029. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9030. // IPv6 with non-default HTTP port
  9031. EXPECT_EQ("[::1]:8080",
  9032. detail::make_host_and_port_string("::1", 8080, false));
  9033. // IPv6 with non-default HTTPS port
  9034. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9035. // IPv6 full address with default port
  9036. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9037. detail::make_host_and_port_string(
  9038. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9039. // IPv6 full address with non-default port
  9040. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9041. detail::make_host_and_port_string(
  9042. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9043. // IPv6 localhost with non-default port
  9044. EXPECT_EQ("[::1]:3000",
  9045. detail::make_host_and_port_string("::1", 3000, false));
  9046. // IPv6 with zone ID (link-local address) with default port
  9047. EXPECT_EQ("[fe80::1%eth0]",
  9048. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9049. // IPv6 with zone ID (link-local address) with non-default port
  9050. EXPECT_EQ("[fe80::1%eth0]:8080",
  9051. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9052. // Edge case: Port 443 with is_ssl=false (should add port)
  9053. EXPECT_EQ("example.com:443",
  9054. detail::make_host_and_port_string("example.com", 443, false));
  9055. // Edge case: Port 80 with is_ssl=true (should add port)
  9056. EXPECT_EQ("example.com:80",
  9057. detail::make_host_and_port_string("example.com", 80, true));
  9058. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9059. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9060. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9061. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9062. // Security fix: Already bracketed IPv6 should not get double brackets
  9063. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9064. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9065. EXPECT_EQ("[::1]:8080",
  9066. detail::make_host_and_port_string("[::1]", 8080, false));
  9067. EXPECT_EQ("[2001:db8::1]:8080",
  9068. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9069. EXPECT_EQ("[fe80::1%eth0]",
  9070. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9071. EXPECT_EQ("[fe80::1%eth0]:8080",
  9072. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9073. // Edge case: Empty host (should return as-is)
  9074. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9075. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9076. // This is a known limitation but shouldn't crash
  9077. EXPECT_EQ("[host:name]",
  9078. detail::make_host_and_port_string("host:name", 80, false));
  9079. // Port number edge cases (no validation, but should not crash)
  9080. EXPECT_EQ("example.com:0",
  9081. detail::make_host_and_port_string("example.com", 0, false));
  9082. EXPECT_EQ("example.com:-1",
  9083. detail::make_host_and_port_string("example.com", -1, false));
  9084. EXPECT_EQ("example.com:65535",
  9085. detail::make_host_and_port_string("example.com", 65535, false));
  9086. EXPECT_EQ("example.com:65536",
  9087. detail::make_host_and_port_string("example.com", 65536, false));
  9088. }
  9089. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9090. Server svr;
  9091. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9092. EXPECT_EQ(res.status, 400);
  9093. });
  9094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9095. auto se = detail::scope_exit([&] {
  9096. svr.stop();
  9097. thread.join();
  9098. ASSERT_FALSE(svr.is_running());
  9099. });
  9100. svr.wait_until_ready();
  9101. Client cli(HOST, PORT);
  9102. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9103. }
  9104. TEST(InvalidHeaderCharsTest, is_field_name) {
  9105. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9106. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9107. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9108. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9109. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9110. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9111. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9112. EXPECT_FALSE(detail::fields::is_field_name(""));
  9113. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9114. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9115. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9116. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9117. }
  9118. TEST(InvalidHeaderCharsTest, is_field_value) {
  9119. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9120. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9121. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9122. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9123. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9124. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9125. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9126. EXPECT_TRUE(detail::fields::is_field_value(""));
  9127. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9128. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9129. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9130. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9131. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9132. }
  9133. TEST(InvalidHeaderCharsTest, OnServer) {
  9134. Server svr;
  9135. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9136. std::string header = "Not Set";
  9137. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9138. res.set_header(header, "value");
  9139. res.set_content("Page Content Page Content", "text/plain");
  9140. });
  9141. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9142. std::string header = "Not Set";
  9143. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9144. res.set_header("X-Test", header);
  9145. res.set_content("Page Content Page Content", "text/plain");
  9146. });
  9147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9148. auto se = detail::scope_exit([&] {
  9149. svr.stop();
  9150. thread.join();
  9151. ASSERT_FALSE(svr.is_running());
  9152. });
  9153. svr.wait_until_ready();
  9154. Client cli(HOST, PORT);
  9155. {
  9156. auto res = cli.Get(
  9157. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9158. ASSERT_TRUE(res);
  9159. EXPECT_EQ("Page Content Page Content", res->body);
  9160. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9161. }
  9162. {
  9163. auto res = cli.Get(
  9164. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9165. ASSERT_TRUE(res);
  9166. EXPECT_EQ("Page Content Page Content", res->body);
  9167. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9168. }
  9169. }
  9170. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9171. auto handled = false;
  9172. Server svr;
  9173. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9174. thread t = thread([&] { svr.listen(HOST, PORT); });
  9175. auto se = detail::scope_exit([&] {
  9176. svr.stop();
  9177. t.join();
  9178. ASSERT_FALSE(svr.is_running());
  9179. ASSERT_FALSE(handled);
  9180. });
  9181. svr.wait_until_ready();
  9182. auto req = "POST /test HTTP/1.1\r\n"
  9183. "Content-Length: x\r\n"
  9184. "\r\n";
  9185. std::string response;
  9186. ASSERT_TRUE(send_request(1, req, &response));
  9187. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9188. response.substr(0, response.find("\r\n")));
  9189. }
  9190. #ifndef _WIN32
  9191. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9192. static constexpr char reject[] = "Unauthorized";
  9193. static constexpr char accept[] = "Upload accepted";
  9194. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9195. Server svr;
  9196. svr.set_expect_100_continue_handler(
  9197. [](const Request & /*req*/, Response &res) {
  9198. res.status = StatusCode::Unauthorized_401;
  9199. res.set_content(reject, "text/plain");
  9200. return res.status;
  9201. });
  9202. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9203. res.set_content(accept, "text/plain");
  9204. });
  9205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9206. auto se = detail::scope_exit([&] {
  9207. svr.stop();
  9208. thread.join();
  9209. ASSERT_FALSE(svr.is_running());
  9210. });
  9211. svr.wait_until_ready();
  9212. {
  9213. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9214. curl_easy_init(), &curl_easy_cleanup};
  9215. ASSERT_NE(curl, nullptr);
  9216. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9217. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9218. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9219. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9220. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9221. &curl_slist_free_all};
  9222. ASSERT_NE(list, nullptr);
  9223. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9224. struct read_data {
  9225. size_t read_size;
  9226. size_t total_size;
  9227. } data = {0, total_size};
  9228. using read_callback_t =
  9229. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9230. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9231. void *userdata) -> size_t {
  9232. read_data *data = (read_data *)userdata;
  9233. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9234. std::fill_n(ptr, size * nmemb, 'A');
  9235. data->read_size += size * nmemb;
  9236. return size * nmemb;
  9237. };
  9238. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9239. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9240. std::vector<char> buffer;
  9241. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9242. using write_callback_t =
  9243. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9244. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9245. void *userdata) -> size_t {
  9246. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9247. buffer->reserve(buffer->size() + size * nmemb + 1);
  9248. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9249. return size * nmemb;
  9250. };
  9251. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9252. {
  9253. const auto res = curl_easy_perform(curl.get());
  9254. ASSERT_EQ(res, CURLE_OK);
  9255. }
  9256. {
  9257. auto response_code = long{};
  9258. const auto res =
  9259. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9260. ASSERT_EQ(res, CURLE_OK);
  9261. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9262. }
  9263. {
  9264. auto dl = curl_off_t{};
  9265. const auto res =
  9266. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9267. ASSERT_EQ(res, CURLE_OK);
  9268. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9269. }
  9270. {
  9271. buffer.push_back('\0');
  9272. ASSERT_STRCASEEQ(buffer.data(), reject);
  9273. }
  9274. }
  9275. }
  9276. #endif
  9277. template <typename S, typename C>
  9278. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9279. svr.Get("/stream", [&](const Request &, Response &res) {
  9280. auto data = new std::string("01234567890123456789");
  9281. res.set_content_provider(
  9282. data->size(), "text/plain",
  9283. [&, data](size_t offset, size_t length, DataSink &sink) {
  9284. const size_t DATA_CHUNK_SIZE = 4;
  9285. const auto &d = *data;
  9286. std::this_thread::sleep_for(std::chrono::seconds(1));
  9287. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9288. return true;
  9289. },
  9290. [data](bool success) {
  9291. EXPECT_FALSE(success);
  9292. delete data;
  9293. });
  9294. });
  9295. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9296. auto i = new size_t(0);
  9297. res.set_content_provider(
  9298. "text/plain",
  9299. [i](size_t, DataSink &sink) {
  9300. if (*i < 5) {
  9301. std::this_thread::sleep_for(std::chrono::seconds(1));
  9302. sink.write("abcd", 4);
  9303. (*i)++;
  9304. } else {
  9305. sink.done();
  9306. }
  9307. return true;
  9308. },
  9309. [i](bool success) {
  9310. EXPECT_FALSE(success);
  9311. delete i;
  9312. });
  9313. });
  9314. svr.Get("/chunked", [&](const Request &, Response &res) {
  9315. auto i = new size_t(0);
  9316. res.set_chunked_content_provider(
  9317. "text/plain",
  9318. [i](size_t, DataSink &sink) {
  9319. if (*i < 5) {
  9320. std::this_thread::sleep_for(std::chrono::seconds(1));
  9321. sink.os << "abcd";
  9322. (*i)++;
  9323. } else {
  9324. sink.done();
  9325. }
  9326. return true;
  9327. },
  9328. [i](bool success) {
  9329. EXPECT_FALSE(success);
  9330. delete i;
  9331. });
  9332. });
  9333. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9334. auto se = detail::scope_exit([&] {
  9335. svr.stop();
  9336. listen_thread.join();
  9337. ASSERT_FALSE(svr.is_running());
  9338. });
  9339. svr.wait_until_ready();
  9340. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9341. {
  9342. auto start = std::chrono::steady_clock::now();
  9343. auto res = cli.Get("/stream");
  9344. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9345. std::chrono::steady_clock::now() - start)
  9346. .count();
  9347. ASSERT_FALSE(res);
  9348. EXPECT_EQ(Error::Read, res.error());
  9349. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9350. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9351. }
  9352. {
  9353. auto start = std::chrono::steady_clock::now();
  9354. auto res = cli.Get("/stream_without_length");
  9355. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9356. std::chrono::steady_clock::now() - start)
  9357. .count();
  9358. ASSERT_FALSE(res);
  9359. EXPECT_EQ(Error::Read, res.error());
  9360. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9361. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9362. }
  9363. {
  9364. auto start = std::chrono::steady_clock::now();
  9365. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9366. EXPECT_EQ("abcd", string(data, data_length));
  9367. return true;
  9368. });
  9369. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9370. std::chrono::steady_clock::now() - start)
  9371. .count();
  9372. ASSERT_FALSE(res);
  9373. EXPECT_EQ(Error::Read, res.error());
  9374. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9375. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9376. }
  9377. }
  9378. TEST(MaxTimeoutTest, ContentStream) {
  9379. time_t timeout = 2000;
  9380. time_t threshold = 200;
  9381. Server svr;
  9382. Client cli("localhost", PORT);
  9383. max_timeout_test(svr, cli, timeout, threshold);
  9384. }
  9385. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9386. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9387. time_t timeout = 2000;
  9388. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9390. SSLClient cli("localhost", PORT);
  9391. cli.enable_server_certificate_verification(false);
  9392. max_timeout_test(svr, cli, timeout, threshold);
  9393. }
  9394. #endif
  9395. class EventDispatcher {
  9396. public:
  9397. EventDispatcher() {}
  9398. bool wait_event(DataSink *sink) {
  9399. unique_lock<mutex> lk(m_);
  9400. int id = id_;
  9401. // Wait with timeout to prevent hanging if client disconnects
  9402. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9403. [&] { return cid_ == id; })) {
  9404. return false; // Timeout occurred
  9405. }
  9406. sink->write(message_.data(), message_.size());
  9407. return true;
  9408. }
  9409. void send_event(const string &message) {
  9410. lock_guard<mutex> lk(m_);
  9411. cid_ = id_++;
  9412. message_ = message;
  9413. cv_.notify_all();
  9414. }
  9415. private:
  9416. mutex m_;
  9417. condition_variable cv_;
  9418. atomic_int id_{0};
  9419. atomic_int cid_{-1};
  9420. string message_;
  9421. };
  9422. TEST(ClientInThreadTest, Issue2068) {
  9423. EventDispatcher ed;
  9424. Server svr;
  9425. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9426. res.set_chunked_content_provider("text/event-stream",
  9427. [&](size_t /*offset*/, DataSink &sink) {
  9428. return ed.wait_event(&sink);
  9429. });
  9430. });
  9431. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9432. svr.wait_until_ready();
  9433. thread event_thread([&] {
  9434. int id = 0;
  9435. while (svr.is_running()) {
  9436. this_thread::sleep_for(chrono::milliseconds(500));
  9437. std::stringstream ss;
  9438. ss << "data: " << id << "\n\n";
  9439. ed.send_event(ss.str());
  9440. id++;
  9441. }
  9442. });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. listen_thread.join();
  9446. event_thread.join();
  9447. ASSERT_FALSE(svr.is_running());
  9448. });
  9449. {
  9450. auto client = detail::make_unique<Client>(HOST, PORT);
  9451. client->set_read_timeout(std::chrono::minutes(10));
  9452. std::atomic<bool> stop{false};
  9453. std::thread t([&] {
  9454. client->Get("/event1",
  9455. [&](const char *, size_t) -> bool { return !stop; });
  9456. });
  9457. std::this_thread::sleep_for(std::chrono::seconds(2));
  9458. stop = true;
  9459. client->stop();
  9460. t.join();
  9461. // Reset client after thread has finished
  9462. client.reset();
  9463. }
  9464. }
  9465. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9466. Server svr;
  9467. svr.Get("/", [](const Request &req, Response &res) {
  9468. EXPECT_EQ(2U, req.trailers.size());
  9469. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9470. // Denied
  9471. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9472. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9473. // Accepted
  9474. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9475. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9476. EXPECT_TRUE(req.has_trailer("X-World"));
  9477. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9478. res.set_content("ok", "text/plain");
  9479. });
  9480. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. t.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. const std::string req = "GET / HTTP/1.1\r\n"
  9488. "Transfer-Encoding: chunked\r\n"
  9489. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9490. "\r\n"
  9491. "0\r\n"
  9492. "Content-Length: 10\r\n"
  9493. "Host: internal.local\r\n"
  9494. "Content-Type: malicious/content\r\n"
  9495. "Cookie: any\r\n"
  9496. "Set-Cookie: any\r\n"
  9497. "X-Forwarded-For: attacker.com\r\n"
  9498. "X-Real-Ip: 1.1.1.1\r\n"
  9499. "X-Hello: hello\r\n"
  9500. "X-World: world\r\n"
  9501. "\r\n";
  9502. std::string res;
  9503. ASSERT_TRUE(send_request(1, req, &res));
  9504. }
  9505. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9506. Server svr;
  9507. std::string observed_remote_addr;
  9508. std::string observed_xff;
  9509. svr.Get("/ip", [&](const Request &req, Response &res) {
  9510. observed_remote_addr = req.remote_addr;
  9511. observed_xff = req.get_header_value("X-Forwarded-For");
  9512. res.set_content("ok", "text/plain");
  9513. });
  9514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. Client cli(HOST, PORT);
  9522. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9523. ASSERT_TRUE(res);
  9524. EXPECT_EQ(StatusCode::OK_200, res->status);
  9525. EXPECT_EQ(observed_xff, "203.0.113.66");
  9526. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9527. observed_remote_addr == "127.0.0.1");
  9528. }
  9529. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9530. Server svr;
  9531. svr.set_trusted_proxies({"203.0.113.66"});
  9532. std::string observed_remote_addr;
  9533. std::string observed_xff;
  9534. svr.Get("/ip", [&](const Request &req, Response &res) {
  9535. observed_remote_addr = req.remote_addr;
  9536. observed_xff = req.get_header_value("X-Forwarded-For");
  9537. res.set_content("ok", "text/plain");
  9538. });
  9539. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. Client cli(HOST, PORT);
  9547. auto res = cli.Get("/ip");
  9548. ASSERT_TRUE(res);
  9549. EXPECT_EQ(StatusCode::OK_200, res->status);
  9550. EXPECT_EQ(observed_xff, "");
  9551. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9552. observed_remote_addr == "127.0.0.1");
  9553. }
  9554. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9555. Server svr;
  9556. svr.set_trusted_proxies({"203.0.113.66"});
  9557. std::string observed_remote_addr;
  9558. std::string observed_xff;
  9559. svr.Get("/ip", [&](const Request &req, Response &res) {
  9560. observed_remote_addr = req.remote_addr;
  9561. observed_xff = req.get_header_value("X-Forwarded-For");
  9562. res.set_content("ok", "text/plain");
  9563. });
  9564. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9565. auto se = detail::scope_exit([&] {
  9566. svr.stop();
  9567. t.join();
  9568. ASSERT_FALSE(svr.is_running());
  9569. });
  9570. svr.wait_until_ready();
  9571. Client cli(HOST, PORT);
  9572. auto res =
  9573. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9574. ASSERT_TRUE(res);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9577. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9578. }
  9579. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9580. Server svr;
  9581. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9582. std::string observed_remote_addr;
  9583. std::string observed_xff;
  9584. svr.Get("/ip", [&](const Request &req, Response &res) {
  9585. observed_remote_addr = req.remote_addr;
  9586. observed_xff = req.get_header_value("X-Forwarded-For");
  9587. res.set_content("ok", "text/plain");
  9588. });
  9589. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. Client cli(HOST, PORT);
  9597. auto res = cli.Get(
  9598. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9599. ASSERT_TRUE(res);
  9600. EXPECT_EQ(StatusCode::OK_200, res->status);
  9601. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9602. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9603. }
  9604. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9605. Server svr;
  9606. svr.set_trusted_proxies({"192.0.2.45"});
  9607. std::string observed_remote_addr;
  9608. std::string observed_xff;
  9609. svr.Get("/ip", [&](const Request &req, Response &res) {
  9610. observed_remote_addr = req.remote_addr;
  9611. observed_xff = req.get_header_value("X-Forwarded-For");
  9612. res.set_content("ok", "text/plain");
  9613. });
  9614. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9615. auto se = detail::scope_exit([&] {
  9616. svr.stop();
  9617. t.join();
  9618. ASSERT_FALSE(svr.is_running());
  9619. });
  9620. svr.wait_until_ready();
  9621. Client cli(HOST, PORT);
  9622. auto res =
  9623. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9624. ASSERT_TRUE(res);
  9625. EXPECT_EQ(StatusCode::OK_200, res->status);
  9626. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9627. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9628. }
  9629. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9630. Server svr;
  9631. svr.set_trusted_proxies({"192.0.2.45"});
  9632. std::string observed_remote_addr;
  9633. std::string observed_xff;
  9634. svr.Get("/ip", [&](const Request &req, Response &res) {
  9635. observed_remote_addr = req.remote_addr;
  9636. observed_xff = req.get_header_value("X-Forwarded-For");
  9637. res.set_content("ok", "text/plain");
  9638. });
  9639. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9640. auto se = detail::scope_exit([&] {
  9641. svr.stop();
  9642. t.join();
  9643. ASSERT_FALSE(svr.is_running());
  9644. });
  9645. svr.wait_until_ready();
  9646. Client cli(HOST, PORT);
  9647. auto res = cli.Get(
  9648. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9649. ASSERT_TRUE(res);
  9650. EXPECT_EQ(StatusCode::OK_200, res->status);
  9651. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9652. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9653. }
  9654. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9655. Server svr;
  9656. svr.set_trusted_proxies({"192.0.2.45"});
  9657. std::string observed_remote_addr;
  9658. std::string observed_xff;
  9659. svr.Get("/ip", [&](const Request &req, Response &res) {
  9660. observed_remote_addr = req.remote_addr;
  9661. observed_xff = req.get_header_value("X-Forwarded-For");
  9662. res.set_content("ok", "text/plain");
  9663. });
  9664. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9665. auto se = detail::scope_exit([&] {
  9666. svr.stop();
  9667. t.join();
  9668. ASSERT_FALSE(svr.is_running());
  9669. });
  9670. svr.wait_until_ready();
  9671. Client cli(HOST, PORT);
  9672. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9673. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9674. ASSERT_TRUE(res);
  9675. EXPECT_EQ(StatusCode::OK_200, res->status);
  9676. // Header parser trims surrounding whitespace of the header value
  9677. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9678. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9679. }
  9680. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9681. Server svr;
  9682. svr.Post("/post", [&](const Request &req, Response &res) {
  9683. res.set_content(req.body, "text/plain");
  9684. });
  9685. svr.Put("/put", [&](const Request &req, Response &res) {
  9686. res.set_content(req.body, "text/plain");
  9687. });
  9688. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9689. res.set_content(req.body, "text/plain");
  9690. });
  9691. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9692. res.set_content(req.body, "text/plain");
  9693. });
  9694. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. t.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. std::string resp;
  9702. // POST without Content-Length
  9703. ASSERT_TRUE(send_request(5,
  9704. "POST /post HTTP/1.1\r\n"
  9705. "Host: localhost\r\n"
  9706. "Connection: close\r\n"
  9707. "\r\n",
  9708. &resp));
  9709. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9710. // PUT without Content-Length
  9711. resp.clear();
  9712. ASSERT_TRUE(send_request(5,
  9713. "PUT /put HTTP/1.1\r\n"
  9714. "Host: localhost\r\n"
  9715. "Connection: close\r\n"
  9716. "\r\n",
  9717. &resp));
  9718. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9719. // PATCH without Content-Length
  9720. resp.clear();
  9721. ASSERT_TRUE(send_request(5,
  9722. "PATCH /patch HTTP/1.1\r\n"
  9723. "Host: localhost\r\n"
  9724. "Connection: close\r\n"
  9725. "\r\n",
  9726. &resp));
  9727. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9728. // DELETE without Content-Length
  9729. resp.clear();
  9730. ASSERT_TRUE(send_request(5,
  9731. "DELETE /delete HTTP/1.1\r\n"
  9732. "Host: localhost\r\n"
  9733. "Connection: close\r\n"
  9734. "\r\n",
  9735. &resp));
  9736. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9737. }
  9738. //==============================================================================
  9739. // open_stream() Tests
  9740. //==============================================================================
  9741. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9742. std::string result;
  9743. char buf[8192];
  9744. ssize_t n;
  9745. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9746. result.append(buf, static_cast<size_t>(n));
  9747. }
  9748. return result;
  9749. }
  9750. // Mock stream for unit tests
  9751. class MockStream : public Stream {
  9752. public:
  9753. std::string data;
  9754. size_t pos = 0;
  9755. ssize_t error_after = -1; // -1 = no error
  9756. explicit MockStream(const std::string &d, ssize_t err = -1)
  9757. : data(d), error_after(err) {}
  9758. bool is_readable() const override { return true; }
  9759. bool wait_readable() const override { return true; }
  9760. bool wait_writable() const override { return true; }
  9761. ssize_t read(char *ptr, size_t size) override {
  9762. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9763. if (pos >= data.size()) return 0;
  9764. size_t limit =
  9765. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9766. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9767. std::memcpy(ptr, data.data() + pos, to_read);
  9768. pos += to_read;
  9769. return static_cast<ssize_t>(to_read);
  9770. }
  9771. ssize_t write(const char *, size_t) override { return -1; }
  9772. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9773. ip = "127.0.0.1";
  9774. port = 0;
  9775. }
  9776. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9777. ip = "127.0.0.1";
  9778. port = 0;
  9779. }
  9780. socket_t socket() const override { return INVALID_SOCKET; }
  9781. time_t duration() const override { return 0; }
  9782. };
  9783. TEST(StreamHandleTest, Basic) {
  9784. ClientImpl::StreamHandle handle;
  9785. EXPECT_FALSE(handle.is_valid());
  9786. handle.response = detail::make_unique<Response>();
  9787. handle.error = Error::Connection;
  9788. EXPECT_FALSE(handle.is_valid());
  9789. handle.error = Error::Success;
  9790. EXPECT_TRUE(handle.is_valid());
  9791. }
  9792. TEST(BodyReaderTest, Basic) {
  9793. MockStream stream("Hello, World!");
  9794. detail::BodyReader reader;
  9795. reader.stream = &stream;
  9796. reader.content_length = 13;
  9797. char buf[32];
  9798. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9799. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9800. EXPECT_TRUE(reader.eof);
  9801. }
  9802. TEST(BodyReaderTest, NoStream) {
  9803. detail::BodyReader reader;
  9804. char buf[32];
  9805. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9806. EXPECT_EQ(Error::Connection, reader.last_error);
  9807. }
  9808. TEST(BodyReaderTest, Error) {
  9809. MockStream stream("Hello, World!", 5);
  9810. detail::BodyReader reader;
  9811. reader.stream = &stream;
  9812. reader.content_length = 13;
  9813. char buf[32];
  9814. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9815. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9816. EXPECT_EQ(Error::Read, reader.last_error);
  9817. }
  9818. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9819. // Mock-based StreamHandle tests relying on private internals are removed.
  9820. class OpenStreamTest : public ::testing::Test {
  9821. protected:
  9822. void SetUp() override {
  9823. svr_.Get("/hello", [](const Request &, Response &res) {
  9824. res.set_content("Hello World!", "text/plain");
  9825. });
  9826. svr_.Get("/large", [](const Request &, Response &res) {
  9827. res.set_content(std::string(10000, 'X'), "text/plain");
  9828. });
  9829. svr_.Get("/chunked", [](const Request &, Response &res) {
  9830. res.set_chunked_content_provider("text/plain",
  9831. [](size_t offset, DataSink &sink) {
  9832. if (offset < 15) {
  9833. sink.write("chunk", 5);
  9834. return true;
  9835. }
  9836. sink.done();
  9837. return true;
  9838. });
  9839. });
  9840. svr_.Get("/compressible", [](const Request &, Response &res) {
  9841. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9842. DataSink &sink) {
  9843. if (offset < 100 * 1024) {
  9844. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9845. sink.write(chunk.data(), chunk.size());
  9846. return true;
  9847. }
  9848. sink.done();
  9849. return true;
  9850. });
  9851. });
  9852. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9853. [](const Request & /*req*/, Response &res) {
  9854. auto i = new int(0);
  9855. res.set_header("Trailer", "Content-Length, X-Allowed");
  9856. res.set_chunked_content_provider(
  9857. "text/plain",
  9858. [i](size_t /*offset*/, DataSink &sink) {
  9859. switch (*i) {
  9860. case 0: sink.os << "123"; break;
  9861. case 1: sink.os << "456"; break;
  9862. case 2: sink.os << "789"; break;
  9863. case 3: {
  9864. sink.done_with_trailer(
  9865. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9866. } break;
  9867. }
  9868. (*i)++;
  9869. return true;
  9870. },
  9871. [i](bool success) {
  9872. EXPECT_TRUE(success);
  9873. delete i;
  9874. });
  9875. });
  9876. // Echo headers endpoint for header-related tests
  9877. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9878. std::string body;
  9879. for (const auto &h : req.headers) {
  9880. body.append(h.first);
  9881. body.push_back(':');
  9882. body.append(h.second);
  9883. body.push_back('\n');
  9884. }
  9885. res.set_content(body, "text/plain");
  9886. });
  9887. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9888. std::string body;
  9889. for (const auto &h : req.headers) {
  9890. body.append(h.first);
  9891. body.push_back(':');
  9892. body.append(h.second);
  9893. body.push_back('\n');
  9894. }
  9895. res.set_content(body, "text/plain");
  9896. });
  9897. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9898. svr_.wait_until_ready();
  9899. }
  9900. void TearDown() override {
  9901. svr_.stop();
  9902. if (thread_.joinable()) thread_.join();
  9903. }
  9904. Server svr_;
  9905. std::thread thread_;
  9906. };
  9907. TEST_F(OpenStreamTest, Basic) {
  9908. Client cli("127.0.0.1", 8787);
  9909. auto handle = cli.open_stream("GET", "/hello");
  9910. EXPECT_TRUE(handle.is_valid());
  9911. EXPECT_EQ("Hello World!", read_all(handle));
  9912. }
  9913. TEST_F(OpenStreamTest, SmallBuffer) {
  9914. Client cli("127.0.0.1", 8787);
  9915. auto handle = cli.open_stream("GET", "/hello");
  9916. std::string result;
  9917. char buf[4];
  9918. ssize_t n;
  9919. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9920. result.append(buf, static_cast<size_t>(n));
  9921. EXPECT_EQ("Hello World!", result);
  9922. }
  9923. TEST_F(OpenStreamTest, DefaultHeaders) {
  9924. Client cli("127.0.0.1", 8787);
  9925. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9926. {
  9927. auto handle = cli.open_stream("GET", "/echo-headers");
  9928. ASSERT_TRUE(handle.is_valid());
  9929. auto body = read_all(handle);
  9930. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  9931. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  9932. std::string::npos);
  9933. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  9934. }
  9935. // open_stream POST with body and no explicit content_type should NOT add
  9936. // text/plain Content-Type (behavior differs from non-streaming path), but
  9937. // should include Content-Length
  9938. {
  9939. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  9940. ASSERT_TRUE(handle.is_valid());
  9941. auto body = read_all(handle);
  9942. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  9943. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  9944. }
  9945. // open_stream POST with explicit Content-Type should preserve it
  9946. {
  9947. auto handle = cli.open_stream("POST", "/echo-headers", {},
  9948. {{"Content-Type", "application/custom"}},
  9949. "{}", "application/custom");
  9950. ASSERT_TRUE(handle.is_valid());
  9951. auto body = read_all(handle);
  9952. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  9953. }
  9954. // User-specified User-Agent must not be overwritten for stream API
  9955. {
  9956. auto handle = cli.open_stream("GET", "/echo-headers", {},
  9957. {{"User-Agent", "MyAgent/1.2"}});
  9958. ASSERT_TRUE(handle.is_valid());
  9959. auto body = read_all(handle);
  9960. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  9961. }
  9962. }
  9963. TEST_F(OpenStreamTest, Large) {
  9964. Client cli("127.0.0.1", 8787);
  9965. auto handle = cli.open_stream("GET", "/large");
  9966. EXPECT_EQ(10000u, read_all(handle).size());
  9967. }
  9968. TEST_F(OpenStreamTest, ConnectionError) {
  9969. Client cli("127.0.0.1", 9999);
  9970. auto handle = cli.open_stream("GET", "/hello");
  9971. EXPECT_FALSE(handle.is_valid());
  9972. }
  9973. TEST_F(OpenStreamTest, Chunked) {
  9974. Client cli("127.0.0.1", 8787);
  9975. auto handle = cli.open_stream("GET", "/chunked");
  9976. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  9977. "Transfer-Encoding") == "chunked");
  9978. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  9979. }
  9980. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  9981. Client cli("127.0.0.1", 8787);
  9982. auto handle =
  9983. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  9984. ASSERT_TRUE(handle.is_valid());
  9985. // Consume body to allow trailers to be received/parsed
  9986. auto body = read_all(handle);
  9987. // Explicitly parse trailers (ensure trailers are available for assertion)
  9988. handle.parse_trailers_if_needed();
  9989. EXPECT_EQ(std::string("123456789"), body);
  9990. // The response should include a Trailer header declaring both names
  9991. ASSERT_TRUE(handle.response);
  9992. EXPECT_TRUE(handle.response->has_header("Trailer"));
  9993. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  9994. handle.response->get_header_value("Trailer"));
  9995. // Prohibited trailer must not be present
  9996. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  9997. // Allowed trailer should be present
  9998. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  9999. EXPECT_EQ(std::string("yes"),
  10000. handle.response->get_trailer_value("X-Allowed"));
  10001. // Verify trailers are NOT present as regular headers
  10002. EXPECT_EQ(std::string(""),
  10003. handle.response->get_header_value("Content-Length"));
  10004. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10005. }
  10006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10007. TEST_F(OpenStreamTest, Gzip) {
  10008. Client cli("127.0.0.1", 8787);
  10009. auto handle = cli.open_stream("GET", "/compressible", {},
  10010. {{"Accept-Encoding", "gzip"}});
  10011. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10012. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10013. }
  10014. #endif
  10015. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10016. TEST_F(OpenStreamTest, Brotli) {
  10017. Client cli("127.0.0.1", 8787);
  10018. auto handle =
  10019. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10020. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10021. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10022. }
  10023. #endif
  10024. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10025. TEST_F(OpenStreamTest, Zstd) {
  10026. Client cli("127.0.0.1", 8787);
  10027. auto handle = cli.open_stream("GET", "/compressible", {},
  10028. {{"Accept-Encoding", "zstd"}});
  10029. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10030. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10031. }
  10032. #endif
  10033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10034. class SSLOpenStreamTest : public ::testing::Test {
  10035. protected:
  10036. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10037. void SetUp() override {
  10038. svr_.Get("/hello", [](const Request &, Response &res) {
  10039. res.set_content("Hello SSL World!", "text/plain");
  10040. });
  10041. svr_.Get("/chunked", [](const Request &, Response &res) {
  10042. res.set_chunked_content_provider("text/plain",
  10043. [](size_t offset, DataSink &sink) {
  10044. if (offset < 15) {
  10045. sink.write("chunk", 5);
  10046. return true;
  10047. }
  10048. sink.done();
  10049. return true;
  10050. });
  10051. });
  10052. svr_.Post("/echo", [](const Request &req, Response &res) {
  10053. res.set_content(req.body, req.get_header_value("Content-Type"));
  10054. });
  10055. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10056. std::string body = req.body;
  10057. res.set_chunked_content_provider(
  10058. "text/plain", [body](size_t offset, DataSink &sink) {
  10059. if (offset < body.size()) {
  10060. sink.write(body.data() + offset, body.size() - offset);
  10061. }
  10062. sink.done();
  10063. return true;
  10064. });
  10065. });
  10066. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10067. svr_.wait_until_ready();
  10068. }
  10069. void TearDown() override {
  10070. svr_.stop();
  10071. if (thread_.joinable()) thread_.join();
  10072. }
  10073. SSLServer svr_;
  10074. std::thread thread_;
  10075. };
  10076. TEST_F(SSLOpenStreamTest, Basic) {
  10077. SSLClient cli("127.0.0.1", 8788);
  10078. cli.enable_server_certificate_verification(false);
  10079. auto handle = cli.open_stream("GET", "/hello");
  10080. ASSERT_TRUE(handle.is_valid());
  10081. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10082. }
  10083. TEST_F(SSLOpenStreamTest, Chunked) {
  10084. SSLClient cli("127.0.0.1", 8788);
  10085. cli.enable_server_certificate_verification(false);
  10086. auto handle = cli.open_stream("GET", "/chunked");
  10087. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10088. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10089. "Transfer-Encoding") == "chunked");
  10090. auto body = read_all(handle);
  10091. EXPECT_EQ("chunkchunkchunk", body);
  10092. }
  10093. TEST_F(SSLOpenStreamTest, Post) {
  10094. SSLClient cli("127.0.0.1", 8788);
  10095. cli.enable_server_certificate_verification(false);
  10096. auto handle =
  10097. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10098. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10099. EXPECT_EQ(200, handle.response->status);
  10100. auto body = read_all(handle);
  10101. EXPECT_EQ("Hello SSL POST", body);
  10102. }
  10103. TEST_F(SSLOpenStreamTest, PostChunked) {
  10104. SSLClient cli("127.0.0.1", 8788);
  10105. cli.enable_server_certificate_verification(false);
  10106. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10107. "Chunked SSL Data", "text/plain");
  10108. ASSERT_TRUE(handle.is_valid());
  10109. EXPECT_EQ(200, handle.response->status);
  10110. auto body = read_all(handle);
  10111. EXPECT_EQ("Chunked SSL Data", body);
  10112. }
  10113. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10114. //==============================================================================
  10115. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10116. // results for various scenarios.
  10117. //==============================================================================
  10118. TEST(ParityTest, GetVsOpenStream) {
  10119. Server svr;
  10120. const std::string path = "/parity";
  10121. const std::string content = "Parity test content: hello world";
  10122. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10123. res.set_content(content, "text/plain");
  10124. });
  10125. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. });
  10131. svr.wait_until_ready();
  10132. Client cli(HOST, PORT);
  10133. // Non-stream path
  10134. auto r1 = cli.Get(path);
  10135. ASSERT_TRUE(r1);
  10136. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10137. // Stream path
  10138. auto h = cli.open_stream("GET", path);
  10139. ASSERT_TRUE(h.is_valid());
  10140. EXPECT_EQ(r1->body, read_all(h));
  10141. }
  10142. // Helper to compress data with provided compressor type T
  10143. template <typename Compressor>
  10144. static std::string compress_payload_for_parity(const std::string &in) {
  10145. std::string out;
  10146. Compressor compressor;
  10147. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10148. [&](const char *data, size_t n) {
  10149. out.append(data, n);
  10150. return true;
  10151. });
  10152. EXPECT_TRUE(ok);
  10153. return out;
  10154. }
  10155. // Helper function for compression parity tests
  10156. template <typename Compressor>
  10157. static void test_compression_parity(const std::string &original,
  10158. const std::string &path,
  10159. const std::string &encoding) {
  10160. const std::string compressed =
  10161. compress_payload_for_parity<Compressor>(original);
  10162. Server svr;
  10163. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10164. res.set_content(compressed, "application/octet-stream");
  10165. res.set_header("Content-Encoding", encoding);
  10166. });
  10167. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10168. auto se = detail::scope_exit([&] {
  10169. svr.stop();
  10170. t.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. Client cli("localhost", 1234);
  10175. // Non-streaming
  10176. {
  10177. auto res = cli.Get(path);
  10178. ASSERT_TRUE(res);
  10179. EXPECT_EQ(StatusCode::OK_200, res->status);
  10180. EXPECT_EQ(original, res->body);
  10181. }
  10182. // Streaming
  10183. {
  10184. auto h = cli.open_stream("GET", path);
  10185. ASSERT_TRUE(h.is_valid());
  10186. EXPECT_EQ(original, read_all(h));
  10187. }
  10188. }
  10189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10190. TEST(ParityTest, Gzip) {
  10191. test_compression_parity<detail::gzip_compressor>(
  10192. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10193. }
  10194. #endif
  10195. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10196. TEST(ParityTest, Brotli) {
  10197. test_compression_parity<detail::brotli_compressor>(
  10198. "Hello, brotli parity test payload", "/parity-br", "br");
  10199. }
  10200. #endif
  10201. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10202. TEST(ParityTest, Zstd) {
  10203. test_compression_parity<detail::zstd_compressor>(
  10204. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10205. }
  10206. #endif
  10207. //==============================================================================
  10208. // New Stream API Tests
  10209. //==============================================================================
  10210. inline std::string read_body(httplib::stream::Result &result) {
  10211. std::string body;
  10212. while (result.next()) {
  10213. body.append(result.data(), result.size());
  10214. }
  10215. return body;
  10216. }
  10217. TEST(ClientConnectionTest, Basic) {
  10218. httplib::ClientConnection conn;
  10219. EXPECT_FALSE(conn.is_open());
  10220. conn.sock = 1;
  10221. EXPECT_TRUE(conn.is_open());
  10222. httplib::ClientConnection conn2(std::move(conn));
  10223. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10224. conn2.sock = INVALID_SOCKET;
  10225. }
  10226. // Unified test server for all stream::* tests
  10227. class StreamApiTest : public ::testing::Test {
  10228. protected:
  10229. void SetUp() override {
  10230. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10231. res.set_content("Hello World!", "text/plain");
  10232. });
  10233. svr_.Get("/echo-params",
  10234. [](const httplib::Request &req, httplib::Response &res) {
  10235. std::string r;
  10236. for (const auto &p : req.params) {
  10237. if (!r.empty()) r += "&";
  10238. r += p.first + "=" + p.second;
  10239. }
  10240. res.set_content(r, "text/plain");
  10241. });
  10242. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10243. res.set_content(req.body, req.get_header_value("Content-Type"));
  10244. });
  10245. svr_.Post("/echo-headers",
  10246. [](const httplib::Request &req, httplib::Response &res) {
  10247. std::string r;
  10248. for (const auto &h : req.headers)
  10249. r += h.first + ": " + h.second + "\n";
  10250. res.set_content(r, "text/plain");
  10251. });
  10252. svr_.Post("/echo-params",
  10253. [](const httplib::Request &req, httplib::Response &res) {
  10254. std::string r = "params:";
  10255. for (const auto &p : req.params)
  10256. r += p.first + "=" + p.second + ";";
  10257. res.set_content(r + " body:" + req.body, "text/plain");
  10258. });
  10259. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10260. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10261. });
  10262. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10263. res.set_content("PUT:" + req.body, "text/plain");
  10264. });
  10265. svr_.Patch("/echo",
  10266. [](const httplib::Request &req, httplib::Response &res) {
  10267. res.set_content("PATCH:" + req.body, "text/plain");
  10268. });
  10269. svr_.Delete(
  10270. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10271. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10272. "text/plain");
  10273. });
  10274. svr_.Get("/head-test",
  10275. [](const httplib::Request &, httplib::Response &res) {
  10276. res.set_content("body for HEAD", "text/plain");
  10277. });
  10278. svr_.Options("/options",
  10279. [](const httplib::Request &, httplib::Response &res) {
  10280. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10281. });
  10282. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10283. svr_.wait_until_ready();
  10284. }
  10285. void TearDown() override {
  10286. svr_.stop();
  10287. if (thread_.joinable()) thread_.join();
  10288. }
  10289. httplib::Server svr_;
  10290. std::thread thread_;
  10291. };
  10292. // stream::Get tests
  10293. TEST_F(StreamApiTest, GetBasic) {
  10294. httplib::Client cli("localhost", 8790);
  10295. auto result = httplib::stream::Get(cli, "/hello");
  10296. ASSERT_TRUE(result.is_valid());
  10297. EXPECT_EQ(200, result.status());
  10298. EXPECT_EQ("Hello World!", read_body(result));
  10299. }
  10300. TEST_F(StreamApiTest, GetWithParams) {
  10301. httplib::Client cli("localhost", 8790);
  10302. httplib::Params params{{"foo", "bar"}};
  10303. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10304. ASSERT_TRUE(result.is_valid());
  10305. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10306. }
  10307. TEST_F(StreamApiTest, GetConnectionError) {
  10308. httplib::Client cli("localhost", 9999);
  10309. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10310. }
  10311. TEST_F(StreamApiTest, Get404) {
  10312. httplib::Client cli("localhost", 8790);
  10313. auto result = httplib::stream::Get(cli, "/nonexistent");
  10314. EXPECT_TRUE(result.is_valid());
  10315. EXPECT_EQ(404, result.status());
  10316. }
  10317. // stream::Post tests
  10318. TEST_F(StreamApiTest, PostBasic) {
  10319. httplib::Client cli("localhost", 8790);
  10320. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10321. "application/json");
  10322. ASSERT_TRUE(result.is_valid());
  10323. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10324. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10325. }
  10326. TEST_F(StreamApiTest, PostWithHeaders) {
  10327. httplib::Client cli("localhost", 8790);
  10328. httplib::Headers headers{{"X-Custom", "value"}};
  10329. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10330. "text/plain");
  10331. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10332. }
  10333. TEST_F(StreamApiTest, PostWithParams) {
  10334. httplib::Client cli("localhost", 8790);
  10335. httplib::Params params{{"k", "v"}};
  10336. auto result =
  10337. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10338. auto body = read_body(result);
  10339. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10340. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10341. }
  10342. TEST_F(StreamApiTest, PostLarge) {
  10343. httplib::Client cli("localhost", 8790);
  10344. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10345. size_t total = 0;
  10346. while (result.next()) {
  10347. total += result.size();
  10348. }
  10349. EXPECT_EQ(100u * 1024u, total);
  10350. }
  10351. // stream::Put/Patch tests
  10352. TEST_F(StreamApiTest, PutAndPatch) {
  10353. httplib::Client cli("localhost", 8790);
  10354. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10355. EXPECT_EQ("PUT:test", read_body(put));
  10356. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10357. EXPECT_EQ("PATCH:test", read_body(patch));
  10358. }
  10359. // stream::Delete tests
  10360. TEST_F(StreamApiTest, Delete) {
  10361. httplib::Client cli("localhost", 8790);
  10362. auto del1 = httplib::stream::Delete(cli, "/resource");
  10363. EXPECT_EQ("Deleted", read_body(del1));
  10364. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10365. EXPECT_EQ("Deleted:data", read_body(del2));
  10366. }
  10367. // stream::Head/Options tests
  10368. TEST_F(StreamApiTest, HeadAndOptions) {
  10369. httplib::Client cli("localhost", 8790);
  10370. auto head = httplib::stream::Head(cli, "/head-test");
  10371. EXPECT_TRUE(head.is_valid());
  10372. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10373. auto opts = httplib::stream::Options(cli, "/options");
  10374. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10375. }
  10376. // SSL stream::* tests
  10377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10378. class SSLStreamApiTest : public ::testing::Test {
  10379. protected:
  10380. void SetUp() override {
  10381. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10382. res.set_content("Hello SSL!", "text/plain");
  10383. });
  10384. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10385. res.set_content(req.body, "text/plain");
  10386. });
  10387. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10388. svr_.wait_until_ready();
  10389. }
  10390. void TearDown() override {
  10391. svr_.stop();
  10392. if (thread_.joinable()) thread_.join();
  10393. }
  10394. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10395. std::thread thread_;
  10396. };
  10397. TEST_F(SSLStreamApiTest, GetAndPost) {
  10398. httplib::SSLClient cli("127.0.0.1", 8803);
  10399. cli.enable_server_certificate_verification(false);
  10400. auto get = httplib::stream::Get(cli, "/hello");
  10401. EXPECT_EQ("Hello SSL!", read_body(get));
  10402. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10403. EXPECT_EQ("test", read_body(post));
  10404. }
  10405. #endif
  10406. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10407. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10408. // BodyReader
  10409. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10410. // Test that read timeout during streaming is detected
  10411. // Use a large content-length response where server delays mid-stream
  10412. Server svr;
  10413. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10414. // Send a large response with delay in the middle
  10415. res.set_content_provider(
  10416. 1000, // content_length
  10417. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10418. if (offset < 100) {
  10419. // Send first 100 bytes immediately
  10420. std::string data(100, 'A');
  10421. sink.write(data.c_str(), data.size());
  10422. return true;
  10423. }
  10424. // Then delay longer than client timeout
  10425. std::this_thread::sleep_for(std::chrono::seconds(3));
  10426. std::string data(900, 'B');
  10427. sink.write(data.c_str(), data.size());
  10428. return true;
  10429. });
  10430. });
  10431. auto port = 8091;
  10432. std::thread t([&]() { svr.listen("localhost", port); });
  10433. svr.wait_until_ready();
  10434. Client cli("localhost", port);
  10435. cli.set_read_timeout(1, 0); // 1 second timeout
  10436. auto handle = cli.open_stream("GET", "/slow-stream");
  10437. ASSERT_TRUE(handle.is_valid());
  10438. char buf[256];
  10439. ssize_t total = 0;
  10440. ssize_t n;
  10441. bool got_error = false;
  10442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10443. total += n;
  10444. }
  10445. if (n < 0) {
  10446. got_error = true;
  10447. // Should be timeout or read error
  10448. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10449. handle.get_read_error() == Error::Read)
  10450. << "Actual error: " << to_string(handle.get_read_error());
  10451. }
  10452. // Either we got an error, or we got less data than expected
  10453. EXPECT_TRUE(got_error || total < 1000)
  10454. << "Expected timeout but got all " << total << " bytes";
  10455. svr.stop();
  10456. t.join();
  10457. }
  10458. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10459. // Test connection closed detection via BodyReader
  10460. Server svr;
  10461. std::atomic<bool> close_now{false};
  10462. svr.Get("/will-close", [&](const Request &, Response &res) {
  10463. res.set_content_provider(
  10464. 10000, // Large content_length that we won't fully send
  10465. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10466. if (offset < 100) {
  10467. std::string data(100, 'X');
  10468. sink.write(data.c_str(), data.size());
  10469. return true;
  10470. }
  10471. // Wait for signal then abort
  10472. while (!close_now) {
  10473. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10474. }
  10475. return false; // Abort - server will close connection
  10476. });
  10477. });
  10478. auto port = 8092;
  10479. std::thread t([&]() { svr.listen("localhost", port); });
  10480. svr.wait_until_ready();
  10481. Client cli("localhost", port);
  10482. auto handle = cli.open_stream("GET", "/will-close");
  10483. ASSERT_TRUE(handle.is_valid());
  10484. char buf[256];
  10485. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10486. EXPECT_GT(n, 0) << "First read should succeed";
  10487. // Signal server to close
  10488. close_now = true;
  10489. // Keep reading until error or EOF
  10490. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10491. // Keep reading
  10492. }
  10493. // Should get an error since content_length wasn't satisfied
  10494. if (n < 0) {
  10495. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10496. handle.get_read_error() == Error::Read)
  10497. << "Actual error: " << to_string(handle.get_read_error());
  10498. }
  10499. svr.stop();
  10500. t.join();
  10501. }
  10502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10503. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10504. // Test that read timeout during SSL streaming is detected
  10505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10506. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10507. res.set_content_provider(
  10508. 1000, "text/plain",
  10509. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10510. if (offset < 100) {
  10511. std::string data(100, 'A');
  10512. sink.write(data.c_str(), data.size());
  10513. return true;
  10514. }
  10515. std::this_thread::sleep_for(std::chrono::seconds(3));
  10516. std::string data(900, 'B');
  10517. sink.write(data.c_str(), data.size());
  10518. return true;
  10519. });
  10520. });
  10521. auto port = 8093;
  10522. std::thread t([&]() { svr.listen("localhost", port); });
  10523. svr.wait_until_ready();
  10524. SSLClient cli("localhost", port);
  10525. cli.enable_server_certificate_verification(false);
  10526. cli.set_read_timeout(1, 0); // 1 second timeout
  10527. auto handle = cli.open_stream("GET", "/slow-stream");
  10528. ASSERT_TRUE(handle.is_valid());
  10529. char buf[256];
  10530. ssize_t total = 0;
  10531. ssize_t n;
  10532. bool got_error = false;
  10533. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10534. total += n;
  10535. }
  10536. if (n < 0) {
  10537. got_error = true;
  10538. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10539. handle.get_read_error() == Error::Read)
  10540. << "Actual error: " << to_string(handle.get_read_error());
  10541. }
  10542. EXPECT_TRUE(got_error || total < 1000)
  10543. << "Expected timeout but got all " << total << " bytes";
  10544. svr.stop();
  10545. t.join();
  10546. }
  10547. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10548. // Test SSL connection closed detection
  10549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10550. std::atomic<bool> close_now{false};
  10551. svr.Get("/will-close", [&](const Request &, Response &res) {
  10552. res.set_content_provider(
  10553. 10000, "text/plain",
  10554. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10555. if (offset < 100) {
  10556. std::string data(100, 'X');
  10557. sink.write(data.c_str(), data.size());
  10558. return true;
  10559. }
  10560. while (!close_now) {
  10561. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10562. }
  10563. return false;
  10564. });
  10565. });
  10566. auto port = 8094;
  10567. std::thread t([&]() { svr.listen("localhost", port); });
  10568. svr.wait_until_ready();
  10569. SSLClient cli("localhost", port);
  10570. cli.enable_server_certificate_verification(false);
  10571. auto handle = cli.open_stream("GET", "/will-close");
  10572. ASSERT_TRUE(handle.is_valid());
  10573. char buf[256];
  10574. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10575. EXPECT_GT(n, 0);
  10576. // Signal server to close
  10577. close_now = true;
  10578. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10579. // Keep reading
  10580. }
  10581. if (n < 0) {
  10582. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10583. handle.get_read_error() == Error::Read)
  10584. << "Actual error: " << to_string(handle.get_read_error());
  10585. }
  10586. svr.stop();
  10587. t.join();
  10588. }
  10589. #endif