test.cc 358 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681
  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-chunked2",
  2630. [&](const Request & /*req*/, Response &res) {
  2631. auto i = new int(0);
  2632. res.set_chunked_content_provider(
  2633. "text/plain",
  2634. [i](size_t /*offset*/, DataSink &sink) {
  2635. switch (*i) {
  2636. case 0: sink.os << "123"; break;
  2637. case 1: sink.os << "456"; break;
  2638. case 2: sink.os << "789"; break;
  2639. case 3: sink.done(); break;
  2640. }
  2641. (*i)++;
  2642. return true;
  2643. },
  2644. [i](bool success) {
  2645. EXPECT_TRUE(success);
  2646. delete i;
  2647. });
  2648. })
  2649. .Get("/streamed-chunked-with-trailer",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. auto i = new int(0);
  2652. res.set_header("Trailer", "Dummy1, Dummy2");
  2653. res.set_chunked_content_provider(
  2654. "text/plain",
  2655. [i](size_t /*offset*/, DataSink &sink) {
  2656. switch (*i) {
  2657. case 0: sink.os << "123"; break;
  2658. case 1: sink.os << "456"; break;
  2659. case 2: sink.os << "789"; break;
  2660. case 3: {
  2661. sink.done_with_trailer(
  2662. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2663. } break;
  2664. }
  2665. (*i)++;
  2666. return true;
  2667. },
  2668. [i](bool success) {
  2669. EXPECT_TRUE(success);
  2670. delete i;
  2671. });
  2672. })
  2673. .Get("/streamed",
  2674. [&](const Request & /*req*/, Response &res) {
  2675. res.set_content_provider(
  2676. 6, "text/plain",
  2677. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2678. sink.os << (offset < 3 ? "a" : "b");
  2679. return true;
  2680. });
  2681. })
  2682. .Get("/streamed-with-range",
  2683. [&](const Request &req, Response &res) {
  2684. auto data = new std::string("abcdefg");
  2685. res.set_content_provider(
  2686. data->size(), "text/plain",
  2687. [data](size_t offset, size_t length, DataSink &sink) {
  2688. size_t DATA_CHUNK_SIZE = 4;
  2689. const auto &d = *data;
  2690. auto out_len =
  2691. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2692. auto ret =
  2693. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2694. EXPECT_TRUE(ret);
  2695. return true;
  2696. },
  2697. [data, &req](bool success) {
  2698. EXPECT_EQ(success, !req.has_param("error"));
  2699. delete data;
  2700. });
  2701. })
  2702. .Get("/streamed-cancel",
  2703. [&](const Request & /*req*/, Response &res) {
  2704. res.set_content_provider(
  2705. size_t(-1), "text/plain",
  2706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2707. sink.os << "data_chunk";
  2708. return true;
  2709. });
  2710. })
  2711. .Get("/regex-with-delimiter",
  2712. [&](const Request &req, Response & /*res*/) {
  2713. ASSERT_TRUE(req.has_param("key"));
  2714. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2715. })
  2716. .Get("/with-range",
  2717. [&](const Request & /*req*/, Response &res) {
  2718. res.set_content("abcdefg", "text/plain");
  2719. })
  2720. .Get("/test-start-time",
  2721. [&](const Request &req, Response & /*res*/) {
  2722. EXPECT_NE(req.start_time_,
  2723. std::chrono::steady_clock::time_point::min());
  2724. })
  2725. .Get("/with-range-customized-response",
  2726. [&](const Request & /*req*/, Response &res) {
  2727. res.status = StatusCode::BadRequest_400;
  2728. res.set_content(JSON_DATA, "application/json");
  2729. })
  2730. .Post("/chunked",
  2731. [&](const Request &req, Response & /*res*/) {
  2732. EXPECT_EQ(req.body, "dechunked post body");
  2733. })
  2734. .Post("/large-chunked",
  2735. [&](const Request &req, Response & /*res*/) {
  2736. std::string expected(6 * 30 * 1024u, 'a');
  2737. EXPECT_EQ(req.body, expected);
  2738. })
  2739. .Post("/multipart",
  2740. [&](const Request &req, Response & /*res*/) {
  2741. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2742. req.form.get_field_count("text2") +
  2743. req.form.get_field_count("file3") +
  2744. req.form.get_field_count("file4"));
  2745. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2746. req.form.get_file_count("file2"));
  2747. ASSERT_TRUE(!req.form.has_file("???"));
  2748. ASSERT_TRUE(!req.form.has_field("???"));
  2749. ASSERT_TRUE(req.body.empty());
  2750. {
  2751. const auto &text = req.form.get_field("text1");
  2752. EXPECT_EQ("text default", text);
  2753. }
  2754. {
  2755. const auto &text = req.form.get_field("text2");
  2756. EXPECT_EQ("aωb", text);
  2757. }
  2758. {
  2759. const auto &file = req.form.get_file("file1");
  2760. EXPECT_EQ("hello.txt", file.filename);
  2761. EXPECT_EQ("text/plain", file.content_type);
  2762. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2763. }
  2764. {
  2765. const auto &file = req.form.get_file("file2");
  2766. EXPECT_EQ("world.json", file.filename);
  2767. EXPECT_EQ("application/json", file.content_type);
  2768. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2769. }
  2770. {
  2771. const auto &text = req.form.get_field("file3");
  2772. EXPECT_EQ(0u, text.size());
  2773. }
  2774. {
  2775. const auto &text = req.form.get_field("file4");
  2776. EXPECT_EQ(0u, text.size());
  2777. }
  2778. })
  2779. .Post("/multipart/multi_file_values",
  2780. [&](const Request &req, Response & /*res*/) {
  2781. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2782. req.form.get_field_count("multi_text1"));
  2783. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2784. ASSERT_TRUE(!req.form.has_file("???"));
  2785. ASSERT_TRUE(!req.form.has_field("???"));
  2786. ASSERT_TRUE(req.body.empty());
  2787. {
  2788. const auto &text = req.form.get_field("text");
  2789. EXPECT_EQ("default text", text);
  2790. }
  2791. {
  2792. const auto &text1_values = req.form.get_fields("multi_text1");
  2793. EXPECT_EQ(2u, text1_values.size());
  2794. EXPECT_EQ("aaaaa", text1_values[0]);
  2795. EXPECT_EQ("bbbbb", text1_values[1]);
  2796. }
  2797. {
  2798. const auto &file1_values = req.form.get_files("multi_file1");
  2799. EXPECT_EQ(2u, file1_values.size());
  2800. auto file1 = file1_values[0];
  2801. EXPECT_EQ(file1.filename, "hello.txt");
  2802. EXPECT_EQ(file1.content_type, "text/plain");
  2803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2804. auto file2 = file1_values[1];
  2805. EXPECT_EQ(file2.filename, "world.json");
  2806. EXPECT_EQ(file2.content_type, "application/json");
  2807. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2808. }
  2809. })
  2810. .Post("/empty",
  2811. [&](const Request &req, Response &res) {
  2812. EXPECT_EQ(req.body, "");
  2813. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2814. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2815. res.set_content("empty", "text/plain");
  2816. })
  2817. .Post("/empty-no-content-type",
  2818. [&](const Request &req, Response &res) {
  2819. EXPECT_EQ(req.body, "");
  2820. EXPECT_FALSE(req.has_header("Content-Type"));
  2821. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2822. res.set_content("empty-no-content-type", "text/plain");
  2823. })
  2824. .Post("/path-only",
  2825. [&](const Request &req, Response &res) {
  2826. EXPECT_EQ(req.body, "");
  2827. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2828. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2829. res.set_content("path-only", "text/plain");
  2830. })
  2831. .Post("/path-headers-only",
  2832. [&](const Request &req, Response &res) {
  2833. EXPECT_EQ(req.body, "");
  2834. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2835. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2836. EXPECT_EQ("world", req.get_header_value("hello"));
  2837. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2838. res.set_content("path-headers-only", "text/plain");
  2839. })
  2840. .Post("/post-large",
  2841. [&](const Request &req, Response &res) {
  2842. EXPECT_EQ(req.body, LARGE_DATA);
  2843. res.set_content(req.body, "text/plain");
  2844. })
  2845. .Post("/post-loopback",
  2846. [&](const Request &, Response &res,
  2847. ContentReader const &content_reader) {
  2848. std::string body;
  2849. content_reader([&](const char *data, size_t data_length) {
  2850. body.append(data, data_length);
  2851. return true;
  2852. });
  2853. res.set_content(body, "text/plain");
  2854. })
  2855. .Put("/put-loopback",
  2856. [&](const Request &, Response &res,
  2857. ContentReader const &content_reader) {
  2858. std::string body;
  2859. content_reader([&](const char *data, size_t data_length) {
  2860. body.append(data, data_length);
  2861. return true;
  2862. });
  2863. res.set_content(body, "text/plain");
  2864. })
  2865. .Patch("/patch-loopback",
  2866. [&](const Request &, Response &res,
  2867. ContentReader const &content_reader) {
  2868. std::string body;
  2869. content_reader([&](const char *data, size_t data_length) {
  2870. body.append(data, data_length);
  2871. return true;
  2872. });
  2873. res.set_content(body, "text/plain");
  2874. })
  2875. .Put("/empty-no-content-type",
  2876. [&](const Request &req, Response &res) {
  2877. EXPECT_EQ(req.body, "");
  2878. EXPECT_FALSE(req.has_header("Content-Type"));
  2879. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2880. res.set_content("empty-no-content-type", "text/plain");
  2881. })
  2882. .Put("/put",
  2883. [&](const Request &req, Response &res) {
  2884. EXPECT_EQ(req.body, "PUT");
  2885. res.set_content(req.body, "text/plain");
  2886. })
  2887. .Put("/put-large",
  2888. [&](const Request &req, Response &res) {
  2889. EXPECT_EQ(req.body, LARGE_DATA);
  2890. res.set_content(req.body, "text/plain");
  2891. })
  2892. .Patch("/patch",
  2893. [&](const Request &req, Response &res) {
  2894. EXPECT_EQ(req.body, "PATCH");
  2895. res.set_content(req.body, "text/plain");
  2896. })
  2897. .Delete("/delete",
  2898. [&](const Request & /*req*/, Response &res) {
  2899. res.set_content("DELETE", "text/plain");
  2900. })
  2901. .Delete("/delete-body",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "content");
  2904. res.set_content(req.body, "text/plain");
  2905. })
  2906. .Options(R"(\*)",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2909. })
  2910. .Get("/request-target",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2913. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2914. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2915. })
  2916. .Get("/long-query-value",
  2917. [&](const Request &req, Response & /*res*/) {
  2918. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2919. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2920. })
  2921. .Get("/too-long-query-value",
  2922. [&](const Request &req, Response & /*res*/) {
  2923. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2924. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2925. })
  2926. .Get("/array-param",
  2927. [&](const Request &req, Response & /*res*/) {
  2928. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2929. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2930. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2931. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2932. })
  2933. .Post("/validate-no-multiple-headers",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2936. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2937. })
  2938. .Post("/content_receiver",
  2939. [&](const Request &req, Response &res,
  2940. const ContentReader &content_reader) {
  2941. if (req.is_multipart_form_data()) {
  2942. std::vector<FormData> items;
  2943. content_reader(
  2944. [&](const FormData &file) {
  2945. items.push_back(file);
  2946. return true;
  2947. },
  2948. [&](const char *data, size_t data_length) {
  2949. items.back().content.append(data, data_length);
  2950. return true;
  2951. });
  2952. EXPECT_EQ(5u, items.size());
  2953. {
  2954. const auto &file = get_file_value(items, "text1");
  2955. EXPECT_TRUE(file.filename.empty());
  2956. EXPECT_EQ("text default", file.content);
  2957. }
  2958. {
  2959. const auto &file = get_file_value(items, "text2");
  2960. EXPECT_TRUE(file.filename.empty());
  2961. EXPECT_EQ("aωb", file.content);
  2962. }
  2963. {
  2964. const auto &file = get_file_value(items, "file1");
  2965. EXPECT_EQ("hello.txt", file.filename);
  2966. EXPECT_EQ("text/plain", file.content_type);
  2967. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2968. }
  2969. {
  2970. const auto &file = get_file_value(items, "file2");
  2971. EXPECT_EQ("world.json", file.filename);
  2972. EXPECT_EQ("application/json", file.content_type);
  2973. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2974. }
  2975. {
  2976. const auto &file = get_file_value(items, "file3");
  2977. EXPECT_TRUE(file.filename.empty());
  2978. EXPECT_EQ("application/octet-stream", file.content_type);
  2979. EXPECT_EQ(0u, file.content.size());
  2980. }
  2981. } else {
  2982. std::string body;
  2983. content_reader([&](const char *data, size_t data_length) {
  2984. EXPECT_EQ(7U, data_length);
  2985. body.append(data, data_length);
  2986. return true;
  2987. });
  2988. EXPECT_EQ(body, "content");
  2989. res.set_content(body, "text/plain");
  2990. }
  2991. })
  2992. .Put("/content_receiver",
  2993. [&](const Request & /*req*/, Response &res,
  2994. const ContentReader &content_reader) {
  2995. std::string body;
  2996. content_reader([&](const char *data, size_t data_length) {
  2997. body.append(data, data_length);
  2998. return true;
  2999. });
  3000. EXPECT_EQ(body, "content");
  3001. res.set_content(body, "text/plain");
  3002. })
  3003. .Patch("/content_receiver",
  3004. [&](const Request & /*req*/, Response &res,
  3005. const ContentReader &content_reader) {
  3006. std::string body;
  3007. content_reader([&](const char *data, size_t data_length) {
  3008. body.append(data, data_length);
  3009. return true;
  3010. });
  3011. EXPECT_EQ(body, "content");
  3012. res.set_content(body, "text/plain");
  3013. })
  3014. .Post("/query-string-and-body",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. ASSERT_TRUE(req.has_param("key"));
  3017. EXPECT_EQ(req.get_param_value("key"), "value");
  3018. EXPECT_EQ(req.body, "content");
  3019. })
  3020. .Get("/last-request",
  3021. [&](const Request &req, Response & /*res*/) {
  3022. EXPECT_EQ("close", req.get_header_value("Connection"));
  3023. })
  3024. .Get(R"(/redirect/(\d+))",
  3025. [&](const Request &req, Response &res) {
  3026. auto num = std::stoi(req.matches[1]) + 1;
  3027. std::string url = "/redirect/" + std::to_string(num);
  3028. res.set_redirect(url);
  3029. })
  3030. .Post("/binary",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(4U, req.body.size());
  3033. EXPECT_EQ("application/octet-stream",
  3034. req.get_header_value("Content-Type"));
  3035. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3036. res.set_content(req.body, "application/octet-stream");
  3037. })
  3038. .Put("/binary",
  3039. [&](const Request &req, Response &res) {
  3040. EXPECT_EQ(4U, req.body.size());
  3041. EXPECT_EQ("application/octet-stream",
  3042. req.get_header_value("Content-Type"));
  3043. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3044. res.set_content(req.body, "application/octet-stream");
  3045. })
  3046. .Patch("/binary",
  3047. [&](const Request &req, Response &res) {
  3048. EXPECT_EQ(4U, req.body.size());
  3049. EXPECT_EQ("application/octet-stream",
  3050. req.get_header_value("Content-Type"));
  3051. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3052. res.set_content(req.body, "application/octet-stream");
  3053. })
  3054. .Delete("/binary",
  3055. [&](const Request &req, Response &res) {
  3056. EXPECT_EQ(4U, req.body.size());
  3057. EXPECT_EQ("application/octet-stream",
  3058. req.get_header_value("Content-Type"));
  3059. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3060. res.set_content(req.body, "application/octet-stream");
  3061. })
  3062. .Get("/issue1772",
  3063. [&](const Request & /*req*/, Response &res) {
  3064. res.status = 401;
  3065. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3066. })
  3067. .Delete("/issue609",
  3068. [](const httplib::Request &, httplib::Response &res,
  3069. const httplib::ContentReader &) {
  3070. res.set_content("ok", "text/plain");
  3071. })
  3072. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3073. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3074. .Get("/compress",
  3075. [&](const Request & /*req*/, Response &res) {
  3076. res.set_content(
  3077. "12345678901234567890123456789012345678901234567890123456789"
  3078. "01234567890123456789012345678901234567890",
  3079. "text/plain");
  3080. })
  3081. .Get("/nocompress",
  3082. [&](const Request & /*req*/, Response &res) {
  3083. res.set_content(
  3084. "12345678901234567890123456789012345678901234567890123456789"
  3085. "01234567890123456789012345678901234567890",
  3086. "application/octet-stream");
  3087. })
  3088. .Post("/compress-multipart",
  3089. [&](const Request &req, Response & /*res*/) {
  3090. EXPECT_EQ(2u, req.form.fields.size());
  3091. ASSERT_TRUE(!req.form.has_field("???"));
  3092. {
  3093. const auto &text = req.form.get_field("key1");
  3094. EXPECT_EQ("test", text);
  3095. }
  3096. {
  3097. const auto &text = req.form.get_field("key2");
  3098. EXPECT_EQ("--abcdefg123", text);
  3099. }
  3100. })
  3101. #endif
  3102. ;
  3103. persons_["john"] = "programmer";
  3104. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3105. svr_.wait_until_ready();
  3106. }
  3107. virtual void TearDown() {
  3108. svr_.stop();
  3109. if (!request_threads_.empty()) {
  3110. std::this_thread::sleep_for(std::chrono::seconds(1));
  3111. for (auto &t : request_threads_) {
  3112. t.join();
  3113. }
  3114. }
  3115. t_.join();
  3116. }
  3117. map<string, string> persons_;
  3118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3119. SSLClient cli_;
  3120. SSLServer svr_;
  3121. #else
  3122. Client cli_;
  3123. Server svr_;
  3124. #endif
  3125. thread t_;
  3126. std::vector<thread> request_threads_;
  3127. };
  3128. TEST_F(ServerTest, GetMethod200) {
  3129. auto res = cli_.Get("/hi");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ("HTTP/1.1", res->version);
  3132. EXPECT_EQ(StatusCode::OK_200, res->status);
  3133. EXPECT_EQ("OK", res->reason);
  3134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3135. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3136. EXPECT_EQ("Hello World!", res->body);
  3137. }
  3138. TEST_F(ServerTest, GetEmptyFile) {
  3139. auto res = cli_.Get("/empty_file");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3143. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3144. EXPECT_EQ("", res->body);
  3145. }
  3146. TEST_F(ServerTest, GetFileContent) {
  3147. auto res = cli_.Get("/file_content");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3151. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3152. EXPECT_EQ("test.html", res->body);
  3153. }
  3154. TEST_F(ServerTest, GetFileContentWithRange) {
  3155. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3158. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3160. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3161. EXPECT_EQ("est", res->body);
  3162. }
  3163. TEST_F(ServerTest, GetFileContentWithContentType) {
  3164. auto res = cli_.Get("/file_content_with_content_type");
  3165. ASSERT_TRUE(res);
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3168. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3169. EXPECT_EQ("file\n", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetInvalidFileContent) {
  3172. auto res = cli_.Get("/invalid_file_content");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3175. }
  3176. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3177. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ("HTTP/1.1", res->version);
  3180. EXPECT_EQ(StatusCode::OK_200, res->status);
  3181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3182. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3183. EXPECT_EQ("Hello World!", res->body);
  3184. }
  3185. TEST_F(ServerTest, GetMethod302) {
  3186. auto res = cli_.Get("/");
  3187. ASSERT_TRUE(res);
  3188. EXPECT_EQ(StatusCode::Found_302, res->status);
  3189. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3190. }
  3191. TEST_F(ServerTest, GetMethod302Redirect) {
  3192. cli_.set_follow_location(true);
  3193. auto res = cli_.Get("/");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("Hello World!", res->body);
  3197. EXPECT_EQ("/hi", res->location);
  3198. }
  3199. TEST_F(ServerTest, GetMethod404) {
  3200. auto res = cli_.Get("/invalid");
  3201. ASSERT_TRUE(res);
  3202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3203. }
  3204. TEST_F(ServerTest, HeadMethod200) {
  3205. auto res = cli_.Head("/hi");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(StatusCode::OK_200, res->status);
  3208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3209. EXPECT_TRUE(res->body.empty());
  3210. }
  3211. TEST_F(ServerTest, HeadMethod200Static) {
  3212. auto res = cli_.Head("/mount/dir/index.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::OK_200, res->status);
  3215. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3216. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3217. EXPECT_TRUE(res->body.empty());
  3218. }
  3219. TEST_F(ServerTest, HeadMethod404) {
  3220. auto res = cli_.Head("/invalid");
  3221. ASSERT_TRUE(res);
  3222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3223. EXPECT_TRUE(res->body.empty());
  3224. }
  3225. TEST_F(ServerTest, GetMethodPersonJohn) {
  3226. auto res = cli_.Get("/person/john");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ("programmer", res->body);
  3231. }
  3232. TEST_F(ServerTest, PostMethod1) {
  3233. auto res = cli_.Get("/person/john1");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. res = cli_.Post("/person", "name=john1&note=coder",
  3237. "application/x-www-form-urlencoded");
  3238. ASSERT_TRUE(res);
  3239. ASSERT_EQ(StatusCode::OK_200, res->status);
  3240. res = cli_.Get("/person/john1");
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. ASSERT_EQ("coder", res->body);
  3245. }
  3246. TEST_F(ServerTest, PostMethod2) {
  3247. auto res = cli_.Get("/person/john2");
  3248. ASSERT_TRUE(res);
  3249. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3250. Params params;
  3251. params.emplace("name", "john2");
  3252. params.emplace("note", "coder");
  3253. res = cli_.Post("/person", params);
  3254. ASSERT_TRUE(res);
  3255. ASSERT_EQ(StatusCode::OK_200, res->status);
  3256. res = cli_.Get("/person/john2");
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3260. ASSERT_EQ("coder", res->body);
  3261. }
  3262. TEST_F(ServerTest, PutMethod3) {
  3263. auto res = cli_.Get("/person/john3");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3266. Params params;
  3267. params.emplace("name", "john3");
  3268. params.emplace("note", "coder");
  3269. res = cli_.Put("/person", params);
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. res = cli_.Get("/person/john3");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3276. ASSERT_EQ("coder", res->body);
  3277. }
  3278. TEST_F(ServerTest, DeleteMethod1) {
  3279. auto res = cli_.Get("/person/john4");
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3282. Params params;
  3283. params.emplace("name", "john4");
  3284. params.emplace("note", "coder");
  3285. res = cli_.Post("/person", params);
  3286. ASSERT_TRUE(res);
  3287. ASSERT_EQ(StatusCode::OK_200, res->status);
  3288. res = cli_.Get("/person/john4");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::OK_200, res->status);
  3291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. ASSERT_EQ("coder", res->body);
  3293. Params delete_params;
  3294. delete_params.emplace("name", "john4");
  3295. res = cli_.Delete("/person", delete_params);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john4");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, DeleteMethod2) {
  3304. auto res = cli_.Get("/person/john5");
  3305. ASSERT_TRUE(res);
  3306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3307. Params params;
  3308. params.emplace("name", "john5");
  3309. params.emplace("note", "developer");
  3310. res = cli_.Post("/person", params);
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. res = cli_.Get("/person/john5");
  3314. ASSERT_TRUE(res);
  3315. ASSERT_EQ(StatusCode::OK_200, res->status);
  3316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3317. ASSERT_EQ("developer", res->body);
  3318. Params delete_params;
  3319. delete_params.emplace("name", "john5");
  3320. Headers headers;
  3321. headers.emplace("Custom-Header", "test-value");
  3322. res = cli_.Delete("/person", headers, delete_params);
  3323. ASSERT_TRUE(res);
  3324. ASSERT_EQ(StatusCode::OK_200, res->status);
  3325. ASSERT_EQ("DELETED", res->body);
  3326. res = cli_.Get("/person/john5");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3329. }
  3330. TEST_F(ServerTest, DeleteMethod3) {
  3331. auto res = cli_.Get("/person/john6");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3334. Params params;
  3335. params.emplace("name", "john6");
  3336. params.emplace("note", "tester");
  3337. res = cli_.Post("/person", params);
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. res = cli_.Get("/person/john6");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3344. ASSERT_EQ("tester", res->body);
  3345. Params delete_params;
  3346. delete_params.emplace("name", "john6");
  3347. Headers headers;
  3348. headers.emplace("Custom-Header", "test-value");
  3349. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john6");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3358. Params params;
  3359. params.emplace("json", JSON_DATA);
  3360. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3361. ASSERT_TRUE(res);
  3362. ASSERT_EQ(StatusCode::OK_200, res->status);
  3363. ASSERT_EQ(JSON_DATA, res->body);
  3364. }
  3365. TEST_F(ServerTest, PostEmptyContent) {
  3366. auto res = cli_.Post("/empty", "", "text/plain");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("empty", res->body);
  3370. }
  3371. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3372. auto res = cli_.Post("/empty-no-content-type");
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. ASSERT_EQ("empty-no-content-type", res->body);
  3376. }
  3377. TEST_F(ServerTest, PostPathOnly) {
  3378. auto res = cli_.Post("/path-only");
  3379. ASSERT_TRUE(res);
  3380. ASSERT_EQ(StatusCode::OK_200, res->status);
  3381. ASSERT_EQ("path-only", res->body);
  3382. }
  3383. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3384. auto res = cli_.Post("/path-headers-only",
  3385. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::OK_200, res->status);
  3388. ASSERT_EQ("path-headers-only", res->body);
  3389. }
  3390. TEST_F(ServerTest, PostLarge) {
  3391. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. EXPECT_EQ(LARGE_DATA, res->body);
  3395. }
  3396. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3397. auto res = cli_.Put("/empty-no-content-type");
  3398. ASSERT_TRUE(res);
  3399. ASSERT_EQ(StatusCode::OK_200, res->status);
  3400. ASSERT_EQ("empty-no-content-type", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethodDir) {
  3403. auto res = cli_.Get("/dir/");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::OK_200, res->status);
  3406. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3407. auto body = R"(<html>
  3408. <head>
  3409. </head>
  3410. <body>
  3411. <a href="/dir/test.html">Test</a>
  3412. <a href="/hi">hi</a>
  3413. </body>
  3414. </html>
  3415. )";
  3416. EXPECT_EQ(body, res->body);
  3417. }
  3418. TEST_F(ServerTest, GetMethodDirTest) {
  3419. auto res = cli_.Get("/dir/test.html");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3423. EXPECT_EQ("test.html", res->body);
  3424. }
  3425. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3426. auto res = cli_.Get("/dir/../dir/test.html");
  3427. ASSERT_TRUE(res);
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3430. EXPECT_EQ("test.html", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethodInvalidPath) {
  3433. auto res = cli_.Get("/dir/../test.html");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3436. }
  3437. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3438. auto res = cli_.Get("/../www/dir/test.html");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3441. }
  3442. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3443. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3446. }
  3447. TEST_F(ServerTest, GetMethodDirMountTest) {
  3448. auto res = cli_.Get("/mount/dir/test.html");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ("test.html", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3455. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::OK_200, res->status);
  3458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("test.html", res->body);
  3460. }
  3461. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3462. auto res = cli_.Get("/mount/dir/../test.html");
  3463. ASSERT_TRUE(res);
  3464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3465. }
  3466. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3467. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3470. }
  3471. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3472. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3475. }
  3476. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3477. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3480. }
  3481. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3482. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3485. }
  3486. TEST_F(ServerTest, PostMethod303) {
  3487. auto res = cli_.Post("/1", "body", "text/plain");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3490. EXPECT_EQ("/2", res->get_header_value("Location"));
  3491. }
  3492. TEST_F(ServerTest, PostMethod303Redirect) {
  3493. cli_.set_follow_location(true);
  3494. auto res = cli_.Post("/1", "body", "text/plain");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("redirected.", res->body);
  3498. EXPECT_EQ("/2", res->location);
  3499. }
  3500. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3501. auto res = cli_.Get("/dir/test.abcde");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3505. EXPECT_EQ("abcde", res->body);
  3506. }
  3507. TEST_F(ServerTest, StaticFileRange) {
  3508. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3509. ASSERT_TRUE(res);
  3510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3511. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3512. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3513. EXPECT_EQ(true, res->has_header("Content-Range"));
  3514. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3515. EXPECT_EQ(std::string("cd"), res->body);
  3516. }
  3517. TEST_F(ServerTest, StaticFileRanges) {
  3518. auto res =
  3519. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3520. ASSERT_TRUE(res);
  3521. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3522. EXPECT_TRUE(
  3523. res->get_header_value("Content-Type")
  3524. .find(
  3525. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3526. 0);
  3527. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3528. }
  3529. TEST_F(ServerTest, StaticFileRangeHead) {
  3530. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3533. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3534. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3535. EXPECT_EQ(true, res->has_header("Content-Range"));
  3536. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3537. }
  3538. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3539. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3544. EXPECT_EQ(true, res->has_header("Content-Range"));
  3545. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3546. res->get_header_value("Content-Range"));
  3547. EXPECT_EQ("LAST\n", res->body);
  3548. }
  3549. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3550. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3551. ASSERT_TRUE(res);
  3552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3555. EXPECT_EQ(true, res->has_header("Content-Range"));
  3556. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3557. }
  3558. TEST_F(ServerTest, StaticFileBigFile) {
  3559. auto res = cli_.Get("/dir/1MB.txt");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::OK_200, res->status);
  3562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3563. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3564. }
  3565. TEST_F(ServerTest, InvalidBaseDirMount) {
  3566. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3567. }
  3568. TEST_F(ServerTest, Binary) {
  3569. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3570. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3571. "application/octet-stream");
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. ASSERT_EQ(4U, res->body.size());
  3575. res = cli_.Put("/binary", binary.data(), binary.size(),
  3576. "application/octet-stream");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ(4U, res->body.size());
  3580. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3581. "application/octet-stream");
  3582. ASSERT_TRUE(res);
  3583. ASSERT_EQ(StatusCode::OK_200, res->status);
  3584. ASSERT_EQ(4U, res->body.size());
  3585. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3586. "application/octet-stream");
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. ASSERT_EQ(4U, res->body.size());
  3590. }
  3591. TEST_F(ServerTest, BinaryString) {
  3592. auto binary = std::string("\x00\x01\x02\x03", 4);
  3593. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::OK_200, res->status);
  3596. ASSERT_EQ(4U, res->body.size());
  3597. res = cli_.Put("/binary", binary, "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_.Patch("/binary", binary, "application/octet-stream");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ(4U, res->body.size());
  3605. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ(4U, res->body.size());
  3609. }
  3610. TEST_F(ServerTest, EmptyRequest) {
  3611. auto res = cli_.Get("");
  3612. ASSERT_TRUE(!res);
  3613. EXPECT_EQ(Error::Connection, res.error());
  3614. }
  3615. TEST_F(ServerTest, LongRequest) {
  3616. std::string request;
  3617. for (size_t i = 0; i < 545; i++) {
  3618. request += "/TooLongRequest";
  3619. }
  3620. request += "OK";
  3621. auto res = cli_.Get(request.c_str());
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3624. }
  3625. TEST_F(ServerTest, TooLongRequest) {
  3626. std::string request;
  3627. for (size_t i = 0; i < 546; i++) {
  3628. request += "/TooLongRequest";
  3629. }
  3630. request += "_NG";
  3631. auto start = std::chrono::high_resolution_clock::now();
  3632. cli_.set_keep_alive(true);
  3633. auto res = cli_.Get(request.c_str());
  3634. auto end = std::chrono::high_resolution_clock::now();
  3635. auto elapsed =
  3636. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3637. .count();
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3640. EXPECT_LE(elapsed, 100);
  3641. EXPECT_EQ("close", res->get_header_value("Connection"));
  3642. EXPECT_FALSE(cli_.is_socket_open());
  3643. }
  3644. TEST_F(ServerTest, AlmostTooLongRequest) {
  3645. // test for #2046 - URI length check shouldn't include other content on req
  3646. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3647. // leading /, space, HTTP/1.1)
  3648. std::string request =
  3649. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3650. auto res = cli_.Get(request.c_str());
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3653. }
  3654. TEST_F(ServerTest, LongHeader) {
  3655. Request req;
  3656. req.method = "GET";
  3657. req.path = "/hi";
  3658. std::string host_and_port;
  3659. host_and_port += HOST;
  3660. host_and_port += ":";
  3661. host_and_port += std::to_string(PORT);
  3662. req.headers.emplace("Host", host_and_port.c_str());
  3663. req.headers.emplace("Accept", "*/*");
  3664. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3665. req.headers.emplace(
  3666. "Header-Name",
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@");
  3696. auto res = std::make_shared<Response>();
  3697. auto error = Error::Success;
  3698. auto ret = cli_.send(req, *res, error);
  3699. ASSERT_TRUE(ret);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. TEST_F(ServerTest, LongQueryValue) {
  3703. auto start = std::chrono::high_resolution_clock::now();
  3704. cli_.set_keep_alive(true);
  3705. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3706. auto end = std::chrono::high_resolution_clock::now();
  3707. auto elapsed =
  3708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3709. .count();
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3712. EXPECT_LE(elapsed, 100);
  3713. EXPECT_EQ("close", res->get_header_value("Connection"));
  3714. EXPECT_FALSE(cli_.is_socket_open());
  3715. }
  3716. TEST_F(ServerTest, TooLongQueryValue) {
  3717. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3718. ASSERT_FALSE(res);
  3719. EXPECT_EQ(Error::Read, res.error());
  3720. }
  3721. TEST_F(ServerTest, TooLongHeader) {
  3722. Request req;
  3723. req.method = "GET";
  3724. req.path = "/hi";
  3725. std::string host_and_port;
  3726. host_and_port += HOST;
  3727. host_and_port += ":";
  3728. host_and_port += std::to_string(PORT);
  3729. req.headers.emplace("Host", host_and_port.c_str());
  3730. req.headers.emplace("Accept", "*/*");
  3731. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3732. req.headers.emplace(
  3733. "Header-Name",
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@");
  3763. auto res = std::make_shared<Response>();
  3764. auto error = Error::Success;
  3765. auto ret = cli_.send(req, *res, error);
  3766. ASSERT_TRUE(ret);
  3767. EXPECT_EQ(StatusCode::OK_200, res->status);
  3768. }
  3769. TEST_F(ServerTest, HeaderCountAtLimit) {
  3770. // Test with headers just under the 100 limit
  3771. httplib::Headers headers;
  3772. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3773. // This should keep us just under the 100 header limit
  3774. for (int i = 0; i < 95; i++) {
  3775. std::string name = "X-Test-Header-" + std::to_string(i);
  3776. std::string value = "value" + std::to_string(i);
  3777. headers.emplace(name, value);
  3778. }
  3779. // This should work fine as we're under the limit
  3780. auto res = cli_.Get("/hi", headers);
  3781. EXPECT_TRUE(res);
  3782. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3783. }
  3784. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3785. // Test with many headers to exceed the 100 limit
  3786. httplib::Headers headers;
  3787. // Add 150 headers to definitely exceed the 100 limit
  3788. for (int i = 0; i < 150; i++) {
  3789. std::string name = "X-Test-Header-" + std::to_string(i);
  3790. std::string value = "value" + std::to_string(i);
  3791. headers.emplace(name, value);
  3792. }
  3793. // This should fail due to exceeding header count limit
  3794. cli_.set_keep_alive(true);
  3795. auto res = cli_.Get("/hi", headers);
  3796. // The request should either fail or return 400 Bad Request
  3797. if (res) {
  3798. // If we get a response, it should be 400 Bad Request
  3799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3800. } else {
  3801. // Or the request should fail entirely
  3802. EXPECT_FALSE(res);
  3803. }
  3804. EXPECT_EQ("close", res->get_header_value("Connection"));
  3805. EXPECT_FALSE(cli_.is_socket_open());
  3806. }
  3807. TEST_F(ServerTest, PercentEncoding) {
  3808. auto res = cli_.Get("/e%6edwith%");
  3809. ASSERT_TRUE(res);
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. }
  3812. TEST_F(ServerTest, PercentEncodingUnicode) {
  3813. auto res = cli_.Get("/e%u006edwith%");
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::OK_200, res->status);
  3816. }
  3817. TEST_F(ServerTest, InvalidPercentEncoding) {
  3818. auto res = cli_.Get("/%endwith%");
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3823. auto res = cli_.Get("/%uendwith%");
  3824. ASSERT_TRUE(res);
  3825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3826. }
  3827. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3828. auto res = cli_.Get("/hello?aaa=bbb%");
  3829. ASSERT_TRUE(res);
  3830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3831. }
  3832. TEST_F(ServerTest, PlusSignEncoding) {
  3833. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ("a +b", res->body);
  3837. }
  3838. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3839. // This test simulates a potential DoS attack using many headers
  3840. // to verify our security fix prevents memory exhaustion
  3841. httplib::Headers attack_headers;
  3842. // Attempt to add many headers like an attacker would (200 headers to far
  3843. // exceed limit)
  3844. for (int i = 0; i < 200; i++) {
  3845. std::string name = "X-Attack-Header-" + std::to_string(i);
  3846. std::string value = "attack_payload_" + std::to_string(i);
  3847. attack_headers.emplace(name, value);
  3848. }
  3849. // Try to POST with excessive headers
  3850. cli_.set_keep_alive(true);
  3851. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3852. // Should either fail or return 400 Bad Request due to security limit
  3853. if (res) {
  3854. // If we get a response, it should be 400 Bad Request
  3855. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3856. } else {
  3857. // Request failed, which is the expected behavior for DoS protection
  3858. EXPECT_FALSE(res);
  3859. }
  3860. EXPECT_EQ("close", res->get_header_value("Connection"));
  3861. EXPECT_FALSE(cli_.is_socket_open());
  3862. }
  3863. TEST_F(ServerTest, MultipartFormData) {
  3864. UploadFormDataItems items = {
  3865. {"text1", "text default", "", ""},
  3866. {"text2", "aωb", "", ""},
  3867. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3868. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3869. {"file3", "", "", "application/octet-stream"},
  3870. {"file4", "", "", " application/json tmp-string "}};
  3871. auto res = cli_.Post("/multipart", items);
  3872. ASSERT_TRUE(res);
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. }
  3875. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3876. UploadFormDataItems items = {
  3877. {"text", "default text", "", ""},
  3878. {"multi_text1", "aaaaa", "", ""},
  3879. {"multi_text1", "bbbbb", "", ""},
  3880. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3881. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3882. "application/json"},
  3883. };
  3884. auto res = cli_.Post("/multipart/multi_file_values", items);
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::OK_200, res->status);
  3887. }
  3888. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3889. auto res = cli_.Get("/hi");
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::OK_200, res->status);
  3892. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3893. EXPECT_EQ("Hello World!", res->body);
  3894. }
  3895. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3896. Request req;
  3897. req.method = "POST";
  3898. req.path = "/chunked";
  3899. std::string host_and_port;
  3900. host_and_port += HOST;
  3901. host_and_port += ":";
  3902. host_and_port += std::to_string(PORT);
  3903. req.headers.emplace("Host", host_and_port.c_str());
  3904. req.headers.emplace("Accept", "*/*");
  3905. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3906. req.headers.emplace("Content-Type", "text/plain");
  3907. req.headers.emplace("Content-Length", "0");
  3908. req.headers.emplace(
  3909. "Transfer-Encoding",
  3910. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3911. // Client does not chunk, so make a chunked body manually.
  3912. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3913. auto res = std::make_shared<Response>();
  3914. auto error = Error::Success;
  3915. auto ret = cli_.send(req, *res, error);
  3916. ASSERT_TRUE(ret);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, GetStreamed2) {
  3920. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3923. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3924. EXPECT_EQ(true, res->has_header("Content-Range"));
  3925. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3926. EXPECT_EQ(std::string("ab"), res->body);
  3927. }
  3928. TEST_F(ServerTest, GetStreamed) {
  3929. auto res = cli_.Get("/streamed");
  3930. ASSERT_TRUE(res);
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3933. EXPECT_EQ(std::string("aaabbb"), res->body);
  3934. }
  3935. TEST_F(ServerTest, GetStreamedWithRange1) {
  3936. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3939. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3940. EXPECT_EQ(true, res->has_header("Content-Range"));
  3941. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3942. EXPECT_EQ(std::string("def"), res->body);
  3943. }
  3944. TEST_F(ServerTest, GetStreamedWithRange2) {
  3945. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3948. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3949. EXPECT_EQ(true, res->has_header("Content-Range"));
  3950. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3951. EXPECT_EQ(std::string("bcdefg"), res->body);
  3952. }
  3953. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3954. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3958. EXPECT_EQ(true, res->has_header("Content-Range"));
  3959. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3960. EXPECT_EQ(std::string("efg"), res->body);
  3961. }
  3962. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3963. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3966. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3967. EXPECT_EQ(false, res->has_header("Content-Range"));
  3968. EXPECT_EQ(0U, res->body.size());
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3971. auto res = cli_.Get("/streamed-with-range",
  3972. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3973. "92233720368547758079223372036854775807"}});
  3974. ASSERT_TRUE(res);
  3975. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3976. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3977. EXPECT_EQ(false, res->has_header("Content-Range"));
  3978. EXPECT_EQ(0U, res->body.size());
  3979. }
  3980. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3981. auto res = cli_.Get(
  3982. "/with-range",
  3983. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3984. {"Accept-Encoding", ""}});
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3987. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3988. EXPECT_EQ(true, res->has_header("Content-Range"));
  3989. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(std::string("abcdefg"), res->body);
  3991. }
  3992. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3993. auto res = cli_.Get("/with-range", {
  3994. {"Range", "bytes=0-"},
  3995. {"Accept-Encoding", ""},
  3996. });
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3999. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4000. EXPECT_EQ(true, res->has_header("Content-Range"));
  4001. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4002. EXPECT_EQ(std::string("abcdefg"), res->body);
  4003. }
  4004. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4005. auto res =
  4006. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4009. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4010. EXPECT_EQ(false, res->has_header("Content-Range"));
  4011. EXPECT_EQ(267U, res->body.size());
  4012. // Check that both range contents are present
  4013. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4014. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4015. // Check that Content-Range headers are present for both ranges
  4016. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4017. std::string::npos);
  4018. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4019. std::string::npos);
  4020. }
  4021. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4022. Ranges ranges;
  4023. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4024. ranges.emplace_back(0, -1);
  4025. }
  4026. auto res =
  4027. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4035. auto res =
  4036. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4039. EXPECT_EQ(5U, res->body.size());
  4040. // Check that overlapping ranges are coalesced into a single range
  4041. EXPECT_EQ("bcdef", res->body);
  4042. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4043. // Should be single range, not multipart
  4044. EXPECT_TRUE(res->has_header("Content-Range"));
  4045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4048. auto res =
  4049. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4050. ASSERT_TRUE(res);
  4051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4052. EXPECT_EQ(268U, res->body.size());
  4053. // Check that both range contents are present
  4054. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4055. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4056. // Check that Content-Range headers are present for both ranges
  4057. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4058. std::string::npos);
  4059. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4060. std::string::npos);
  4061. }
  4062. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4063. auto res =
  4064. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ(269U, res->body.size());
  4068. // Check that both duplicate range contents are present
  4069. size_t first_abc = res->body.find("abc\r\n");
  4070. EXPECT_TRUE(first_abc != std::string::npos);
  4071. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4072. EXPECT_TRUE(second_abc != std::string::npos);
  4073. // Check that Content-Range headers are present for both ranges
  4074. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4075. EXPECT_TRUE(first_range != std::string::npos);
  4076. size_t second_range =
  4077. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4078. EXPECT_TRUE(second_range != std::string::npos);
  4079. }
  4080. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4081. auto res = cli_.Get("/streamed-with-range?error",
  4082. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4085. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(false, res->has_header("Content-Range"));
  4087. EXPECT_EQ(0U, res->body.size());
  4088. }
  4089. TEST_F(ServerTest, GetStreamedEndless) {
  4090. uint64_t offset = 0;
  4091. auto res = cli_.Get("/streamed-cancel",
  4092. [&](const char * /*data*/, uint64_t data_length) {
  4093. if (offset < 100) {
  4094. offset += data_length;
  4095. return true;
  4096. }
  4097. return false;
  4098. });
  4099. ASSERT_TRUE(!res);
  4100. EXPECT_EQ(Error::Canceled, res.error());
  4101. }
  4102. TEST_F(ServerTest, ClientStop) {
  4103. std::atomic_size_t count{4};
  4104. std::vector<std::thread> threads;
  4105. for (auto i = count.load(); i != 0; --i) {
  4106. threads.emplace_back([&]() {
  4107. auto res = cli_.Get("/streamed-cancel",
  4108. [&](const char *, uint64_t) { return true; });
  4109. --count;
  4110. ASSERT_TRUE(!res);
  4111. EXPECT_TRUE(res.error() == Error::Canceled ||
  4112. res.error() == Error::Read || res.error() == Error::Write);
  4113. });
  4114. }
  4115. std::this_thread::sleep_for(std::chrono::seconds(2));
  4116. while (count != 0) {
  4117. cli_.stop();
  4118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4119. }
  4120. for (auto &t : threads) {
  4121. t.join();
  4122. }
  4123. }
  4124. TEST_F(ServerTest, GetWithRange1) {
  4125. auto res = cli_.Get("/with-range", {
  4126. make_range_header({{3, 5}}),
  4127. {"Accept-Encoding", ""},
  4128. });
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4131. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4132. EXPECT_EQ(true, res->has_header("Content-Range"));
  4133. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4134. EXPECT_EQ(std::string("def"), res->body);
  4135. }
  4136. TEST_F(ServerTest, GetWithRange2) {
  4137. auto res = cli_.Get("/with-range", {
  4138. make_range_header({{1, -1}}),
  4139. {"Accept-Encoding", ""},
  4140. });
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4143. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4144. EXPECT_EQ(true, res->has_header("Content-Range"));
  4145. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4146. EXPECT_EQ(std::string("bcdefg"), res->body);
  4147. }
  4148. TEST_F(ServerTest, GetWithRange3) {
  4149. auto res = cli_.Get("/with-range", {
  4150. make_range_header({{0, 0}}),
  4151. {"Accept-Encoding", ""},
  4152. });
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4155. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ(true, res->has_header("Content-Range"));
  4157. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4158. EXPECT_EQ(std::string("a"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetWithRange4) {
  4161. auto res = cli_.Get("/with-range", {
  4162. make_range_header({{-1, 2}}),
  4163. {"Accept-Encoding", ""},
  4164. });
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4167. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ(true, res->has_header("Content-Range"));
  4169. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4170. EXPECT_EQ(std::string("fg"), res->body);
  4171. }
  4172. TEST_F(ServerTest, GetWithRange5) {
  4173. auto res = cli_.Get("/with-range", {
  4174. make_range_header({{0, 5}}),
  4175. {"Accept-Encoding", ""},
  4176. });
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4179. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4180. EXPECT_EQ(true, res->has_header("Content-Range"));
  4181. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4182. EXPECT_EQ(std::string("abcdef"), res->body);
  4183. }
  4184. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4185. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4188. }
  4189. TEST_F(ServerTest, GetWithRangeMultipart) {
  4190. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(false, res->has_header("Content-Range"));
  4195. EXPECT_EQ(267U, res->body.size());
  4196. }
  4197. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4198. auto res =
  4199. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4202. }
  4203. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4204. auto res = cli_.Get("/with-range-customized-response",
  4205. {{make_range_header({{1, 2}})}});
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4208. EXPECT_EQ(true, res->has_header("Content-Length"));
  4209. EXPECT_EQ(false, res->has_header("Content-Range"));
  4210. EXPECT_EQ(JSON_DATA, res->body);
  4211. }
  4212. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4213. auto res = cli_.Get("/with-range-customized-response",
  4214. {{make_range_header({{1, 2}, {4, 5}})}});
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4217. EXPECT_EQ(true, res->has_header("Content-Length"));
  4218. EXPECT_EQ(false, res->has_header("Content-Range"));
  4219. EXPECT_EQ(JSON_DATA, res->body);
  4220. }
  4221. TEST_F(ServerTest, Issue1772) {
  4222. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4225. }
  4226. TEST_F(ServerTest, Issue609) {
  4227. auto res = cli_.Delete("/issue609");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. EXPECT_EQ(std::string("ok"), res->body);
  4231. }
  4232. TEST_F(ServerTest, GetStreamedChunked) {
  4233. auto res = cli_.Get("/streamed-chunked");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ(std::string("123456789"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetStreamedChunked2) {
  4239. auto res = cli_.Get("/streamed-chunked2");
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::OK_200, res->status);
  4242. EXPECT_EQ(std::string("123456789"), res->body);
  4243. }
  4244. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4245. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::OK_200, res->status);
  4248. EXPECT_EQ(std::string("123456789"), res->body);
  4249. EXPECT_TRUE(res->has_header("Trailer"));
  4250. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4251. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4252. // Trailers are now stored separately from headers (security fix)
  4253. EXPECT_EQ(2U, res->trailers.size());
  4254. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4255. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4256. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4257. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4258. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4259. // Verify trailers are NOT in headers (security verification)
  4260. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4261. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4262. }
  4263. TEST_F(ServerTest, LargeChunkedPost) {
  4264. Request req;
  4265. req.method = "POST";
  4266. req.path = "/large-chunked";
  4267. std::string host_and_port;
  4268. host_and_port += HOST;
  4269. host_and_port += ":";
  4270. host_and_port += std::to_string(PORT);
  4271. req.headers.emplace("Host", host_and_port.c_str());
  4272. req.headers.emplace("Accept", "*/*");
  4273. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4274. req.headers.emplace("Content-Type", "text/plain");
  4275. req.headers.emplace("Content-Length", "0");
  4276. req.headers.emplace("Transfer-Encoding", "chunked");
  4277. std::string long_string(30 * 1024u, 'a');
  4278. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4279. // Attempt to make a large enough post to exceed OS buffers, to test that
  4280. // the server handles short reads if the full chunk data isn't available.
  4281. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4282. auto res = std::make_shared<Response>();
  4283. auto error = Error::Success;
  4284. auto ret = cli_.send(req, *res, error);
  4285. ASSERT_TRUE(ret);
  4286. EXPECT_EQ(StatusCode::OK_200, res->status);
  4287. }
  4288. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4289. auto res = cli_.Get("/remote_addr");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4293. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4294. }
  4295. TEST_F(ServerTest, GetMethodLocalAddr) {
  4296. auto res = cli_.Get("/local_addr");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4300. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4301. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4302. }
  4303. TEST_F(ServerTest, HTTPResponseSplitting) {
  4304. auto res = cli_.Get("/http_response_splitting");
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::OK_200, res->status);
  4307. }
  4308. TEST_F(ServerTest, SlowRequest) {
  4309. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4310. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4311. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4312. }
  4313. #if 0
  4314. TEST_F(ServerTest, SlowPost) {
  4315. char buffer[64 * 1024];
  4316. memset(buffer, 0x42, sizeof(buffer));
  4317. auto res = cli_.Post(
  4318. "/slowpost", 64 * 1024 * 1024,
  4319. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4320. auto ret = sink.write(buffer, sizeof(buffer));
  4321. EXPECT_TRUE(ret);
  4322. return true;
  4323. },
  4324. "text/plain");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. }
  4328. TEST_F(ServerTest, SlowPostFail) {
  4329. char buffer[64 * 1024];
  4330. memset(buffer, 0x42, sizeof(buffer));
  4331. cli_.set_write_timeout(std::chrono::seconds(0));
  4332. auto res = cli_.Post(
  4333. "/slowpost", 64 * 1024 * 1024,
  4334. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4335. sink.write(buffer, sizeof(buffer));
  4336. return true;
  4337. },
  4338. "text/plain");
  4339. ASSERT_TRUE(!res);
  4340. EXPECT_EQ(Error::Write, res.error());
  4341. }
  4342. #endif
  4343. TEST_F(ServerTest, Put) {
  4344. auto res = cli_.Put("/put", "PUT", "text/plain");
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ("PUT", res->body);
  4348. }
  4349. TEST_F(ServerTest, PutWithContentProvider) {
  4350. auto res = cli_.Put(
  4351. "/put", 3,
  4352. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4353. sink.os << "PUT";
  4354. return true;
  4355. },
  4356. "text/plain");
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. EXPECT_EQ("PUT", res->body);
  4360. }
  4361. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4362. auto res = cli_.Post(
  4363. "/post", 42,
  4364. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4365. return false;
  4366. },
  4367. "text/plain");
  4368. ASSERT_TRUE(!res);
  4369. EXPECT_EQ(Error::Canceled, res.error());
  4370. }
  4371. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4372. auto res = cli_.Put(
  4373. "/put",
  4374. [](size_t /*offset*/, DataSink &sink) {
  4375. sink.os << "PUT";
  4376. sink.done();
  4377. return true;
  4378. },
  4379. "text/plain");
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. EXPECT_EQ("PUT", res->body);
  4383. }
  4384. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4385. auto res = cli_.Post(
  4386. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4387. "text/plain");
  4388. ASSERT_TRUE(!res);
  4389. EXPECT_EQ(Error::Canceled, res.error());
  4390. }
  4391. TEST_F(ServerTest, PostLoopBack) {
  4392. std::string body;
  4393. auto res = cli_.Post(
  4394. "/post-loopback", 9,
  4395. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4396. EXPECT_EQ(9u, length);
  4397. sink.write("123", 3);
  4398. sink.write("456", 3);
  4399. sink.write("789", 3);
  4400. return true;
  4401. },
  4402. "text/plain",
  4403. [&body](const char *data, size_t data_length) {
  4404. body.append(data, data_length);
  4405. return true;
  4406. });
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("123456789", body);
  4410. }
  4411. TEST_F(ServerTest, PutLoopBack) {
  4412. std::string body;
  4413. auto res = cli_.Put(
  4414. "/put-loopback", 9,
  4415. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4416. EXPECT_EQ(9u, length);
  4417. sink.write("123", 3);
  4418. sink.write("456", 3);
  4419. sink.write("789", 3);
  4420. return true;
  4421. },
  4422. "text/plain",
  4423. [&body](const char *data, size_t data_length) {
  4424. body.append(data, data_length);
  4425. return true;
  4426. });
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::OK_200, res->status);
  4429. EXPECT_EQ("123456789", body);
  4430. }
  4431. TEST_F(ServerTest, PatchLoopBack) {
  4432. std::string body;
  4433. auto res = cli_.Patch(
  4434. "/patch-loopback", 9,
  4435. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4436. EXPECT_EQ(9u, length);
  4437. sink.write("123", 3);
  4438. sink.write("456", 3);
  4439. sink.write("789", 3);
  4440. return true;
  4441. },
  4442. "text/plain",
  4443. [&body](const char *data, size_t data_length) {
  4444. body.append(data, data_length);
  4445. return true;
  4446. });
  4447. ASSERT_TRUE(res);
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("123456789", body);
  4450. }
  4451. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4452. std::string body;
  4453. auto res = cli_.Post(
  4454. "/post-loopback",
  4455. [](size_t /*offset*/, DataSink &sink) {
  4456. sink.write("123", 3);
  4457. sink.write("456", 3);
  4458. sink.write("789", 3);
  4459. sink.done();
  4460. return true;
  4461. },
  4462. "text/plain",
  4463. [&body](const char *data, size_t data_length) {
  4464. body.append(data, data_length);
  4465. return true;
  4466. });
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ("123456789", body);
  4470. }
  4471. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4472. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4473. cli_.set_compress(true);
  4474. auto res = cli_.Put(
  4475. "/put", 3,
  4476. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4477. sink.os << "PUT";
  4478. return true;
  4479. },
  4480. "text/plain");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("PUT", res->body);
  4484. }
  4485. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4486. cli_.set_compress(true);
  4487. auto res = cli_.Post(
  4488. "/post", 42,
  4489. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4490. return false;
  4491. },
  4492. "text/plain");
  4493. ASSERT_TRUE(!res);
  4494. EXPECT_EQ(Error::Canceled, res.error());
  4495. }
  4496. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4497. cli_.set_compress(true);
  4498. auto res = cli_.Put(
  4499. "/put",
  4500. [](size_t /*offset*/, DataSink &sink) {
  4501. sink.os << "PUT";
  4502. sink.done();
  4503. return true;
  4504. },
  4505. "text/plain");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("PUT", res->body);
  4509. }
  4510. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4511. cli_.set_compress(true);
  4512. auto res = cli_.Post(
  4513. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4514. "text/plain");
  4515. ASSERT_TRUE(!res);
  4516. EXPECT_EQ(Error::Canceled, res.error());
  4517. }
  4518. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4519. cli_.set_compress(true);
  4520. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(LARGE_DATA, res->body);
  4524. }
  4525. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4527. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4528. Client cli(s.c_str());
  4529. cli.enable_server_certificate_verification(false);
  4530. #else
  4531. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4532. Client cli(s.c_str());
  4533. #endif
  4534. cli.set_compress(true);
  4535. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ(LARGE_DATA, res->body);
  4539. // The compressed size should be less than a 10th of the original. May vary
  4540. // depending on the zlib library.
  4541. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4542. static_cast<uint64_t>(10 * 1024 * 1024));
  4543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4544. }
  4545. TEST_F(ServerTest, PutContentWithDeflate) {
  4546. cli_.set_compress(false);
  4547. Headers headers;
  4548. headers.emplace("Content-Encoding", "deflate");
  4549. // PUT in deflate format:
  4550. auto res = cli_.Put("/put", headers,
  4551. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("PUT", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4557. Headers headers;
  4558. headers.emplace("Accept-Encoding", "gzip, deflate");
  4559. auto res = cli_.Get("/streamed-chunked", headers);
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ(std::string("123456789"), res->body);
  4563. }
  4564. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4565. Headers headers;
  4566. headers.emplace("Accept-Encoding", "gzip, deflate");
  4567. auto res = cli_.Get("/streamed-chunked2", headers);
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ(std::string("123456789"), res->body);
  4571. }
  4572. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4573. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4574. ASSERT_TRUE(res);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST(GzipDecompressor, ChunkedDecompression) {
  4578. std::string data;
  4579. for (size_t i = 0; i < 32 * 1024; ++i) {
  4580. data.push_back(static_cast<char>('a' + i % 26));
  4581. }
  4582. std::string compressed_data;
  4583. {
  4584. httplib::detail::gzip_compressor compressor;
  4585. bool result = compressor.compress(
  4586. data.data(), data.size(),
  4587. /*last=*/true,
  4588. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4589. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4590. compressed_data_size);
  4591. return true;
  4592. });
  4593. ASSERT_TRUE(result);
  4594. }
  4595. std::string decompressed_data;
  4596. {
  4597. httplib::detail::gzip_decompressor decompressor;
  4598. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4599. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4600. size_t chunk_size = 130;
  4601. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4602. chunk_begin += chunk_size) {
  4603. size_t current_chunk_size =
  4604. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4605. bool result = decompressor.decompress(
  4606. compressed_data.data() + chunk_begin, current_chunk_size,
  4607. [&](const char *decompressed_data_chunk,
  4608. size_t decompressed_data_chunk_size) {
  4609. decompressed_data.insert(decompressed_data.size(),
  4610. decompressed_data_chunk,
  4611. decompressed_data_chunk_size);
  4612. return true;
  4613. });
  4614. ASSERT_TRUE(result);
  4615. }
  4616. }
  4617. ASSERT_EQ(data, decompressed_data);
  4618. }
  4619. TEST(GzipDecompressor, DeflateDecompression) {
  4620. std::string original_text = "Raw deflate without gzip";
  4621. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4622. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4623. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4624. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4625. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4626. std::string decompressed_data;
  4627. {
  4628. httplib::detail::gzip_decompressor decompressor;
  4629. bool result = decompressor.decompress(
  4630. compressed_data.data(), compressed_data.size(),
  4631. [&](const char *decompressed_data_chunk,
  4632. size_t decompressed_data_chunk_size) {
  4633. decompressed_data.insert(decompressed_data.size(),
  4634. decompressed_data_chunk,
  4635. decompressed_data_chunk_size);
  4636. return true;
  4637. });
  4638. ASSERT_TRUE(result);
  4639. }
  4640. ASSERT_EQ(original_text, decompressed_data);
  4641. }
  4642. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4643. std::string original_text = "Raw deflate without gzip";
  4644. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4645. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4646. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4647. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4648. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4649. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4650. std::string decompressed_data;
  4651. {
  4652. httplib::detail::gzip_decompressor decompressor;
  4653. bool result = decompressor.decompress(
  4654. compressed_data.data(), compressed_data.size(),
  4655. [&](const char *decompressed_data_chunk,
  4656. size_t decompressed_data_chunk_size) {
  4657. decompressed_data.insert(decompressed_data.size(),
  4658. decompressed_data_chunk,
  4659. decompressed_data_chunk_size);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(result);
  4663. }
  4664. ASSERT_EQ(original_text, decompressed_data);
  4665. }
  4666. #ifdef _WIN32
  4667. TEST(GzipDecompressor, LargeRandomData) {
  4668. // prepare large random data that is difficult to be compressed and is
  4669. // expected to have large size even when compressed
  4670. std::random_device seed_gen;
  4671. std::mt19937 random(seed_gen());
  4672. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4673. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4674. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4675. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4676. // compress data over 4GiB
  4677. std::string compressed_data;
  4678. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4679. httplib::detail::gzip_compressor compressor;
  4680. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4681. data.size() * sizeof(std::uint32_t), true,
  4682. [&](const char *data, size_t size) {
  4683. compressed_data.insert(
  4684. compressed_data.size(), data, size);
  4685. return true;
  4686. });
  4687. ASSERT_TRUE(result);
  4688. // FIXME: compressed data size is expected to be greater than 4GiB,
  4689. // but there is no guarantee
  4690. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4691. // decompress data over 4GiB
  4692. std::string decompressed_data;
  4693. decompressed_data.reserve(data_size);
  4694. httplib::detail::gzip_decompressor decompressor;
  4695. result = decompressor.decompress(
  4696. compressed_data.data(), compressed_data.size(),
  4697. [&](const char *data, size_t size) {
  4698. decompressed_data.insert(decompressed_data.size(), data, size);
  4699. return true;
  4700. });
  4701. ASSERT_TRUE(result);
  4702. // compare
  4703. ASSERT_EQ(data_size, decompressed_data.size());
  4704. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4705. 0);
  4706. }
  4707. #endif
  4708. #endif
  4709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4710. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4711. Headers headers;
  4712. headers.emplace("Accept-Encoding", "br");
  4713. auto res = cli_.Get("/streamed-chunked", headers);
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ(std::string("123456789"), res->body);
  4717. }
  4718. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4719. Headers headers;
  4720. headers.emplace("Accept-Encoding", "br");
  4721. auto res = cli_.Get("/streamed-chunked2", headers);
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ(std::string("123456789"), res->body);
  4725. }
  4726. #endif
  4727. TEST_F(ServerTest, Patch) {
  4728. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("PATCH", res->body);
  4732. }
  4733. TEST_F(ServerTest, Delete) {
  4734. auto res = cli_.Delete("/delete");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("DELETE", res->body);
  4738. }
  4739. TEST_F(ServerTest, DeleteContentReceiver) {
  4740. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("content", res->body);
  4744. }
  4745. TEST_F(ServerTest, Options) {
  4746. auto res = cli_.Options("*");
  4747. ASSERT_TRUE(res);
  4748. EXPECT_EQ(StatusCode::OK_200, res->status);
  4749. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4750. EXPECT_TRUE(res->body.empty());
  4751. }
  4752. TEST_F(ServerTest, URL) {
  4753. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4754. ASSERT_TRUE(res);
  4755. EXPECT_EQ(StatusCode::OK_200, res->status);
  4756. }
  4757. TEST_F(ServerTest, ArrayParam) {
  4758. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. }
  4762. TEST_F(ServerTest, NoMultipleHeaders) {
  4763. Headers headers = {{"Content-Length", "5"}};
  4764. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4765. "text/plain");
  4766. ASSERT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. }
  4769. TEST_F(ServerTest, PostContentReceiver) {
  4770. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4771. ASSERT_TRUE(res);
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("content", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4776. UploadFormDataItems items = {
  4777. {"text1", "text default", "", ""},
  4778. {"text2", "aωb", "", ""},
  4779. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4780. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4781. {"file3", "", "", "application/octet-stream"},
  4782. };
  4783. auto res = cli_.Post("/content_receiver", items);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. }
  4787. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4788. UploadFormDataItems items = {
  4789. {"text1", "text default", "", ""},
  4790. {"text2", "aωb", "", ""},
  4791. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4792. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4793. {"file3", "", "", "application/octet-stream"},
  4794. };
  4795. auto boundary = std::string("+++++");
  4796. std::string body;
  4797. for (const auto &item : items) {
  4798. body += "--" + boundary + "\r\n";
  4799. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4800. if (!item.filename.empty()) {
  4801. body += "; filename=\"" + item.filename + "\"";
  4802. }
  4803. body += "\r\n";
  4804. if (!item.content_type.empty()) {
  4805. body += "Content-Type: " + item.content_type + "\r\n";
  4806. }
  4807. body += "\r\n";
  4808. body += item.content + "\r\n";
  4809. }
  4810. body += "--" + boundary + "--\r\n";
  4811. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4812. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, PostContentReceiverGzip) {
  4817. cli_.set_compress(true);
  4818. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4819. ASSERT_TRUE(res);
  4820. ASSERT_EQ(StatusCode::OK_200, res->status);
  4821. ASSERT_EQ("content", res->body);
  4822. }
  4823. TEST_F(ServerTest, PutContentReceiver) {
  4824. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PatchContentReceiver) {
  4830. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4831. ASSERT_TRUE(res);
  4832. ASSERT_EQ(StatusCode::OK_200, res->status);
  4833. ASSERT_EQ("content", res->body);
  4834. }
  4835. template <typename ClientType>
  4836. void TestWithHeadersAndContentReceiver(
  4837. ClientType &cli,
  4838. std::function<Result(ClientType &, const std::string &, const Headers &,
  4839. const std::string &, const std::string &,
  4840. ContentReceiver, DownloadProgress)>
  4841. request_func) {
  4842. Headers headers;
  4843. headers.emplace("X-Custom-Header", "test-value");
  4844. std::string received_body;
  4845. auto res = request_func(
  4846. cli, "/content_receiver", headers, "content", "application/json",
  4847. [&](const char *data, size_t data_length) {
  4848. received_body.append(data, data_length);
  4849. return true;
  4850. },
  4851. nullptr);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ("content", received_body);
  4855. }
  4856. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4858. using ClientT = SSLClient;
  4859. #else
  4860. using ClientT = Client;
  4861. #endif
  4862. TestWithHeadersAndContentReceiver<ClientT>(
  4863. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4864. const std::string &body, const std::string &content_type,
  4865. ContentReceiver receiver, DownloadProgress progress) {
  4866. return cli.Post(path, headers, body, content_type, receiver, progress);
  4867. });
  4868. }
  4869. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4870. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4871. using ClientT = SSLClient;
  4872. #else
  4873. using ClientT = Client;
  4874. #endif
  4875. TestWithHeadersAndContentReceiver<ClientT>(
  4876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4877. const std::string &body, const std::string &content_type,
  4878. ContentReceiver receiver, DownloadProgress progress) {
  4879. return cli.Put(path, headers, body, content_type, receiver, progress);
  4880. });
  4881. }
  4882. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  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.Patch(path, headers, body, content_type, receiver, progress);
  4893. });
  4894. }
  4895. template <typename ClientType>
  4896. void TestWithHeadersAndContentReceiverWithProgress(
  4897. ClientType &cli,
  4898. std::function<Result(ClientType &, const std::string &, const Headers &,
  4899. const std::string &, const std::string &,
  4900. ContentReceiver, DownloadProgress)>
  4901. request_func) {
  4902. Headers headers;
  4903. headers.emplace("X-Test-Header", "progress-test");
  4904. std::string received_body;
  4905. auto progress_called = false;
  4906. auto res = request_func(
  4907. cli, "/content_receiver", headers, "content", "text/plain",
  4908. [&](const char *data, size_t data_length) {
  4909. received_body.append(data, data_length);
  4910. return true;
  4911. },
  4912. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4913. progress_called = true;
  4914. return true;
  4915. });
  4916. ASSERT_TRUE(res);
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("content", received_body);
  4919. EXPECT_TRUE(progress_called);
  4920. }
  4921. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4922. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4923. using ClientT = SSLClient;
  4924. #else
  4925. using ClientT = Client;
  4926. #endif
  4927. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4928. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4929. const std::string &body, const std::string &content_type,
  4930. ContentReceiver receiver, DownloadProgress progress) {
  4931. return cli.Post(path, headers, body, content_type, receiver, progress);
  4932. });
  4933. }
  4934. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4936. using ClientT = SSLClient;
  4937. #else
  4938. using ClientT = Client;
  4939. #endif
  4940. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4941. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4942. const std::string &body, const std::string &content_type,
  4943. ContentReceiver receiver, DownloadProgress progress) {
  4944. return cli.Put(path, headers, body, content_type, receiver, progress);
  4945. });
  4946. }
  4947. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  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.Patch(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. template <typename ClientType>
  4961. void TestWithHeadersAndContentReceiverError(
  4962. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4963. const Headers &, const std::string &,
  4964. const std::string &, ContentReceiver)>
  4965. request_func) {
  4966. Headers headers;
  4967. headers.emplace("X-Error-Test", "true");
  4968. std::string received_body;
  4969. auto receiver_failed = false;
  4970. auto res =
  4971. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4972. [&](const char *data, size_t data_length) {
  4973. received_body.append(data, data_length);
  4974. receiver_failed = true;
  4975. return false;
  4976. });
  4977. ASSERT_FALSE(res);
  4978. EXPECT_TRUE(receiver_failed);
  4979. }
  4980. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4982. using ClientT = SSLClient;
  4983. #else
  4984. using ClientT = Client;
  4985. #endif
  4986. TestWithHeadersAndContentReceiverError<ClientT>(
  4987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4988. const std::string &body, const std::string &content_type,
  4989. ContentReceiver receiver) {
  4990. return cli.Post(path, headers, body, content_type, receiver);
  4991. });
  4992. }
  4993. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4995. using ClientT = SSLClient;
  4996. #else
  4997. using ClientT = Client;
  4998. #endif
  4999. TestWithHeadersAndContentReceiverError<ClientT>(
  5000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5001. const std::string &body, const std::string &content_type,
  5002. ContentReceiver receiver) {
  5003. return cli.Put(path, headers, body, content_type, receiver);
  5004. });
  5005. }
  5006. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  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.Patch(path, headers, body, content_type, receiver);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PostQueryStringAndBody) {
  5020. auto res =
  5021. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5022. ASSERT_TRUE(res);
  5023. ASSERT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. TEST_F(ServerTest, HTTP2Magic) {
  5026. Request req;
  5027. req.method = "PRI";
  5028. req.path = "*";
  5029. req.body = "SM";
  5030. auto res = std::make_shared<Response>();
  5031. auto error = Error::Success;
  5032. auto ret = cli_.send(req, *res, error);
  5033. ASSERT_TRUE(ret);
  5034. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5035. }
  5036. TEST_F(ServerTest, KeepAlive) {
  5037. auto res = cli_.Get("/hi");
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5041. EXPECT_EQ("Hello World!", res->body);
  5042. res = cli_.Get("/hi");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5046. EXPECT_EQ("Hello World!", res->body);
  5047. res = cli_.Get("/hi");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("Hello World!", res->body);
  5052. res = cli_.Get("/not-exist");
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. res = cli_.Post("/empty", "", "text/plain");
  5056. ASSERT_TRUE(res);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_EQ("empty", res->body);
  5060. EXPECT_EQ("close", res->get_header_value("Connection"));
  5061. res = cli_.Post(
  5062. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5063. "text/plain");
  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("empty", res->body);
  5068. cli_.set_keep_alive(false);
  5069. res = cli_.Get("/last-request");
  5070. ASSERT_TRUE(res);
  5071. EXPECT_EQ(StatusCode::OK_200, res->status);
  5072. EXPECT_EQ("close", res->get_header_value("Connection"));
  5073. }
  5074. TEST_F(ServerTest, TooManyRedirect) {
  5075. cli_.set_follow_location(true);
  5076. auto res = cli_.Get("/redirect/0");
  5077. ASSERT_TRUE(!res);
  5078. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5079. }
  5080. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5081. Request req;
  5082. req.method = "FOOBAR";
  5083. req.path = "/hi";
  5084. cli_.set_keep_alive(true);
  5085. auto res = cli_.send(req);
  5086. ASSERT_TRUE(res);
  5087. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5088. EXPECT_EQ("close", res->get_header_value("Connection"));
  5089. EXPECT_FALSE(cli_.is_socket_open());
  5090. }
  5091. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5093. TEST_F(ServerTest, Gzip) {
  5094. Headers headers;
  5095. headers.emplace("Accept-Encoding", "gzip, deflate");
  5096. auto res = cli_.Get("/compress", headers);
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5102. "7890123456789012345678901234567890",
  5103. res->body);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. }
  5106. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5107. Headers headers;
  5108. headers.emplace("Accept-Encoding", "");
  5109. auto res = cli_.Get("/compress", headers);
  5110. ASSERT_TRUE(res);
  5111. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5114. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5115. "7890123456789012345678901234567890",
  5116. res->body);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST_F(ServerTest, GzipWithContentReceiver) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "gzip, deflate");
  5122. std::string body;
  5123. auto res = cli_.Get("/compress", headers,
  5124. [&](const char *data, uint64_t data_length) {
  5125. EXPECT_EQ(100U, data_length);
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. ASSERT_TRUE(res);
  5130. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5133. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5134. "7890123456789012345678901234567890",
  5135. body);
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. }
  5138. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5139. Headers headers;
  5140. headers.emplace("Accept-Encoding", "gzip, deflate");
  5141. cli_.set_decompress(false);
  5142. auto res = cli_.Get("/compress", headers);
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5146. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5147. EXPECT_EQ(33U, res->body.size());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5151. Headers headers;
  5152. headers.emplace("Accept-Encoding", "");
  5153. std::string body;
  5154. auto res = cli_.Get("/compress", headers,
  5155. [&](const char *data, uint64_t data_length) {
  5156. EXPECT_EQ(100U, data_length);
  5157. body.append(data, data_length);
  5158. return true;
  5159. });
  5160. ASSERT_TRUE(res);
  5161. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5162. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5163. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5164. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5165. "7890123456789012345678901234567890",
  5166. body);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. }
  5169. TEST_F(ServerTest, NoGzip) {
  5170. Headers headers;
  5171. headers.emplace("Accept-Encoding", "gzip, deflate");
  5172. auto res = cli_.Get("/nocompress", headers);
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5175. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5176. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5177. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5178. "7890123456789012345678901234567890",
  5179. res->body);
  5180. EXPECT_EQ(StatusCode::OK_200, res->status);
  5181. }
  5182. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5183. Headers headers;
  5184. headers.emplace("Accept-Encoding", "gzip, deflate");
  5185. std::string body;
  5186. auto res = cli_.Get("/nocompress", headers,
  5187. [&](const char *data, uint64_t data_length) {
  5188. EXPECT_EQ(100U, data_length);
  5189. body.append(data, data_length);
  5190. return true;
  5191. });
  5192. ASSERT_TRUE(res);
  5193. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5194. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5195. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5196. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5197. "7890123456789012345678901234567890",
  5198. body);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. }
  5201. TEST_F(ServerTest, MultipartFormDataGzip) {
  5202. UploadFormDataItems items = {
  5203. {"key1", "test", "", ""},
  5204. {"key2", "--abcdefg123", "", ""},
  5205. };
  5206. cli_.set_compress(true);
  5207. auto res = cli_.Post("/compress-multipart", items);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. }
  5211. #endif
  5212. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5213. TEST_F(ServerTest, Brotli) {
  5214. Headers headers;
  5215. headers.emplace("Accept-Encoding", "br");
  5216. auto res = cli_.Get("/compress", headers);
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5220. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5221. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5222. "7890123456789012345678901234567890",
  5223. res->body);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. }
  5226. #endif
  5227. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5228. TEST_F(ServerTest, Zstd) {
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "zstd");
  5231. auto res = cli_.Get("/compress", headers);
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5237. "7890123456789012345678901234567890",
  5238. res->body);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "");
  5244. auto res = cli_.Get("/compress", headers);
  5245. ASSERT_TRUE(res);
  5246. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5249. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5250. "7890123456789012345678901234567890",
  5251. res->body);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "zstd");
  5257. std::string body;
  5258. auto res = cli_.Get("/compress", headers,
  5259. [&](const char *data, uint64_t data_length) {
  5260. EXPECT_EQ(100U, data_length);
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5266. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5269. "7890123456789012345678901234567890",
  5270. body);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5274. Headers headers;
  5275. headers.emplace("Accept-Encoding", "zstd");
  5276. cli_.set_decompress(false);
  5277. auto res = cli_.Get("/compress", headers);
  5278. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5279. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5280. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5281. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5285. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ(26U, res->body.size());
  5288. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5289. 0);
  5290. }
  5291. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5292. Headers headers;
  5293. headers.emplace("Accept-Encoding", "");
  5294. std::string body;
  5295. auto res = cli_.Get("/compress", headers,
  5296. [&](const char *data, uint64_t data_length) {
  5297. EXPECT_EQ(100U, data_length);
  5298. body.append(data, data_length);
  5299. return true;
  5300. });
  5301. ASSERT_TRUE(res);
  5302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5306. "7890123456789012345678901234567890",
  5307. body);
  5308. EXPECT_EQ(StatusCode::OK_200, res->status);
  5309. }
  5310. TEST_F(ServerTest, NoZstd) {
  5311. Headers headers;
  5312. headers.emplace("Accept-Encoding", "zstd");
  5313. auto res = cli_.Get("/nocompress", headers);
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5316. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5317. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5318. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5319. "7890123456789012345678901234567890",
  5320. res->body);
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5324. Headers headers;
  5325. headers.emplace("Accept-Encoding", "zstd");
  5326. std::string body;
  5327. auto res = cli_.Get("/nocompress", headers,
  5328. [&](const char *data, uint64_t data_length) {
  5329. EXPECT_EQ(100U, data_length);
  5330. body.append(data, data_length);
  5331. return true;
  5332. });
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5335. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5336. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5338. "7890123456789012345678901234567890",
  5339. body);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. }
  5342. // TODO: How to enable zstd ??
  5343. TEST_F(ServerTest, MultipartFormDataZstd) {
  5344. UploadFormDataItems items = {
  5345. {"key1", "test", "", ""},
  5346. {"key2", "--abcdefg123", "", ""},
  5347. };
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "zstd");
  5350. cli_.set_compress(true);
  5351. auto res = cli_.Post("/compress-multipart", headers, items);
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. }
  5355. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5356. Headers headers;
  5357. headers.emplace("Accept-Encoding", "zstd");
  5358. cli_.set_compress(true);
  5359. auto res = cli_.Put(
  5360. "/put", headers, 3,
  5361. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5362. sink.os << "PUT";
  5363. return true;
  5364. },
  5365. "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. // Pre-compression logging tests
  5371. TEST_F(ServerTest, PreCompressionLogging) {
  5372. // Test data for compression (matches the actual /compress endpoint content)
  5373. const std::string test_content =
  5374. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5375. "3456789012345678901234567890";
  5376. // Variables to capture logging data
  5377. std::string pre_compression_body;
  5378. std::string pre_compression_content_type;
  5379. std::string pre_compression_content_encoding;
  5380. std::string post_compression_body;
  5381. std::string post_compression_content_type;
  5382. std::string post_compression_content_encoding;
  5383. // Set up pre-compression logger
  5384. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5385. const Response &res) {
  5386. pre_compression_body = res.body;
  5387. pre_compression_content_type = res.get_header_value("Content-Type");
  5388. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5389. });
  5390. // Set up post-compression logger
  5391. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5392. post_compression_body = res.body;
  5393. post_compression_content_type = res.get_header_value("Content-Type");
  5394. post_compression_content_encoding =
  5395. res.get_header_value("Content-Encoding");
  5396. });
  5397. // Test with gzip compression
  5398. Headers headers;
  5399. headers.emplace("Accept-Encoding", "gzip");
  5400. auto res = cli_.Get("/compress", headers);
  5401. // Verify response was compressed
  5402. ASSERT_TRUE(res);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5405. // Verify pre-compression logger captured uncompressed content
  5406. EXPECT_EQ(test_content, pre_compression_body);
  5407. EXPECT_EQ("text/plain", pre_compression_content_type);
  5408. EXPECT_TRUE(pre_compression_content_encoding
  5409. .empty()); // No encoding header before compression
  5410. // Verify post-compression logger captured compressed content
  5411. EXPECT_NE(test_content,
  5412. post_compression_body); // Should be different after compression
  5413. EXPECT_EQ("text/plain", post_compression_content_type);
  5414. EXPECT_EQ("gzip", post_compression_content_encoding);
  5415. // Verify compressed content is smaller
  5416. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5417. }
  5418. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5419. const std::string test_content =
  5420. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5421. "3456789012345678901234567890";
  5422. std::string pre_compression_body;
  5423. std::string post_compression_body;
  5424. svr_.set_pre_compression_logger(
  5425. [&](const Request & /*req*/, const Response &res) {
  5426. pre_compression_body = res.body;
  5427. });
  5428. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5429. post_compression_body = res.body;
  5430. });
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "br");
  5433. auto res = cli_.Get("/compress", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5437. // Verify pre-compression content is uncompressed
  5438. EXPECT_EQ(test_content, pre_compression_body);
  5439. // Verify post-compression content is compressed
  5440. EXPECT_NE(test_content, post_compression_body);
  5441. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5442. }
  5443. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5444. const std::string test_content =
  5445. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5446. "3456789012345678901234567890";
  5447. std::string pre_compression_body;
  5448. std::string post_compression_body;
  5449. svr_.set_pre_compression_logger(
  5450. [&](const Request & /*req*/, const Response &res) {
  5451. pre_compression_body = res.body;
  5452. });
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. });
  5456. // Request without compression (use /nocompress endpoint)
  5457. Headers headers;
  5458. auto res = cli_.Get("/nocompress", headers);
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5462. // Pre-compression logger should not be called when no compression is applied
  5463. EXPECT_TRUE(
  5464. pre_compression_body.empty()); // Pre-compression logger not called
  5465. EXPECT_EQ(
  5466. test_content,
  5467. post_compression_body); // Post-compression logger captures final content
  5468. }
  5469. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5470. const std::string test_content =
  5471. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5472. "3456789012345678901234567890";
  5473. std::string pre_compression_body;
  5474. bool pre_logger_called = false;
  5475. // Set only pre-compression logger
  5476. svr_.set_pre_compression_logger(
  5477. [&](const Request & /*req*/, const Response &res) {
  5478. pre_compression_body = res.body;
  5479. pre_logger_called = true;
  5480. });
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5487. // Verify pre-compression logger was called
  5488. EXPECT_TRUE(pre_logger_called);
  5489. EXPECT_EQ(test_content, pre_compression_body);
  5490. }
  5491. TEST(ZstdDecompressor, ChunkedDecompression) {
  5492. std::string data;
  5493. for (size_t i = 0; i < 32 * 1024; ++i) {
  5494. data.push_back(static_cast<char>('a' + i % 26));
  5495. }
  5496. std::string compressed_data;
  5497. {
  5498. httplib::detail::zstd_compressor compressor;
  5499. bool result = compressor.compress(
  5500. data.data(), data.size(),
  5501. /*last=*/true,
  5502. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5503. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5504. compressed_data_size);
  5505. return true;
  5506. });
  5507. ASSERT_TRUE(result);
  5508. }
  5509. std::string decompressed_data;
  5510. {
  5511. httplib::detail::zstd_decompressor decompressor;
  5512. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5513. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5514. size_t chunk_size = 130;
  5515. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5516. chunk_begin += chunk_size) {
  5517. size_t current_chunk_size =
  5518. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5519. bool result = decompressor.decompress(
  5520. compressed_data.data() + chunk_begin, current_chunk_size,
  5521. [&](const char *decompressed_data_chunk,
  5522. size_t decompressed_data_chunk_size) {
  5523. decompressed_data.insert(decompressed_data.size(),
  5524. decompressed_data_chunk,
  5525. decompressed_data_chunk_size);
  5526. return true;
  5527. });
  5528. ASSERT_TRUE(result);
  5529. }
  5530. }
  5531. ASSERT_EQ(data, decompressed_data);
  5532. }
  5533. TEST(ZstdDecompressor, Decompress) {
  5534. std::string original_text = "Compressed with ZSTD";
  5535. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5536. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5537. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5538. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5539. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5540. std::string decompressed_data;
  5541. {
  5542. httplib::detail::zstd_decompressor decompressor;
  5543. bool result = decompressor.decompress(
  5544. compressed_data.data(), compressed_data.size(),
  5545. [&](const char *decompressed_data_chunk,
  5546. size_t decompressed_data_chunk_size) {
  5547. decompressed_data.insert(decompressed_data.size(),
  5548. decompressed_data_chunk,
  5549. decompressed_data_chunk_size);
  5550. return true;
  5551. });
  5552. ASSERT_TRUE(result);
  5553. }
  5554. ASSERT_EQ(original_text, decompressed_data);
  5555. }
  5556. #endif
  5557. // Sends a raw request to a server listening at HOST:PORT.
  5558. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5559. std::string *resp = nullptr) {
  5560. auto error = Error::Success;
  5561. auto client_sock = detail::create_client_socket(
  5562. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5563. /*connection_timeout_sec=*/5, 0,
  5564. /*read_timeout_sec=*/5, 0,
  5565. /*write_timeout_sec=*/5, 0, std::string(), error);
  5566. if (client_sock == INVALID_SOCKET) { return false; }
  5567. auto ret = detail::process_client_socket(
  5568. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5569. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5570. if (req.size() !=
  5571. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5572. return false;
  5573. }
  5574. char buf[512];
  5575. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5576. while (line_reader.getline()) {
  5577. if (resp) { *resp += line_reader.ptr(); }
  5578. }
  5579. return true;
  5580. });
  5581. detail::close_socket(client_sock);
  5582. return ret;
  5583. }
  5584. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5585. Server svr;
  5586. std::string header_value;
  5587. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5588. header_value = req.get_header_value("foo");
  5589. res.set_content("ok", "text/plain");
  5590. });
  5591. thread t = thread([&] { svr.listen(HOST, PORT); });
  5592. auto se = detail::scope_exit([&] {
  5593. svr.stop();
  5594. t.join();
  5595. ASSERT_FALSE(svr.is_running());
  5596. });
  5597. svr.wait_until_ready();
  5598. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5599. // like characters are not treated the same - use vertical tab and escape.
  5600. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5601. "foo: \t \v bar \x1B\t \r\n"
  5602. "Connection: close\r\n"
  5603. "\r\n";
  5604. std::string res;
  5605. ASSERT_TRUE(send_request(5, req, &res));
  5606. EXPECT_EQ(header_value, "");
  5607. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5608. }
  5609. // Sends a raw request and verifies that there isn't a crash or exception.
  5610. static void test_raw_request(const std::string &req,
  5611. std::string *out = nullptr) {
  5612. Server svr;
  5613. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5614. res.set_content("ok", "text/plain");
  5615. });
  5616. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5617. res.set_content("ok", "text/plain");
  5618. });
  5619. svr.Get("/header_field_value_check",
  5620. [&](const Request & /*req*/, Response &res) {
  5621. res.set_content("ok", "text/plain");
  5622. });
  5623. // Server read timeout must be longer than the client read timeout for the
  5624. // bug to reproduce, probably to force the server to process a request
  5625. // without a trailing blank line.
  5626. const time_t client_read_timeout_sec = 1;
  5627. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5628. bool listen_thread_ok = false;
  5629. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5630. auto se = detail::scope_exit([&] {
  5631. svr.stop();
  5632. t.join();
  5633. ASSERT_FALSE(svr.is_running());
  5634. EXPECT_TRUE(listen_thread_ok);
  5635. });
  5636. svr.wait_until_ready();
  5637. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5638. }
  5639. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5640. // A certain header line causes an exception if the header property is parsed
  5641. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5642. test_raw_request(
  5643. "GET /hi HTTP/1.1\r\n"
  5644. " : "
  5645. " "
  5646. " ");
  5647. }
  5648. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5649. // A certain header line causes an exception if the header property *name* is
  5650. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5651. // greedy matcher and requires backtracking when there are a lot of ":"
  5652. // characters.
  5653. // This occurs with libc++ but not libstdc++.
  5654. test_raw_request(
  5655. "GET /hi HTTP/1.1\r\n"
  5656. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5657. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5658. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5659. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5660. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5661. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5662. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5663. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5664. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5665. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5666. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5667. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5668. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5669. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5670. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5671. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5672. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5673. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5674. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5675. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5676. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5677. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5678. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5679. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5680. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5681. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5682. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5683. "&&&%%%");
  5684. }
  5685. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5686. // Make sure this doesn't crash the server.
  5687. // In a previous version of the header line regex, the "\r" rendered the line
  5688. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5689. // a new position where the leading white space ended and the field value
  5690. // began.
  5691. // The crash occurs with libc++ but not libstdc++.
  5692. test_raw_request("GET /hi HTTP/1.1\r\n"
  5693. "a:" +
  5694. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5695. "\r\n"
  5696. "\r\n");
  5697. }
  5698. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5699. std::string out;
  5700. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5701. "Content-Type: text/plain\r\n"
  5702. "Transfer-Encoding: chunked\r\n"
  5703. "\r\n"
  5704. "nothex\r\n",
  5705. &out);
  5706. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5707. }
  5708. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5709. std::string out;
  5710. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5711. "Content-Type: text/plain\r\n"
  5712. "Transfer-Encoding: chunked\r\n"
  5713. "\r\n"
  5714. "3\r\n"
  5715. "xyz\r\n"
  5716. "NaN\r\n",
  5717. &out);
  5718. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5719. }
  5720. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5721. std::string out;
  5722. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5723. "Content-Type: text/plain\r\n"
  5724. "Transfer-Encoding: chunked\r\n"
  5725. "\r\n"
  5726. // Length is too large for 64 bits.
  5727. "1ffffffffffffffff\r\n"
  5728. "xyz\r\n",
  5729. &out);
  5730. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5731. }
  5732. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5733. test_raw_request("GET /hi HTTP/1.1\r\n"
  5734. "Content-Type: text/plain\r\n\r");
  5735. }
  5736. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5737. std::string out;
  5738. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5740. }
  5741. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5742. std::string out;
  5743. std::string request(
  5744. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5745. test_raw_request(request, &out);
  5746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5747. }
  5748. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5749. std::string out;
  5750. std::string request(
  5751. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5752. test_raw_request(request, &out);
  5753. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5754. }
  5755. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5756. std::string out;
  5757. std::string request(
  5758. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5759. test_raw_request(request, &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5763. std::string out;
  5764. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5765. "Test: \r\n\r\n",
  5766. &out);
  5767. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5768. }
  5769. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5770. Server svr;
  5771. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5772. res.set_header("Cache-Control", "no-cache");
  5773. res.set_chunked_content_provider(
  5774. "text/event-stream", [](size_t offset, DataSink &sink) {
  5775. std::string s = "data:";
  5776. s += std::to_string(offset);
  5777. s += "\n\n";
  5778. auto ret = sink.write(s.data(), s.size());
  5779. EXPECT_TRUE(ret);
  5780. std::this_thread::sleep_for(std::chrono::seconds(1));
  5781. return true;
  5782. });
  5783. });
  5784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5785. svr.wait_until_ready();
  5786. Client client(HOST, PORT);
  5787. const Headers headers = {{"Accept", "text/event-stream"}};
  5788. auto get_thread = std::thread([&client, &headers]() {
  5789. auto res = client.Get(
  5790. "/events", headers,
  5791. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5792. });
  5793. auto se = detail::scope_exit([&] {
  5794. svr.stop();
  5795. get_thread.join();
  5796. listen_thread.join();
  5797. ASSERT_FALSE(svr.is_running());
  5798. });
  5799. // Give GET time to get a few messages.
  5800. std::this_thread::sleep_for(std::chrono::seconds(2));
  5801. }
  5802. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5803. httplib::Server svr;
  5804. svr.Post("/hi",
  5805. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5806. res.status = StatusCode::OK_200;
  5807. });
  5808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5809. svr.wait_until_ready();
  5810. Client cli(HOST, PORT);
  5811. auto res = cli.Post("/hi", "data", "text/plain");
  5812. ASSERT_TRUE(res);
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. svr.stop();
  5815. thread.join();
  5816. ASSERT_FALSE(svr.is_running());
  5817. res = cli.Post("/hi", "data", "text/plain");
  5818. ASSERT_FALSE(res);
  5819. }
  5820. TEST(ServerStopTest, ListenFailure) {
  5821. Server svr;
  5822. auto t = thread([&]() {
  5823. auto ret = svr.listen("????", PORT);
  5824. EXPECT_FALSE(ret);
  5825. });
  5826. svr.wait_until_ready();
  5827. svr.stop();
  5828. t.join();
  5829. }
  5830. TEST(ServerStopTest, Decommision) {
  5831. Server svr;
  5832. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5833. for (int i = 0; i < 4; i++) {
  5834. auto is_even = !(i % 2);
  5835. std::thread t{[&] {
  5836. try {
  5837. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5838. if (is_even) {
  5839. throw std::runtime_error("Some thing that happens to go wrong.");
  5840. }
  5841. svr.listen(HOST, PORT);
  5842. } catch (...) { svr.decommission(); }
  5843. }};
  5844. svr.wait_until_ready();
  5845. // Server is up
  5846. {
  5847. Client cli(HOST, PORT);
  5848. auto res = cli.Get("/hi");
  5849. if (is_even) {
  5850. EXPECT_FALSE(res);
  5851. } else {
  5852. EXPECT_TRUE(res);
  5853. EXPECT_EQ("hi...", res->body);
  5854. }
  5855. }
  5856. svr.stop();
  5857. t.join();
  5858. // Server is down...
  5859. {
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/hi");
  5862. EXPECT_FALSE(res);
  5863. }
  5864. }
  5865. }
  5866. // Helper function for string body upload progress tests
  5867. template <typename SetupHandler, typename ClientCall>
  5868. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5869. ClientCall &&client_call,
  5870. const string &body) {
  5871. Server svr;
  5872. setup_handler(svr);
  5873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5874. auto se = detail::scope_exit([&] {
  5875. svr.stop();
  5876. t.join();
  5877. });
  5878. svr.wait_until_ready();
  5879. Client cli(HOST, PORT);
  5880. vector<uint64_t> progress_values;
  5881. bool progress_called = false;
  5882. auto res =
  5883. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5884. progress_values.push_back(current);
  5885. progress_called = true;
  5886. return true;
  5887. });
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(200, res->status);
  5890. EXPECT_TRUE(progress_called);
  5891. }
  5892. TEST(UploadProgressTest, PostStringBodyBasic) {
  5893. TestStringBodyUploadProgress(
  5894. [](Server &svr) {
  5895. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5896. res.set_content("received", "text/plain");
  5897. });
  5898. },
  5899. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5900. return cli.Post("/test", body, "text/plain", progress_callback);
  5901. },
  5902. "test data for upload progress");
  5903. }
  5904. TEST(UploadProgressTest, PutStringBodyBasic) {
  5905. TestStringBodyUploadProgress(
  5906. [](Server &svr) {
  5907. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5908. res.set_content("put received", "text/plain");
  5909. });
  5910. },
  5911. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5912. return cli.Put("/test", body, "text/plain", progress_callback);
  5913. },
  5914. "put test data for upload progress");
  5915. }
  5916. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5917. TestStringBodyUploadProgress(
  5918. [](Server &svr) {
  5919. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5920. res.set_content("patch received", "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5924. return cli.Patch("/test", body, "text/plain", progress_callback);
  5925. },
  5926. "patch test data for upload progress");
  5927. }
  5928. // Helper function for content provider upload progress tests
  5929. template <typename SetupHandler, typename ClientCall>
  5930. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5931. ClientCall &&client_call) {
  5932. Server svr;
  5933. setup_handler(svr);
  5934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5935. auto se = detail::scope_exit([&] {
  5936. svr.stop();
  5937. t.join();
  5938. });
  5939. svr.wait_until_ready();
  5940. Client cli(HOST, PORT);
  5941. vector<uint64_t> progress_values;
  5942. auto res =
  5943. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5944. progress_values.push_back(current);
  5945. return true;
  5946. });
  5947. ASSERT_TRUE(res);
  5948. EXPECT_EQ(200, res->status);
  5949. EXPECT_FALSE(progress_values.empty());
  5950. }
  5951. TEST(UploadProgressTest, PostContentProviderProgress) {
  5952. TestContentProviderUploadProgress(
  5953. [](Server &svr) {
  5954. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5955. res.set_content("provider received", "text/plain");
  5956. });
  5957. },
  5958. [](Client &cli, UploadProgress progress_callback) {
  5959. return cli.Post(
  5960. "/test", 10,
  5961. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5962. sink.os << "test data";
  5963. return true;
  5964. },
  5965. "text/plain", progress_callback);
  5966. });
  5967. }
  5968. // Helper function for multipart upload progress tests
  5969. template <typename SetupHandler, typename ClientCall>
  5970. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5971. ClientCall &&client_call,
  5972. const string &endpoint) {
  5973. Server svr;
  5974. setup_handler(svr);
  5975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5976. auto se = detail::scope_exit([&] {
  5977. svr.stop();
  5978. t.join();
  5979. });
  5980. svr.wait_until_ready();
  5981. Client cli(HOST, PORT);
  5982. vector<uint64_t> progress_values;
  5983. UploadFormDataItems items = {
  5984. {"field1", "value1", "", ""},
  5985. {"field2", "longer value for progress tracking test", "", ""},
  5986. {"file1", "file content data for upload progress", "test.txt",
  5987. "text/plain"}};
  5988. auto res = client_call(cli, endpoint, items,
  5989. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5990. progress_values.push_back(current);
  5991. return true;
  5992. });
  5993. ASSERT_TRUE(res);
  5994. EXPECT_EQ(200, res->status);
  5995. EXPECT_FALSE(progress_values.empty());
  5996. }
  5997. TEST(UploadProgressTest, PostMultipartProgress) {
  5998. TestMultipartUploadProgress(
  5999. [](Server &svr) {
  6000. svr.Post("/multipart", [](const Request &req, Response &res) {
  6001. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6002. res.set_content("multipart received", "text/plain");
  6003. });
  6004. },
  6005. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6006. UploadProgress progress_callback) {
  6007. return cli.Post(endpoint, items, progress_callback);
  6008. },
  6009. "/multipart");
  6010. }
  6011. // Helper function for basic download progress tests
  6012. template <typename SetupHandler, typename ClientCall>
  6013. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6014. ClientCall &&client_call, const string &endpoint,
  6015. size_t expected_content_size) {
  6016. Server svr;
  6017. setup_handler(svr);
  6018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6019. auto se = detail::scope_exit([&] {
  6020. svr.stop();
  6021. t.join();
  6022. });
  6023. svr.wait_until_ready();
  6024. Client cli(HOST, PORT);
  6025. vector<uint64_t> progress_values;
  6026. auto res = client_call(cli, endpoint,
  6027. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6028. progress_values.push_back(current);
  6029. return true;
  6030. });
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(200, res->status);
  6033. EXPECT_FALSE(progress_values.empty());
  6034. EXPECT_EQ(expected_content_size, res->body.size());
  6035. }
  6036. TEST(DownloadProgressTest, GetBasic) {
  6037. TestBasicDownloadProgress(
  6038. [](Server &svr) {
  6039. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6040. string content(1000, 'D');
  6041. res.set_content(content, "text/plain");
  6042. });
  6043. },
  6044. [](Client &cli, const string &endpoint,
  6045. DownloadProgress progress_callback) {
  6046. return cli.Get(endpoint, progress_callback);
  6047. },
  6048. "/download", 1000u);
  6049. }
  6050. // Helper function for content receiver download progress tests
  6051. template <typename SetupHandler, typename ClientCall>
  6052. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6053. ClientCall &&client_call,
  6054. const string &endpoint,
  6055. size_t expected_content_size) {
  6056. Server svr;
  6057. setup_handler(svr);
  6058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6059. auto se = detail::scope_exit([&] {
  6060. svr.stop();
  6061. t.join();
  6062. });
  6063. svr.wait_until_ready();
  6064. Client cli(HOST, PORT);
  6065. vector<uint64_t> progress_values;
  6066. string received_body;
  6067. auto res = client_call(
  6068. cli, endpoint,
  6069. [&](const char *data, size_t data_length) -> bool {
  6070. received_body.append(data, data_length);
  6071. return true;
  6072. },
  6073. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6074. progress_values.push_back(current);
  6075. return true;
  6076. });
  6077. ASSERT_TRUE(res);
  6078. EXPECT_EQ(200, res->status);
  6079. EXPECT_FALSE(progress_values.empty());
  6080. EXPECT_EQ(expected_content_size, received_body.size());
  6081. EXPECT_TRUE(res->body.empty());
  6082. }
  6083. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6084. TestContentReceiverDownloadProgress(
  6085. [](Server &svr) {
  6086. svr.Get("/download-receiver",
  6087. [](const Request & /*req*/, Response &res) {
  6088. string content(2000, 'R');
  6089. res.set_content(content, "text/plain");
  6090. });
  6091. },
  6092. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6093. DownloadProgress progress_callback) {
  6094. return cli.Get(endpoint, content_receiver, progress_callback);
  6095. },
  6096. "/download-receiver", 2000u);
  6097. }
  6098. TEST(StreamingTest, NoContentLengthStreaming) {
  6099. Server svr;
  6100. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6101. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6102. if (offset < 6) {
  6103. sink.os << (offset < 3 ? "a" : "b");
  6104. } else {
  6105. sink.done();
  6106. }
  6107. return true;
  6108. });
  6109. });
  6110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6111. auto listen_se = detail::scope_exit([&] {
  6112. svr.stop();
  6113. listen_thread.join();
  6114. ASSERT_FALSE(svr.is_running());
  6115. });
  6116. svr.wait_until_ready();
  6117. Client client(HOST, PORT);
  6118. auto get_thread = std::thread([&client]() {
  6119. std::string s;
  6120. auto res =
  6121. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6122. s += std::string(data, len);
  6123. return true;
  6124. });
  6125. ASSERT_TRUE(res);
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ("aaabbb", s);
  6128. });
  6129. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6130. // Give GET time to get a few messages.
  6131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6132. }
  6133. TEST(MountTest, Unmount) {
  6134. Server svr;
  6135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. listen_thread.join();
  6139. ASSERT_FALSE(svr.is_running());
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli("localhost", PORT);
  6143. svr.set_mount_point("/mount2", "./www2");
  6144. auto res = cli.Get("/");
  6145. ASSERT_TRUE(res);
  6146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6147. res = cli.Get("/mount2/dir/test.html");
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. svr.set_mount_point("/", "./www");
  6151. res = cli.Get("/dir/");
  6152. ASSERT_TRUE(res);
  6153. EXPECT_EQ(StatusCode::OK_200, res->status);
  6154. svr.remove_mount_point("/");
  6155. res = cli.Get("/dir/");
  6156. ASSERT_TRUE(res);
  6157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6158. svr.remove_mount_point("/mount2");
  6159. res = cli.Get("/mount2/dir/test.html");
  6160. ASSERT_TRUE(res);
  6161. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6162. }
  6163. TEST(MountTest, Redicect) {
  6164. Server svr;
  6165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6166. auto se = detail::scope_exit([&] {
  6167. svr.stop();
  6168. listen_thread.join();
  6169. ASSERT_FALSE(svr.is_running());
  6170. });
  6171. svr.set_mount_point("/", "./www");
  6172. svr.wait_until_ready();
  6173. Client cli("localhost", PORT);
  6174. auto res = cli.Get("/dir/");
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. res = cli.Get("/dir");
  6178. ASSERT_TRUE(res);
  6179. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6180. res = cli.Get("/file");
  6181. ASSERT_TRUE(res);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli.Get("/file/");
  6184. ASSERT_TRUE(res);
  6185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6186. cli.set_follow_location(true);
  6187. res = cli.Get("/dir");
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST(MountTest, MultibytesPathName) {
  6192. Server svr;
  6193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6194. auto se = detail::scope_exit([&] {
  6195. svr.stop();
  6196. listen_thread.join();
  6197. ASSERT_FALSE(svr.is_running());
  6198. });
  6199. svr.set_mount_point("/", "./www");
  6200. svr.wait_until_ready();
  6201. Client cli("localhost", PORT);
  6202. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6206. }
  6207. TEST(KeepAliveTest, ReadTimeout) {
  6208. Server svr;
  6209. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6210. std::this_thread::sleep_for(std::chrono::seconds(2));
  6211. res.set_content("a", "text/plain");
  6212. });
  6213. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6214. res.set_content("b", "text/plain");
  6215. });
  6216. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6217. auto se = detail::scope_exit([&] {
  6218. svr.stop();
  6219. listen_thread.join();
  6220. ASSERT_FALSE(svr.is_running());
  6221. });
  6222. svr.wait_until_ready();
  6223. Client cli("localhost", PORT);
  6224. cli.set_keep_alive(true);
  6225. cli.set_read_timeout(std::chrono::seconds(1));
  6226. auto resa = cli.Get("/a");
  6227. ASSERT_FALSE(resa);
  6228. EXPECT_EQ(Error::Read, resa.error());
  6229. auto resb = cli.Get("/b");
  6230. ASSERT_TRUE(resb);
  6231. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6232. EXPECT_EQ("b", resb->body);
  6233. }
  6234. TEST(KeepAliveTest, MaxCount) {
  6235. size_t keep_alive_max_count = 3;
  6236. Server svr;
  6237. svr.set_keep_alive_max_count(keep_alive_max_count);
  6238. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6239. res.set_content("Hello World!", "text/plain");
  6240. });
  6241. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6242. auto se = detail::scope_exit([&] {
  6243. svr.stop();
  6244. listen_thread.join();
  6245. ASSERT_FALSE(svr.is_running());
  6246. });
  6247. svr.wait_until_ready();
  6248. Client cli(HOST, PORT);
  6249. cli.set_keep_alive(true);
  6250. for (size_t i = 0; i < 5; i++) {
  6251. auto result = cli.Get("/hi");
  6252. ASSERT_TRUE(result);
  6253. EXPECT_EQ(StatusCode::OK_200, result->status);
  6254. if (i == keep_alive_max_count - 1) {
  6255. EXPECT_EQ("close", result->get_header_value("Connection"));
  6256. } else {
  6257. EXPECT_FALSE(result->has_header("Connection"));
  6258. }
  6259. }
  6260. }
  6261. TEST(KeepAliveTest, Issue1041) {
  6262. Server svr;
  6263. svr.set_keep_alive_timeout(3);
  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. auto result = cli.Get("/hi");
  6277. ASSERT_TRUE(result);
  6278. EXPECT_EQ(StatusCode::OK_200, result->status);
  6279. std::this_thread::sleep_for(std::chrono::seconds(5));
  6280. result = cli.Get("/hi");
  6281. ASSERT_TRUE(result);
  6282. EXPECT_EQ(StatusCode::OK_200, result->status);
  6283. }
  6284. TEST(KeepAliveTest, Issue1959) {
  6285. Server svr;
  6286. svr.set_keep_alive_timeout(5);
  6287. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6288. res.set_content("a", "text/plain");
  6289. });
  6290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6291. auto se = detail::scope_exit([&] {
  6292. if (!svr.is_running()) return;
  6293. svr.stop();
  6294. listen_thread.join();
  6295. ASSERT_FALSE(svr.is_running());
  6296. });
  6297. svr.wait_until_ready();
  6298. Client cli("localhost", PORT);
  6299. cli.set_keep_alive(true);
  6300. using namespace std::chrono;
  6301. auto start = steady_clock::now();
  6302. cli.Get("/a");
  6303. svr.stop();
  6304. listen_thread.join();
  6305. auto end = steady_clock::now();
  6306. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6307. EXPECT_LT(elapsed, 5000);
  6308. }
  6309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6310. TEST(KeepAliveTest, SSLClientReconnection) {
  6311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6312. ASSERT_TRUE(svr.is_valid());
  6313. svr.set_keep_alive_timeout(1);
  6314. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6315. res.set_content("Hello World!", "text/plain");
  6316. });
  6317. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6318. auto se = detail::scope_exit([&] {
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. SSLClient cli(HOST, PORT);
  6325. cli.enable_server_certificate_verification(false);
  6326. cli.set_keep_alive(true);
  6327. auto result = cli.Get("/hi");
  6328. ASSERT_TRUE(result);
  6329. EXPECT_EQ(StatusCode::OK_200, result->status);
  6330. result = cli.Get("/hi");
  6331. ASSERT_TRUE(result);
  6332. EXPECT_EQ(StatusCode::OK_200, result->status);
  6333. std::this_thread::sleep_for(std::chrono::seconds(2));
  6334. // Recoonect
  6335. result = cli.Get("/hi");
  6336. ASSERT_TRUE(result);
  6337. EXPECT_EQ(StatusCode::OK_200, result->status);
  6338. result = cli.Get("/hi");
  6339. ASSERT_TRUE(result);
  6340. EXPECT_EQ(StatusCode::OK_200, result->status);
  6341. }
  6342. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6344. ASSERT_TRUE(svr.is_valid());
  6345. svr.set_keep_alive_timeout(1);
  6346. std::string content = "reconnect";
  6347. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6348. res.set_content("Hello World!", "text/plain");
  6349. });
  6350. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. listen_thread.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.wait_until_ready();
  6357. SSLClient cli(HOST, PORT);
  6358. cli.enable_server_certificate_verification(false);
  6359. cli.set_keep_alive(true);
  6360. auto result = cli.Post(
  6361. "/hi", content.size(),
  6362. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6363. sink.write(content.c_str(), content.size());
  6364. return true;
  6365. },
  6366. "text/plain");
  6367. ASSERT_TRUE(result);
  6368. EXPECT_EQ(200, result->status);
  6369. std::this_thread::sleep_for(std::chrono::seconds(2));
  6370. // Recoonect
  6371. result = cli.Post(
  6372. "/hi", content.size(),
  6373. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6374. sink.write(content.c_str(), content.size());
  6375. return true;
  6376. },
  6377. "text/plain");
  6378. ASSERT_TRUE(result);
  6379. EXPECT_EQ(200, result->status);
  6380. result = cli.Post(
  6381. "/hi", content.size(),
  6382. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6383. sink.write(content.c_str(), content.size());
  6384. return true;
  6385. },
  6386. "text/plain");
  6387. ASSERT_TRUE(result);
  6388. EXPECT_EQ(200, result->status);
  6389. }
  6390. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6391. {
  6392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6393. ASSERT_TRUE(svr.is_valid());
  6394. svr.Get("/sni", [&](const Request &req, Response &res) {
  6395. std::string expected;
  6396. if (req.ssl) {
  6397. if (const char *sni =
  6398. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6399. expected = sni;
  6400. }
  6401. }
  6402. EXPECT_EQ(expected, req.get_param_value("expected"));
  6403. res.set_content("ok", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. {
  6413. SSLClient cli("localhost", PORT);
  6414. cli.enable_server_certificate_verification(false);
  6415. auto res = cli.Get("/sni?expected=localhost");
  6416. ASSERT_TRUE(res);
  6417. }
  6418. {
  6419. SSLClient cli("::1", PORT);
  6420. cli.enable_server_certificate_verification(false);
  6421. auto res = cli.Get("/sni?expected=");
  6422. ASSERT_TRUE(res);
  6423. }
  6424. }
  6425. }
  6426. #endif
  6427. TEST(ClientProblemDetectionTest, ContentProvider) {
  6428. Server svr;
  6429. size_t content_length = 1024 * 1024;
  6430. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6431. res.set_content_provider(
  6432. content_length, "text/plain",
  6433. [&](size_t offset, size_t length, DataSink &sink) {
  6434. auto out_len = std::min(length, static_cast<size_t>(1024));
  6435. std::string out(out_len, '@');
  6436. sink.write(out.data(), out_len);
  6437. return offset < 4096;
  6438. },
  6439. [](bool success) { ASSERT_FALSE(success); });
  6440. });
  6441. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6442. res.set_content_provider(
  6443. 0, "text/plain",
  6444. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6445. EXPECT_TRUE(false);
  6446. return true;
  6447. },
  6448. [](bool success) { ASSERT_FALSE(success); });
  6449. });
  6450. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6451. auto se = detail::scope_exit([&] {
  6452. svr.stop();
  6453. listen_thread.join();
  6454. ASSERT_FALSE(svr.is_running());
  6455. });
  6456. svr.wait_until_ready();
  6457. Client cli("localhost", PORT);
  6458. {
  6459. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6460. size_t /*data_length*/) { return false; });
  6461. ASSERT_FALSE(res);
  6462. }
  6463. {
  6464. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6465. size_t /*data_length*/) { return false; });
  6466. ASSERT_TRUE(res);
  6467. }
  6468. }
  6469. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6470. Server svr;
  6471. svr.set_error_handler([](Request const &, Response &res) -> void {
  6472. res.set_chunked_content_provider(
  6473. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6474. sink.os << "hello";
  6475. sink.os << "world";
  6476. sink.done();
  6477. return true;
  6478. });
  6479. });
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. Client cli("localhost", PORT);
  6488. auto res = cli.Get("/");
  6489. ASSERT_TRUE(res);
  6490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6491. EXPECT_EQ("helloworld", res->body);
  6492. }
  6493. TEST(LongPollingTest, ClientCloseDetection) {
  6494. Server svr;
  6495. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6496. res.set_chunked_content_provider(
  6497. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6498. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6499. sink.os << "hello";
  6500. auto count = 10;
  6501. while (count > 0 && sink.is_writable()) {
  6502. this_thread::sleep_for(chrono::milliseconds(10));
  6503. count--;
  6504. }
  6505. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6506. return true;
  6507. });
  6508. });
  6509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6510. auto se = detail::scope_exit([&] {
  6511. svr.stop();
  6512. listen_thread.join();
  6513. ASSERT_FALSE(svr.is_running());
  6514. });
  6515. svr.wait_until_ready();
  6516. Client cli("localhost", PORT);
  6517. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6518. EXPECT_EQ("hello", string(data, data_length));
  6519. return false; // close the socket immediately.
  6520. });
  6521. ASSERT_FALSE(res);
  6522. }
  6523. TEST(GetWithParametersTest, GetWithParameters) {
  6524. Server svr;
  6525. svr.Get("/", [&](const Request &req, Response &) {
  6526. EXPECT_EQ("world", req.get_param_value("hello"));
  6527. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6528. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6529. });
  6530. svr.Get("/params", [&](const Request &req, Response &) {
  6531. EXPECT_EQ("world", req.get_param_value("hello"));
  6532. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6533. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6534. });
  6535. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6536. EXPECT_EQ("resource-id", req.matches[1]);
  6537. EXPECT_EQ("foo", req.get_param_value("param1"));
  6538. EXPECT_EQ("bar", req.get_param_value("param2"));
  6539. });
  6540. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6541. EXPECT_EQ("user-id", req.path_params.at("id"));
  6542. EXPECT_EQ("foo", req.get_param_value("param1"));
  6543. EXPECT_EQ("bar", req.get_param_value("param2"));
  6544. });
  6545. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6546. auto se = detail::scope_exit([&] {
  6547. svr.stop();
  6548. listen_thread.join();
  6549. ASSERT_FALSE(svr.is_running());
  6550. });
  6551. svr.wait_until_ready();
  6552. {
  6553. Client cli(HOST, PORT);
  6554. Params params;
  6555. params.emplace("hello", "world");
  6556. params.emplace("hello2", "world2");
  6557. params.emplace("hello3", "world3");
  6558. auto res = cli.Get("/", params, Headers{});
  6559. ASSERT_TRUE(res);
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. }
  6562. {
  6563. Client cli(HOST, PORT);
  6564. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6565. ASSERT_TRUE(res);
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. }
  6568. {
  6569. Client cli(HOST, PORT);
  6570. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6571. ASSERT_TRUE(res);
  6572. EXPECT_EQ(StatusCode::OK_200, res->status);
  6573. }
  6574. {
  6575. Client cli(HOST, PORT);
  6576. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. }
  6581. TEST(GetWithParametersTest, GetWithParameters2) {
  6582. Server svr;
  6583. svr.Get("/", [&](const Request &req, Response &res) {
  6584. auto text = req.get_param_value("hello");
  6585. res.set_content(text, "text/plain");
  6586. });
  6587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6588. auto se = detail::scope_exit([&] {
  6589. svr.stop();
  6590. listen_thread.join();
  6591. ASSERT_FALSE(svr.is_running());
  6592. });
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. Params params;
  6596. params.emplace("hello", "world");
  6597. std::string body;
  6598. auto res = cli.Get("/", params, Headers{},
  6599. [&](const char *data, size_t data_length) {
  6600. body.append(data, data_length);
  6601. return true;
  6602. });
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ("world", body);
  6606. }
  6607. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6609. auto host = "httpbin.org";
  6610. auto path = std::string{"/range/32"};
  6611. #else
  6612. auto host = "nghttp2.org";
  6613. auto path = std::string{"/httpbin/range/32"};
  6614. #endif
  6615. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6616. SSLClient cli(host);
  6617. #else
  6618. Client cli(host);
  6619. #endif
  6620. cli.set_default_headers({make_range_header({{1, 10}})});
  6621. cli.set_connection_timeout(5);
  6622. {
  6623. auto res = cli.Get(path);
  6624. ASSERT_TRUE(res);
  6625. EXPECT_EQ("bcdefghijk", res->body);
  6626. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6627. }
  6628. {
  6629. auto res = cli.Get(path);
  6630. ASSERT_TRUE(res);
  6631. EXPECT_EQ("bcdefghijk", res->body);
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. }
  6634. }
  6635. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6636. Server svr;
  6637. svr.set_default_headers({{"Hello", "World"}});
  6638. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6639. res.set_content("ok", "text/plain");
  6640. });
  6641. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6642. auto se = detail::scope_exit([&] {
  6643. svr.stop();
  6644. listen_thread.join();
  6645. ASSERT_FALSE(svr.is_running());
  6646. });
  6647. svr.wait_until_ready();
  6648. Client cli("localhost", PORT);
  6649. auto res = cli.Get("/");
  6650. ASSERT_TRUE(res);
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. EXPECT_EQ("ok", res->body);
  6653. EXPECT_EQ("World", res->get_header_value("Hello"));
  6654. }
  6655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6656. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6658. ASSERT_TRUE(svr.is_valid());
  6659. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6660. std::this_thread::sleep_for(std::chrono::seconds(2));
  6661. res.set_content("a", "text/plain");
  6662. });
  6663. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6664. res.set_content("b", "text/plain");
  6665. });
  6666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6667. auto se = detail::scope_exit([&] {
  6668. svr.stop();
  6669. listen_thread.join();
  6670. ASSERT_FALSE(svr.is_running());
  6671. });
  6672. svr.wait_until_ready();
  6673. SSLClient cli("localhost", PORT);
  6674. cli.enable_server_certificate_verification(false);
  6675. cli.set_keep_alive(true);
  6676. cli.set_read_timeout(std::chrono::seconds(1));
  6677. auto resa = cli.Get("/a");
  6678. ASSERT_TRUE(!resa);
  6679. EXPECT_EQ(Error::Read, resa.error());
  6680. auto resb = cli.Get("/b");
  6681. ASSERT_TRUE(resb);
  6682. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6683. EXPECT_EQ("b", resb->body);
  6684. }
  6685. #endif
  6686. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6687. protected:
  6688. ServerTestWithAI_PASSIVE()
  6689. : cli_(HOST, PORT)
  6690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6691. ,
  6692. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6693. #endif
  6694. {
  6695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6696. cli_.enable_server_certificate_verification(false);
  6697. #endif
  6698. }
  6699. virtual void SetUp() {
  6700. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6701. res.set_content("Hello World!", "text/plain");
  6702. });
  6703. t_ = thread(
  6704. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6705. svr_.wait_until_ready();
  6706. }
  6707. virtual void TearDown() {
  6708. svr_.stop();
  6709. t_.join();
  6710. }
  6711. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6712. SSLClient cli_;
  6713. SSLServer svr_;
  6714. #else
  6715. Client cli_;
  6716. Server svr_;
  6717. #endif
  6718. thread t_;
  6719. };
  6720. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6721. auto res = cli_.Get("/hi");
  6722. ASSERT_TRUE(res);
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6725. EXPECT_EQ("Hello World!", res->body);
  6726. }
  6727. class ServerUpDownTest : public ::testing::Test {
  6728. protected:
  6729. ServerUpDownTest() : cli_(HOST, PORT) {}
  6730. virtual void SetUp() {
  6731. t_ = thread([&]() {
  6732. svr_.bind_to_any_port(HOST);
  6733. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6734. ASSERT_TRUE(svr_.listen_after_bind());
  6735. });
  6736. svr_.wait_until_ready();
  6737. }
  6738. virtual void TearDown() {
  6739. svr_.stop();
  6740. t_.join();
  6741. }
  6742. Client cli_;
  6743. Server svr_;
  6744. thread t_;
  6745. };
  6746. TEST_F(ServerUpDownTest, QuickStartStop) {
  6747. // Should not crash, especially when run with
  6748. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6749. }
  6750. class PayloadMaxLengthTest : public ::testing::Test {
  6751. protected:
  6752. PayloadMaxLengthTest()
  6753. : cli_(HOST, PORT)
  6754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6755. ,
  6756. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6757. #endif
  6758. {
  6759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6760. cli_.enable_server_certificate_verification(false);
  6761. #endif
  6762. }
  6763. virtual void SetUp() {
  6764. svr_.set_payload_max_length(8);
  6765. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6766. res.set_content("test", "text/plain");
  6767. });
  6768. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6769. svr_.wait_until_ready();
  6770. }
  6771. virtual void TearDown() {
  6772. svr_.stop();
  6773. t_.join();
  6774. }
  6775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6776. SSLClient cli_;
  6777. SSLServer svr_;
  6778. #else
  6779. Client cli_;
  6780. Server svr_;
  6781. #endif
  6782. thread t_;
  6783. };
  6784. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6785. auto res = cli_.Post("/test", "123456789", "text/plain");
  6786. ASSERT_TRUE(res);
  6787. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6788. res = cli_.Post("/test", "12345678", "text/plain");
  6789. ASSERT_TRUE(res);
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. }
  6792. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6793. // Test chunked encoding with payload exceeding the 8-byte limit
  6794. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6795. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6796. ASSERT_TRUE(res);
  6797. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6798. }
  6799. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6800. // Test chunked encoding with payload within the 8-byte limit
  6801. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6802. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6803. ASSERT_TRUE(res);
  6804. EXPECT_EQ(StatusCode::OK_200, res->status);
  6805. }
  6806. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6807. // Test using send_request to send chunked data exceeding payload limit
  6808. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6809. "Host: " +
  6810. std::string(HOST) + ":" + std::to_string(PORT) +
  6811. "\r\n"
  6812. "Transfer-Encoding: chunked\r\n"
  6813. "Connection: close\r\n"
  6814. "\r\n"
  6815. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6816. "0123456789\r\n"
  6817. "0\r\n" // End chunk
  6818. "\r\n";
  6819. std::string response;
  6820. bool result = send_request(1, chunked_request, &response);
  6821. if (!result) {
  6822. // If send_request fails, it might be because the server closed the
  6823. // connection due to payload limit enforcement, which is acceptable
  6824. SUCCEED()
  6825. << "Server rejected oversized chunked request (connection closed)";
  6826. } else {
  6827. // If we got a response, check if it's an error response or connection was
  6828. // closed early Short response length indicates connection was closed due to
  6829. // payload limit
  6830. if (response.length() <= 10) {
  6831. SUCCEED() << "Server closed connection for oversized chunked request";
  6832. } else {
  6833. // Check for error status codes
  6834. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6835. response.find("Payload Too Large") != std::string::npos ||
  6836. response.find("400") != std::string::npos);
  6837. }
  6838. }
  6839. }
  6840. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6841. // Test request without Content-Length header exceeding payload limit
  6842. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6843. "Host: " +
  6844. std::string(HOST) + ":" +
  6845. std::to_string(PORT) +
  6846. "\r\n"
  6847. "Connection: close\r\n"
  6848. "\r\n";
  6849. // Add payload exceeding the 8-byte limit
  6850. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6851. request_without_content_length += large_payload;
  6852. std::string response;
  6853. bool result = send_request(1, request_without_content_length, &response);
  6854. if (!result) {
  6855. // If send_request fails, server likely closed connection due to payload
  6856. // limit
  6857. SUCCEED() << "Server rejected oversized request without Content-Length "
  6858. "(connection closed)";
  6859. } else {
  6860. // Check if server responded with error or closed connection early
  6861. if (response.length() <= 10) {
  6862. SUCCEED() << "Server closed connection for oversized request without "
  6863. "Content-Length";
  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, NoContentLengthWithinLimit) {
  6873. // Test request without Content-Length header within 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 within the 8-byte limit
  6882. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6883. request_without_content_length += small_payload;
  6884. std::string response;
  6885. bool result = send_request(1, request_without_content_length, &response);
  6886. // For requests without Content-Length, the server may have different behavior
  6887. // The key is that it should not reject due to payload limit for small
  6888. // payloads
  6889. if (result) {
  6890. // Check for any HTTP response (success or error, but not connection closed)
  6891. if (response.length() > 10) {
  6892. SUCCEED()
  6893. << "Server processed request without Content-Length within limit";
  6894. } else {
  6895. // Short response might indicate connection closed, which is acceptable
  6896. SUCCEED() << "Server closed connection for request without "
  6897. "Content-Length (acceptable behavior)";
  6898. }
  6899. } else {
  6900. // Connection failure might be due to protocol requirements
  6901. SUCCEED() << "Connection issue with request without Content-Length "
  6902. "(environment-specific)";
  6903. }
  6904. }
  6905. class LargePayloadMaxLengthTest : public ::testing::Test {
  6906. protected:
  6907. LargePayloadMaxLengthTest()
  6908. : cli_(HOST, PORT)
  6909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6910. ,
  6911. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6912. #endif
  6913. {
  6914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6915. cli_.enable_server_certificate_verification(false);
  6916. #endif
  6917. }
  6918. virtual void SetUp() {
  6919. // Set 10MB payload limit
  6920. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6921. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6922. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6923. res.set_content("Large payload test", "text/plain");
  6924. });
  6925. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6926. svr_.wait_until_ready();
  6927. }
  6928. virtual void TearDown() {
  6929. svr_.stop();
  6930. t_.join();
  6931. }
  6932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6933. SSLClient cli_;
  6934. SSLServer svr_;
  6935. #else
  6936. Client cli_;
  6937. Server svr_;
  6938. #endif
  6939. thread t_;
  6940. };
  6941. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6942. // Test chunked encoding with payload within 10MB limit
  6943. std::string medium_payload(5 * 1024 * 1024,
  6944. 'A'); // 5MB payload, within 10MB limit
  6945. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6946. ASSERT_TRUE(res);
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6950. // Test chunked encoding with payload exceeding 10MB limit
  6951. std::string large_payload(12 * 1024 * 1024,
  6952. 'B'); // 12MB payload, exceeds 10MB limit
  6953. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6954. ASSERT_TRUE(res);
  6955. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6956. }
  6957. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6958. // Test request without Content-Length header within 10MB limit
  6959. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6960. "Host: " +
  6961. std::string(HOST) + ":" +
  6962. std::to_string(PORT) +
  6963. "\r\n"
  6964. "Connection: close\r\n"
  6965. "\r\n";
  6966. // Add 1MB payload (within 10MB limit)
  6967. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6968. request_without_content_length += medium_payload;
  6969. std::string response;
  6970. bool result = send_request(5, request_without_content_length, &response);
  6971. if (result) {
  6972. // Should get a proper HTTP response for payloads within limit
  6973. if (response.length() > 10) {
  6974. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6975. "10MB limit";
  6976. } else {
  6977. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6978. "Content-Length)";
  6979. }
  6980. } else {
  6981. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6982. }
  6983. }
  6984. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6985. // Test request without Content-Length header exceeding 10MB limit
  6986. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6987. "Host: " +
  6988. std::string(HOST) + ":" +
  6989. std::to_string(PORT) +
  6990. "\r\n"
  6991. "Connection: close\r\n"
  6992. "\r\n";
  6993. // Add 12MB payload (exceeds 10MB limit)
  6994. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6995. request_without_content_length += large_payload;
  6996. std::string response;
  6997. bool result = send_request(10, request_without_content_length, &response);
  6998. if (!result) {
  6999. // Server should close connection due to payload limit
  7000. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7001. "(connection closed)";
  7002. } else {
  7003. // Check for error response
  7004. if (response.length() <= 10) {
  7005. SUCCEED()
  7006. << "Server closed connection for 12MB request exceeding 10MB limit";
  7007. } else {
  7008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7009. response.find("Payload Too Large") != std::string::npos ||
  7010. response.find("400") != std::string::npos);
  7011. }
  7012. }
  7013. }
  7014. TEST(HostAndPortPropertiesTest, NoSSL) {
  7015. httplib::Client cli("www.google.com", 1234);
  7016. ASSERT_EQ("www.google.com", cli.host());
  7017. ASSERT_EQ(1234, cli.port());
  7018. }
  7019. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7020. httplib::Client cli("www.google.com:1234");
  7021. ASSERT_EQ("www.google.com", cli.host());
  7022. ASSERT_EQ(1234, cli.port());
  7023. }
  7024. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7025. TEST(HostAndPortPropertiesTest, SSL) {
  7026. httplib::SSLClient cli("www.google.com");
  7027. ASSERT_EQ("www.google.com", cli.host());
  7028. ASSERT_EQ(443, cli.port());
  7029. }
  7030. #endif
  7031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7032. TEST(SSLClientTest, UpdateCAStore) {
  7033. httplib::SSLClient httplib_client("www.google.com");
  7034. auto ca_store_1 = X509_STORE_new();
  7035. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7036. nullptr);
  7037. httplib_client.set_ca_cert_store(ca_store_1);
  7038. auto ca_store_2 = X509_STORE_new();
  7039. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7040. nullptr);
  7041. httplib_client.set_ca_cert_store(ca_store_2);
  7042. }
  7043. TEST(SSLClientTest, ServerNameIndication_Online) {
  7044. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7045. auto host = "httpbin.org";
  7046. auto path = std::string{"/get"};
  7047. #else
  7048. auto host = "nghttp2.org";
  7049. auto path = std::string{"/httpbin/get"};
  7050. #endif
  7051. SSLClient cli(host, 443);
  7052. auto res = cli.Get(path);
  7053. ASSERT_TRUE(res);
  7054. ASSERT_EQ(StatusCode::OK_200, res->status);
  7055. }
  7056. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7057. // Use a site that will cause SSL verification failure due to self-signed cert
  7058. SSLClient cli("self-signed.badssl.com", 443);
  7059. cli.enable_server_certificate_verification(true);
  7060. auto res = cli.Get("/");
  7061. ASSERT_TRUE(!res);
  7062. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7063. // For SSL server verification errors, ssl_error should be 0, only
  7064. // ssl_openssl_error should be set
  7065. EXPECT_EQ(0, res.ssl_error());
  7066. // Verify OpenSSL error is captured for SSLServerVerification
  7067. // This occurs when SSL_get_verify_result() returns a verification failure
  7068. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7069. res.ssl_openssl_error());
  7070. }
  7071. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7072. // Use a site where hostname doesn't match the certificate
  7073. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7074. SSLClient cli("wrong.host.badssl.com", 443);
  7075. cli.enable_server_certificate_verification(true);
  7076. cli.enable_server_hostname_verification(true);
  7077. auto res = cli.Get("/");
  7078. ASSERT_TRUE(!res);
  7079. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7080. // For SSL hostname verification errors, ssl_error should be 0, only
  7081. // ssl_openssl_error should be set
  7082. EXPECT_EQ(0, res.ssl_error());
  7083. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7084. // This occurs when verify_host() fails due to hostname mismatch
  7085. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7086. res.ssl_openssl_error());
  7087. }
  7088. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7089. Client cli("https://google.com");
  7090. auto res = cli.Get("/");
  7091. ASSERT_TRUE(res);
  7092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7093. }
  7094. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7095. SSLClient cli("google.com");
  7096. cli.set_ca_cert_path(CA_CERT_FILE);
  7097. auto res = cli.Get("/");
  7098. ASSERT_TRUE(res);
  7099. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7100. }
  7101. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7102. SSLClient cli("google.com");
  7103. cli.enable_server_certificate_verification(true);
  7104. cli.set_ca_cert_path("hello");
  7105. auto res = cli.Get("/");
  7106. ASSERT_TRUE(!res);
  7107. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7108. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7109. // should be set
  7110. EXPECT_EQ(0, res.ssl_error());
  7111. // Verify OpenSSL error is captured for SSLLoadingCerts
  7112. // This error occurs when SSL_CTX_load_verify_locations() fails
  7113. // > openssl errstr 0x80000002
  7114. // error:80000002:system library::No such file or directory
  7115. // > openssl errstr 0xA000126
  7116. // error:0A000126:SSL routines::unexpected eof while reading
  7117. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7118. res.ssl_openssl_error() == 0xA000126);
  7119. }
  7120. TEST(SSLClientTest, ServerCertificateVerification4) {
  7121. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7122. ASSERT_TRUE(svr.is_valid());
  7123. svr.Get("/test", [&](const Request &, Response &res) {
  7124. res.set_content("test", "text/plain");
  7125. svr.stop();
  7126. ASSERT_TRUE(true);
  7127. });
  7128. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7129. auto se = detail::scope_exit([&] {
  7130. t.join();
  7131. ASSERT_FALSE(svr.is_running());
  7132. });
  7133. svr.wait_until_ready();
  7134. SSLClient cli("127.0.0.1", PORT);
  7135. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7136. cli.enable_server_certificate_verification(true);
  7137. cli.set_connection_timeout(30);
  7138. auto res = cli.Get("/test");
  7139. ASSERT_TRUE(res);
  7140. ASSERT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7143. std::string cert;
  7144. read_file(CA_CERT_FILE, cert);
  7145. SSLClient cli("google.com");
  7146. cli.load_ca_cert_store(cert.data(), cert.size());
  7147. const auto res = cli.Get("/");
  7148. ASSERT_TRUE(res);
  7149. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7150. }
  7151. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7152. // clang-format off
  7153. static constexpr char cert[] =
  7154. "GlobalSign Root CA\n"
  7155. "==================\n"
  7156. "-----BEGIN CERTIFICATE-----\n"
  7157. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7158. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7159. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7160. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7161. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7162. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7163. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7164. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7165. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7166. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7167. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7168. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7169. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7170. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7171. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7172. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7173. "-----END CERTIFICATE-----\n";
  7174. // clang-format on
  7175. SSLClient cli("google.com");
  7176. cli.load_ca_cert_store(cert, sizeof(cert));
  7177. const auto res = cli.Get("/");
  7178. ASSERT_TRUE(res);
  7179. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7180. }
  7181. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7182. SSLClient cli("www.youtube.com");
  7183. cli.set_ca_cert_path(CA_CERT_FILE);
  7184. cli.enable_server_certificate_verification(true);
  7185. cli.set_follow_location(true);
  7186. auto res = cli.Get("/");
  7187. ASSERT_TRUE(res);
  7188. ASSERT_EQ(StatusCode::OK_200, res->status);
  7189. }
  7190. TEST(SSLClientTest, Issue2004_Online) {
  7191. Client client("https://google.com");
  7192. client.set_follow_location(true);
  7193. auto res = client.Get("/");
  7194. ASSERT_TRUE(res);
  7195. ASSERT_EQ(StatusCode::OK_200, res->status);
  7196. auto body = res->body;
  7197. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7198. }
  7199. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7200. // Create SSLClient with invalid cert/key to make is_valid() return false
  7201. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7202. "nonexistent_key.pem");
  7203. // is_valid() should be false due to cert loading failure
  7204. ASSERT_FALSE(cli.is_valid());
  7205. auto res = cli.Get("/");
  7206. ASSERT_FALSE(res);
  7207. EXPECT_EQ(Error::SSLConnection, res.error());
  7208. }
  7209. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7210. // Test for Issue #2251: SSL error not properly reported when client cert
  7211. // and key paths are swapped or mismatched
  7212. // This simulates the scenario where user accidentally swaps the cert and key
  7213. // files
  7214. // Using client cert file as private key and vice versa (completely wrong)
  7215. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7216. // Should fail validation due to cert/key mismatch
  7217. ASSERT_FALSE(cli.is_valid());
  7218. // Attempt to make a request should fail with proper error
  7219. auto res = cli.Get("/");
  7220. ASSERT_FALSE(res);
  7221. EXPECT_EQ(Error::SSLConnection, res.error());
  7222. // SSL error should be recorded in the Result object (this is the key fix for
  7223. // Issue #2251)
  7224. auto openssl_error = res.ssl_openssl_error();
  7225. EXPECT_NE(0u, openssl_error);
  7226. }
  7227. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7228. // Another variant: using valid file paths but with mismatched cert/key pair
  7229. // This tests the case where files exist but contain incompatible key material
  7230. // Using client cert with wrong key (cert2 key)
  7231. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7232. // Should fail validation
  7233. ASSERT_FALSE(cli.is_valid());
  7234. auto res = cli.Get("/");
  7235. ASSERT_FALSE(res);
  7236. // Must report error properly, not appear as success
  7237. EXPECT_EQ(Error::SSLConnection, res.error());
  7238. // OpenSSL error should be captured in Result
  7239. EXPECT_NE(0u, res.ssl_openssl_error());
  7240. }
  7241. #if 0
  7242. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7243. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7244. ASSERT_TRUE(cli != nullptr);
  7245. cli->set_address_family(AF_INET6);
  7246. cli->set_interface("en0");
  7247. auto res = cli->Get("/get");
  7248. ASSERT_TRUE(res);
  7249. ASSERT_EQ(StatusCode::OK_200, res->status);
  7250. }
  7251. #endif
  7252. void ClientCertPresent(
  7253. const std::string &client_cert_file,
  7254. const std::string &client_private_key_file,
  7255. const std::string &client_encrypted_private_key_pass = std::string()) {
  7256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7257. CLIENT_CA_CERT_DIR);
  7258. ASSERT_TRUE(svr.is_valid());
  7259. svr.Get("/test", [&](const Request &req, Response &res) {
  7260. res.set_content("test", "text/plain");
  7261. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7262. ASSERT_TRUE(peer_cert != nullptr);
  7263. auto subject_name = X509_get_subject_name(peer_cert);
  7264. ASSERT_TRUE(subject_name != nullptr);
  7265. std::string common_name;
  7266. {
  7267. char name[BUFSIZ];
  7268. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7269. name, sizeof(name));
  7270. common_name.assign(name, static_cast<size_t>(name_len));
  7271. }
  7272. EXPECT_EQ("Common Name", common_name);
  7273. X509_free(peer_cert);
  7274. });
  7275. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7276. auto se = detail::scope_exit([&] {
  7277. svr.stop();
  7278. t.join();
  7279. ASSERT_FALSE(svr.is_running());
  7280. });
  7281. svr.wait_until_ready();
  7282. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7283. client_encrypted_private_key_pass);
  7284. cli.enable_server_certificate_verification(false);
  7285. cli.set_connection_timeout(30);
  7286. auto res = cli.Get("/test");
  7287. ASSERT_TRUE(res);
  7288. ASSERT_EQ(StatusCode::OK_200, res->status);
  7289. }
  7290. TEST(SSLClientServerTest, ClientCertPresent) {
  7291. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7292. }
  7293. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7294. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7295. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7296. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7297. }
  7298. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7299. void MemoryClientCertPresent(
  7300. const std::string &client_cert_file,
  7301. const std::string &client_private_key_file,
  7302. const std::string &client_encrypted_private_key_pass = std::string()) {
  7303. auto f = fopen(SERVER_CERT_FILE, "r+");
  7304. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7305. fclose(f);
  7306. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7307. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7308. fclose(f);
  7309. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7310. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7311. auto client_ca_cert_store = X509_STORE_new();
  7312. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7313. X509_free(client_cert);
  7314. fclose(f);
  7315. f = fopen(client_cert_file.c_str(), "r+");
  7316. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7317. fclose(f);
  7318. f = fopen(client_private_key_file.c_str(), "r+");
  7319. auto client_private_key = PEM_read_PrivateKey(
  7320. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7321. fclose(f);
  7322. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7323. ASSERT_TRUE(svr.is_valid());
  7324. svr.Get("/test", [&](const Request &req, Response &res) {
  7325. res.set_content("test", "text/plain");
  7326. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7327. ASSERT_TRUE(peer_cert != nullptr);
  7328. auto subject_name = X509_get_subject_name(peer_cert);
  7329. ASSERT_TRUE(subject_name != nullptr);
  7330. std::string common_name;
  7331. {
  7332. char name[BUFSIZ];
  7333. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7334. name, sizeof(name));
  7335. common_name.assign(name, static_cast<size_t>(name_len));
  7336. }
  7337. EXPECT_EQ("Common Name", common_name);
  7338. X509_free(peer_cert);
  7339. });
  7340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7341. auto se = detail::scope_exit([&] {
  7342. svr.stop();
  7343. t.join();
  7344. ASSERT_FALSE(svr.is_running());
  7345. });
  7346. svr.wait_until_ready();
  7347. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7348. client_encrypted_private_key_pass);
  7349. cli.enable_server_certificate_verification(false);
  7350. cli.set_connection_timeout(30);
  7351. auto res = cli.Get("/test");
  7352. ASSERT_TRUE(res);
  7353. ASSERT_EQ(StatusCode::OK_200, res->status);
  7354. X509_free(server_cert);
  7355. EVP_PKEY_free(server_private_key);
  7356. X509_free(client_cert);
  7357. EVP_PKEY_free(client_private_key);
  7358. }
  7359. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7360. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7361. }
  7362. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7363. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7364. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7365. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7366. }
  7367. #endif
  7368. TEST(SSLClientServerTest, ClientCertMissing) {
  7369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7370. CLIENT_CA_CERT_DIR);
  7371. ASSERT_TRUE(svr.is_valid());
  7372. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7373. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. t.join();
  7377. ASSERT_FALSE(svr.is_running());
  7378. });
  7379. svr.wait_until_ready();
  7380. SSLClient cli(HOST, PORT);
  7381. cli.set_connection_timeout(30);
  7382. auto res = cli.Get("/test");
  7383. ASSERT_TRUE(!res);
  7384. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7385. // For SSL server verification errors, ssl_error should be 0, only
  7386. // ssl_openssl_error should be set
  7387. EXPECT_EQ(0, res.ssl_error());
  7388. // Verify OpenSSL error is captured for SSLServerVerification
  7389. // Note: This test may have different error codes depending on the exact
  7390. // verification failure
  7391. EXPECT_NE(0UL, res.ssl_openssl_error());
  7392. }
  7393. TEST(SSLClientServerTest, TrustDirOptional) {
  7394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7395. ASSERT_TRUE(svr.is_valid());
  7396. svr.Get("/test", [&](const Request &, Response &res) {
  7397. res.set_content("test", "text/plain");
  7398. });
  7399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7400. auto se = detail::scope_exit([&] {
  7401. svr.stop();
  7402. t.join();
  7403. ASSERT_FALSE(svr.is_running());
  7404. });
  7405. svr.wait_until_ready();
  7406. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7407. cli.enable_server_certificate_verification(false);
  7408. cli.set_connection_timeout(30);
  7409. auto res = cli.Get("/test");
  7410. ASSERT_TRUE(res);
  7411. ASSERT_EQ(StatusCode::OK_200, res->status);
  7412. }
  7413. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7414. class NoListenSSLServer : public SSLServer {
  7415. public:
  7416. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7417. const char *client_ca_cert_file_path,
  7418. const char *client_ca_cert_dir_path = nullptr)
  7419. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7420. client_ca_cert_dir_path),
  7421. stop_(false) {}
  7422. std::atomic_bool stop_;
  7423. private:
  7424. bool process_and_close_socket(socket_t /*sock*/) override {
  7425. // Don't create SSL context
  7426. while (!stop_.load()) {
  7427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7428. }
  7429. return true;
  7430. }
  7431. };
  7432. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7433. CLIENT_CA_CERT_FILE);
  7434. ASSERT_TRUE(svr.is_valid());
  7435. svr.Get("/test", [&](const Request &, Response &res) {
  7436. res.set_content("test", "text/plain");
  7437. });
  7438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7439. auto se = detail::scope_exit([&] {
  7440. svr.stop_ = true;
  7441. svr.stop();
  7442. t.join();
  7443. ASSERT_FALSE(svr.is_running());
  7444. });
  7445. svr.wait_until_ready();
  7446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7447. cli.enable_server_certificate_verification(false);
  7448. cli.set_connection_timeout(1);
  7449. auto res = cli.Get("/test");
  7450. ASSERT_TRUE(!res);
  7451. EXPECT_EQ(Error::SSLConnection, res.error());
  7452. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7453. }
  7454. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7455. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7456. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7457. SSL_CTX_set_options(&ssl_ctx,
  7458. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7459. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7460. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7461. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7462. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7463. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7464. "ECDHE-DSS-AES128-SHA256:"
  7465. "ECDHE-RSA-AES256-SHA256:"
  7466. "ECDHE-DSS-AES256-SHA256:";
  7467. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7468. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7469. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7470. SSL_FILETYPE_PEM) != 1) {
  7471. return false;
  7472. }
  7473. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7474. CLIENT_CA_CERT_DIR);
  7475. SSL_CTX_set_verify(
  7476. &ssl_ctx,
  7477. SSL_VERIFY_PEER |
  7478. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7479. nullptr);
  7480. return true;
  7481. };
  7482. SSLServer svr(setup_ssl_ctx_callback);
  7483. ASSERT_TRUE(svr.is_valid());
  7484. svr.Get("/test", [&](const Request &req, Response &res) {
  7485. res.set_content("test", "text/plain");
  7486. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7487. ASSERT_TRUE(peer_cert != nullptr);
  7488. auto subject_name = X509_get_subject_name(peer_cert);
  7489. ASSERT_TRUE(subject_name != nullptr);
  7490. std::string common_name;
  7491. {
  7492. char name[BUFSIZ];
  7493. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7494. name, sizeof(name));
  7495. common_name.assign(name, static_cast<size_t>(name_len));
  7496. }
  7497. EXPECT_EQ("Common Name", common_name);
  7498. X509_free(peer_cert);
  7499. });
  7500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7501. auto se = detail::scope_exit([&] {
  7502. svr.stop();
  7503. t.join();
  7504. ASSERT_FALSE(svr.is_running());
  7505. });
  7506. svr.wait_until_ready();
  7507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7508. cli.enable_server_certificate_verification(false);
  7509. cli.set_connection_timeout(30);
  7510. auto res = cli.Get("/test");
  7511. ASSERT_TRUE(res);
  7512. ASSERT_EQ(StatusCode::OK_200, res->status);
  7513. }
  7514. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7516. ASSERT_TRUE(svr.is_valid());
  7517. // Set up a handler to verify client certificate is present
  7518. bool client_cert_verified = false;
  7519. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7520. // Verify that client certificate was provided
  7521. client_cert_verified = true;
  7522. res.set_content("success", "text/plain");
  7523. });
  7524. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7525. auto se = detail::scope_exit([&] {
  7526. svr.stop();
  7527. t.join();
  7528. ASSERT_FALSE(svr.is_running());
  7529. });
  7530. svr.wait_until_ready();
  7531. // Client with certificate
  7532. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7533. cli.enable_server_certificate_verification(false);
  7534. cli.set_connection_timeout(30);
  7535. auto res = cli.Get("/test");
  7536. ASSERT_TRUE(res);
  7537. ASSERT_EQ(StatusCode::OK_200, res->status);
  7538. ASSERT_TRUE(client_cert_verified);
  7539. EXPECT_EQ("success", res->body);
  7540. }
  7541. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7542. // Test that when client CA cert file is provided,
  7543. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7544. // Create a server with client authentication
  7545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7546. ASSERT_TRUE(svr.is_valid());
  7547. // We can't directly access the SSL_CTX from SSLServer to verify,
  7548. // but we can test that the server properly requests client certificates
  7549. // and accepts valid ones from the specified CA
  7550. bool handler_called = false;
  7551. svr.Get("/test", [&](const Request &req, Response &res) {
  7552. handler_called = true;
  7553. // Verify that a client certificate was provided
  7554. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7555. ASSERT_TRUE(peer_cert != nullptr);
  7556. // Get the issuer name
  7557. auto issuer_name = X509_get_issuer_name(peer_cert);
  7558. ASSERT_TRUE(issuer_name != nullptr);
  7559. char issuer_buf[256];
  7560. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7561. // The client certificate should be issued by our test CA
  7562. std::string issuer_str(issuer_buf);
  7563. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7564. X509_free(peer_cert);
  7565. res.set_content("authenticated", "text/plain");
  7566. });
  7567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7568. auto se = detail::scope_exit([&] {
  7569. svr.stop();
  7570. t.join();
  7571. ASSERT_FALSE(svr.is_running());
  7572. });
  7573. svr.wait_until_ready();
  7574. // Connect with a client certificate issued by the CA
  7575. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7576. cli.enable_server_certificate_verification(false);
  7577. cli.set_connection_timeout(30);
  7578. auto res = cli.Get("/test");
  7579. ASSERT_TRUE(res);
  7580. ASSERT_EQ(StatusCode::OK_200, res->status);
  7581. ASSERT_TRUE(handler_called);
  7582. EXPECT_EQ("authenticated", res->body);
  7583. }
  7584. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7585. // Test 1: Valid CA file - no error should be recorded
  7586. {
  7587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7588. CLIENT_CA_CERT_FILE);
  7589. ASSERT_TRUE(svr.is_valid());
  7590. // With valid setup, last_ssl_error should be 0
  7591. EXPECT_EQ(0, svr.ssl_last_error());
  7592. }
  7593. // Test 2: Invalid CA file content
  7594. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7595. {
  7596. // Create a temporary file with completely invalid content
  7597. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7598. {
  7599. std::ofstream ofs(temp_invalid_ca);
  7600. ofs << "This is not a certificate file at all\n";
  7601. ofs << "Just plain text content\n";
  7602. }
  7603. // Create server with invalid CA file
  7604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7605. // Clean up temporary file
  7606. std::remove(temp_invalid_ca);
  7607. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7608. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7609. // Note: SSL_CTX_load_verify_locations typically fails first,
  7610. // but our error handling code path is still exercised
  7611. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7612. }
  7613. }
  7614. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7615. // Test SSL server using X509_STORE constructor with client CA certificates
  7616. // This test verifies that Phase 2 implementation correctly extracts CA names
  7617. // from an X509_STORE and sets them in the SSL context
  7618. // Load the CA certificate into memory
  7619. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7620. ASSERT_NE(nullptr, bio);
  7621. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7622. BIO_free(bio);
  7623. ASSERT_NE(nullptr, ca_cert);
  7624. // Create an X509_STORE and add the CA certificate
  7625. auto store = X509_STORE_new();
  7626. ASSERT_NE(nullptr, store);
  7627. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7628. // Load server certificate and private key
  7629. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7630. ASSERT_NE(nullptr, cert_bio);
  7631. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7632. BIO_free(cert_bio);
  7633. ASSERT_NE(nullptr, server_cert);
  7634. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7635. ASSERT_NE(nullptr, key_bio);
  7636. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7637. BIO_free(key_bio);
  7638. ASSERT_NE(nullptr, server_key);
  7639. // Create SSLServer with X509_STORE constructor
  7640. // Note: X509_STORE ownership is transferred to SSL_CTX
  7641. SSLServer svr(server_cert, server_key, store);
  7642. ASSERT_TRUE(svr.is_valid());
  7643. // No SSL error should be recorded for valid setup
  7644. EXPECT_EQ(0, svr.ssl_last_error());
  7645. // Set up server endpoints
  7646. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7647. res.set_content("ok", "text/plain");
  7648. });
  7649. // Start server in a thread
  7650. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7651. svr.wait_until_ready();
  7652. // Connect with client certificate (using constructor with paths)
  7653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7654. cli.enable_server_certificate_verification(false);
  7655. auto res = cli.Get("/test-x509store");
  7656. ASSERT_TRUE(res);
  7657. EXPECT_EQ(200, res->status);
  7658. EXPECT_EQ("ok", res->body);
  7659. // Clean up
  7660. X509_free(server_cert);
  7661. EVP_PKEY_free(server_key);
  7662. X509_free(ca_cert);
  7663. svr.stop();
  7664. server_thread.join();
  7665. }
  7666. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7667. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7668. // prepare large data
  7669. std::random_device seed_gen;
  7670. std::mt19937 random(seed_gen());
  7671. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7672. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7673. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7674. // server
  7675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7676. ASSERT_TRUE(svr.is_valid());
  7677. svr.Post("/binary", [&](const Request &req, Response &res) {
  7678. EXPECT_EQ(large_size_byte, req.body.size());
  7679. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7680. res.set_content(req.body, "application/octet-stream");
  7681. });
  7682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7683. auto se = detail::scope_exit([&] {
  7684. svr.stop();
  7685. listen_thread.join();
  7686. ASSERT_FALSE(svr.is_running());
  7687. });
  7688. svr.wait_until_ready();
  7689. // client POST
  7690. SSLClient cli("localhost", PORT);
  7691. cli.enable_server_certificate_verification(false);
  7692. cli.set_read_timeout(std::chrono::seconds(100));
  7693. cli.set_write_timeout(std::chrono::seconds(100));
  7694. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7695. large_size_byte, "application/octet-stream");
  7696. // compare
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(large_size_byte, res->body.size());
  7699. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7700. }
  7701. #endif
  7702. #ifdef _WIN32
  7703. TEST(CleanupTest, WSACleanup) {
  7704. int ret = WSACleanup();
  7705. ASSERT_EQ(0, ret);
  7706. }
  7707. #endif
  7708. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7709. TEST(NoSSLSupport, SimpleInterface) {
  7710. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7711. }
  7712. #endif
  7713. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7714. TEST(InvalidScheme, SimpleInterface) {
  7715. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7716. }
  7717. #endif
  7718. TEST(NoScheme, SimpleInterface) {
  7719. Client cli("yahoo.com:80");
  7720. ASSERT_TRUE(cli.is_valid());
  7721. }
  7722. TEST(SendAPI, SimpleInterface_Online) {
  7723. Client cli("http://yahoo.com");
  7724. Request req;
  7725. req.method = "GET";
  7726. req.path = "/";
  7727. auto res = cli.send(req);
  7728. ASSERT_TRUE(res);
  7729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7730. }
  7731. TEST(SendAPI, WithParamsInRequest) {
  7732. Server svr;
  7733. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7734. EXPECT_TRUE(req.has_param("test"));
  7735. EXPECT_EQ("test_value", req.get_param_value("test"));
  7736. });
  7737. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7738. auto se = detail::scope_exit([&] {
  7739. svr.stop();
  7740. t.join();
  7741. ASSERT_FALSE(svr.is_running());
  7742. });
  7743. svr.wait_until_ready();
  7744. Client cli(HOST, PORT);
  7745. {
  7746. Request req;
  7747. req.method = "GET";
  7748. req.path = "/";
  7749. req.params.emplace("test", "test_value");
  7750. auto res = cli.send(req);
  7751. ASSERT_TRUE(res);
  7752. }
  7753. {
  7754. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7755. ASSERT_TRUE(res);
  7756. }
  7757. }
  7758. TEST(ClientImplMethods, GetSocketTest) {
  7759. httplib::Server svr;
  7760. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7761. res.status = StatusCode::OK_200;
  7762. });
  7763. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7764. auto se = detail::scope_exit([&] {
  7765. svr.stop();
  7766. thread.join();
  7767. ASSERT_FALSE(svr.is_running());
  7768. });
  7769. svr.wait_until_ready();
  7770. {
  7771. httplib::Client cli("http://127.0.0.1:3333");
  7772. cli.set_keep_alive(true);
  7773. // Use the behavior of cpp-httplib of opening the connection
  7774. // only when the first request happens. If that changes,
  7775. // this test would be obsolete.
  7776. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7777. // This also implicitly tests the server. But other tests would fail much
  7778. // earlier than this one to be considered.
  7779. auto res = cli.Get("/");
  7780. ASSERT_TRUE(res);
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7783. }
  7784. }
  7785. // Disabled due to out-of-memory problem on GitHub Actions
  7786. #ifdef _WIN64
  7787. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7788. // allocate content size larger than 2GB in memory
  7789. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7790. char *content = (char *)malloc(content_size);
  7791. ASSERT_TRUE(content);
  7792. Server svr;
  7793. svr.Get("/foo",
  7794. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7795. res.set_content(content, content_size, "application/octet-stream");
  7796. });
  7797. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. listen_thread.join();
  7801. if (content) free(content);
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. svr.wait_until_ready();
  7805. Client cli(HOST, PORT);
  7806. auto res = cli.Get("/foo");
  7807. ASSERT_TRUE(res);
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ(content_size, res->body.length());
  7810. }
  7811. #endif
  7812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7813. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7814. Client cli("http://yahoo.com");
  7815. auto res = cli.Get("/");
  7816. ASSERT_TRUE(res);
  7817. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7818. cli.set_follow_location(true);
  7819. res = cli.Get("/");
  7820. ASSERT_TRUE(res);
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7823. }
  7824. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7825. Client cli("https://yahoo.com");
  7826. auto res = cli.Get("/");
  7827. ASSERT_TRUE(res);
  7828. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7829. cli.set_follow_location(true);
  7830. res = cli.Get("/");
  7831. ASSERT_TRUE(res);
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7834. }
  7835. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7836. Client cli("https://yahoo.com");
  7837. auto res = cli.Get("/");
  7838. ASSERT_TRUE(res);
  7839. ASSERT_FALSE(!res);
  7840. ASSERT_TRUE(res);
  7841. ASSERT_FALSE(res == nullptr);
  7842. ASSERT_TRUE(res != nullptr);
  7843. EXPECT_EQ(Error::Success, res.error());
  7844. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7845. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7846. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7847. cli.set_follow_location(true);
  7848. res = cli.Get("/");
  7849. ASSERT_TRUE(res);
  7850. EXPECT_EQ(Error::Success, res.error());
  7851. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7852. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7855. }
  7856. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7857. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7858. Client cli("https://cdnjs.cloudflare.com");
  7859. auto res =
  7860. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7861. ASSERT_TRUE(res);
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ(287630U, res->body.size());
  7864. EXPECT_EQ("application/javascript; charset=utf-8",
  7865. res->get_header_value("Content-Type"));
  7866. }
  7867. #endif
  7868. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7869. #undef REDIR_HOST // Silence compiler warning
  7870. #define REDIR_HOST "https://httpbingo.org"
  7871. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7872. Client cli(REDIR_HOST);
  7873. cli.set_follow_location(true);
  7874. auto res =
  7875. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7876. ASSERT_TRUE(res);
  7877. EXPECT_EQ(StatusCode::OK_200, res->status);
  7878. }
  7879. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7880. Client cli(REDIR_HOST);
  7881. cli.set_follow_location(true);
  7882. Params params;
  7883. params.emplace("url", "http://example.com");
  7884. params.emplace("status_code", "302");
  7885. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7886. ASSERT_TRUE(res);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7890. Client cli(REDIR_HOST);
  7891. cli.set_follow_location(true);
  7892. Params params;
  7893. params.emplace("url", "http://example.com");
  7894. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7895. ASSERT_TRUE(res);
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. }
  7898. TEST(HttpToHttpsRedirectTest, CertFile) {
  7899. Server svr;
  7900. ASSERT_TRUE(svr.is_valid());
  7901. svr.Get("/index", [&](const Request &, Response &res) {
  7902. res.set_redirect("https://127.0.0.1:1235/index");
  7903. svr.stop();
  7904. });
  7905. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7906. ASSERT_TRUE(ssl_svr.is_valid());
  7907. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7908. res.set_content("test", "text/plain");
  7909. ssl_svr.stop();
  7910. });
  7911. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7912. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7913. auto se = detail::scope_exit([&] {
  7914. t2.join();
  7915. t.join();
  7916. ASSERT_FALSE(svr.is_running());
  7917. });
  7918. svr.wait_until_ready();
  7919. ssl_svr.wait_until_ready();
  7920. Client cli("127.0.0.1", PORT);
  7921. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7922. cli.enable_server_certificate_verification(true);
  7923. cli.set_follow_location(true);
  7924. cli.set_connection_timeout(30);
  7925. auto res = cli.Get("/index");
  7926. ASSERT_TRUE(res);
  7927. ASSERT_EQ(StatusCode::OK_200, res->status);
  7928. }
  7929. TEST(SSLClientRedirectTest, CertFile) {
  7930. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7931. ASSERT_TRUE(ssl_svr1.is_valid());
  7932. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7933. res.set_redirect("https://127.0.0.1:1235/index");
  7934. ssl_svr1.stop();
  7935. });
  7936. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7937. ASSERT_TRUE(ssl_svr2.is_valid());
  7938. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7939. res.set_content("test", "text/plain");
  7940. ssl_svr2.stop();
  7941. });
  7942. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7943. thread t2 =
  7944. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7945. auto se = detail::scope_exit([&] {
  7946. t2.join();
  7947. t.join();
  7948. ASSERT_FALSE(ssl_svr1.is_running());
  7949. });
  7950. ssl_svr1.wait_until_ready();
  7951. ssl_svr2.wait_until_ready();
  7952. SSLClient cli("127.0.0.1", PORT);
  7953. std::string cert;
  7954. read_file(SERVER_CERT2_FILE, cert);
  7955. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7956. cli.enable_server_certificate_verification(true);
  7957. cli.set_follow_location(true);
  7958. cli.set_connection_timeout(30);
  7959. auto res = cli.Get("/index");
  7960. ASSERT_TRUE(res);
  7961. ASSERT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST(MultipartFormDataTest, LargeData) {
  7964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7965. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7966. const ContentReader &content_reader) {
  7967. if (req.is_multipart_form_data()) {
  7968. std::vector<FormData> items;
  7969. content_reader(
  7970. [&](const FormData &file) {
  7971. items.push_back(file);
  7972. return true;
  7973. },
  7974. [&](const char *data, size_t data_length) {
  7975. items.back().content.append(data, data_length);
  7976. return true;
  7977. });
  7978. EXPECT_TRUE(std::string(items[0].name) == "document");
  7979. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7980. EXPECT_TRUE(items[0].filename == "2MB_data");
  7981. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7982. EXPECT_TRUE(items[1].name == "hello");
  7983. EXPECT_TRUE(items[1].content == "world");
  7984. EXPECT_TRUE(items[1].filename == "");
  7985. EXPECT_TRUE(items[1].content_type == "");
  7986. } else {
  7987. std::string body;
  7988. content_reader([&](const char *data, size_t data_length) {
  7989. body.append(data, data_length);
  7990. return true;
  7991. });
  7992. }
  7993. });
  7994. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7995. auto se = detail::scope_exit([&] {
  7996. svr.stop();
  7997. t.join();
  7998. ASSERT_FALSE(svr.is_running());
  7999. });
  8000. svr.wait_until_ready();
  8001. {
  8002. std::string data(1024 * 1024 * 2, '.');
  8003. std::stringstream buffer;
  8004. buffer << data;
  8005. Client cli("https://localhost:8080");
  8006. cli.enable_server_certificate_verification(false);
  8007. UploadFormDataItems items{
  8008. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8009. {"hello", "world", "", ""},
  8010. };
  8011. auto res = cli.Post("/post", items);
  8012. ASSERT_TRUE(res);
  8013. ASSERT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. }
  8016. TEST(MultipartFormDataTest, DataProviderItems) {
  8017. std::random_device seed_gen;
  8018. std::mt19937 random(seed_gen());
  8019. std::string rand1;
  8020. rand1.resize(1000);
  8021. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8022. std::string rand2;
  8023. rand2.resize(3000);
  8024. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8026. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8027. const ContentReader &content_reader) {
  8028. ASSERT_FALSE(req.is_multipart_form_data());
  8029. std::string body;
  8030. content_reader([&](const char *data, size_t data_length) {
  8031. body.append(data, data_length);
  8032. return true;
  8033. });
  8034. EXPECT_EQ(body, "");
  8035. });
  8036. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8037. const ContentReader &content_reader) {
  8038. ASSERT_TRUE(req.is_multipart_form_data());
  8039. std::vector<FormData> items;
  8040. content_reader(
  8041. [&](const FormData &file) {
  8042. items.push_back(file);
  8043. return true;
  8044. },
  8045. [&](const char *data, size_t data_length) {
  8046. items.back().content.append(data, data_length);
  8047. return true;
  8048. });
  8049. ASSERT_TRUE(items.size() == 2);
  8050. EXPECT_EQ(std::string(items[0].name), "name1");
  8051. EXPECT_EQ(items[0].content, "Testing123");
  8052. EXPECT_EQ(items[0].filename, "filename1");
  8053. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8054. EXPECT_EQ(items[1].name, "name2");
  8055. EXPECT_EQ(items[1].content, "Testing456");
  8056. EXPECT_EQ(items[1].filename, "");
  8057. EXPECT_EQ(items[1].content_type, "");
  8058. });
  8059. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8060. const ContentReader &content_reader) {
  8061. ASSERT_TRUE(req.is_multipart_form_data());
  8062. std::vector<FormData> items;
  8063. content_reader(
  8064. [&](const FormData &file) {
  8065. items.push_back(file);
  8066. return true;
  8067. },
  8068. [&](const char *data, size_t data_length) {
  8069. items.back().content.append(data, data_length);
  8070. return true;
  8071. });
  8072. ASSERT_TRUE(items.size() == 2);
  8073. EXPECT_EQ(items[0].name, "name3");
  8074. EXPECT_EQ(items[0].content, rand1);
  8075. EXPECT_EQ(items[0].filename, "filename3");
  8076. EXPECT_EQ(items[0].content_type, "");
  8077. EXPECT_EQ(items[1].name, "name4");
  8078. EXPECT_EQ(items[1].content, rand2);
  8079. EXPECT_EQ(items[1].filename, "filename4");
  8080. EXPECT_EQ(items[1].content_type, "");
  8081. });
  8082. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8083. const ContentReader &content_reader) {
  8084. ASSERT_TRUE(req.is_multipart_form_data());
  8085. std::vector<FormData> items;
  8086. content_reader(
  8087. [&](const FormData &file) {
  8088. items.push_back(file);
  8089. return true;
  8090. },
  8091. [&](const char *data, size_t data_length) {
  8092. items.back().content.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(items.size() == 4);
  8096. EXPECT_EQ(std::string(items[0].name), "name1");
  8097. EXPECT_EQ(items[0].content, "Testing123");
  8098. EXPECT_EQ(items[0].filename, "filename1");
  8099. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8100. EXPECT_EQ(items[1].name, "name2");
  8101. EXPECT_EQ(items[1].content, "Testing456");
  8102. EXPECT_EQ(items[1].filename, "");
  8103. EXPECT_EQ(items[1].content_type, "");
  8104. EXPECT_EQ(items[2].name, "name3");
  8105. EXPECT_EQ(items[2].content, rand1);
  8106. EXPECT_EQ(items[2].filename, "filename3");
  8107. EXPECT_EQ(items[2].content_type, "");
  8108. EXPECT_EQ(items[3].name, "name4");
  8109. EXPECT_EQ(items[3].content, rand2);
  8110. EXPECT_EQ(items[3].filename, "filename4");
  8111. EXPECT_EQ(items[3].content_type, "");
  8112. });
  8113. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8114. auto se = detail::scope_exit([&] {
  8115. svr.stop();
  8116. t.join();
  8117. ASSERT_FALSE(svr.is_running());
  8118. });
  8119. svr.wait_until_ready();
  8120. {
  8121. Client cli("https://localhost:8080");
  8122. cli.enable_server_certificate_verification(false);
  8123. UploadFormDataItems items{
  8124. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8125. {"name2", "Testing456", "", ""}, // not a file
  8126. };
  8127. {
  8128. auto res = cli.Post("/post-none", {}, {}, {});
  8129. ASSERT_TRUE(res);
  8130. ASSERT_EQ(StatusCode::OK_200, res->status);
  8131. }
  8132. FormDataProviderItems providers;
  8133. {
  8134. auto res =
  8135. cli.Post("/post-items", {}, items, providers); // empty providers
  8136. ASSERT_TRUE(res);
  8137. ASSERT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. providers.push_back({"name3",
  8140. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8141. // test the offset is given correctly at each step
  8142. if (!offset)
  8143. sink.os.write(rand1.data(), 30);
  8144. else if (offset == 30)
  8145. sink.os.write(rand1.data() + 30, 300);
  8146. else if (offset == 330)
  8147. sink.os.write(rand1.data() + 330, 670);
  8148. else if (offset == rand1.size())
  8149. sink.done();
  8150. return true;
  8151. },
  8152. "filename3",
  8153. {}});
  8154. providers.push_back({"name4",
  8155. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8156. // test the offset is given correctly at each step
  8157. if (!offset)
  8158. sink.os.write(rand2.data(), 2000);
  8159. else if (offset == 2000)
  8160. sink.os.write(rand2.data() + 2000, 1);
  8161. else if (offset == 2001)
  8162. sink.os.write(rand2.data() + 2001, 999);
  8163. else if (offset == rand2.size())
  8164. sink.done();
  8165. return true;
  8166. },
  8167. "filename4",
  8168. {}});
  8169. {
  8170. auto res = cli.Post("/post-providers", {}, {}, providers);
  8171. ASSERT_TRUE(res);
  8172. ASSERT_EQ(StatusCode::OK_200, res->status);
  8173. }
  8174. {
  8175. auto res = cli.Post("/post-both", {}, items, providers);
  8176. ASSERT_TRUE(res);
  8177. ASSERT_EQ(StatusCode::OK_200, res->status);
  8178. }
  8179. }
  8180. }
  8181. TEST(MultipartFormDataTest, BadHeader) {
  8182. Server svr;
  8183. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8184. res.set_content("ok", "text/plain");
  8185. });
  8186. thread t = thread([&] { svr.listen(HOST, PORT); });
  8187. auto se = detail::scope_exit([&] {
  8188. svr.stop();
  8189. t.join();
  8190. ASSERT_FALSE(svr.is_running());
  8191. });
  8192. svr.wait_until_ready();
  8193. const std::string body =
  8194. "This is the preamble. It is to be ignored, though it\r\n"
  8195. "is a handy place for composition agents to include an\r\n"
  8196. "explanatory note to non-MIME conformant readers.\r\n"
  8197. "\r\n"
  8198. "\r\n"
  8199. "--simple boundary\r\n"
  8200. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8201. ": BAD...\r\n"
  8202. "\r\n"
  8203. "value1\r\n"
  8204. "--simple boundary\r\n"
  8205. "Content-Disposition: form-data; name=\"field2\"; "
  8206. "filename=\"example.txt\"\r\n"
  8207. "\r\n"
  8208. "value2\r\n"
  8209. "--simple boundary--\r\n"
  8210. "This is the epilogue. It is also to be ignored.\r\n";
  8211. std::string content_type =
  8212. R"(multipart/form-data; boundary="simple boundary")";
  8213. Client cli(HOST, PORT);
  8214. auto res = cli.Post("/post", body, content_type.c_str());
  8215. ASSERT_TRUE(res);
  8216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8217. }
  8218. TEST(MultipartFormDataTest, WithPreamble) {
  8219. Server svr;
  8220. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8221. res.set_content("ok", "text/plain");
  8222. });
  8223. thread t = thread([&] { svr.listen(HOST, PORT); });
  8224. auto se = detail::scope_exit([&] {
  8225. svr.stop();
  8226. t.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. });
  8229. svr.wait_until_ready();
  8230. const std::string body =
  8231. "This is the preamble. It is to be ignored, though it\r\n"
  8232. "is a handy place for composition agents to include an\r\n"
  8233. "explanatory note to non-MIME conformant readers.\r\n"
  8234. "\r\n"
  8235. "\r\n"
  8236. "--simple boundary\r\n"
  8237. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8238. "\r\n"
  8239. "value1\r\n"
  8240. "--simple boundary\r\n"
  8241. "Content-Disposition: form-data; name=\"field2\"; "
  8242. "filename=\"example.txt\"\r\n"
  8243. "\r\n"
  8244. "value2\r\n"
  8245. "--simple boundary--\r\n"
  8246. "This is the epilogue. It is also to be ignored.\r\n";
  8247. std::string content_type =
  8248. R"(multipart/form-data; boundary="simple boundary")";
  8249. Client cli(HOST, PORT);
  8250. auto res = cli.Post("/post", body, content_type.c_str());
  8251. ASSERT_TRUE(res);
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. }
  8254. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8256. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8257. const ContentReader &content_reader) {
  8258. if (req.is_multipart_form_data()) {
  8259. std::vector<FormData> items;
  8260. content_reader(
  8261. [&](const FormData &file) {
  8262. items.push_back(file);
  8263. return true;
  8264. },
  8265. [&](const char *data, size_t data_length) {
  8266. items.back().content.append(data, data_length);
  8267. return true;
  8268. });
  8269. EXPECT_TRUE(std::string(items[0].name) == "document");
  8270. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8271. EXPECT_TRUE(items[0].filename == "2MB_data");
  8272. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8273. EXPECT_TRUE(items[1].name == "hello");
  8274. EXPECT_TRUE(items[1].content == "world");
  8275. EXPECT_TRUE(items[1].filename == "");
  8276. EXPECT_TRUE(items[1].content_type == "");
  8277. } else {
  8278. std::string body;
  8279. content_reader([&](const char *data, size_t data_length) {
  8280. body.append(data, data_length);
  8281. return true;
  8282. });
  8283. }
  8284. });
  8285. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8286. auto se = detail::scope_exit([&] {
  8287. svr.stop();
  8288. t.join();
  8289. ASSERT_FALSE(svr.is_running());
  8290. });
  8291. svr.wait_until_ready();
  8292. {
  8293. std::string data(1024 * 1024 * 2, '.');
  8294. std::stringstream buffer;
  8295. buffer << data;
  8296. Client cli("https://localhost:8080");
  8297. cli.enable_server_certificate_verification(false);
  8298. UploadFormDataItems items{
  8299. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8300. {"hello", "world", "", ""},
  8301. };
  8302. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8303. ASSERT_TRUE(res);
  8304. ASSERT_EQ(StatusCode::OK_200, res->status);
  8305. }
  8306. }
  8307. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8308. std::string data(1024 * 1024 * 2, '&');
  8309. std::stringstream buffer;
  8310. buffer << data;
  8311. Client cli("https://localhost:8080");
  8312. UploadFormDataItems items{
  8313. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8314. {"hello", "world", "", ""},
  8315. };
  8316. for (const char &c : " \t\r\n") {
  8317. auto res =
  8318. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8319. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8320. ASSERT_FALSE(res);
  8321. }
  8322. }
  8323. TEST(MultipartFormDataTest, PutFormData) {
  8324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8325. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8326. const ContentReader &content_reader) {
  8327. if (req.is_multipart_form_data()) {
  8328. std::vector<FormData> items;
  8329. content_reader(
  8330. [&](const FormData &file) {
  8331. items.push_back(file);
  8332. return true;
  8333. },
  8334. [&](const char *data, size_t data_length) {
  8335. items.back().content.append(data, data_length);
  8336. return true;
  8337. });
  8338. EXPECT_TRUE(std::string(items[0].name) == "document");
  8339. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8340. EXPECT_TRUE(items[0].filename == "2MB_data");
  8341. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8342. EXPECT_TRUE(items[1].name == "hello");
  8343. EXPECT_TRUE(items[1].content == "world");
  8344. EXPECT_TRUE(items[1].filename == "");
  8345. EXPECT_TRUE(items[1].content_type == "");
  8346. } else {
  8347. std::string body;
  8348. content_reader([&](const char *data, size_t data_length) {
  8349. body.append(data, data_length);
  8350. return true;
  8351. });
  8352. }
  8353. });
  8354. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8355. auto se = detail::scope_exit([&] {
  8356. svr.stop();
  8357. t.join();
  8358. ASSERT_FALSE(svr.is_running());
  8359. });
  8360. svr.wait_until_ready();
  8361. {
  8362. std::string data(1024 * 1024 * 2, '&');
  8363. std::stringstream buffer;
  8364. buffer << data;
  8365. Client cli("https://localhost:8080");
  8366. cli.enable_server_certificate_verification(false);
  8367. UploadFormDataItems items{
  8368. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8369. {"hello", "world", "", ""},
  8370. };
  8371. auto res = cli.Put("/put", items);
  8372. ASSERT_TRUE(res);
  8373. ASSERT_EQ(StatusCode::OK_200, res->status);
  8374. }
  8375. }
  8376. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8378. svr.Put("/put_customboundary",
  8379. [&](const Request &req, const Response & /*res*/,
  8380. const ContentReader &content_reader) {
  8381. if (req.is_multipart_form_data()) {
  8382. std::vector<FormData> items;
  8383. content_reader(
  8384. [&](const FormData &file) {
  8385. items.push_back(file);
  8386. return true;
  8387. },
  8388. [&](const char *data, size_t data_length) {
  8389. items.back().content.append(data, data_length);
  8390. return true;
  8391. });
  8392. EXPECT_TRUE(std::string(items[0].name) == "document");
  8393. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8394. EXPECT_TRUE(items[0].filename == "2MB_data");
  8395. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8396. EXPECT_TRUE(items[1].name == "hello");
  8397. EXPECT_TRUE(items[1].content == "world");
  8398. EXPECT_TRUE(items[1].filename == "");
  8399. EXPECT_TRUE(items[1].content_type == "");
  8400. } else {
  8401. std::string body;
  8402. content_reader([&](const char *data, size_t data_length) {
  8403. body.append(data, data_length);
  8404. return true;
  8405. });
  8406. }
  8407. });
  8408. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8409. auto se = detail::scope_exit([&] {
  8410. svr.stop();
  8411. t.join();
  8412. ASSERT_FALSE(svr.is_running());
  8413. });
  8414. svr.wait_until_ready();
  8415. {
  8416. std::string data(1024 * 1024 * 2, '&');
  8417. std::stringstream buffer;
  8418. buffer << data;
  8419. Client cli("https://localhost:8080");
  8420. cli.enable_server_certificate_verification(false);
  8421. UploadFormDataItems items{
  8422. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8423. {"hello", "world", "", ""},
  8424. };
  8425. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8426. ASSERT_TRUE(res);
  8427. ASSERT_EQ(StatusCode::OK_200, res->status);
  8428. }
  8429. }
  8430. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8431. std::string data(1024 * 1024 * 2, '&');
  8432. std::stringstream buffer;
  8433. buffer << data;
  8434. Client cli("https://localhost:8080");
  8435. cli.enable_server_certificate_verification(false);
  8436. UploadFormDataItems items{
  8437. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8438. {"hello", "world", "", ""},
  8439. };
  8440. for (const char &c : " \t\r\n") {
  8441. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8442. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8443. ASSERT_FALSE(res);
  8444. }
  8445. }
  8446. TEST(MultipartFormDataTest, AlternateFilename) {
  8447. auto handled = false;
  8448. Server svr;
  8449. svr.Post("/test", [&](const Request &req, Response &res) {
  8450. ASSERT_EQ(2u, req.form.files.size());
  8451. ASSERT_EQ(1u, req.form.fields.size());
  8452. // Test files
  8453. const auto &file1 = req.form.get_file("file1");
  8454. ASSERT_EQ("file1", file1.name);
  8455. ASSERT_EQ("A.txt", file1.filename);
  8456. ASSERT_EQ("text/plain", file1.content_type);
  8457. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8458. const auto &file2 = req.form.get_file("file2");
  8459. ASSERT_EQ("file2", file2.name);
  8460. ASSERT_EQ("a.html", file2.filename);
  8461. ASSERT_EQ("text/html", file2.content_type);
  8462. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8463. file2.content);
  8464. // Test text field
  8465. const auto &text = req.form.get_field("text");
  8466. ASSERT_EQ("text default", text);
  8467. res.set_content("ok", "text/plain");
  8468. handled = true;
  8469. });
  8470. thread t = thread([&] { svr.listen(HOST, PORT); });
  8471. auto se = detail::scope_exit([&] {
  8472. svr.stop();
  8473. t.join();
  8474. ASSERT_FALSE(svr.is_running());
  8475. ASSERT_TRUE(handled);
  8476. });
  8477. svr.wait_until_ready();
  8478. auto req = "POST /test HTTP/1.1\r\n"
  8479. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8480. "Content-Length: 399\r\n"
  8481. "\r\n"
  8482. "----------\r\n"
  8483. "Content-Disposition: form-data; name=\"text\"\r\n"
  8484. "\r\n"
  8485. "text default\r\n"
  8486. "----------\r\n"
  8487. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8488. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8489. "Content-Type: text/plain\r\n"
  8490. "\r\n"
  8491. "Content of a.txt.\r\n"
  8492. "\r\n"
  8493. "----------\r\n"
  8494. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8495. "\"a.html\"\r\n"
  8496. "Content-Type: text/html\r\n"
  8497. "\r\n"
  8498. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8499. "\r\n"
  8500. "------------\r\n";
  8501. ASSERT_TRUE(send_request(1, req));
  8502. }
  8503. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8504. auto handled = false;
  8505. Server svr;
  8506. svr.Post("/test", [&](const Request &req, Response &) {
  8507. ASSERT_EQ(2u, req.form.fields.size());
  8508. const auto &text1 = req.form.get_field("text1");
  8509. ASSERT_EQ("text1", text1);
  8510. const auto &text2 = req.form.get_field("text2");
  8511. ASSERT_EQ("text2", text2);
  8512. handled = true;
  8513. });
  8514. thread t = thread([&] { svr.listen(HOST, PORT); });
  8515. auto se = detail::scope_exit([&] {
  8516. svr.stop();
  8517. t.join();
  8518. ASSERT_FALSE(svr.is_running());
  8519. ASSERT_TRUE(handled);
  8520. });
  8521. svr.wait_until_ready();
  8522. auto req = "POST /test HTTP/1.1\r\n"
  8523. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8524. "Content-Length: 146\r\n"
  8525. "\r\n----------\r\n"
  8526. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8527. "\r\n"
  8528. "text1"
  8529. "\r\n----------\r\n"
  8530. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8531. "\r\n"
  8532. "text2"
  8533. "\r\n------------";
  8534. std::string response;
  8535. ASSERT_TRUE(send_request(1, req, &response));
  8536. ASSERT_EQ("200", response.substr(9, 3));
  8537. }
  8538. TEST(MultipartFormDataTest, ContentLength) {
  8539. auto handled = false;
  8540. Server svr;
  8541. svr.Post("/test", [&](const Request &req, Response &) {
  8542. ASSERT_EQ(2u, req.form.fields.size());
  8543. const auto &text1 = req.form.get_field("text1");
  8544. ASSERT_EQ("text1", text1);
  8545. const auto &text2 = req.form.get_field("text2");
  8546. ASSERT_EQ("text2", text2);
  8547. handled = true;
  8548. });
  8549. thread t = thread([&] { svr.listen(HOST, PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. t.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. ASSERT_TRUE(handled);
  8555. });
  8556. svr.wait_until_ready();
  8557. auto req = "POST /test HTTP/1.1\r\n"
  8558. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8559. "Content-Length: 167\r\n"
  8560. "\r\n----------\r\n"
  8561. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8562. "Content-Length: 5\r\n"
  8563. "\r\n"
  8564. "text1"
  8565. "\r\n----------\r\n"
  8566. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8567. "\r\n"
  8568. "text2"
  8569. "\r\n------------\r\n";
  8570. std::string response;
  8571. ASSERT_TRUE(send_request(1, req, &response));
  8572. ASSERT_EQ("200", response.substr(9, 3));
  8573. }
  8574. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8575. auto handled = false;
  8576. Server svr;
  8577. svr.Post("/test", [&](const Request &req, Response &) {
  8578. ASSERT_EQ(2u, req.form.fields.size());
  8579. const auto &text1 = req.form.get_field("text1");
  8580. ASSERT_EQ("text1", text1);
  8581. // TODO: Add header access for text fields if needed
  8582. const auto &text2 = req.form.get_field("text2");
  8583. ASSERT_EQ("text2", text2);
  8584. // TODO: Header access for text fields needs to be implemented
  8585. // auto &headers = it->second.headers;
  8586. // ASSERT_EQ(3U, headers.size());
  8587. // auto custom_header = headers.find("x-whatever");
  8588. // ASSERT_TRUE(custom_header != headers.end());
  8589. // ASSERT_NE("customvalue", custom_header->second);
  8590. // ASSERT_EQ("CustomValue", custom_header->second);
  8591. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8592. handled = true;
  8593. });
  8594. thread t = thread([&] { svr.listen(HOST, PORT); });
  8595. auto se = detail::scope_exit([&] {
  8596. svr.stop();
  8597. t.join();
  8598. ASSERT_FALSE(svr.is_running());
  8599. ASSERT_TRUE(handled);
  8600. });
  8601. svr.wait_until_ready();
  8602. auto req = "POST /test HTTP/1.1\r\n"
  8603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8604. "Content-Length: 232\r\n"
  8605. "\r\n----------\r\n"
  8606. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8607. "Content-Length: 5\r\n"
  8608. "X-Test: 1\r\n"
  8609. "\r\n"
  8610. "text1"
  8611. "\r\n----------\r\n"
  8612. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8613. "Content-Type: text/plain\r\n"
  8614. "X-Whatever: CustomValue\r\n"
  8615. "\r\n"
  8616. "text2"
  8617. "\r\n------------\r\n"
  8618. "That should be disregarded. Not even read";
  8619. std::string response;
  8620. ASSERT_TRUE(send_request(1, req, &response));
  8621. ASSERT_EQ("200", response.substr(9, 3));
  8622. }
  8623. #endif
  8624. TEST(MultipartFormDataTest, LargeHeader) {
  8625. auto handled = false;
  8626. Server svr;
  8627. svr.Post("/test", [&](const Request &req, Response &) {
  8628. ASSERT_EQ(1u, req.form.fields.size());
  8629. const auto &text = req.form.get_field("name1");
  8630. ASSERT_EQ("text1", text);
  8631. handled = true;
  8632. });
  8633. thread t = thread([&] { svr.listen(HOST, PORT); });
  8634. auto se = detail::scope_exit([&] {
  8635. svr.stop();
  8636. t.join();
  8637. ASSERT_FALSE(svr.is_running());
  8638. ASSERT_TRUE(handled);
  8639. });
  8640. svr.wait_until_ready();
  8641. auto boundary = std::string("cpp-httplib-multipart-data");
  8642. std::string content = "--" + boundary +
  8643. "\r\n"
  8644. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8645. "\r\n"
  8646. "text1\r\n"
  8647. "--" +
  8648. boundary + "--\r\n";
  8649. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8650. "Content-Type: multipart/form-data;boundary=" +
  8651. boundary +
  8652. "\r\n"
  8653. "Content-Length: " +
  8654. std::to_string(content.size()) +
  8655. "\r\n"
  8656. "Dummy-Header: ";
  8657. std::string header_suffix = "\r\n"
  8658. "\r\n";
  8659. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8660. size_t header_dummy_size =
  8661. read_buff_size -
  8662. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8663. auto header_dummy = std::string(header_dummy_size, '@');
  8664. auto req = header_prefix + header_dummy + header_suffix + content;
  8665. std::string response;
  8666. ASSERT_TRUE(send_request(1, req, &response));
  8667. ASSERT_EQ("200", response.substr(9, 3));
  8668. }
  8669. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8670. static constexpr unsigned int number_of_tasks{1000000};
  8671. std::atomic_uint count{0};
  8672. std::unique_ptr<TaskQueue> task_queue{
  8673. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8674. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8675. auto queued = task_queue->enqueue(
  8676. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8677. EXPECT_TRUE(queued);
  8678. }
  8679. EXPECT_NO_THROW(task_queue->shutdown());
  8680. EXPECT_EQ(number_of_tasks, count.load());
  8681. }
  8682. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8683. static constexpr unsigned int number_of_tasks{1000000};
  8684. static constexpr unsigned int qlimit{2};
  8685. unsigned int queued_count{0};
  8686. std::atomic_uint count{0};
  8687. std::unique_ptr<TaskQueue> task_queue{
  8688. new ThreadPool{/*num_threads=*/1, qlimit}};
  8689. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8690. if (task_queue->enqueue(
  8691. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8692. queued_count++;
  8693. }
  8694. }
  8695. EXPECT_NO_THROW(task_queue->shutdown());
  8696. EXPECT_EQ(queued_count, count.load());
  8697. EXPECT_TRUE(queued_count <= number_of_tasks);
  8698. EXPECT_TRUE(queued_count >= qlimit);
  8699. }
  8700. TEST(TaskQueueTest, MaxQueuedRequests) {
  8701. static constexpr unsigned int qlimit{3};
  8702. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8703. std::condition_variable sem_cv;
  8704. std::mutex sem_mtx;
  8705. int credits = 0;
  8706. bool queued;
  8707. /* Fill up the queue with tasks that will block until we give them credits to
  8708. * complete. */
  8709. for (unsigned int n = 0; n <= qlimit;) {
  8710. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8711. std::unique_lock<std::mutex> lock(sem_mtx);
  8712. while (credits <= 0) {
  8713. sem_cv.wait(lock);
  8714. }
  8715. /* Consume the credit and signal the test code if they are all gone. */
  8716. if (--credits == 0) { sem_cv.notify_one(); }
  8717. });
  8718. if (n < qlimit) {
  8719. /* The first qlimit enqueues must succeed. */
  8720. EXPECT_TRUE(queued);
  8721. } else {
  8722. /* The last one will succeed only when the worker thread
  8723. * starts and dequeues the first blocking task. Although
  8724. * not necessary for the correctness of this test, we sleep for
  8725. * a short while to avoid busy waiting. */
  8726. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8727. }
  8728. if (queued) { n++; }
  8729. }
  8730. /* Further enqueues must fail since the queue is full. */
  8731. for (auto i = 0; i < 4; i++) {
  8732. queued = task_queue->enqueue([] {});
  8733. EXPECT_FALSE(queued);
  8734. }
  8735. /* Give the credits to allow the previous tasks to complete. */
  8736. {
  8737. std::unique_lock<std::mutex> lock(sem_mtx);
  8738. credits += qlimit + 1;
  8739. }
  8740. sem_cv.notify_all();
  8741. /* Wait for all the credits to be consumed. */
  8742. {
  8743. std::unique_lock<std::mutex> lock(sem_mtx);
  8744. while (credits > 0) {
  8745. sem_cv.wait(lock);
  8746. }
  8747. }
  8748. /* Check that we are able again to enqueue at least qlimit tasks. */
  8749. for (unsigned int i = 0; i < qlimit; i++) {
  8750. queued = task_queue->enqueue([] {});
  8751. EXPECT_TRUE(queued);
  8752. }
  8753. EXPECT_NO_THROW(task_queue->shutdown());
  8754. }
  8755. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8756. Server svr;
  8757. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8758. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8759. });
  8760. svr.Get("/hello", [](const Request &req, Response &res) {
  8761. res.set_content(req.get_param_value("key"), "text/plain");
  8762. });
  8763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8764. auto se = detail::scope_exit([&] {
  8765. svr.stop();
  8766. thread.join();
  8767. ASSERT_FALSE(svr.is_running());
  8768. });
  8769. svr.wait_until_ready();
  8770. {
  8771. Client cli(HOST, PORT);
  8772. cli.set_follow_location(true);
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("val&key2=val2", res->body);
  8777. }
  8778. }
  8779. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8780. Server svr;
  8781. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8782. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8783. });
  8784. svr.Get("/hello", [](const Request &req, Response &res) {
  8785. res.set_content(req.get_param_value("key"), "text/plain");
  8786. });
  8787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8788. auto se = detail::scope_exit([&] {
  8789. svr.stop();
  8790. thread.join();
  8791. ASSERT_FALSE(svr.is_running());
  8792. });
  8793. svr.wait_until_ready();
  8794. {
  8795. Client cli(HOST, PORT);
  8796. cli.set_follow_location(true);
  8797. auto res = cli.Get("/");
  8798. ASSERT_TRUE(res);
  8799. EXPECT_EQ(StatusCode::OK_200, res->status);
  8800. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8801. }
  8802. }
  8803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8804. TEST(RedirectTest, Issue2185_Online) {
  8805. SSLClient client("github.com");
  8806. client.set_follow_location(true);
  8807. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8808. "Coollab-Windows.zip");
  8809. ASSERT_TRUE(res);
  8810. EXPECT_EQ(StatusCode::OK_200, res->status);
  8811. EXPECT_EQ(9920427U, res->body.size());
  8812. }
  8813. #endif
  8814. TEST(VulnerabilityTest, CRLFInjection) {
  8815. Server svr;
  8816. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8817. res.set_content("Hello 1", "text/plain");
  8818. });
  8819. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8820. res.set_content("Hello 2", "text/plain");
  8821. });
  8822. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8823. res.set_content("Hello 3", "text/plain");
  8824. });
  8825. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8826. res.set_content("Hello 4", "text/plain");
  8827. });
  8828. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8829. for (const auto &x : req.headers) {
  8830. auto key = x.first;
  8831. EXPECT_STRNE("evil", key.c_str());
  8832. }
  8833. });
  8834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8835. auto se = detail::scope_exit([&] {
  8836. svr.stop();
  8837. thread.join();
  8838. ASSERT_FALSE(svr.is_running());
  8839. });
  8840. svr.wait_until_ready();
  8841. {
  8842. Client cli(HOST, PORT);
  8843. cli.Post("/test1", "A=B",
  8844. "application/x-www-form-urlencoded\r\nevil: hello1");
  8845. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8846. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8847. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8848. }
  8849. }
  8850. TEST(PathParamsTest, StaticMatch) {
  8851. const auto pattern = "/users/all";
  8852. detail::PathParamsMatcher matcher(pattern);
  8853. Request request;
  8854. request.path = "/users/all";
  8855. ASSERT_TRUE(matcher.match(request));
  8856. std::unordered_map<std::string, std::string> expected_params = {};
  8857. EXPECT_EQ(request.path_params, expected_params);
  8858. }
  8859. TEST(PathParamsTest, StaticMismatch) {
  8860. const auto pattern = "/users/all";
  8861. detail::PathParamsMatcher matcher(pattern);
  8862. Request request;
  8863. request.path = "/users/1";
  8864. ASSERT_FALSE(matcher.match(request));
  8865. }
  8866. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8867. const auto pattern = "/users/:id/subscriptions";
  8868. detail::PathParamsMatcher matcher(pattern);
  8869. Request request;
  8870. request.path = "/users/42/subscriptions";
  8871. ASSERT_TRUE(matcher.match(request));
  8872. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8873. EXPECT_EQ(request.path_params, expected_params);
  8874. }
  8875. TEST(PathParamsTest, SingleParamInTheEnd) {
  8876. const auto pattern = "/users/:id";
  8877. detail::PathParamsMatcher matcher(pattern);
  8878. Request request;
  8879. request.path = "/users/24";
  8880. ASSERT_TRUE(matcher.match(request));
  8881. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8882. EXPECT_EQ(request.path_params, expected_params);
  8883. }
  8884. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8885. const auto pattern = "/users/:id/";
  8886. detail::PathParamsMatcher matcher(pattern);
  8887. Request request;
  8888. request.path = "/users/42/";
  8889. ASSERT_TRUE(matcher.match(request));
  8890. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8891. EXPECT_EQ(request.path_params, expected_params);
  8892. }
  8893. TEST(PathParamsTest, EmptyParam) {
  8894. const auto pattern = "/users/:id/";
  8895. detail::PathParamsMatcher matcher(pattern);
  8896. Request request;
  8897. request.path = "/users//";
  8898. ASSERT_TRUE(matcher.match(request));
  8899. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8900. EXPECT_EQ(request.path_params, expected_params);
  8901. }
  8902. TEST(PathParamsTest, FragmentMismatch) {
  8903. const auto pattern = "/users/:id/";
  8904. detail::PathParamsMatcher matcher(pattern);
  8905. Request request;
  8906. request.path = "/admins/24/";
  8907. ASSERT_FALSE(matcher.match(request));
  8908. }
  8909. TEST(PathParamsTest, ExtraFragments) {
  8910. const auto pattern = "/users/:id";
  8911. detail::PathParamsMatcher matcher(pattern);
  8912. Request request;
  8913. request.path = "/users/42/subscriptions";
  8914. ASSERT_FALSE(matcher.match(request));
  8915. }
  8916. TEST(PathParamsTest, MissingTrailingParam) {
  8917. const auto pattern = "/users/:id";
  8918. detail::PathParamsMatcher matcher(pattern);
  8919. Request request;
  8920. request.path = "/users";
  8921. ASSERT_FALSE(matcher.match(request));
  8922. }
  8923. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8924. const auto pattern = "/users/:id/subscriptions";
  8925. detail::PathParamsMatcher matcher(pattern);
  8926. Request request;
  8927. request.path = "/users/subscriptions";
  8928. ASSERT_FALSE(matcher.match(request));
  8929. }
  8930. TEST(PathParamsTest, MultipleParams) {
  8931. const auto pattern = "/users/:userid/subscriptions/:subid";
  8932. detail::PathParamsMatcher matcher(pattern);
  8933. Request request;
  8934. request.path = "/users/42/subscriptions/2";
  8935. ASSERT_TRUE(matcher.match(request));
  8936. std::unordered_map<std::string, std::string> expected_params = {
  8937. {"userid", "42"}, {"subid", "2"}};
  8938. EXPECT_EQ(request.path_params, expected_params);
  8939. }
  8940. TEST(PathParamsTest, SequenceOfParams) {
  8941. const auto pattern = "/values/:x/:y/:z";
  8942. detail::PathParamsMatcher matcher(pattern);
  8943. Request request;
  8944. request.path = "/values/1/2/3";
  8945. ASSERT_TRUE(matcher.match(request));
  8946. std::unordered_map<std::string, std::string> expected_params = {
  8947. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8948. EXPECT_EQ(request.path_params, expected_params);
  8949. }
  8950. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8951. const auto pattern = "/prefix:suffix";
  8952. detail::PathParamsMatcher matcher(pattern);
  8953. Request request;
  8954. request.path = "/prefix:suffix";
  8955. ASSERT_TRUE(matcher.match(request));
  8956. const std::unordered_map<std::string, std::string> expected_params = {};
  8957. EXPECT_EQ(request.path_params, expected_params);
  8958. }
  8959. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8960. // If ipv6 regex working, regex match codepath is taken.
  8961. // else port will default to 80 in Client impl
  8962. int clientImplMagicPort = 80;
  8963. int port = 4321;
  8964. // above ports must be different to avoid false negative
  8965. EXPECT_NE(clientImplMagicPort, port);
  8966. std::string ipV6TestURL = "http://[ff06::c3]";
  8967. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8968. CLIENT_PRIVATE_KEY_FILE);
  8969. EXPECT_EQ(cli.port(), port);
  8970. }
  8971. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8972. auto file_path = "./www/dir/index.html";
  8973. auto dir_path = "./www/dir";
  8974. detail::FileStat stat_file(file_path);
  8975. EXPECT_TRUE(stat_file.is_file());
  8976. EXPECT_FALSE(stat_file.is_dir());
  8977. detail::FileStat stat_dir(dir_path);
  8978. EXPECT_FALSE(stat_dir.is_file());
  8979. EXPECT_TRUE(stat_dir.is_dir());
  8980. }
  8981. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8982. // IPv4 with default HTTP port (80)
  8983. EXPECT_EQ("example.com",
  8984. detail::make_host_and_port_string("example.com", 80, false));
  8985. // IPv4 with default HTTPS port (443)
  8986. EXPECT_EQ("example.com",
  8987. detail::make_host_and_port_string("example.com", 443, true));
  8988. // IPv4 with non-default HTTP port
  8989. EXPECT_EQ("example.com:8080",
  8990. detail::make_host_and_port_string("example.com", 8080, false));
  8991. // IPv4 with non-default HTTPS port
  8992. EXPECT_EQ("example.com:8443",
  8993. detail::make_host_and_port_string("example.com", 8443, true));
  8994. // IPv6 with default HTTP port (80)
  8995. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8996. // IPv6 with default HTTPS port (443)
  8997. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8998. // IPv6 with non-default HTTP port
  8999. EXPECT_EQ("[::1]:8080",
  9000. detail::make_host_and_port_string("::1", 8080, false));
  9001. // IPv6 with non-default HTTPS port
  9002. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9003. // IPv6 full address with default port
  9004. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9005. detail::make_host_and_port_string(
  9006. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9007. // IPv6 full address with non-default port
  9008. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9009. detail::make_host_and_port_string(
  9010. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9011. // IPv6 localhost with non-default port
  9012. EXPECT_EQ("[::1]:3000",
  9013. detail::make_host_and_port_string("::1", 3000, false));
  9014. // IPv6 with zone ID (link-local address) with default port
  9015. EXPECT_EQ("[fe80::1%eth0]",
  9016. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9017. // IPv6 with zone ID (link-local address) with non-default port
  9018. EXPECT_EQ("[fe80::1%eth0]:8080",
  9019. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9020. // Edge case: Port 443 with is_ssl=false (should add port)
  9021. EXPECT_EQ("example.com:443",
  9022. detail::make_host_and_port_string("example.com", 443, false));
  9023. // Edge case: Port 80 with is_ssl=true (should add port)
  9024. EXPECT_EQ("example.com:80",
  9025. detail::make_host_and_port_string("example.com", 80, true));
  9026. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9027. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9028. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9029. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9030. // Security fix: Already bracketed IPv6 should not get double brackets
  9031. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9032. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9033. EXPECT_EQ("[::1]:8080",
  9034. detail::make_host_and_port_string("[::1]", 8080, false));
  9035. EXPECT_EQ("[2001:db8::1]:8080",
  9036. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9037. EXPECT_EQ("[fe80::1%eth0]",
  9038. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9039. EXPECT_EQ("[fe80::1%eth0]:8080",
  9040. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9041. // Edge case: Empty host (should return as-is)
  9042. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9043. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9044. // This is a known limitation but shouldn't crash
  9045. EXPECT_EQ("[host:name]",
  9046. detail::make_host_and_port_string("host:name", 80, false));
  9047. // Port number edge cases (no validation, but should not crash)
  9048. EXPECT_EQ("example.com:0",
  9049. detail::make_host_and_port_string("example.com", 0, false));
  9050. EXPECT_EQ("example.com:-1",
  9051. detail::make_host_and_port_string("example.com", -1, false));
  9052. EXPECT_EQ("example.com:65535",
  9053. detail::make_host_and_port_string("example.com", 65535, false));
  9054. EXPECT_EQ("example.com:65536",
  9055. detail::make_host_and_port_string("example.com", 65536, false));
  9056. }
  9057. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9058. Server svr;
  9059. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9060. EXPECT_EQ(res.status, 400);
  9061. });
  9062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9063. auto se = detail::scope_exit([&] {
  9064. svr.stop();
  9065. thread.join();
  9066. ASSERT_FALSE(svr.is_running());
  9067. });
  9068. svr.wait_until_ready();
  9069. Client cli(HOST, PORT);
  9070. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9071. }
  9072. TEST(InvalidHeaderCharsTest, is_field_name) {
  9073. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9074. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9075. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9076. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9077. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9078. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9079. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9080. EXPECT_FALSE(detail::fields::is_field_name(""));
  9081. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9082. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9083. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9084. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9085. }
  9086. TEST(InvalidHeaderCharsTest, is_field_value) {
  9087. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9088. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9089. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9090. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9091. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9092. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9093. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9094. EXPECT_TRUE(detail::fields::is_field_value(""));
  9095. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9096. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9097. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9098. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9099. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9100. }
  9101. TEST(InvalidHeaderCharsTest, OnServer) {
  9102. Server svr;
  9103. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9104. std::string header = "Not Set";
  9105. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9106. res.set_header(header, "value");
  9107. res.set_content("Page Content Page Content", "text/plain");
  9108. });
  9109. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9110. std::string header = "Not Set";
  9111. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9112. res.set_header("X-Test", header);
  9113. res.set_content("Page Content Page Content", "text/plain");
  9114. });
  9115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9116. auto se = detail::scope_exit([&] {
  9117. svr.stop();
  9118. thread.join();
  9119. ASSERT_FALSE(svr.is_running());
  9120. });
  9121. svr.wait_until_ready();
  9122. Client cli(HOST, PORT);
  9123. {
  9124. auto res = cli.Get(
  9125. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9126. ASSERT_TRUE(res);
  9127. EXPECT_EQ("Page Content Page Content", res->body);
  9128. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9129. }
  9130. {
  9131. auto res = cli.Get(
  9132. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_EQ("Page Content Page Content", res->body);
  9135. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9136. }
  9137. }
  9138. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9139. auto handled = false;
  9140. Server svr;
  9141. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9142. thread t = thread([&] { svr.listen(HOST, PORT); });
  9143. auto se = detail::scope_exit([&] {
  9144. svr.stop();
  9145. t.join();
  9146. ASSERT_FALSE(svr.is_running());
  9147. ASSERT_FALSE(handled);
  9148. });
  9149. svr.wait_until_ready();
  9150. auto req = "POST /test HTTP/1.1\r\n"
  9151. "Content-Length: x\r\n"
  9152. "\r\n";
  9153. std::string response;
  9154. ASSERT_TRUE(send_request(1, req, &response));
  9155. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9156. response.substr(0, response.find("\r\n")));
  9157. }
  9158. #ifndef _WIN32
  9159. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9160. static constexpr char reject[] = "Unauthorized";
  9161. static constexpr char accept[] = "Upload accepted";
  9162. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9163. Server svr;
  9164. svr.set_expect_100_continue_handler(
  9165. [](const Request & /*req*/, Response &res) {
  9166. res.status = StatusCode::Unauthorized_401;
  9167. res.set_content(reject, "text/plain");
  9168. return res.status;
  9169. });
  9170. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9171. res.set_content(accept, "text/plain");
  9172. });
  9173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9174. auto se = detail::scope_exit([&] {
  9175. svr.stop();
  9176. thread.join();
  9177. ASSERT_FALSE(svr.is_running());
  9178. });
  9179. svr.wait_until_ready();
  9180. {
  9181. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9182. curl_easy_init(), &curl_easy_cleanup};
  9183. ASSERT_NE(curl, nullptr);
  9184. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9185. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9186. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9187. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9188. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9189. &curl_slist_free_all};
  9190. ASSERT_NE(list, nullptr);
  9191. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9192. struct read_data {
  9193. size_t read_size;
  9194. size_t total_size;
  9195. } data = {0, total_size};
  9196. using read_callback_t =
  9197. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9198. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9199. void *userdata) -> size_t {
  9200. read_data *data = (read_data *)userdata;
  9201. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9202. std::fill_n(ptr, size * nmemb, 'A');
  9203. data->read_size += size * nmemb;
  9204. return size * nmemb;
  9205. };
  9206. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9207. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9208. std::vector<char> buffer;
  9209. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9210. using write_callback_t =
  9211. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9212. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9213. void *userdata) -> size_t {
  9214. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9215. buffer->reserve(buffer->size() + size * nmemb + 1);
  9216. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9217. return size * nmemb;
  9218. };
  9219. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9220. {
  9221. const auto res = curl_easy_perform(curl.get());
  9222. ASSERT_EQ(res, CURLE_OK);
  9223. }
  9224. {
  9225. auto response_code = long{};
  9226. const auto res =
  9227. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9228. ASSERT_EQ(res, CURLE_OK);
  9229. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9230. }
  9231. {
  9232. auto dl = curl_off_t{};
  9233. const auto res =
  9234. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9235. ASSERT_EQ(res, CURLE_OK);
  9236. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9237. }
  9238. {
  9239. buffer.push_back('\0');
  9240. ASSERT_STRCASEEQ(buffer.data(), reject);
  9241. }
  9242. }
  9243. }
  9244. #endif
  9245. template <typename S, typename C>
  9246. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9247. svr.Get("/stream", [&](const Request &, Response &res) {
  9248. auto data = new std::string("01234567890123456789");
  9249. res.set_content_provider(
  9250. data->size(), "text/plain",
  9251. [&, data](size_t offset, size_t length, DataSink &sink) {
  9252. const size_t DATA_CHUNK_SIZE = 4;
  9253. const auto &d = *data;
  9254. std::this_thread::sleep_for(std::chrono::seconds(1));
  9255. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9256. return true;
  9257. },
  9258. [data](bool success) {
  9259. EXPECT_FALSE(success);
  9260. delete data;
  9261. });
  9262. });
  9263. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9264. auto i = new size_t(0);
  9265. res.set_content_provider(
  9266. "text/plain",
  9267. [i](size_t, DataSink &sink) {
  9268. if (*i < 5) {
  9269. std::this_thread::sleep_for(std::chrono::seconds(1));
  9270. sink.write("abcd", 4);
  9271. (*i)++;
  9272. } else {
  9273. sink.done();
  9274. }
  9275. return true;
  9276. },
  9277. [i](bool success) {
  9278. EXPECT_FALSE(success);
  9279. delete i;
  9280. });
  9281. });
  9282. svr.Get("/chunked", [&](const Request &, Response &res) {
  9283. auto i = new size_t(0);
  9284. res.set_chunked_content_provider(
  9285. "text/plain",
  9286. [i](size_t, DataSink &sink) {
  9287. if (*i < 5) {
  9288. std::this_thread::sleep_for(std::chrono::seconds(1));
  9289. sink.os << "abcd";
  9290. (*i)++;
  9291. } else {
  9292. sink.done();
  9293. }
  9294. return true;
  9295. },
  9296. [i](bool success) {
  9297. EXPECT_FALSE(success);
  9298. delete i;
  9299. });
  9300. });
  9301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9302. auto se = detail::scope_exit([&] {
  9303. svr.stop();
  9304. listen_thread.join();
  9305. ASSERT_FALSE(svr.is_running());
  9306. });
  9307. svr.wait_until_ready();
  9308. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9309. {
  9310. auto start = std::chrono::steady_clock::now();
  9311. auto res = cli.Get("/stream");
  9312. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9313. std::chrono::steady_clock::now() - start)
  9314. .count();
  9315. ASSERT_FALSE(res);
  9316. EXPECT_EQ(Error::Read, res.error());
  9317. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9318. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9319. }
  9320. {
  9321. auto start = std::chrono::steady_clock::now();
  9322. auto res = cli.Get("/stream_without_length");
  9323. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9324. std::chrono::steady_clock::now() - start)
  9325. .count();
  9326. ASSERT_FALSE(res);
  9327. EXPECT_EQ(Error::Read, res.error());
  9328. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9329. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9330. }
  9331. {
  9332. auto start = std::chrono::steady_clock::now();
  9333. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9334. EXPECT_EQ("abcd", string(data, data_length));
  9335. return true;
  9336. });
  9337. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9338. std::chrono::steady_clock::now() - start)
  9339. .count();
  9340. ASSERT_FALSE(res);
  9341. EXPECT_EQ(Error::Read, res.error());
  9342. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9343. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9344. }
  9345. }
  9346. TEST(MaxTimeoutTest, ContentStream) {
  9347. time_t timeout = 2000;
  9348. time_t threshold = 200;
  9349. Server svr;
  9350. Client cli("localhost", PORT);
  9351. max_timeout_test(svr, cli, timeout, threshold);
  9352. }
  9353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9354. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9355. time_t timeout = 2000;
  9356. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9358. SSLClient cli("localhost", PORT);
  9359. cli.enable_server_certificate_verification(false);
  9360. max_timeout_test(svr, cli, timeout, threshold);
  9361. }
  9362. #endif
  9363. class EventDispatcher {
  9364. public:
  9365. EventDispatcher() {}
  9366. bool wait_event(DataSink *sink) {
  9367. unique_lock<mutex> lk(m_);
  9368. int id = id_;
  9369. // Wait with timeout to prevent hanging if client disconnects
  9370. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9371. [&] { return cid_ == id; })) {
  9372. return false; // Timeout occurred
  9373. }
  9374. sink->write(message_.data(), message_.size());
  9375. return true;
  9376. }
  9377. void send_event(const string &message) {
  9378. lock_guard<mutex> lk(m_);
  9379. cid_ = id_++;
  9380. message_ = message;
  9381. cv_.notify_all();
  9382. }
  9383. private:
  9384. mutex m_;
  9385. condition_variable cv_;
  9386. atomic_int id_{0};
  9387. atomic_int cid_{-1};
  9388. string message_;
  9389. };
  9390. TEST(ClientInThreadTest, Issue2068) {
  9391. EventDispatcher ed;
  9392. Server svr;
  9393. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9394. res.set_chunked_content_provider("text/event-stream",
  9395. [&](size_t /*offset*/, DataSink &sink) {
  9396. return ed.wait_event(&sink);
  9397. });
  9398. });
  9399. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9400. svr.wait_until_ready();
  9401. thread event_thread([&] {
  9402. int id = 0;
  9403. while (svr.is_running()) {
  9404. this_thread::sleep_for(chrono::milliseconds(500));
  9405. std::stringstream ss;
  9406. ss << "data: " << id << "\n\n";
  9407. ed.send_event(ss.str());
  9408. id++;
  9409. }
  9410. });
  9411. auto se = detail::scope_exit([&] {
  9412. svr.stop();
  9413. listen_thread.join();
  9414. event_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. {
  9418. auto client = detail::make_unique<Client>(HOST, PORT);
  9419. client->set_read_timeout(std::chrono::minutes(10));
  9420. std::atomic<bool> stop{false};
  9421. std::thread t([&] {
  9422. client->Get("/event1",
  9423. [&](const char *, size_t) -> bool { return !stop; });
  9424. });
  9425. std::this_thread::sleep_for(std::chrono::seconds(2));
  9426. stop = true;
  9427. client->stop();
  9428. t.join();
  9429. // Reset client after thread has finished
  9430. client.reset();
  9431. }
  9432. }
  9433. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9434. Server svr;
  9435. svr.Get("/", [](const Request &req, Response &res) {
  9436. EXPECT_EQ(2U, req.trailers.size());
  9437. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9438. // Denied
  9439. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9440. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9441. // Accepted
  9442. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9443. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9444. EXPECT_TRUE(req.has_trailer("X-World"));
  9445. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. const std::string req = "GET / HTTP/1.1\r\n"
  9456. "Transfer-Encoding: chunked\r\n"
  9457. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9458. "\r\n"
  9459. "0\r\n"
  9460. "Content-Length: 10\r\n"
  9461. "Host: internal.local\r\n"
  9462. "Content-Type: malicious/content\r\n"
  9463. "Cookie: any\r\n"
  9464. "Set-Cookie: any\r\n"
  9465. "X-Forwarded-For: attacker.com\r\n"
  9466. "X-Real-Ip: 1.1.1.1\r\n"
  9467. "X-Hello: hello\r\n"
  9468. "X-World: world\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(1, req, &res));
  9472. }
  9473. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9474. Server svr;
  9475. std::string observed_remote_addr;
  9476. std::string observed_xff;
  9477. svr.Get("/ip", [&](const Request &req, Response &res) {
  9478. observed_remote_addr = req.remote_addr;
  9479. observed_xff = req.get_header_value("X-Forwarded-For");
  9480. res.set_content("ok", "text/plain");
  9481. });
  9482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9483. auto se = detail::scope_exit([&] {
  9484. svr.stop();
  9485. t.join();
  9486. ASSERT_FALSE(svr.is_running());
  9487. });
  9488. svr.wait_until_ready();
  9489. Client cli(HOST, PORT);
  9490. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9491. ASSERT_TRUE(res);
  9492. EXPECT_EQ(StatusCode::OK_200, res->status);
  9493. EXPECT_EQ(observed_xff, "203.0.113.66");
  9494. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9495. observed_remote_addr == "127.0.0.1");
  9496. }
  9497. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9498. Server svr;
  9499. svr.set_trusted_proxies({"203.0.113.66"});
  9500. std::string observed_remote_addr;
  9501. std::string observed_xff;
  9502. svr.Get("/ip", [&](const Request &req, Response &res) {
  9503. observed_remote_addr = req.remote_addr;
  9504. observed_xff = req.get_header_value("X-Forwarded-For");
  9505. res.set_content("ok", "text/plain");
  9506. });
  9507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9508. auto se = detail::scope_exit([&] {
  9509. svr.stop();
  9510. t.join();
  9511. ASSERT_FALSE(svr.is_running());
  9512. });
  9513. svr.wait_until_ready();
  9514. Client cli(HOST, PORT);
  9515. auto res = cli.Get("/ip");
  9516. ASSERT_TRUE(res);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. EXPECT_EQ(observed_xff, "");
  9519. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9520. observed_remote_addr == "127.0.0.1");
  9521. }
  9522. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9523. Server svr;
  9524. svr.set_trusted_proxies({"203.0.113.66"});
  9525. std::string observed_remote_addr;
  9526. std::string observed_xff;
  9527. svr.Get("/ip", [&](const Request &req, Response &res) {
  9528. observed_remote_addr = req.remote_addr;
  9529. observed_xff = req.get_header_value("X-Forwarded-For");
  9530. res.set_content("ok", "text/plain");
  9531. });
  9532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9533. auto se = detail::scope_exit([&] {
  9534. svr.stop();
  9535. t.join();
  9536. ASSERT_FALSE(svr.is_running());
  9537. });
  9538. svr.wait_until_ready();
  9539. Client cli(HOST, PORT);
  9540. auto res =
  9541. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9542. ASSERT_TRUE(res);
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9545. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9546. }
  9547. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9548. Server svr;
  9549. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9550. std::string observed_remote_addr;
  9551. std::string observed_xff;
  9552. svr.Get("/ip", [&](const Request &req, Response &res) {
  9553. observed_remote_addr = req.remote_addr;
  9554. observed_xff = req.get_header_value("X-Forwarded-For");
  9555. res.set_content("ok", "text/plain");
  9556. });
  9557. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9558. auto se = detail::scope_exit([&] {
  9559. svr.stop();
  9560. t.join();
  9561. ASSERT_FALSE(svr.is_running());
  9562. });
  9563. svr.wait_until_ready();
  9564. Client cli(HOST, PORT);
  9565. auto res = cli.Get(
  9566. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9567. ASSERT_TRUE(res);
  9568. EXPECT_EQ(StatusCode::OK_200, res->status);
  9569. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9570. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9571. }
  9572. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9573. Server svr;
  9574. svr.set_trusted_proxies({"192.0.2.45"});
  9575. std::string observed_remote_addr;
  9576. std::string observed_xff;
  9577. svr.Get("/ip", [&](const Request &req, Response &res) {
  9578. observed_remote_addr = req.remote_addr;
  9579. observed_xff = req.get_header_value("X-Forwarded-For");
  9580. res.set_content("ok", "text/plain");
  9581. });
  9582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9583. auto se = detail::scope_exit([&] {
  9584. svr.stop();
  9585. t.join();
  9586. ASSERT_FALSE(svr.is_running());
  9587. });
  9588. svr.wait_until_ready();
  9589. Client cli(HOST, PORT);
  9590. auto res =
  9591. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9592. ASSERT_TRUE(res);
  9593. EXPECT_EQ(StatusCode::OK_200, res->status);
  9594. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9595. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9596. }
  9597. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9598. Server svr;
  9599. svr.set_trusted_proxies({"192.0.2.45"});
  9600. std::string observed_remote_addr;
  9601. std::string observed_xff;
  9602. svr.Get("/ip", [&](const Request &req, Response &res) {
  9603. observed_remote_addr = req.remote_addr;
  9604. observed_xff = req.get_header_value("X-Forwarded-For");
  9605. res.set_content("ok", "text/plain");
  9606. });
  9607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9608. auto se = detail::scope_exit([&] {
  9609. svr.stop();
  9610. t.join();
  9611. ASSERT_FALSE(svr.is_running());
  9612. });
  9613. svr.wait_until_ready();
  9614. Client cli(HOST, PORT);
  9615. auto res = cli.Get(
  9616. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9617. ASSERT_TRUE(res);
  9618. EXPECT_EQ(StatusCode::OK_200, res->status);
  9619. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9620. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9621. }
  9622. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9623. Server svr;
  9624. svr.set_trusted_proxies({"192.0.2.45"});
  9625. std::string observed_remote_addr;
  9626. std::string observed_xff;
  9627. svr.Get("/ip", [&](const Request &req, Response &res) {
  9628. observed_remote_addr = req.remote_addr;
  9629. observed_xff = req.get_header_value("X-Forwarded-For");
  9630. res.set_content("ok", "text/plain");
  9631. });
  9632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9633. auto se = detail::scope_exit([&] {
  9634. svr.stop();
  9635. t.join();
  9636. ASSERT_FALSE(svr.is_running());
  9637. });
  9638. svr.wait_until_ready();
  9639. Client cli(HOST, PORT);
  9640. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9641. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9642. ASSERT_TRUE(res);
  9643. EXPECT_EQ(StatusCode::OK_200, res->status);
  9644. // Header parser trims surrounding whitespace of the header value
  9645. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9646. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9647. }
  9648. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9649. Server svr;
  9650. svr.Post("/post", [&](const Request &req, Response &res) {
  9651. res.set_content(req.body, "text/plain");
  9652. });
  9653. svr.Put("/put", [&](const Request &req, Response &res) {
  9654. res.set_content(req.body, "text/plain");
  9655. });
  9656. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9657. res.set_content(req.body, "text/plain");
  9658. });
  9659. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9660. res.set_content(req.body, "text/plain");
  9661. });
  9662. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9663. auto se = detail::scope_exit([&] {
  9664. svr.stop();
  9665. t.join();
  9666. ASSERT_FALSE(svr.is_running());
  9667. });
  9668. svr.wait_until_ready();
  9669. std::string resp;
  9670. // POST without Content-Length
  9671. ASSERT_TRUE(send_request(5,
  9672. "POST /post HTTP/1.1\r\n"
  9673. "Host: localhost\r\n"
  9674. "Connection: close\r\n"
  9675. "\r\n",
  9676. &resp));
  9677. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9678. // PUT without Content-Length
  9679. resp.clear();
  9680. ASSERT_TRUE(send_request(5,
  9681. "PUT /put HTTP/1.1\r\n"
  9682. "Host: localhost\r\n"
  9683. "Connection: close\r\n"
  9684. "\r\n",
  9685. &resp));
  9686. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9687. // PATCH without Content-Length
  9688. resp.clear();
  9689. ASSERT_TRUE(send_request(5,
  9690. "PATCH /patch HTTP/1.1\r\n"
  9691. "Host: localhost\r\n"
  9692. "Connection: close\r\n"
  9693. "\r\n",
  9694. &resp));
  9695. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9696. // DELETE without Content-Length
  9697. resp.clear();
  9698. ASSERT_TRUE(send_request(5,
  9699. "DELETE /delete HTTP/1.1\r\n"
  9700. "Host: localhost\r\n"
  9701. "Connection: close\r\n"
  9702. "\r\n",
  9703. &resp));
  9704. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9705. }