test.cc 436 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. Server svr;
  74. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  75. res.set_content("Benchmark Response", "text/plain");
  76. });
  77. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  78. auto se = detail::scope_exit([&] {
  79. svr.stop();
  80. listen_thread.join();
  81. ASSERT_FALSE(svr.is_running());
  82. });
  83. svr.wait_until_ready();
  84. Client cli(host, PORT);
  85. // Warm-up request to establish connection and resolve DNS
  86. auto warmup_res = cli.Get("/benchmark");
  87. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  88. // Run multiple trials and collect timings
  89. const int num_trials = 20;
  90. std::vector<int64_t> timings;
  91. timings.reserve(num_trials);
  92. for (int i = 0; i < num_trials; i++) {
  93. auto start = std::chrono::high_resolution_clock::now();
  94. auto res = cli.Get("/benchmark");
  95. auto end = std::chrono::high_resolution_clock::now();
  96. auto elapsed =
  97. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  98. .count();
  99. // Assertions after timing measurement to avoid overhead
  100. ASSERT_TRUE(res);
  101. EXPECT_EQ(StatusCode::OK_200, res->status);
  102. timings.push_back(elapsed);
  103. }
  104. // Calculate 25th percentile (lower quartile)
  105. std::sort(timings.begin(), timings.end());
  106. auto p25 = timings[num_trials / 4];
  107. // Format timings for output
  108. std::ostringstream timings_str;
  109. timings_str << "[";
  110. for (size_t i = 0; i < timings.size(); i++) {
  111. if (i > 0) timings_str << ", ";
  112. timings_str << timings[i];
  113. }
  114. timings_str << "]";
  115. // Localhost HTTP GET should be fast even in CI environments
  116. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  117. << "ms (Issue #1777). Timings: " << timings_str.str();
  118. }
  119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  120. #ifdef _WIN32
  121. // Windows Certificate Verification Tests
  122. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  123. // Test 1: Default behavior (Windows verification enabled)
  124. SSLClient cli("www.google.com", 443);
  125. cli.enable_server_certificate_verification(true);
  126. auto res = cli.Get("/");
  127. // Should succeed or fail gracefully (may fail due to network)
  128. // The important thing is that Windows verification was enabled
  129. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  130. }
  131. TEST(SSLClientTest, WindowsCertificateVerification_DisableWindows) {
  132. // Test 2: Disable Windows verification (OpenSSL only)
  133. SSLClient cli("www.google.com", 443);
  134. cli.enable_server_certificate_verification(true);
  135. cli.enable_windows_certificate_verification(false);
  136. auto res = cli.Get("/");
  137. // Should work with OpenSSL verification only
  138. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  139. }
  140. TEST(SSLClientTest, WindowsCertificateVerification_CustomTimeout) {
  141. // Test 3: Custom timeout
  142. SSLClient cli("www.google.com", 443);
  143. cli.enable_server_certificate_verification(true);
  144. cli.set_windows_certificate_verification_timeout(2);
  145. auto res = cli.Get("/");
  146. // Should complete within reasonable time
  147. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  148. }
  149. TEST(SSLClientTest, WindowsCertificateVerification_InvalidCertificate) {
  150. // Test 4: Invalid certificate (should fail)
  151. SSLClient cli("self-signed.badssl.com", 443);
  152. cli.enable_server_certificate_verification(true);
  153. auto res = cli.Get("/");
  154. // Should fail due to invalid certificate
  155. EXPECT_FALSE(res);
  156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  157. }
  158. TEST(SSLClientTest, WindowsCertificateVerification_CachingBehavior) {
  159. // Test 5: Multiple connections (test caching)
  160. SSLClient cli("www.google.com", 443);
  161. cli.enable_server_certificate_verification(true);
  162. // First connection
  163. auto res1 = cli.Get("/");
  164. auto start2 = std::chrono::high_resolution_clock::now();
  165. // Second connection (should use cache)
  166. auto res2 = cli.Get("/");
  167. auto end2 = std::chrono::high_resolution_clock::now();
  168. auto duration2 =
  169. std::chrono::duration_cast<std::chrono::milliseconds>(end2 - start2);
  170. // Second connection should be fast (cache hit)
  171. if (res2) {
  172. EXPECT_NE(StatusCode::InternalServerError_500, res2->status);
  173. // Cache should make second connection faster (very loose bound)
  174. EXPECT_LT(duration2.count(), 5000); // Within 5 seconds
  175. }
  176. }
  177. #endif
  178. #endif
  179. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  180. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  181. class UnixSocketTest : public ::testing::Test {
  182. protected:
  183. void TearDown() override { std::remove(pathname_.c_str()); }
  184. void client_GET(const std::string &addr) {
  185. httplib::Client cli{addr};
  186. cli.set_address_family(AF_UNIX);
  187. ASSERT_TRUE(cli.is_valid());
  188. const auto &result = cli.Get(pattern_);
  189. ASSERT_TRUE(result) << "error: " << result.error();
  190. const auto &resp = result.value();
  191. EXPECT_EQ(resp.status, StatusCode::OK_200);
  192. EXPECT_EQ(resp.body, content_);
  193. }
  194. const std::string pathname_{"./httplib-server.sock"};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. }
  215. #if defined(__linux__) || \
  216. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  217. TEST_F(UnixSocketTest, PeerPid) {
  218. httplib::Server svr;
  219. std::string remote_port_val;
  220. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  221. res.set_content(content_, "text/plain");
  222. remote_port_val = std::to_string(req.remote_port);
  223. });
  224. std::thread t{[&] {
  225. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  226. }};
  227. auto se = detail::scope_exit([&] {
  228. svr.stop();
  229. t.join();
  230. ASSERT_FALSE(svr.is_running());
  231. });
  232. svr.wait_until_ready();
  233. ASSERT_TRUE(svr.is_running());
  234. client_GET(pathname_);
  235. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  236. }
  237. #endif
  238. #ifdef __linux__
  239. TEST_F(UnixSocketTest, abstract) {
  240. constexpr char svr_path[]{"\x00httplib-server.sock"};
  241. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  242. httplib::Server svr;
  243. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  244. res.set_content(content_, "text/plain");
  245. });
  246. std::thread t{[&] {
  247. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  248. }};
  249. auto se = detail::scope_exit([&] {
  250. svr.stop();
  251. t.join();
  252. ASSERT_FALSE(svr.is_running());
  253. });
  254. svr.wait_until_ready();
  255. ASSERT_TRUE(svr.is_running());
  256. client_GET(abstract_addr);
  257. }
  258. #endif
  259. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  260. httplib::Server svr;
  261. std::string received_host_header;
  262. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  263. // Capture the Host header sent by the client
  264. auto host_iter = req.headers.find("Host");
  265. if (host_iter != req.headers.end()) {
  266. received_host_header = host_iter->second;
  267. }
  268. res.set_content(content_, "text/plain");
  269. });
  270. std::thread t{[&] {
  271. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  272. }};
  273. auto se = detail::scope_exit([&] {
  274. svr.stop();
  275. t.join();
  276. ASSERT_FALSE(svr.is_running());
  277. });
  278. svr.wait_until_ready();
  279. ASSERT_TRUE(svr.is_running());
  280. // Test that Host header is automatically set to "localhost" for Unix socket
  281. // connections
  282. httplib::Client cli{pathname_};
  283. cli.set_address_family(AF_UNIX);
  284. ASSERT_TRUE(cli.is_valid());
  285. const auto &result = cli.Get(pattern_);
  286. ASSERT_TRUE(result) << "error: " << result.error();
  287. const auto &resp = result.value();
  288. EXPECT_EQ(resp.status, StatusCode::OK_200);
  289. EXPECT_EQ(resp.body, content_);
  290. // Verify that Host header was automatically set to "localhost"
  291. EXPECT_EQ(received_host_header, "localhost");
  292. }
  293. #ifndef _WIN32
  294. TEST(SocketStream, wait_writable_UNIX) {
  295. int fds[2];
  296. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  297. const auto asSocketStream = [&](socket_t fd,
  298. std::function<bool(Stream &)> func) {
  299. return detail::process_client_socket(
  300. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  301. };
  302. asSocketStream(fds[0], [&](Stream &s0) {
  303. EXPECT_EQ(s0.socket(), fds[0]);
  304. EXPECT_TRUE(s0.wait_writable());
  305. EXPECT_EQ(0, close(fds[1]));
  306. EXPECT_FALSE(s0.wait_writable());
  307. return true;
  308. });
  309. EXPECT_EQ(0, close(fds[0]));
  310. }
  311. TEST(SocketStream, wait_writable_INET) {
  312. sockaddr_in addr;
  313. memset(&addr, 0, sizeof(addr));
  314. addr.sin_family = AF_INET;
  315. addr.sin_port = htons(PORT + 1);
  316. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  317. int disconnected_svr_sock = -1;
  318. std::thread svr{[&] {
  319. const int s = socket(AF_INET, SOCK_STREAM, 0);
  320. ASSERT_LE(0, s);
  321. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  322. ASSERT_EQ(0, listen(s, 1));
  323. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  324. ASSERT_EQ(0, close(s));
  325. }};
  326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  327. std::thread cli{[&] {
  328. const int s = socket(AF_INET, SOCK_STREAM, 0);
  329. ASSERT_LE(0, s);
  330. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  331. ASSERT_EQ(0, close(s));
  332. }};
  333. cli.join();
  334. svr.join();
  335. ASSERT_NE(disconnected_svr_sock, -1);
  336. const auto asSocketStream = [&](socket_t fd,
  337. std::function<bool(Stream &)> func) {
  338. return detail::process_client_socket(
  339. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  340. };
  341. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  342. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  343. EXPECT_FALSE(ss.wait_writable());
  344. return true;
  345. });
  346. ASSERT_EQ(0, close(disconnected_svr_sock));
  347. }
  348. #endif // #ifndef _WIN32
  349. TEST(ClientTest, MoveConstructible) {
  350. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  351. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  352. }
  353. TEST(ClientTest, MoveAssignable) {
  354. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  355. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  356. }
  357. #ifdef _WIN32
  358. TEST(StartupTest, WSAStartup) {
  359. WSADATA wsaData;
  360. int ret = WSAStartup(0x0002, &wsaData);
  361. ASSERT_EQ(0, ret);
  362. }
  363. #endif
  364. TEST(DecodePathTest, PercentCharacter) {
  365. EXPECT_EQ(
  366. decode_path_component(
  367. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  368. u8"descrip=Gastos áéíóúñÑ 6");
  369. }
  370. TEST(DecodePathTest, PercentCharacterNUL) {
  371. string expected;
  372. expected.push_back('x');
  373. expected.push_back('\0');
  374. expected.push_back('x');
  375. EXPECT_EQ(decode_path_component("x%00x"), expected);
  376. }
  377. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  378. string unescapedCharacters = "-_.!~*'()";
  379. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  380. }
  381. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  382. string reservedCharacters = ";,/?:@&=+$";
  383. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  384. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  385. }
  386. TEST(ClientQueryOrder, PreserveOrder) {
  387. // This test reproduces Issue #2259: client may reorder query parameters
  388. // when sending a GET request. The expected behavior is that the client
  389. // preserves the original query string order when the caller supplied it
  390. // as part of the path.
  391. Server svr;
  392. svr.Get("/", [&](const Request &req, Response &res) {
  393. // Echo back the raw target so the test can assert ordering
  394. res.set_content(req.target, "text/plain");
  395. });
  396. std::thread t{[&] { svr.listen(HOST, PORT); }};
  397. auto se = detail::scope_exit([&] {
  398. svr.stop();
  399. t.join();
  400. ASSERT_FALSE(svr.is_running());
  401. });
  402. svr.wait_until_ready();
  403. Client cli(HOST, PORT);
  404. ASSERT_TRUE(cli.is_valid());
  405. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  406. auto res = cli.Get(original);
  407. ASSERT_TRUE(res);
  408. // Expect the echoed target to exactly match the original path (order
  409. // preserved)
  410. EXPECT_EQ(res->body, original);
  411. }
  412. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  413. string chineseCharacters = u8"中国語";
  414. string russianCharacters = u8"дом";
  415. string brazilianCharacters = u8"óculos";
  416. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  417. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  418. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  419. "%D0%B4%D0%BE%D0%BC");
  420. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  421. }
  422. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  423. string unescapedCharacters = "-_.!~*'()";
  424. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  425. }
  426. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  427. string reservedCharacters = ";,/?:@&=+$";
  428. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  429. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  430. }
  431. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  432. string chineseCharacters = u8"中国語";
  433. string russianCharacters = u8"дом";
  434. string brazilianCharacters = u8"óculos";
  435. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  436. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  437. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  438. "%D0%B4%D0%BE%D0%BC");
  439. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  440. }
  441. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  442. // Issue #2082 use case: encoding path component with ampersand
  443. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  444. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  445. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  446. }
  447. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  448. string unescapedCharacters = "-_.!~*'()";
  449. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  450. }
  451. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  452. string reservedCharacters = ";,/?:@&=+$#";
  453. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  454. }
  455. TEST(EncodeUriTest, TestUTF8Characters) {
  456. string chineseCharacters = u8"中国語";
  457. string russianCharacters = u8"дом";
  458. string brazilianCharacters = u8"óculos";
  459. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  460. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  461. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  462. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  463. }
  464. TEST(EncodeUriTest, TestCompleteUri) {
  465. string uri =
  466. "https://example.com/path/to/resource?query=value&param=test#fragment";
  467. EXPECT_EQ(
  468. httplib::encode_uri(uri),
  469. "https://example.com/path/to/resource?query=value&param=test#fragment");
  470. }
  471. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  472. string uri =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. EXPECT_EQ(httplib::encode_uri(uri),
  475. "https://example.com/path%20with%20spaces/"
  476. "file%20name.html?q=hello%20world");
  477. }
  478. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  479. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  480. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  481. }
  482. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  483. string unescapedCharacters = "-_.!~*'()";
  484. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  485. }
  486. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  487. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  488. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  489. string encodedBrazilian = "%C3%B3culos";
  490. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  491. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  492. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  493. }
  494. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  495. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  497. "Piri Tommy Villiers - on & on");
  498. }
  499. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  500. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  501. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  502. }
  503. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  504. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  505. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  506. }
  507. TEST(DecodeUriTest, TestUTF8Characters) {
  508. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  509. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  510. string encodedBrazilian = "%C3%B3culos";
  511. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  512. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  513. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  514. }
  515. TEST(DecodeUriTest, TestCompleteUri) {
  516. string encodedUri = "https://example.com/path%20with%20spaces/"
  517. "file%20name.html?q=hello%20world";
  518. EXPECT_EQ(
  519. httplib::decode_uri(encodedUri),
  520. "https://example.com/path with spaces/file name.html?q=hello world");
  521. }
  522. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  523. string original =
  524. "https://example.com/path with spaces/file name.html?q=hello world";
  525. string encoded = httplib::encode_uri(original);
  526. string decoded = httplib::decode_uri(encoded);
  527. EXPECT_EQ(decoded, original);
  528. }
  529. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  530. string original = "Piri Tommy Villiers - on & on";
  531. string encoded = httplib::encode_uri_component(original);
  532. string decoded = httplib::decode_uri_component(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(TrimTests, TrimStringTests) {
  536. EXPECT_EQ("abc", detail::trim_copy("abc"));
  537. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  538. EXPECT_TRUE(detail::trim_copy("").empty());
  539. }
  540. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  541. // Simple case without quality values
  542. std::vector<std::string> result1;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/html,application/json,text/plain", result1));
  545. EXPECT_EQ(result1.size(), 3U);
  546. EXPECT_EQ(result1[0], "text/html");
  547. EXPECT_EQ(result1[1], "application/json");
  548. EXPECT_EQ(result1[2], "text/plain");
  549. // With quality values
  550. std::vector<std::string> result2;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  553. EXPECT_EQ(result2.size(), 3U);
  554. EXPECT_EQ(result2[0], "application/json"); // highest q value
  555. EXPECT_EQ(result2[1], "text/html");
  556. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  557. }
  558. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  559. // Mixed with and without quality values
  560. std::vector<std::string> result;
  561. EXPECT_TRUE(detail::parse_accept_header(
  562. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  563. EXPECT_EQ(result.size(), 3U);
  564. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  565. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  566. EXPECT_EQ(result[2], "application/json"); // q=0.5
  567. }
  568. TEST(ParseAcceptHeaderTest, EdgeCases) {
  569. // Empty header
  570. std::vector<std::string> empty_result;
  571. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  572. EXPECT_TRUE(empty_result.empty());
  573. // Single type
  574. std::vector<std::string> single_result;
  575. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  576. EXPECT_EQ(single_result.size(), 1U);
  577. EXPECT_EQ(single_result[0], "application/json");
  578. // Wildcard types
  579. std::vector<std::string> wildcard_result;
  580. EXPECT_TRUE(detail::parse_accept_header(
  581. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  582. EXPECT_EQ(wildcard_result.size(), 3U);
  583. EXPECT_EQ(wildcard_result[0], "application/json");
  584. EXPECT_EQ(wildcard_result[1], "text/*");
  585. EXPECT_EQ(wildcard_result[2], "*/*");
  586. }
  587. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  588. // Common browser Accept header
  589. std::vector<std::string> browser_result;
  590. EXPECT_TRUE(
  591. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  592. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  593. browser_result));
  594. EXPECT_EQ(browser_result.size(), 6U);
  595. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  596. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  597. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  598. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  599. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  600. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  601. // API client header
  602. std::vector<std::string> api_result;
  603. EXPECT_TRUE(detail::parse_accept_header(
  604. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  605. api_result));
  606. EXPECT_EQ(api_result.size(), 3U);
  607. EXPECT_EQ(api_result[0], "application/json");
  608. EXPECT_EQ(api_result[1], "application/xml");
  609. EXPECT_EQ(api_result[2], "text/plain");
  610. }
  611. TEST(ParseAcceptHeaderTest, SpecialCases) {
  612. // Quality value with 3 decimal places
  613. std::vector<std::string> decimal_result;
  614. EXPECT_TRUE(detail::parse_accept_header(
  615. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  616. EXPECT_EQ(decimal_result.size(), 2U);
  617. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  618. EXPECT_EQ(decimal_result[1], "text/html");
  619. // Zero quality (should still be included but with lowest priority)
  620. std::vector<std::string> zero_q_result;
  621. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  622. zero_q_result));
  623. EXPECT_EQ(zero_q_result.size(), 2U);
  624. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  625. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  626. // No spaces around commas
  627. std::vector<std::string> no_space_result;
  628. EXPECT_TRUE(detail::parse_accept_header(
  629. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  630. no_space_result));
  631. EXPECT_EQ(no_space_result.size(), 3U);
  632. EXPECT_EQ(no_space_result[0], "text/html");
  633. EXPECT_EQ(no_space_result[1], "application/json");
  634. EXPECT_EQ(no_space_result[2], "text/plain");
  635. }
  636. TEST(ParseAcceptHeaderTest, InvalidCases) {
  637. std::vector<std::string> result;
  638. // Invalid quality value (> 1.0)
  639. EXPECT_FALSE(
  640. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  641. // Invalid quality value (< 0.0)
  642. EXPECT_FALSE(
  643. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  644. // Invalid quality value (not a number)
  645. EXPECT_FALSE(detail::parse_accept_header(
  646. "text/html;q=invalid,application/json", result));
  647. // Empty quality value
  648. EXPECT_FALSE(
  649. detail::parse_accept_header("text/html;q=,application/json", result));
  650. // Invalid media type format (no slash and not wildcard)
  651. EXPECT_FALSE(
  652. detail::parse_accept_header("invalidtype,application/json", result));
  653. // Empty media type
  654. result.clear();
  655. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  656. // Only commas
  657. result.clear();
  658. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  659. // Valid cases should still work
  660. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  661. EXPECT_EQ(result.size(), 1U);
  662. EXPECT_EQ(result[0], "*/*");
  663. EXPECT_TRUE(detail::parse_accept_header("*", result));
  664. EXPECT_EQ(result.size(), 1U);
  665. EXPECT_EQ(result[0], "*");
  666. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  667. EXPECT_EQ(result.size(), 1U);
  668. EXPECT_EQ(result[0], "text/*");
  669. }
  670. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  671. Server svr;
  672. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  673. EXPECT_EQ(req.accept_content_types.size(), 3U);
  674. EXPECT_EQ(req.accept_content_types[0], "application/json");
  675. EXPECT_EQ(req.accept_content_types[1], "text/html");
  676. EXPECT_EQ(req.accept_content_types[2], "*/*");
  677. res.set_content("ok", "text/plain");
  678. });
  679. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  680. EXPECT_TRUE(false);
  681. res.set_content("bad request", "text/plain");
  682. });
  683. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  684. auto se = detail::scope_exit([&] {
  685. svr.stop();
  686. listen_thread.join();
  687. ASSERT_FALSE(svr.is_running());
  688. });
  689. svr.wait_until_ready();
  690. Client cli("localhost", PORT);
  691. {
  692. auto res =
  693. cli.Get("/accept_ok",
  694. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  695. ASSERT_TRUE(res);
  696. EXPECT_EQ(StatusCode::OK_200, res->status);
  697. }
  698. {
  699. auto res = cli.Get("/accept_bad_request",
  700. {{"Accept", "text/html;q=abc,application/json"}});
  701. ASSERT_TRUE(res);
  702. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  703. }
  704. }
  705. TEST(DivideTest, DivideStringTests) {
  706. auto divide = [](const std::string &str, char d) {
  707. std::string lhs;
  708. std::string rhs;
  709. detail::divide(str, d,
  710. [&](const char *lhs_data, std::size_t lhs_size,
  711. const char *rhs_data, std::size_t rhs_size) {
  712. lhs.assign(lhs_data, lhs_size);
  713. rhs.assign(rhs_data, rhs_size);
  714. });
  715. return std::make_pair(std::move(lhs), std::move(rhs));
  716. };
  717. {
  718. const auto res = divide("", '=');
  719. EXPECT_EQ(res.first, "");
  720. EXPECT_EQ(res.second, "");
  721. }
  722. {
  723. const auto res = divide("=", '=');
  724. EXPECT_EQ(res.first, "");
  725. EXPECT_EQ(res.second, "");
  726. }
  727. {
  728. const auto res = divide(" ", '=');
  729. EXPECT_EQ(res.first, " ");
  730. EXPECT_EQ(res.second, "");
  731. }
  732. {
  733. const auto res = divide("a", '=');
  734. EXPECT_EQ(res.first, "a");
  735. EXPECT_EQ(res.second, "");
  736. }
  737. {
  738. const auto res = divide("a=", '=');
  739. EXPECT_EQ(res.first, "a");
  740. EXPECT_EQ(res.second, "");
  741. }
  742. {
  743. const auto res = divide("=b", '=');
  744. EXPECT_EQ(res.first, "");
  745. EXPECT_EQ(res.second, "b");
  746. }
  747. {
  748. const auto res = divide("a=b", '=');
  749. EXPECT_EQ(res.first, "a");
  750. EXPECT_EQ(res.second, "b");
  751. }
  752. {
  753. const auto res = divide("a=b=", '=');
  754. EXPECT_EQ(res.first, "a");
  755. EXPECT_EQ(res.second, "b=");
  756. }
  757. {
  758. const auto res = divide("a=b=c", '=');
  759. EXPECT_EQ(res.first, "a");
  760. EXPECT_EQ(res.second, "b=c");
  761. }
  762. }
  763. TEST(SplitTest, ParseQueryString) {
  764. string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  767. [&](const char *b, const char *e) {
  768. string key, val;
  769. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  770. if (key.empty()) {
  771. key.assign(b2, e2);
  772. } else {
  773. val.assign(b2, e2);
  774. }
  775. });
  776. dic.emplace(key, val);
  777. });
  778. EXPECT_EQ("val1", dic.find("key1")->second);
  779. EXPECT_EQ("val2", dic.find("key2")->second);
  780. EXPECT_EQ("val3", dic.find("key3")->second);
  781. }
  782. TEST(SplitTest, ParseInvalidQueryTests) {
  783. {
  784. string s = " ";
  785. Params dict;
  786. detail::parse_query_text(s, dict);
  787. EXPECT_TRUE(dict.empty());
  788. }
  789. {
  790. string s = " = =";
  791. Params dict;
  792. detail::parse_query_text(s, dict);
  793. EXPECT_TRUE(dict.empty());
  794. }
  795. }
  796. TEST(ParseQueryTest, ParseQueryString) {
  797. {
  798. std::string s = "key1=val1&key2=val2&key3=val3";
  799. Params dic;
  800. detail::parse_query_text(s, dic);
  801. EXPECT_EQ("val1", dic.find("key1")->second);
  802. EXPECT_EQ("val2", dic.find("key2")->second);
  803. EXPECT_EQ("val3", dic.find("key3")->second);
  804. }
  805. {
  806. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  807. Params dic;
  808. detail::parse_query_text(s, dic);
  809. EXPECT_EQ("", dic.find("key1")->second);
  810. EXPECT_EQ("val1", dic.find("key2")->second);
  811. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  812. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  813. }
  814. }
  815. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  816. Params dic;
  817. EXPECT_EQ(detail::params_to_query_str(dic), "");
  818. dic.emplace("key1", "val1");
  819. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  820. dic.emplace("key2", "val2");
  821. dic.emplace("key3", "val3");
  822. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  823. }
  824. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  825. string content_type = "multipart/form-data; boundary=something";
  826. string boundary;
  827. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  828. EXPECT_TRUE(ret);
  829. EXPECT_EQ(boundary, "something");
  830. }
  831. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  832. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  833. string boundary;
  834. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  835. EXPECT_TRUE(ret);
  836. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  837. }
  838. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  839. string content_type =
  840. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  841. string boundary;
  842. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  843. EXPECT_TRUE(ret);
  844. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  845. }
  846. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  847. string content_type =
  848. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  849. string boundary;
  850. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  851. EXPECT_TRUE(ret);
  852. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  853. }
  854. TEST(GetHeaderValueTest, DefaultValue) {
  855. Headers headers = {{"Dummy", "Dummy"}};
  856. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  857. EXPECT_STREQ("text/plain", val);
  858. }
  859. TEST(GetHeaderValueTest, DefaultValueInt) {
  860. Headers headers = {{"Dummy", "Dummy"}};
  861. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  862. EXPECT_EQ(100ull, val);
  863. }
  864. TEST(GetHeaderValueTest, RegularValue) {
  865. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  866. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  867. EXPECT_STREQ("text/html", val);
  868. }
  869. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  870. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  871. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  872. EXPECT_STREQ("text/html", val);
  873. }
  874. TEST(GetHeaderValueTest, SetContent) {
  875. Response res;
  876. res.set_content("html", "text/html");
  877. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  878. res.set_content("text", "text/plain");
  879. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  880. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  881. }
  882. TEST(GetHeaderValueTest, RegularValueInt) {
  883. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  884. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  885. EXPECT_EQ(100ull, val);
  886. }
  887. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  888. Headers headers = {{"Content-Length", "x"}};
  889. auto is_invalid_value = false;
  890. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  891. is_invalid_value);
  892. EXPECT_EQ(0ull, val);
  893. EXPECT_TRUE(is_invalid_value);
  894. }
  895. TEST(GetHeaderValueTest, Range) {
  896. {
  897. Headers headers = {make_range_header({{1, -1}})};
  898. auto val = detail::get_header_value(headers, "Range", 0, 0);
  899. EXPECT_STREQ("bytes=1-", val);
  900. }
  901. {
  902. Headers headers = {make_range_header({{-1, 1}})};
  903. auto val = detail::get_header_value(headers, "Range", 0, 0);
  904. EXPECT_STREQ("bytes=-1", val);
  905. }
  906. {
  907. Headers headers = {make_range_header({{1, 10}})};
  908. auto val = detail::get_header_value(headers, "Range", 0, 0);
  909. EXPECT_STREQ("bytes=1-10", val);
  910. }
  911. {
  912. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  913. auto val = detail::get_header_value(headers, "Range", 0, 0);
  914. EXPECT_STREQ("bytes=1-10, 100-", val);
  915. }
  916. {
  917. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  919. EXPECT_STREQ("bytes=1-10, 100-200", val);
  920. }
  921. {
  922. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  924. EXPECT_STREQ("bytes=0-0, -1", val);
  925. }
  926. }
  927. TEST(ParseHeaderValueTest, Range) {
  928. {
  929. Ranges ranges;
  930. auto ret = detail::parse_range_header("bytes=1-", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(1u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(-1, ranges[0].second);
  935. }
  936. {
  937. Ranges ranges;
  938. auto ret = detail::parse_range_header("bytes=-1", ranges);
  939. EXPECT_TRUE(ret);
  940. EXPECT_EQ(1u, ranges.size());
  941. EXPECT_EQ(-1, ranges[0].first);
  942. EXPECT_EQ(1u, ranges[0].second);
  943. }
  944. {
  945. Ranges ranges;
  946. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  947. EXPECT_TRUE(ret);
  948. EXPECT_EQ(1u, ranges.size());
  949. EXPECT_EQ(1u, ranges[0].first);
  950. EXPECT_EQ(10u, ranges[0].second);
  951. }
  952. {
  953. Ranges ranges;
  954. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  955. EXPECT_FALSE(ret);
  956. }
  957. {
  958. Ranges ranges;
  959. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  960. EXPECT_TRUE(ret);
  961. EXPECT_EQ(2u, ranges.size());
  962. EXPECT_EQ(1u, ranges[0].first);
  963. EXPECT_EQ(10u, ranges[0].second);
  964. EXPECT_EQ(100u, ranges[1].first);
  965. EXPECT_EQ(-1, ranges[1].second);
  966. }
  967. {
  968. Ranges ranges;
  969. auto ret =
  970. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  971. EXPECT_TRUE(ret);
  972. EXPECT_EQ(3u, ranges.size());
  973. EXPECT_EQ(1u, ranges[0].first);
  974. EXPECT_EQ(10u, ranges[0].second);
  975. EXPECT_EQ(100u, ranges[1].first);
  976. EXPECT_EQ(200u, ranges[1].second);
  977. EXPECT_EQ(300u, ranges[2].first);
  978. EXPECT_EQ(400u, ranges[2].second);
  979. }
  980. {
  981. Ranges ranges;
  982. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  991. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  992. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  993. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  994. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  995. EXPECT_TRUE(ranges.empty());
  996. }
  997. }
  998. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  999. Request req;
  1000. req.set_header("Accept-Encoding", "gzip");
  1001. Response res;
  1002. res.set_header("Content-Type", "text/plain");
  1003. auto ret = detail::encoding_type(req, res);
  1004. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1005. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1006. #else
  1007. EXPECT_TRUE(ret == detail::EncodingType::None);
  1008. #endif
  1009. }
  1010. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1011. Request req;
  1012. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1013. Response res;
  1014. res.set_header("Content-Type", "text/plain");
  1015. auto ret = detail::encoding_type(req, res);
  1016. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1018. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1019. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1020. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1021. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1022. #else
  1023. EXPECT_TRUE(ret == detail::EncodingType::None);
  1024. #endif
  1025. }
  1026. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1027. Request req;
  1028. req.set_header("Accept-Encoding",
  1029. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1030. Response res;
  1031. res.set_header("Content-Type", "text/plain");
  1032. auto ret = detail::encoding_type(req, res);
  1033. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1035. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1036. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1037. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1039. #else
  1040. EXPECT_TRUE(ret == detail::EncodingType::None);
  1041. #endif
  1042. }
  1043. TEST(BufferStreamTest, read) {
  1044. detail::BufferStream strm1;
  1045. Stream &strm = strm1;
  1046. EXPECT_EQ(5, strm.write("hello"));
  1047. char buf[512];
  1048. EXPECT_EQ(2, strm.read(buf, 2));
  1049. EXPECT_EQ('h', buf[0]);
  1050. EXPECT_EQ('e', buf[1]);
  1051. EXPECT_EQ(2, strm.read(buf, 2));
  1052. EXPECT_EQ('l', buf[0]);
  1053. EXPECT_EQ('l', buf[1]);
  1054. EXPECT_EQ(1, strm.read(buf, 1));
  1055. EXPECT_EQ('o', buf[0]);
  1056. EXPECT_EQ(0, strm.read(buf, 1));
  1057. }
  1058. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1059. auto host = "www.httpwatch.com";
  1060. auto ip = hosted_at(host);
  1061. EXPECT_EQ("23.96.13.243", ip);
  1062. std::vector<std::string> addrs;
  1063. hosted_at(host, addrs);
  1064. EXPECT_EQ(1u, addrs.size());
  1065. }
  1066. #if 0 // It depends on each test environment...
  1067. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1068. auto host = "www.youtube.com";
  1069. std::vector<std::string> addrs;
  1070. hosted_at(host, addrs);
  1071. EXPECT_EQ(20u, addrs.size());
  1072. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1073. EXPECT_TRUE(it != addrs.end());
  1074. }
  1075. #endif
  1076. class ChunkedEncodingTest : public ::testing::Test {
  1077. protected:
  1078. ChunkedEncodingTest()
  1079. : cli_(HOST, PORT)
  1080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1081. ,
  1082. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1083. #endif
  1084. {
  1085. cli_.set_connection_timeout(2);
  1086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1087. cli_.enable_server_certificate_verification(false);
  1088. #endif
  1089. }
  1090. virtual void SetUp() {
  1091. read_file("./image.jpg", image_data_);
  1092. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1093. res.set_content("Hello World!", "text/plain");
  1094. });
  1095. svr_.Get(
  1096. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1097. res.set_chunked_content_provider(
  1098. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1099. size_t remaining = image_data_.size() - offset;
  1100. if (remaining == 0) {
  1101. sink.done();
  1102. } else {
  1103. constexpr size_t CHUNK_SIZE = 1024;
  1104. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1105. sink.write(&image_data_[offset], send_size);
  1106. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1107. }
  1108. return true;
  1109. });
  1110. });
  1111. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1112. svr_.wait_until_ready();
  1113. }
  1114. virtual void TearDown() {
  1115. svr_.stop();
  1116. if (!request_threads_.empty()) {
  1117. std::this_thread::sleep_for(std::chrono::seconds(1));
  1118. for (auto &t : request_threads_) {
  1119. t.join();
  1120. }
  1121. }
  1122. t_.join();
  1123. }
  1124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1125. SSLClient cli_;
  1126. SSLServer svr_;
  1127. #else
  1128. Client cli_;
  1129. Server svr_;
  1130. #endif
  1131. thread t_;
  1132. std::vector<thread> request_threads_;
  1133. std::string image_data_;
  1134. };
  1135. TEST_F(ChunkedEncodingTest, NormalGet) {
  1136. auto res = cli_.Get("/chunked");
  1137. ASSERT_TRUE(res);
  1138. std::string out;
  1139. read_file("./image.jpg", out);
  1140. EXPECT_EQ(StatusCode::OK_200, res->status);
  1141. EXPECT_EQ(out, res->body);
  1142. }
  1143. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1144. std::string body;
  1145. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1146. body.append(data, data_length);
  1147. return true;
  1148. });
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get(
  1158. "/chunked",
  1159. [&](const Response &response) {
  1160. EXPECT_EQ(StatusCode::OK_200, response.status);
  1161. return true;
  1162. },
  1163. [&](const char *data, size_t data_length) {
  1164. body.append(data, data_length);
  1165. return true;
  1166. });
  1167. ASSERT_TRUE(res);
  1168. std::string out;
  1169. read_file("./image.jpg", out);
  1170. EXPECT_EQ(StatusCode::OK_200, res->status);
  1171. EXPECT_EQ(out, body);
  1172. }
  1173. TEST(RangeTest, FromHTTPBin_Online) {
  1174. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1175. auto host = "httpcan.org";
  1176. auto path = std::string{"/range/32"};
  1177. #else
  1178. auto host = "nghttp2.org";
  1179. auto path = std::string{"/httpbin/range/32"};
  1180. #endif
  1181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(5);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. }
  1195. {
  1196. Headers headers = {make_range_header({{1, -1}})};
  1197. auto res = cli.Get(path, headers);
  1198. ASSERT_TRUE(res);
  1199. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1200. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1201. }
  1202. {
  1203. Headers headers = {make_range_header({{1, 10}})};
  1204. auto res = cli.Get(path, headers);
  1205. ASSERT_TRUE(res);
  1206. EXPECT_EQ("bcdefghijk", res->body);
  1207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1208. }
  1209. {
  1210. Headers headers = {make_range_header({{0, 31}})};
  1211. auto res = cli.Get(path, headers);
  1212. ASSERT_TRUE(res);
  1213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1214. EXPECT_EQ(StatusCode::OK_200, res->status);
  1215. }
  1216. {
  1217. Headers headers = {make_range_header({{0, -1}})};
  1218. auto res = cli.Get(path, headers);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1221. EXPECT_EQ(StatusCode::OK_200, res->status);
  1222. }
  1223. {
  1224. Headers headers = {make_range_header({{0, 32}})};
  1225. auto res = cli.Get(path, headers);
  1226. ASSERT_TRUE(res);
  1227. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1228. }
  1229. }
  1230. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1231. auto host = "unresolvableaddress.local";
  1232. auto path = std::string{"/"};
  1233. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1234. auto port = 443;
  1235. SSLClient cli(host, port);
  1236. #else
  1237. auto port = 80;
  1238. Client cli(host, port);
  1239. #endif
  1240. cli.set_connection_timeout(1);
  1241. {
  1242. auto res = cli.Get(path);
  1243. ASSERT_FALSE(res);
  1244. }
  1245. std::this_thread::sleep_for(std::chrono::seconds(8));
  1246. }
  1247. TEST(ConnectionErrorTest, InvalidHost) {
  1248. auto host = "-abcde.com";
  1249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1250. auto port = 443;
  1251. SSLClient cli(host, port);
  1252. #else
  1253. auto port = 80;
  1254. Client cli(host, port);
  1255. #endif
  1256. cli.set_connection_timeout(std::chrono::seconds(2));
  1257. auto res = cli.Get("/");
  1258. ASSERT_TRUE(!res);
  1259. EXPECT_EQ(Error::Connection, res.error());
  1260. }
  1261. TEST(ConnectionErrorTest, InvalidHost2) {
  1262. auto host = "httpcan.org/";
  1263. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1264. SSLClient cli(host);
  1265. #else
  1266. Client cli(host);
  1267. #endif
  1268. cli.set_connection_timeout(std::chrono::seconds(2));
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Connection, res.error());
  1272. }
  1273. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1274. auto host = "httpcan.org/";
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_connection_timeout(std::chrono::seconds(2));
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. stringstream s;
  1284. s << "error code: " << res.error();
  1285. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1286. }
  1287. TEST(ConnectionErrorTest, InvalidPort) {
  1288. auto host = "localhost";
  1289. auto port = 44380;
  1290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1291. SSLClient cli(host, port);
  1292. #else
  1293. Client cli(host, port);
  1294. #endif
  1295. cli.set_connection_timeout(std::chrono::seconds(2));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(!res);
  1298. EXPECT_TRUE(Error::Connection == res.error() ||
  1299. Error::ConnectionTimeout == res.error());
  1300. }
  1301. TEST(ConnectionErrorTest, Timeout_Online) {
  1302. auto host = "google.com";
  1303. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1304. auto port = 44380;
  1305. SSLClient cli(host, port);
  1306. #else
  1307. auto port = 8080;
  1308. Client cli(host, port);
  1309. #endif
  1310. cli.set_connection_timeout(std::chrono::seconds(2));
  1311. // only probe one address type so that the error reason
  1312. // correlates to the timed-out IPv4, not the unsupported
  1313. // IPv6 connection attempt
  1314. cli.set_address_family(AF_INET);
  1315. auto res = cli.Get("/");
  1316. ASSERT_TRUE(!res);
  1317. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1318. }
  1319. TEST(CancelTest, NoCancel_Online) {
  1320. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1321. auto host = "httpcan.org";
  1322. auto path = std::string{"/range/32"};
  1323. #else
  1324. auto host = "nghttp2.org";
  1325. auto path = std::string{"/httpbin/range/32"};
  1326. #endif
  1327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1328. auto port = 443;
  1329. SSLClient cli(host, port);
  1330. #else
  1331. auto port = 80;
  1332. Client cli(host, port);
  1333. #endif
  1334. cli.set_connection_timeout(std::chrono::seconds(5));
  1335. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1336. ASSERT_TRUE(res);
  1337. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1338. EXPECT_EQ(StatusCode::OK_200, res->status);
  1339. }
  1340. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1341. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1342. auto host = "httpcan.org";
  1343. auto path = std::string{"/range/32"};
  1344. #else
  1345. auto host = "nghttp2.org";
  1346. auto path = std::string{"/httpbin/range/32"};
  1347. #endif
  1348. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1349. auto port = 443;
  1350. SSLClient cli(host, port);
  1351. #else
  1352. auto port = 80;
  1353. Client cli(host, port);
  1354. #endif
  1355. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1356. cli.set_connection_timeout(std::chrono::seconds(5));
  1357. ASSERT_TRUE(!res);
  1358. EXPECT_EQ(Error::Canceled, res.error());
  1359. }
  1360. TEST(CancelTest, WithCancelLargePayload_Online) {
  1361. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1362. auto host = "httpcan.org";
  1363. auto path = std::string{"/range/65536"};
  1364. #else
  1365. auto host = "nghttp2.org";
  1366. auto path = std::string{"/httpbin/range/65536"};
  1367. #endif
  1368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1369. auto port = 443;
  1370. SSLClient cli(host, port);
  1371. #else
  1372. auto port = 80;
  1373. Client cli(host, port);
  1374. #endif
  1375. cli.set_connection_timeout(std::chrono::seconds(5));
  1376. uint32_t count = 0;
  1377. auto res =
  1378. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1379. ASSERT_TRUE(!res);
  1380. EXPECT_EQ(Error::Canceled, res.error());
  1381. }
  1382. TEST(CancelTest, NoCancelPost) {
  1383. Server svr;
  1384. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1385. res.set_content("Hello World!", "text/plain");
  1386. });
  1387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1388. auto se = detail::scope_exit([&] {
  1389. svr.stop();
  1390. thread.join();
  1391. ASSERT_FALSE(svr.is_running());
  1392. });
  1393. svr.wait_until_ready();
  1394. Client cli(HOST, PORT);
  1395. cli.set_connection_timeout(std::chrono::seconds(5));
  1396. auto res =
  1397. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1398. "application/json", [](uint64_t, uint64_t) { return true; });
  1399. ASSERT_TRUE(res);
  1400. EXPECT_EQ("Hello World!", res->body);
  1401. EXPECT_EQ(StatusCode::OK_200, res->status);
  1402. }
  1403. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1404. Server svr;
  1405. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1406. res.set_content("Hello World!", "text/plain");
  1407. });
  1408. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1409. auto se = detail::scope_exit([&] {
  1410. svr.stop();
  1411. thread.join();
  1412. ASSERT_FALSE(svr.is_running());
  1413. });
  1414. svr.wait_until_ready();
  1415. Client cli(HOST, PORT);
  1416. cli.set_connection_timeout(std::chrono::seconds(5));
  1417. auto res =
  1418. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1419. "application/json", [](uint64_t, uint64_t) { return false; });
  1420. ASSERT_TRUE(!res);
  1421. EXPECT_EQ(Error::Canceled, res.error());
  1422. }
  1423. TEST(CancelTest, WithCancelLargePayloadPost) {
  1424. Server svr;
  1425. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1426. res.set_content(LARGE_DATA, "text/plain");
  1427. });
  1428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1429. auto se = detail::scope_exit([&] {
  1430. svr.stop();
  1431. thread.join();
  1432. ASSERT_FALSE(svr.is_running());
  1433. });
  1434. svr.wait_until_ready();
  1435. Client cli(HOST, PORT);
  1436. cli.set_connection_timeout(std::chrono::seconds(5));
  1437. auto res =
  1438. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1439. "application/json", [](uint64_t, uint64_t) { return false; });
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_EQ(Error::Canceled, res.error());
  1442. }
  1443. TEST(CancelTest, NoCancelPut) {
  1444. Server svr;
  1445. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1446. res.set_content("Hello World!", "text/plain");
  1447. });
  1448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1449. auto se = detail::scope_exit([&] {
  1450. svr.stop();
  1451. thread.join();
  1452. ASSERT_FALSE(svr.is_running());
  1453. });
  1454. svr.wait_until_ready();
  1455. Client cli(HOST, PORT);
  1456. cli.set_connection_timeout(std::chrono::seconds(5));
  1457. auto res =
  1458. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1459. "application/json", [](uint64_t, uint64_t) { return true; });
  1460. ASSERT_TRUE(res);
  1461. EXPECT_EQ("Hello World!", res->body);
  1462. EXPECT_EQ(StatusCode::OK_200, res->status);
  1463. }
  1464. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1465. Server svr;
  1466. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1467. res.set_content("Hello World!", "text/plain");
  1468. });
  1469. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1470. auto se = detail::scope_exit([&] {
  1471. svr.stop();
  1472. thread.join();
  1473. ASSERT_FALSE(svr.is_running());
  1474. });
  1475. svr.wait_until_ready();
  1476. Client cli(HOST, PORT);
  1477. cli.set_connection_timeout(std::chrono::seconds(5));
  1478. auto res =
  1479. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1480. "application/json", [](uint64_t, uint64_t) { return false; });
  1481. ASSERT_TRUE(!res);
  1482. EXPECT_EQ(Error::Canceled, res.error());
  1483. }
  1484. TEST(CancelTest, WithCancelLargePayloadPut) {
  1485. Server svr;
  1486. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1487. res.set_content(LARGE_DATA, "text/plain");
  1488. });
  1489. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1490. auto se = detail::scope_exit([&] {
  1491. svr.stop();
  1492. thread.join();
  1493. ASSERT_FALSE(svr.is_running());
  1494. });
  1495. svr.wait_until_ready();
  1496. Client cli(HOST, PORT);
  1497. cli.set_connection_timeout(std::chrono::seconds(5));
  1498. auto res =
  1499. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1500. "application/json", [](uint64_t, uint64_t) { return false; });
  1501. ASSERT_TRUE(!res);
  1502. EXPECT_EQ(Error::Canceled, res.error());
  1503. }
  1504. TEST(CancelTest, NoCancelPatch) {
  1505. Server svr;
  1506. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content("Hello World!", "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_connection_timeout(std::chrono::seconds(5));
  1518. auto res =
  1519. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1520. "application/json", [](uint64_t, uint64_t) { return true; });
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("Hello World!", res->body);
  1523. EXPECT_EQ(StatusCode::OK_200, res->status);
  1524. }
  1525. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1526. Server svr;
  1527. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return false; });
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Canceled, res.error());
  1544. }
  1545. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1546. Server svr;
  1547. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1548. res.set_content(LARGE_DATA, "text/plain");
  1549. });
  1550. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1551. auto se = detail::scope_exit([&] {
  1552. svr.stop();
  1553. thread.join();
  1554. ASSERT_FALSE(svr.is_running());
  1555. });
  1556. svr.wait_until_ready();
  1557. Client cli(HOST, PORT);
  1558. cli.set_connection_timeout(std::chrono::seconds(5));
  1559. auto res =
  1560. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1561. "application/json", [](uint64_t, uint64_t) { return false; });
  1562. ASSERT_TRUE(!res);
  1563. EXPECT_EQ(Error::Canceled, res.error());
  1564. }
  1565. TEST(CancelTest, NoCancelDelete) {
  1566. Server svr;
  1567. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1568. res.set_content("Hello World!", "text/plain");
  1569. });
  1570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. thread.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. Client cli(HOST, PORT);
  1578. cli.set_connection_timeout(std::chrono::seconds(5));
  1579. auto res =
  1580. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1581. "application/json", [](uint64_t, uint64_t) { return true; });
  1582. ASSERT_TRUE(res);
  1583. EXPECT_EQ("Hello World!", res->body);
  1584. EXPECT_EQ(StatusCode::OK_200, res->status);
  1585. }
  1586. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1587. Server svr;
  1588. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1589. res.set_content("Hello World!", "text/plain");
  1590. });
  1591. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1592. auto se = detail::scope_exit([&] {
  1593. svr.stop();
  1594. thread.join();
  1595. ASSERT_FALSE(svr.is_running());
  1596. });
  1597. svr.wait_until_ready();
  1598. Client cli(HOST, PORT);
  1599. cli.set_connection_timeout(std::chrono::seconds(5));
  1600. auto res =
  1601. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1602. "application/json", [](uint64_t, uint64_t) { return false; });
  1603. ASSERT_TRUE(!res);
  1604. EXPECT_EQ(Error::Canceled, res.error());
  1605. }
  1606. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1607. Server svr;
  1608. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1609. res.set_content(LARGE_DATA, "text/plain");
  1610. });
  1611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1612. auto se = detail::scope_exit([&] {
  1613. svr.stop();
  1614. thread.join();
  1615. ASSERT_FALSE(svr.is_running());
  1616. });
  1617. svr.wait_until_ready();
  1618. Client cli(HOST, PORT);
  1619. cli.set_connection_timeout(std::chrono::seconds(5));
  1620. auto res =
  1621. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1622. "application/json", [](uint64_t, uint64_t) { return false; });
  1623. ASSERT_TRUE(!res);
  1624. EXPECT_EQ(Error::Canceled, res.error());
  1625. }
  1626. static std::string remove_whitespace(const std::string &input) {
  1627. std::string output;
  1628. output.reserve(input.size());
  1629. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1630. [](unsigned char c) { return !std::isspace(c); });
  1631. return output;
  1632. }
  1633. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1634. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1635. auto host = "httpcan.org";
  1636. auto path = std::string{"/basic-auth/hello/world"};
  1637. #else
  1638. auto host = "nghttp2.org";
  1639. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1640. #endif
  1641. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. #else
  1645. auto port = 80;
  1646. Client cli(host, port);
  1647. #endif
  1648. {
  1649. auto res = cli.Get(path);
  1650. ASSERT_TRUE(res);
  1651. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1652. }
  1653. {
  1654. auto res =
  1655. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1658. remove_whitespace(res->body));
  1659. EXPECT_EQ(StatusCode::OK_200, res->status);
  1660. }
  1661. {
  1662. cli.set_basic_auth("hello", "world");
  1663. auto res = cli.Get(path);
  1664. ASSERT_TRUE(res);
  1665. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1666. remove_whitespace(res->body));
  1667. EXPECT_EQ(StatusCode::OK_200, res->status);
  1668. }
  1669. {
  1670. cli.set_basic_auth("hello", "bad");
  1671. auto res = cli.Get(path);
  1672. ASSERT_TRUE(res);
  1673. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1674. }
  1675. {
  1676. cli.set_basic_auth("bad", "world");
  1677. auto res = cli.Get(path);
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. }
  1682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1683. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1684. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1685. auto host = "httpcan.org";
  1686. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1687. auto paths = std::vector<std::string>{
  1688. "/digest-auth/auth/hello/world/MD5",
  1689. "/digest-auth/auth/hello/world/SHA-256",
  1690. "/digest-auth/auth/hello/world/SHA-512",
  1691. };
  1692. #else
  1693. auto host = "nghttp2.org";
  1694. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1695. auto paths = std::vector<std::string>{
  1696. "/httpbin/digest-auth/auth/hello/world/MD5",
  1697. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1698. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1699. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1700. };
  1701. #endif
  1702. auto port = 443;
  1703. SSLClient cli(host, port);
  1704. {
  1705. auto res = cli.Get(unauth_path);
  1706. ASSERT_TRUE(res);
  1707. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1708. }
  1709. {
  1710. cli.set_digest_auth("hello", "world");
  1711. for (const auto &path : paths) {
  1712. auto res = cli.Get(path.c_str());
  1713. ASSERT_TRUE(res);
  1714. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1715. std::string algo(path.substr(path.rfind('/') + 1));
  1716. EXPECT_EQ(
  1717. remove_whitespace("{\"algorithm\":\"" + algo +
  1718. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1719. remove_whitespace(res->body));
  1720. #else
  1721. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1722. remove_whitespace(res->body));
  1723. #endif
  1724. EXPECT_EQ(StatusCode::OK_200, res->status);
  1725. }
  1726. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1727. cli.set_digest_auth("hello", "bad");
  1728. for (const auto &path : paths) {
  1729. auto res = cli.Get(path.c_str());
  1730. ASSERT_TRUE(res);
  1731. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1732. }
  1733. #endif
  1734. }
  1735. }
  1736. #endif
  1737. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1738. auto host = "google.com";
  1739. auto another_host = "example.com";
  1740. auto wrong_ip = "0.0.0.0";
  1741. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1742. SSLClient cli(host);
  1743. #else
  1744. Client cli(host);
  1745. #endif
  1746. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1747. auto res = cli.Get("/");
  1748. ASSERT_TRUE(res);
  1749. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1750. }
  1751. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1752. auto host = "google.com";
  1753. auto wrong_ip = "0.0.0.0";
  1754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1755. SSLClient cli(host);
  1756. #else
  1757. Client cli(host);
  1758. #endif
  1759. cli.set_hostname_addr_map({{host, wrong_ip}});
  1760. auto res = cli.Get("/");
  1761. ASSERT_TRUE(!res);
  1762. EXPECT_EQ(Error::Connection, res.error());
  1763. }
  1764. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1765. auto host = "nghttp2.org";
  1766. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1767. SSLClient cli(host);
  1768. #else
  1769. Client cli(host);
  1770. #endif
  1771. cli.set_follow_location(true);
  1772. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::OK_200, res->status);
  1775. }
  1776. TEST(RedirectTest, Redirect_Online) {
  1777. auto host = "nghttp2.org";
  1778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1779. SSLClient cli(host);
  1780. #else
  1781. Client cli(host);
  1782. #endif
  1783. cli.set_follow_location(true);
  1784. auto res = cli.Get("/httpbin/redirect/3");
  1785. ASSERT_TRUE(res);
  1786. EXPECT_EQ(StatusCode::OK_200, res->status);
  1787. }
  1788. TEST(RelativeRedirectTest, Redirect_Online) {
  1789. auto host = "nghttp2.org";
  1790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1791. SSLClient cli(host);
  1792. #else
  1793. Client cli(host);
  1794. #endif
  1795. cli.set_follow_location(true);
  1796. auto res = cli.Get("/httpbin/relative-redirect/3");
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::OK_200, res->status);
  1799. }
  1800. TEST(TooManyRedirectTest, Redirect_Online) {
  1801. auto host = "nghttp2.org";
  1802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1803. SSLClient cli(host);
  1804. #else
  1805. Client cli(host);
  1806. #endif
  1807. cli.set_follow_location(true);
  1808. auto res = cli.Get("/httpbin/redirect/21");
  1809. ASSERT_TRUE(!res);
  1810. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1811. }
  1812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1813. TEST(YahooRedirectTest, Redirect_Online) {
  1814. Client cli("yahoo.com");
  1815. auto res = cli.Get("/");
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1818. cli.set_follow_location(true);
  1819. res = cli.Get("/");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::OK_200, res->status);
  1822. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1823. }
  1824. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1825. #define REDIR_HOST "httpbingo.org"
  1826. #define REDIR_PATH "/redirect-to"
  1827. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1828. SSLClient cli(REDIR_HOST);
  1829. cli.set_follow_location(true);
  1830. auto res =
  1831. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. }
  1835. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1836. SSLClient cli(REDIR_HOST);
  1837. cli.set_follow_location(true);
  1838. Params params;
  1839. params.emplace("url", "http://example.com");
  1840. params.emplace("status_code", "302");
  1841. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(StatusCode::OK_200, res->status);
  1844. }
  1845. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1846. SSLClient cli(REDIR_HOST);
  1847. cli.set_follow_location(true);
  1848. Params params;
  1849. params.emplace("url", "http://example.com");
  1850. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1851. ASSERT_TRUE(res);
  1852. EXPECT_EQ(StatusCode::OK_200, res->status);
  1853. }
  1854. TEST(UrlWithSpace, Redirect_Online) {
  1855. SSLClient cli("edge.forgecdn.net");
  1856. cli.set_follow_location(true);
  1857. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1858. ASSERT_TRUE(res);
  1859. EXPECT_EQ(StatusCode::OK_200, res->status);
  1860. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1861. }
  1862. #endif
  1863. #if !defined(_WIN32) && !defined(_WIN64)
  1864. TEST(ReceiveSignals, Signal) {
  1865. auto setupSignalHandlers = []() {
  1866. struct sigaction act;
  1867. sigemptyset(&act.sa_mask);
  1868. act.sa_flags = SA_SIGINFO;
  1869. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1870. switch (sig) {
  1871. case SIGINT:
  1872. default: break;
  1873. }
  1874. };
  1875. ::sigaction(SIGINT, &act, nullptr);
  1876. };
  1877. Server svr;
  1878. int port = 0;
  1879. auto thread = std::thread([&]() {
  1880. setupSignalHandlers();
  1881. port = svr.bind_to_any_port(HOST);
  1882. svr.listen_after_bind();
  1883. });
  1884. auto se = detail::scope_exit([&] {
  1885. svr.stop();
  1886. thread.join();
  1887. ASSERT_FALSE(svr.is_running());
  1888. });
  1889. svr.wait_until_ready();
  1890. ASSERT_TRUE(svr.is_running());
  1891. pthread_kill(thread.native_handle(), SIGINT);
  1892. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1893. ASSERT_TRUE(svr.is_running());
  1894. }
  1895. #endif
  1896. TEST(RedirectToDifferentPort, Redirect) {
  1897. Server svr1;
  1898. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1899. res.set_content("Hello World!", "text/plain");
  1900. });
  1901. int svr1_port = 0;
  1902. auto thread1 = std::thread([&]() {
  1903. svr1_port = svr1.bind_to_any_port(HOST);
  1904. svr1.listen_after_bind();
  1905. });
  1906. Server svr2;
  1907. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1908. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1909. });
  1910. int svr2_port = 0;
  1911. auto thread2 = std::thread([&]() {
  1912. svr2_port = svr2.bind_to_any_port(HOST);
  1913. svr2.listen_after_bind();
  1914. });
  1915. auto se = detail::scope_exit([&] {
  1916. svr2.stop();
  1917. thread2.join();
  1918. svr1.stop();
  1919. thread1.join();
  1920. ASSERT_FALSE(svr2.is_running());
  1921. ASSERT_FALSE(svr1.is_running());
  1922. });
  1923. svr1.wait_until_ready();
  1924. svr2.wait_until_ready();
  1925. Client cli("localhost", svr2_port);
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get("/2");
  1928. ASSERT_TRUE(res);
  1929. EXPECT_EQ(StatusCode::OK_200, res->status);
  1930. EXPECT_EQ("Hello World!", res->body);
  1931. }
  1932. TEST(RedirectFromPageWithContent, Redirect) {
  1933. Server svr;
  1934. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1935. res.set_content("___", "text/plain");
  1936. res.set_redirect("/2");
  1937. });
  1938. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1939. res.set_content("Hello World!", "text/plain");
  1940. });
  1941. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1942. auto se = detail::scope_exit([&] {
  1943. svr.stop();
  1944. th.join();
  1945. ASSERT_FALSE(svr.is_running());
  1946. });
  1947. svr.wait_until_ready();
  1948. {
  1949. Client cli("localhost", PORT);
  1950. cli.set_follow_location(true);
  1951. std::string body;
  1952. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1953. body.append(data, data_length);
  1954. return true;
  1955. });
  1956. ASSERT_TRUE(res);
  1957. EXPECT_EQ(StatusCode::OK_200, res->status);
  1958. EXPECT_EQ("Hello World!", body);
  1959. }
  1960. {
  1961. Client cli("localhost", PORT);
  1962. std::string body;
  1963. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1964. body.append(data, data_length);
  1965. return true;
  1966. });
  1967. ASSERT_TRUE(res);
  1968. EXPECT_EQ(StatusCode::Found_302, res->status);
  1969. EXPECT_EQ("___", body);
  1970. }
  1971. }
  1972. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1973. Server svr;
  1974. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("___", "text/plain");
  1976. // res.set_redirect("/2");
  1977. res.set_redirect("http://[::1]:1234/2");
  1978. });
  1979. svr.Get("/2", [&](const Request &req, Response &res) {
  1980. auto host_header = req.headers.find("Host");
  1981. ASSERT_TRUE(host_header != req.headers.end());
  1982. EXPECT_EQ("[::1]:1234", host_header->second);
  1983. res.set_content("Hello World!", "text/plain");
  1984. });
  1985. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1986. auto se = detail::scope_exit([&] {
  1987. svr.stop();
  1988. th.join();
  1989. ASSERT_FALSE(svr.is_running());
  1990. });
  1991. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1992. // actually starts anything, so the condition !svr.is_running() will
  1993. // always remain true, and the loop never stops.
  1994. // This basically counts how many milliseconds have passed since the
  1995. // call to svr.listen(), and if after 5 seconds nothing started yet
  1996. // aborts the test.
  1997. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1998. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1999. ASSERT_LT(milliseconds, 5000U);
  2000. }
  2001. {
  2002. Client cli("http://[::1]:1234");
  2003. cli.set_follow_location(true);
  2004. std::string body;
  2005. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2006. body.append(data, data_length);
  2007. return true;
  2008. });
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", body);
  2012. }
  2013. {
  2014. Client cli("http://[::1]:1234");
  2015. std::string body;
  2016. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2017. body.append(data, data_length);
  2018. return true;
  2019. });
  2020. ASSERT_TRUE(res);
  2021. EXPECT_EQ(StatusCode::Found_302, res->status);
  2022. EXPECT_EQ("___", body);
  2023. }
  2024. }
  2025. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2026. Server svr;
  2027. svr.Get("/foo", [](const Request &req, Response &res) {
  2028. auto a = req.params.find("a");
  2029. if (a != req.params.end()) {
  2030. res.set_content((*a).second, "text/plain");
  2031. res.status = StatusCode::OK_200;
  2032. } else {
  2033. res.status = StatusCode::BadRequest_400;
  2034. }
  2035. });
  2036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2037. auto se = detail::scope_exit([&] {
  2038. svr.stop();
  2039. thread.join();
  2040. ASSERT_FALSE(svr.is_running());
  2041. });
  2042. svr.wait_until_ready();
  2043. {
  2044. Client cli(HOST, PORT);
  2045. cli.set_path_encode(false);
  2046. auto res = cli.Get("/foo?a=explicitly+encoded");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. // This expects it back with a space, as the `+` won't have been
  2050. // url-encoded, and server-side the params get decoded turning `+`
  2051. // into spaces.
  2052. EXPECT_EQ("explicitly encoded", res->body);
  2053. }
  2054. }
  2055. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2056. Server svr;
  2057. svr.Get("/", [](const Request &req, Response &) {
  2058. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2059. });
  2060. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2061. auto se = detail::scope_exit([&] {
  2062. svr.stop();
  2063. thread.join();
  2064. ASSERT_FALSE(svr.is_running());
  2065. });
  2066. svr.wait_until_ready();
  2067. {
  2068. Client cli(HOST, PORT);
  2069. cli.set_path_encode(false);
  2070. auto res = cli.Get("/?something=%0A");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::OK_200, res->status);
  2073. }
  2074. }
  2075. TEST(BindServerTest, DISABLED_BindDualStack) {
  2076. Server svr;
  2077. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2078. res.set_content("Hello World!", "text/plain");
  2079. });
  2080. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2081. auto se = detail::scope_exit([&] {
  2082. svr.stop();
  2083. thread.join();
  2084. ASSERT_FALSE(svr.is_running());
  2085. });
  2086. svr.wait_until_ready();
  2087. {
  2088. Client cli("127.0.0.1", PORT);
  2089. auto res = cli.Get("/1");
  2090. ASSERT_TRUE(res);
  2091. EXPECT_EQ(StatusCode::OK_200, res->status);
  2092. EXPECT_EQ("Hello World!", res->body);
  2093. }
  2094. {
  2095. Client cli("::1", PORT);
  2096. auto res = cli.Get("/1");
  2097. ASSERT_TRUE(res);
  2098. EXPECT_EQ(StatusCode::OK_200, res->status);
  2099. EXPECT_EQ("Hello World!", res->body);
  2100. }
  2101. }
  2102. TEST(BindServerTest, BindAndListenSeparately) {
  2103. Server svr;
  2104. int port = svr.bind_to_any_port("0.0.0.0");
  2105. ASSERT_TRUE(svr.is_valid());
  2106. ASSERT_TRUE(port > 0);
  2107. svr.stop();
  2108. }
  2109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2110. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2112. CLIENT_CA_CERT_DIR);
  2113. int port = svr.bind_to_any_port("0.0.0.0");
  2114. ASSERT_TRUE(svr.is_valid());
  2115. ASSERT_TRUE(port > 0);
  2116. svr.stop();
  2117. }
  2118. #endif
  2119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2120. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2121. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2122. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2123. int port = svr.bind_to_any_port("0.0.0.0");
  2124. ASSERT_TRUE(svr.is_valid());
  2125. ASSERT_TRUE(port > 0);
  2126. svr.stop();
  2127. }
  2128. #endif
  2129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2130. X509 *readCertificate(const std::string &strFileName) {
  2131. std::ifstream inStream(strFileName);
  2132. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2133. std::istreambuf_iterator<char>());
  2134. if (strCertPEM.empty()) return (nullptr);
  2135. BIO *pbCert = BIO_new(BIO_s_mem());
  2136. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2137. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2138. BIO_free(pbCert);
  2139. return (pCert);
  2140. }
  2141. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2142. std::ifstream inStream(strFileName);
  2143. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2144. std::istreambuf_iterator<char>());
  2145. if (strPrivateKeyPEM.empty()) return (nullptr);
  2146. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2147. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2148. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2149. BIO_free(pbPrivKey);
  2150. return (pPrivateKey);
  2151. }
  2152. TEST(BindServerTest, UpdateCerts) {
  2153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2154. int port = svr.bind_to_any_port("0.0.0.0");
  2155. ASSERT_TRUE(svr.is_valid());
  2156. ASSERT_TRUE(port > 0);
  2157. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2158. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2159. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2160. ASSERT_TRUE(cert != nullptr);
  2161. ASSERT_TRUE(ca_cert != nullptr);
  2162. ASSERT_TRUE(key != nullptr);
  2163. X509_STORE *cert_store = X509_STORE_new();
  2164. X509_STORE_add_cert(cert_store, ca_cert);
  2165. svr.update_certs(cert, key, cert_store);
  2166. ASSERT_TRUE(svr.is_valid());
  2167. svr.stop();
  2168. X509_free(cert);
  2169. X509_free(ca_cert);
  2170. EVP_PKEY_free(key);
  2171. }
  2172. #endif
  2173. TEST(ErrorHandlerTest, ContentLength) {
  2174. Server svr;
  2175. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2176. res.status = StatusCode::OK_200;
  2177. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2178. "text/html"); // <= Content-Length still 13
  2179. });
  2180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2181. res.set_content("Hello World!\n", "text/plain");
  2182. res.status = 524;
  2183. });
  2184. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2185. auto se = detail::scope_exit([&] {
  2186. svr.stop();
  2187. thread.join();
  2188. ASSERT_FALSE(svr.is_running());
  2189. });
  2190. svr.wait_until_ready();
  2191. {
  2192. Client cli(HOST, PORT);
  2193. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2194. ASSERT_TRUE(res);
  2195. EXPECT_EQ(StatusCode::OK_200, res->status);
  2196. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2197. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2198. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2199. }
  2200. }
  2201. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2202. TEST(ExceptionTest, WithoutExceptionHandler) {
  2203. Server svr;
  2204. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2205. throw std::runtime_error("exception...");
  2206. });
  2207. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2208. throw std::runtime_error("exception\r\n...");
  2209. });
  2210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2211. auto se = detail::scope_exit([&] {
  2212. svr.stop();
  2213. listen_thread.join();
  2214. ASSERT_FALSE(svr.is_running());
  2215. });
  2216. svr.wait_until_ready();
  2217. Client cli("localhost", PORT);
  2218. {
  2219. auto res = cli.Get("/exception");
  2220. ASSERT_TRUE(res);
  2221. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2222. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2223. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2224. }
  2225. {
  2226. auto res = cli.Get("/unknown");
  2227. ASSERT_TRUE(res);
  2228. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2229. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2230. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2231. }
  2232. }
  2233. TEST(ExceptionTest, WithExceptionHandler) {
  2234. Server svr;
  2235. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2236. std::exception_ptr ep) {
  2237. EXPECT_FALSE(ep == nullptr);
  2238. try {
  2239. std::rethrow_exception(ep);
  2240. } catch (std::exception &e) {
  2241. EXPECT_EQ("abc", std::string(e.what()));
  2242. } catch (...) {}
  2243. res.status = StatusCode::InternalServerError_500;
  2244. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2245. "text/html"); // <= Content-Length still 13 at this point
  2246. });
  2247. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2248. res.set_content("Hello World!\n", "text/plain");
  2249. throw std::runtime_error("abc");
  2250. });
  2251. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2252. auto se = detail::scope_exit([&] {
  2253. svr.stop();
  2254. thread.join();
  2255. ASSERT_FALSE(svr.is_running());
  2256. });
  2257. svr.wait_until_ready();
  2258. for (size_t i = 0; i < 10; i++) {
  2259. Client cli(HOST, PORT);
  2260. for (size_t j = 0; j < 100; j++) {
  2261. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2262. ASSERT_TRUE(res);
  2263. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2264. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2265. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2266. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2267. }
  2268. cli.set_keep_alive(true);
  2269. for (size_t j = 0; j < 100; j++) {
  2270. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2273. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2274. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2275. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2276. }
  2277. }
  2278. }
  2279. TEST(ExceptionTest, AndErrorHandler) {
  2280. Server svr;
  2281. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2282. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2283. });
  2284. svr.set_exception_handler(
  2285. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2286. EXPECT_FALSE(ep == nullptr);
  2287. try {
  2288. std::rethrow_exception(ep);
  2289. } catch (std::exception &e) {
  2290. res.set_content(e.what(), "text/html");
  2291. } catch (...) {}
  2292. res.status = StatusCode::InternalServerError_500;
  2293. });
  2294. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2295. throw std::runtime_error("EXCEPTION");
  2296. });
  2297. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2298. res.set_content("ERROR", "text/html");
  2299. res.status = StatusCode::InternalServerError_500;
  2300. });
  2301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2302. auto se = detail::scope_exit([&] {
  2303. svr.stop();
  2304. thread.join();
  2305. ASSERT_FALSE(svr.is_running());
  2306. });
  2307. svr.wait_until_ready();
  2308. Client cli(HOST, PORT);
  2309. {
  2310. auto res = cli.Get("/exception");
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2313. EXPECT_EQ("EXCEPTION", res->body);
  2314. }
  2315. {
  2316. auto res = cli.Get("/error");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2319. EXPECT_EQ("ERROR", res->body);
  2320. }
  2321. {
  2322. auto res = cli.Get("/invalid");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2325. EXPECT_EQ("NOT_FOUND", res->body);
  2326. }
  2327. }
  2328. #endif
  2329. TEST(NoContentTest, ContentLength) {
  2330. Server svr;
  2331. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2332. res.status = StatusCode::NoContent_204;
  2333. });
  2334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2335. auto se = detail::scope_exit([&] {
  2336. svr.stop();
  2337. thread.join();
  2338. ASSERT_FALSE(svr.is_running());
  2339. });
  2340. svr.wait_until_ready();
  2341. {
  2342. Client cli(HOST, PORT);
  2343. auto res = cli.Get("/hi");
  2344. ASSERT_TRUE(res);
  2345. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2346. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2347. }
  2348. }
  2349. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2350. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2352. ASSERT_TRUE(svr.is_valid());
  2353. #else
  2354. Server svr;
  2355. #endif
  2356. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2357. if (req.path == "/routing_handler") {
  2358. res.set_header("PRE_ROUTING", "on");
  2359. res.set_content("Routing Handler", "text/plain");
  2360. return httplib::Server::HandlerResponse::Handled;
  2361. }
  2362. return httplib::Server::HandlerResponse::Unhandled;
  2363. });
  2364. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2365. res.set_content("Error", "text/html");
  2366. });
  2367. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2368. if (req.path == "/routing_handler") {
  2369. res.set_header("POST_ROUTING", "on");
  2370. }
  2371. });
  2372. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2373. res.set_content("Hello World!\n", "text/plain");
  2374. });
  2375. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2376. auto se = detail::scope_exit([&] {
  2377. svr.stop();
  2378. thread.join();
  2379. ASSERT_FALSE(svr.is_running());
  2380. });
  2381. svr.wait_until_ready();
  2382. {
  2383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2384. SSLClient cli(HOST, PORT);
  2385. cli.enable_server_certificate_verification(false);
  2386. #else
  2387. Client cli(HOST, PORT);
  2388. #endif
  2389. auto res = cli.Get("/routing_handler");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. EXPECT_EQ("Routing Handler", res->body);
  2393. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2394. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2395. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2396. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2397. }
  2398. {
  2399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2400. SSLClient cli(HOST, PORT);
  2401. cli.enable_server_certificate_verification(false);
  2402. #else
  2403. Client cli(HOST, PORT);
  2404. #endif
  2405. auto res = cli.Get("/hi");
  2406. ASSERT_TRUE(res);
  2407. EXPECT_EQ(StatusCode::OK_200, res->status);
  2408. EXPECT_EQ("Hello World!\n", res->body);
  2409. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2410. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2411. }
  2412. {
  2413. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2414. SSLClient cli(HOST, PORT);
  2415. cli.enable_server_certificate_verification(false);
  2416. #else
  2417. Client cli(HOST, PORT);
  2418. #endif
  2419. auto res = cli.Get("/aaa");
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2422. EXPECT_EQ("Error", res->body);
  2423. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2424. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2425. }
  2426. }
  2427. TEST(RequestHandlerTest, PreRequestHandler) {
  2428. auto route_path = "/user/:user";
  2429. Server svr;
  2430. svr.Get("/hi", [](const Request &, Response &res) {
  2431. res.set_content("hi", "text/plain");
  2432. });
  2433. svr.Get(route_path, [](const Request &req, Response &res) {
  2434. res.set_content(req.path_params.at("user"), "text/plain");
  2435. });
  2436. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2437. if (req.matched_route == route_path) {
  2438. auto user = req.path_params.at("user");
  2439. if (user != "john") {
  2440. res.status = StatusCode::Forbidden_403;
  2441. res.set_content("error", "text/html");
  2442. return Server::HandlerResponse::Handled;
  2443. }
  2444. }
  2445. return Server::HandlerResponse::Unhandled;
  2446. });
  2447. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2448. auto se = detail::scope_exit([&] {
  2449. svr.stop();
  2450. thread.join();
  2451. ASSERT_FALSE(svr.is_running());
  2452. });
  2453. svr.wait_until_ready();
  2454. Client cli(HOST, PORT);
  2455. {
  2456. auto res = cli.Get("/hi");
  2457. ASSERT_TRUE(res);
  2458. EXPECT_EQ(StatusCode::OK_200, res->status);
  2459. EXPECT_EQ("hi", res->body);
  2460. }
  2461. {
  2462. auto res = cli.Get("/user/john");
  2463. ASSERT_TRUE(res);
  2464. EXPECT_EQ(StatusCode::OK_200, res->status);
  2465. EXPECT_EQ("john", res->body);
  2466. }
  2467. {
  2468. auto res = cli.Get("/user/invalid-user");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2471. EXPECT_EQ("error", res->body);
  2472. }
  2473. }
  2474. TEST(InvalidFormatTest, StatusCode) {
  2475. Server svr;
  2476. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2477. res.set_content("Hello World!\n", "text/plain");
  2478. res.status = 9999; // Status should be a three-digit code...
  2479. });
  2480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2481. auto se = detail::scope_exit([&] {
  2482. svr.stop();
  2483. thread.join();
  2484. ASSERT_FALSE(svr.is_running());
  2485. });
  2486. svr.wait_until_ready();
  2487. {
  2488. Client cli(HOST, PORT);
  2489. auto res = cli.Get("/hi");
  2490. ASSERT_FALSE(res);
  2491. }
  2492. }
  2493. TEST(URLFragmentTest, WithFragment) {
  2494. Server svr;
  2495. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2496. EXPECT_TRUE(req.target == "/hi");
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. {
  2506. Client cli(HOST, PORT);
  2507. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2508. EXPECT_TRUE(res);
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. res = cli.Get("/hi%23key1=val1=key2=val2");
  2511. EXPECT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2513. }
  2514. }
  2515. TEST(HeaderWriter, SetHeaderWriter) {
  2516. Server svr;
  2517. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2518. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2519. return detail::write_headers(strm, hdrs);
  2520. });
  2521. svr.Get("/hi", [](const Request &req, Response &res) {
  2522. auto it = req.headers.find("CustomClientHeader");
  2523. EXPECT_TRUE(it != req.headers.end());
  2524. EXPECT_EQ(it->second, "CustomClientValue");
  2525. res.set_content("Hello World!\n", "text/plain");
  2526. });
  2527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2528. auto se = detail::scope_exit([&] {
  2529. svr.stop();
  2530. thread.join();
  2531. ASSERT_FALSE(svr.is_running());
  2532. });
  2533. svr.wait_until_ready();
  2534. {
  2535. Client cli(HOST, PORT);
  2536. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2537. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2538. return detail::write_headers(strm, hdrs);
  2539. });
  2540. auto res = cli.Get("/hi");
  2541. EXPECT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::OK_200, res->status);
  2543. auto it = res->headers.find("CustomServerHeader");
  2544. EXPECT_TRUE(it != res->headers.end());
  2545. EXPECT_EQ(it->second, "CustomServerValue");
  2546. }
  2547. }
  2548. class ServerTest : public ::testing::Test {
  2549. protected:
  2550. ServerTest()
  2551. : cli_(HOST, PORT)
  2552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2553. ,
  2554. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2555. #endif
  2556. {
  2557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2558. cli_.enable_server_certificate_verification(false);
  2559. #endif
  2560. }
  2561. virtual void SetUp() {
  2562. svr_.set_mount_point("/", "./www");
  2563. svr_.set_mount_point("/mount", "./www2");
  2564. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2565. svr_.Get("/hi",
  2566. [&](const Request & /*req*/, Response &res) {
  2567. res.set_content("Hello World!", "text/plain");
  2568. })
  2569. .Get("/file_content",
  2570. [&](const Request & /*req*/, Response &res) {
  2571. res.set_file_content("./www/dir/test.html");
  2572. })
  2573. .Get("/file_content_with_content_type",
  2574. [&](const Request & /*req*/, Response &res) {
  2575. res.set_file_content("./www/file", "text/plain");
  2576. })
  2577. .Get("/invalid_file_content",
  2578. [&](const Request & /*req*/, Response &res) {
  2579. res.set_file_content("./www/dir/invalid_file_path");
  2580. })
  2581. .Get("/http_response_splitting",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2584. EXPECT_EQ(0U, res.headers.size());
  2585. EXPECT_FALSE(res.has_header("a"));
  2586. res.set_header("a", "1\nSet-Cookie: a=1");
  2587. EXPECT_EQ(0U, res.headers.size());
  2588. EXPECT_FALSE(res.has_header("a"));
  2589. res.set_header("a", "1\rSet-Cookie: a=1");
  2590. EXPECT_EQ(0U, res.headers.size());
  2591. EXPECT_FALSE(res.has_header("a"));
  2592. res.set_header("a\r\nb", "0");
  2593. EXPECT_EQ(0U, res.headers.size());
  2594. EXPECT_FALSE(res.has_header("a"));
  2595. res.set_header("a\rb", "0");
  2596. EXPECT_EQ(0U, res.headers.size());
  2597. EXPECT_FALSE(res.has_header("a"));
  2598. res.set_header("a\nb", "0");
  2599. EXPECT_EQ(0U, res.headers.size());
  2600. EXPECT_FALSE(res.has_header("a"));
  2601. res.set_redirect("1\r\nSet-Cookie: a=1");
  2602. EXPECT_EQ(0U, res.headers.size());
  2603. EXPECT_FALSE(res.has_header("Location"));
  2604. })
  2605. .Get("/slow",
  2606. [&](const Request & /*req*/, Response &res) {
  2607. std::this_thread::sleep_for(std::chrono::seconds(2));
  2608. res.set_content("slow", "text/plain");
  2609. })
  2610. #if 0
  2611. .Post("/slowpost",
  2612. [&](const Request & /*req*/, Response &res) {
  2613. std::this_thread::sleep_for(std::chrono::seconds(2));
  2614. res.set_content("slow", "text/plain");
  2615. })
  2616. #endif
  2617. .Get("/remote_addr",
  2618. [&](const Request &req, Response &res) {
  2619. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2620. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2621. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2622. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2623. res.set_content(req.remote_addr, "text/plain");
  2624. })
  2625. .Get("/local_addr",
  2626. [&](const Request &req, Response &res) {
  2627. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2628. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2629. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2630. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2631. auto local_addr = req.local_addr;
  2632. auto local_port = std::to_string(req.local_port);
  2633. res.set_content(local_addr.append(":").append(local_port),
  2634. "text/plain");
  2635. })
  2636. .Get("/endwith%",
  2637. [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. })
  2640. .Get("/a\\+\\+b",
  2641. [&](const Request &req, Response &res) {
  2642. ASSERT_TRUE(req.has_param("a +b"));
  2643. auto val = req.get_param_value("a +b");
  2644. res.set_content(val, "text/plain");
  2645. })
  2646. .Get("/", [&](const Request & /*req*/,
  2647. Response &res) { res.set_redirect("/hi"); })
  2648. .Post("/1",
  2649. [](const Request & /*req*/, Response &res) {
  2650. res.set_redirect("/2", StatusCode::SeeOther_303);
  2651. })
  2652. .Get("/2",
  2653. [](const Request & /*req*/, Response &res) {
  2654. res.set_content("redirected.", "text/plain");
  2655. res.status = StatusCode::OK_200;
  2656. })
  2657. .Post("/person",
  2658. [&](const Request &req, Response &res) {
  2659. if (req.has_param("name") && req.has_param("note")) {
  2660. persons_[req.get_param_value("name")] =
  2661. req.get_param_value("note");
  2662. } else {
  2663. res.status = StatusCode::BadRequest_400;
  2664. }
  2665. })
  2666. .Put("/person",
  2667. [&](const Request &req, Response &res) {
  2668. if (req.has_param("name") && req.has_param("note")) {
  2669. persons_[req.get_param_value("name")] =
  2670. req.get_param_value("note");
  2671. } else {
  2672. res.status = StatusCode::BadRequest_400;
  2673. }
  2674. })
  2675. .Get("/person/(.*)",
  2676. [&](const Request &req, Response &res) {
  2677. string name = req.matches[1];
  2678. if (persons_.find(name) != persons_.end()) {
  2679. auto note = persons_[name];
  2680. res.set_content(note, "text/plain");
  2681. } else {
  2682. res.status = StatusCode::NotFound_404;
  2683. }
  2684. })
  2685. .Delete("/person",
  2686. [&](const Request &req, Response &res) {
  2687. if (req.has_param("name")) {
  2688. string name = req.get_param_value("name");
  2689. if (persons_.find(name) != persons_.end()) {
  2690. persons_.erase(name);
  2691. res.set_content("DELETED", "text/plain");
  2692. } else {
  2693. res.status = StatusCode::NotFound_404;
  2694. }
  2695. } else {
  2696. res.status = StatusCode::BadRequest_400;
  2697. }
  2698. })
  2699. .Post("/x-www-form-urlencoded-json",
  2700. [&](const Request &req, Response &res) {
  2701. auto json = req.get_param_value("json");
  2702. ASSERT_EQ(JSON_DATA, json);
  2703. res.set_content(json, "appliation/json");
  2704. res.status = StatusCode::OK_200;
  2705. })
  2706. .Get("/streamed-chunked",
  2707. [&](const Request & /*req*/, Response &res) {
  2708. res.set_chunked_content_provider(
  2709. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2710. sink.os << "123";
  2711. sink.os << "456";
  2712. sink.os << "789";
  2713. sink.done();
  2714. return true;
  2715. });
  2716. })
  2717. .Get("/streamed-chunked-with-prohibited-trailer",
  2718. [&](const Request & /*req*/, Response &res) {
  2719. auto i = new int(0);
  2720. // Declare both a prohibited trailer (Content-Length) and an
  2721. // allowed one
  2722. res.set_header("Trailer", "Content-Length, X-Allowed");
  2723. res.set_chunked_content_provider(
  2724. "text/plain",
  2725. [i](size_t /*offset*/, DataSink &sink) {
  2726. switch (*i) {
  2727. case 0: sink.os << "123"; break;
  2728. case 1: sink.os << "456"; break;
  2729. case 2: sink.os << "789"; break;
  2730. case 3: {
  2731. sink.done_with_trailer(
  2732. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2733. } break;
  2734. }
  2735. (*i)++;
  2736. return true;
  2737. },
  2738. [i](bool success) {
  2739. EXPECT_TRUE(success);
  2740. delete i;
  2741. });
  2742. })
  2743. .Get("/streamed-chunked2",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. auto i = new int(0);
  2746. res.set_chunked_content_provider(
  2747. "text/plain",
  2748. [i](size_t /*offset*/, DataSink &sink) {
  2749. switch (*i) {
  2750. case 0: sink.os << "123"; break;
  2751. case 1: sink.os << "456"; break;
  2752. case 2: sink.os << "789"; break;
  2753. case 3: sink.done(); break;
  2754. }
  2755. (*i)++;
  2756. return true;
  2757. },
  2758. [i](bool success) {
  2759. EXPECT_TRUE(success);
  2760. delete i;
  2761. });
  2762. })
  2763. .Get("/streamed-chunked-with-trailer",
  2764. [&](const Request & /*req*/, Response &res) {
  2765. auto i = new int(0);
  2766. res.set_header("Trailer", "Dummy1, Dummy2");
  2767. res.set_chunked_content_provider(
  2768. "text/plain",
  2769. [i](size_t /*offset*/, DataSink &sink) {
  2770. switch (*i) {
  2771. case 0: sink.os << "123"; break;
  2772. case 1: sink.os << "456"; break;
  2773. case 2: sink.os << "789"; break;
  2774. case 3: {
  2775. sink.done_with_trailer(
  2776. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2777. } break;
  2778. }
  2779. (*i)++;
  2780. return true;
  2781. },
  2782. [i](bool success) {
  2783. EXPECT_TRUE(success);
  2784. delete i;
  2785. });
  2786. })
  2787. .Get("/streamed",
  2788. [&](const Request & /*req*/, Response &res) {
  2789. res.set_content_provider(
  2790. 6, "text/plain",
  2791. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2792. sink.os << (offset < 3 ? "a" : "b");
  2793. return true;
  2794. });
  2795. })
  2796. .Get("/streamed-with-range",
  2797. [&](const Request &req, Response &res) {
  2798. auto data = new std::string("abcdefg");
  2799. res.set_content_provider(
  2800. data->size(), "text/plain",
  2801. [data](size_t offset, size_t length, DataSink &sink) {
  2802. size_t DATA_CHUNK_SIZE = 4;
  2803. const auto &d = *data;
  2804. auto out_len =
  2805. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2806. auto ret =
  2807. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2808. EXPECT_TRUE(ret);
  2809. return true;
  2810. },
  2811. [data, &req](bool success) {
  2812. EXPECT_EQ(success, !req.has_param("error"));
  2813. delete data;
  2814. });
  2815. })
  2816. .Get("/streamed-cancel",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. res.set_content_provider(
  2819. size_t(-1), "text/plain",
  2820. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2821. sink.os << "data_chunk";
  2822. return true;
  2823. });
  2824. })
  2825. .Get("/regex-with-delimiter",
  2826. [&](const Request &req, Response & /*res*/) {
  2827. ASSERT_TRUE(req.has_param("key"));
  2828. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2829. })
  2830. .Get("/with-range",
  2831. [&](const Request & /*req*/, Response &res) {
  2832. res.set_content("abcdefg", "text/plain");
  2833. })
  2834. .Get("/test-start-time",
  2835. [&](const Request &req, Response & /*res*/) {
  2836. EXPECT_NE(req.start_time_,
  2837. std::chrono::steady_clock::time_point::min());
  2838. })
  2839. .Get("/with-range-customized-response",
  2840. [&](const Request & /*req*/, Response &res) {
  2841. res.status = StatusCode::BadRequest_400;
  2842. res.set_content(JSON_DATA, "application/json");
  2843. })
  2844. .Post("/chunked",
  2845. [&](const Request &req, Response & /*res*/) {
  2846. EXPECT_EQ(req.body, "dechunked post body");
  2847. })
  2848. .Post("/large-chunked",
  2849. [&](const Request &req, Response & /*res*/) {
  2850. std::string expected(6 * 30 * 1024u, 'a');
  2851. EXPECT_EQ(req.body, expected);
  2852. })
  2853. .Post("/multipart",
  2854. [&](const Request &req, Response & /*res*/) {
  2855. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2856. req.form.get_field_count("text2") +
  2857. req.form.get_field_count("file3") +
  2858. req.form.get_field_count("file4"));
  2859. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2860. req.form.get_file_count("file2"));
  2861. ASSERT_TRUE(!req.form.has_file("???"));
  2862. ASSERT_TRUE(!req.form.has_field("???"));
  2863. ASSERT_TRUE(req.body.empty());
  2864. {
  2865. const auto &text = req.form.get_field("text1");
  2866. EXPECT_EQ("text default", text);
  2867. }
  2868. {
  2869. const auto &text = req.form.get_field("text2");
  2870. EXPECT_EQ("aωb", text);
  2871. }
  2872. {
  2873. const auto &file = req.form.get_file("file1");
  2874. EXPECT_EQ("hello.txt", file.filename);
  2875. EXPECT_EQ("text/plain", file.content_type);
  2876. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2877. }
  2878. {
  2879. const auto &file = req.form.get_file("file2");
  2880. EXPECT_EQ("world.json", file.filename);
  2881. EXPECT_EQ("application/json", file.content_type);
  2882. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2883. }
  2884. {
  2885. const auto &text = req.form.get_field("file3");
  2886. EXPECT_EQ(0u, text.size());
  2887. }
  2888. {
  2889. const auto &text = req.form.get_field("file4");
  2890. EXPECT_EQ(0u, text.size());
  2891. }
  2892. })
  2893. .Post("/multipart/multi_file_values",
  2894. [&](const Request &req, Response & /*res*/) {
  2895. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2896. req.form.get_field_count("multi_text1"));
  2897. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2898. ASSERT_TRUE(!req.form.has_file("???"));
  2899. ASSERT_TRUE(!req.form.has_field("???"));
  2900. ASSERT_TRUE(req.body.empty());
  2901. {
  2902. const auto &text = req.form.get_field("text");
  2903. EXPECT_EQ("default text", text);
  2904. }
  2905. {
  2906. const auto &text1_values = req.form.get_fields("multi_text1");
  2907. EXPECT_EQ(2u, text1_values.size());
  2908. EXPECT_EQ("aaaaa", text1_values[0]);
  2909. EXPECT_EQ("bbbbb", text1_values[1]);
  2910. }
  2911. {
  2912. const auto &file1_values = req.form.get_files("multi_file1");
  2913. EXPECT_EQ(2u, file1_values.size());
  2914. auto file1 = file1_values[0];
  2915. EXPECT_EQ(file1.filename, "hello.txt");
  2916. EXPECT_EQ(file1.content_type, "text/plain");
  2917. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2918. auto file2 = file1_values[1];
  2919. EXPECT_EQ(file2.filename, "world.json");
  2920. EXPECT_EQ(file2.content_type, "application/json");
  2921. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2922. }
  2923. })
  2924. .Post("/empty",
  2925. [&](const Request &req, Response &res) {
  2926. EXPECT_EQ(req.body, "");
  2927. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2928. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2929. res.set_content("empty", "text/plain");
  2930. })
  2931. .Post("/empty-no-content-type",
  2932. [&](const Request &req, Response &res) {
  2933. EXPECT_EQ(req.body, "");
  2934. EXPECT_FALSE(req.has_header("Content-Type"));
  2935. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2936. res.set_content("empty-no-content-type", "text/plain");
  2937. })
  2938. .Post("/path-only",
  2939. [&](const Request &req, Response &res) {
  2940. EXPECT_EQ(req.body, "");
  2941. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2942. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2943. res.set_content("path-only", "text/plain");
  2944. })
  2945. .Post("/path-headers-only",
  2946. [&](const Request &req, Response &res) {
  2947. EXPECT_EQ(req.body, "");
  2948. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2949. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2950. EXPECT_EQ("world", req.get_header_value("hello"));
  2951. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2952. res.set_content("path-headers-only", "text/plain");
  2953. })
  2954. .Post("/post-large",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, LARGE_DATA);
  2957. res.set_content(req.body, "text/plain");
  2958. })
  2959. .Post("/post-loopback",
  2960. [&](const Request &, Response &res,
  2961. ContentReader const &content_reader) {
  2962. std::string body;
  2963. content_reader([&](const char *data, size_t data_length) {
  2964. body.append(data, data_length);
  2965. return true;
  2966. });
  2967. res.set_content(body, "text/plain");
  2968. })
  2969. .Put("/put-loopback",
  2970. [&](const Request &, Response &res,
  2971. ContentReader const &content_reader) {
  2972. std::string body;
  2973. content_reader([&](const char *data, size_t data_length) {
  2974. body.append(data, data_length);
  2975. return true;
  2976. });
  2977. res.set_content(body, "text/plain");
  2978. })
  2979. .Patch("/patch-loopback",
  2980. [&](const Request &, Response &res,
  2981. ContentReader const &content_reader) {
  2982. std::string body;
  2983. content_reader([&](const char *data, size_t data_length) {
  2984. body.append(data, data_length);
  2985. return true;
  2986. });
  2987. res.set_content(body, "text/plain");
  2988. })
  2989. .Put("/empty-no-content-type",
  2990. [&](const Request &req, Response &res) {
  2991. EXPECT_EQ(req.body, "");
  2992. EXPECT_FALSE(req.has_header("Content-Type"));
  2993. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2994. res.set_content("empty-no-content-type", "text/plain");
  2995. })
  2996. .Put("/put",
  2997. [&](const Request &req, Response &res) {
  2998. EXPECT_EQ(req.body, "PUT");
  2999. res.set_content(req.body, "text/plain");
  3000. })
  3001. .Put("/put-large",
  3002. [&](const Request &req, Response &res) {
  3003. EXPECT_EQ(req.body, LARGE_DATA);
  3004. res.set_content(req.body, "text/plain");
  3005. })
  3006. .Patch("/patch",
  3007. [&](const Request &req, Response &res) {
  3008. EXPECT_EQ(req.body, "PATCH");
  3009. res.set_content(req.body, "text/plain");
  3010. })
  3011. .Delete("/delete",
  3012. [&](const Request & /*req*/, Response &res) {
  3013. res.set_content("DELETE", "text/plain");
  3014. })
  3015. .Delete("/delete-body",
  3016. [&](const Request &req, Response &res) {
  3017. EXPECT_EQ(req.body, "content");
  3018. res.set_content(req.body, "text/plain");
  3019. })
  3020. .Options(R"(\*)",
  3021. [&](const Request & /*req*/, Response &res) {
  3022. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3023. })
  3024. .Get("/request-target",
  3025. [&](const Request &req, Response & /*res*/) {
  3026. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3027. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3028. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3029. })
  3030. .Get("/long-query-value",
  3031. [&](const Request &req, Response & /*res*/) {
  3032. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3033. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3034. })
  3035. .Get("/too-long-query-value",
  3036. [&](const Request &req, Response & /*res*/) {
  3037. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3038. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3039. })
  3040. .Get("/array-param",
  3041. [&](const Request &req, Response & /*res*/) {
  3042. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3043. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3044. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3045. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3046. })
  3047. .Post("/validate-no-multiple-headers",
  3048. [&](const Request &req, Response & /*res*/) {
  3049. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3050. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3051. })
  3052. .Post("/content_receiver",
  3053. [&](const Request &req, Response &res,
  3054. const ContentReader &content_reader) {
  3055. if (req.is_multipart_form_data()) {
  3056. std::vector<FormData> items;
  3057. content_reader(
  3058. [&](const FormData &file) {
  3059. items.push_back(file);
  3060. return true;
  3061. },
  3062. [&](const char *data, size_t data_length) {
  3063. items.back().content.append(data, data_length);
  3064. return true;
  3065. });
  3066. EXPECT_EQ(5u, items.size());
  3067. {
  3068. const auto &file = get_file_value(items, "text1");
  3069. EXPECT_TRUE(file.filename.empty());
  3070. EXPECT_EQ("text default", file.content);
  3071. }
  3072. {
  3073. const auto &file = get_file_value(items, "text2");
  3074. EXPECT_TRUE(file.filename.empty());
  3075. EXPECT_EQ("aωb", file.content);
  3076. }
  3077. {
  3078. const auto &file = get_file_value(items, "file1");
  3079. EXPECT_EQ("hello.txt", file.filename);
  3080. EXPECT_EQ("text/plain", file.content_type);
  3081. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3082. }
  3083. {
  3084. const auto &file = get_file_value(items, "file2");
  3085. EXPECT_EQ("world.json", file.filename);
  3086. EXPECT_EQ("application/json", file.content_type);
  3087. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3088. }
  3089. {
  3090. const auto &file = get_file_value(items, "file3");
  3091. EXPECT_TRUE(file.filename.empty());
  3092. EXPECT_EQ("application/octet-stream", file.content_type);
  3093. EXPECT_EQ(0u, file.content.size());
  3094. }
  3095. } else {
  3096. std::string body;
  3097. content_reader([&](const char *data, size_t data_length) {
  3098. EXPECT_EQ(7U, data_length);
  3099. body.append(data, data_length);
  3100. return true;
  3101. });
  3102. EXPECT_EQ(body, "content");
  3103. res.set_content(body, "text/plain");
  3104. }
  3105. })
  3106. .Put("/content_receiver",
  3107. [&](const Request & /*req*/, Response &res,
  3108. const ContentReader &content_reader) {
  3109. std::string body;
  3110. content_reader([&](const char *data, size_t data_length) {
  3111. body.append(data, data_length);
  3112. return true;
  3113. });
  3114. EXPECT_EQ(body, "content");
  3115. res.set_content(body, "text/plain");
  3116. })
  3117. .Patch("/content_receiver",
  3118. [&](const Request & /*req*/, Response &res,
  3119. const ContentReader &content_reader) {
  3120. std::string body;
  3121. content_reader([&](const char *data, size_t data_length) {
  3122. body.append(data, data_length);
  3123. return true;
  3124. });
  3125. EXPECT_EQ(body, "content");
  3126. res.set_content(body, "text/plain");
  3127. })
  3128. .Post("/query-string-and-body",
  3129. [&](const Request &req, Response & /*res*/) {
  3130. ASSERT_TRUE(req.has_param("key"));
  3131. EXPECT_EQ(req.get_param_value("key"), "value");
  3132. EXPECT_EQ(req.body, "content");
  3133. })
  3134. .Get("/last-request",
  3135. [&](const Request &req, Response & /*res*/) {
  3136. EXPECT_EQ("close", req.get_header_value("Connection"));
  3137. })
  3138. .Get(R"(/redirect/(\d+))",
  3139. [&](const Request &req, Response &res) {
  3140. auto num = std::stoi(req.matches[1]) + 1;
  3141. std::string url = "/redirect/" + std::to_string(num);
  3142. res.set_redirect(url);
  3143. })
  3144. .Post("/binary",
  3145. [&](const Request &req, Response &res) {
  3146. EXPECT_EQ(4U, req.body.size());
  3147. EXPECT_EQ("application/octet-stream",
  3148. req.get_header_value("Content-Type"));
  3149. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3150. res.set_content(req.body, "application/octet-stream");
  3151. })
  3152. .Put("/binary",
  3153. [&](const Request &req, Response &res) {
  3154. EXPECT_EQ(4U, req.body.size());
  3155. EXPECT_EQ("application/octet-stream",
  3156. req.get_header_value("Content-Type"));
  3157. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3158. res.set_content(req.body, "application/octet-stream");
  3159. })
  3160. .Patch("/binary",
  3161. [&](const Request &req, Response &res) {
  3162. EXPECT_EQ(4U, req.body.size());
  3163. EXPECT_EQ("application/octet-stream",
  3164. req.get_header_value("Content-Type"));
  3165. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3166. res.set_content(req.body, "application/octet-stream");
  3167. })
  3168. .Delete("/binary",
  3169. [&](const Request &req, Response &res) {
  3170. EXPECT_EQ(4U, req.body.size());
  3171. EXPECT_EQ("application/octet-stream",
  3172. req.get_header_value("Content-Type"));
  3173. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3174. res.set_content(req.body, "application/octet-stream");
  3175. })
  3176. .Get("/issue1772",
  3177. [&](const Request & /*req*/, Response &res) {
  3178. res.status = 401;
  3179. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3180. })
  3181. .Delete("/issue609",
  3182. [](const httplib::Request &, httplib::Response &res,
  3183. const httplib::ContentReader &) {
  3184. res.set_content("ok", "text/plain");
  3185. })
  3186. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3187. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3188. .Get("/compress",
  3189. [&](const Request & /*req*/, Response &res) {
  3190. res.set_content(
  3191. "12345678901234567890123456789012345678901234567890123456789"
  3192. "01234567890123456789012345678901234567890",
  3193. "text/plain");
  3194. })
  3195. .Get("/nocompress",
  3196. [&](const Request & /*req*/, Response &res) {
  3197. res.set_content(
  3198. "12345678901234567890123456789012345678901234567890123456789"
  3199. "01234567890123456789012345678901234567890",
  3200. "application/octet-stream");
  3201. })
  3202. .Post("/compress-multipart",
  3203. [&](const Request &req, Response & /*res*/) {
  3204. EXPECT_EQ(2u, req.form.fields.size());
  3205. ASSERT_TRUE(!req.form.has_field("???"));
  3206. {
  3207. const auto &text = req.form.get_field("key1");
  3208. EXPECT_EQ("test", text);
  3209. }
  3210. {
  3211. const auto &text = req.form.get_field("key2");
  3212. EXPECT_EQ("--abcdefg123", text);
  3213. }
  3214. })
  3215. #endif
  3216. ;
  3217. persons_["john"] = "programmer";
  3218. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3219. svr_.wait_until_ready();
  3220. }
  3221. virtual void TearDown() {
  3222. svr_.stop();
  3223. if (!request_threads_.empty()) {
  3224. std::this_thread::sleep_for(std::chrono::seconds(1));
  3225. for (auto &t : request_threads_) {
  3226. t.join();
  3227. }
  3228. }
  3229. t_.join();
  3230. }
  3231. map<string, string> persons_;
  3232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3233. SSLClient cli_;
  3234. SSLServer svr_;
  3235. #else
  3236. Client cli_;
  3237. Server svr_;
  3238. #endif
  3239. thread t_;
  3240. std::vector<thread> request_threads_;
  3241. };
  3242. TEST_F(ServerTest, GetMethod200) {
  3243. auto res = cli_.Get("/hi");
  3244. ASSERT_TRUE(res);
  3245. EXPECT_EQ("HTTP/1.1", res->version);
  3246. EXPECT_EQ(StatusCode::OK_200, res->status);
  3247. EXPECT_EQ("OK", res->reason);
  3248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3249. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3250. EXPECT_EQ("Hello World!", res->body);
  3251. }
  3252. TEST_F(ServerTest, GetEmptyFile) {
  3253. auto res = cli_.Get("/empty_file");
  3254. ASSERT_TRUE(res);
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3257. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3258. EXPECT_EQ("", res->body);
  3259. }
  3260. TEST_F(ServerTest, GetFileContent) {
  3261. auto res = cli_.Get("/file_content");
  3262. ASSERT_TRUE(res);
  3263. EXPECT_EQ(StatusCode::OK_200, res->status);
  3264. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3265. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3266. EXPECT_EQ("test.html", res->body);
  3267. }
  3268. TEST_F(ServerTest, GetFileContentWithRange) {
  3269. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3270. ASSERT_TRUE(res);
  3271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3272. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3273. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3274. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3275. EXPECT_EQ("est", res->body);
  3276. }
  3277. TEST_F(ServerTest, GetFileContentWithContentType) {
  3278. auto res = cli_.Get("/file_content_with_content_type");
  3279. ASSERT_TRUE(res);
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3282. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3283. EXPECT_EQ("file\n", res->body);
  3284. }
  3285. TEST_F(ServerTest, GetInvalidFileContent) {
  3286. auto res = cli_.Get("/invalid_file_content");
  3287. ASSERT_TRUE(res);
  3288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3289. }
  3290. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3291. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ("HTTP/1.1", res->version);
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3296. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. TEST_F(ServerTest, GetMethod302) {
  3300. auto res = cli_.Get("/");
  3301. ASSERT_TRUE(res);
  3302. EXPECT_EQ(StatusCode::Found_302, res->status);
  3303. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3304. }
  3305. TEST_F(ServerTest, GetMethod302Redirect) {
  3306. cli_.set_follow_location(true);
  3307. auto res = cli_.Get("/");
  3308. ASSERT_TRUE(res);
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. EXPECT_EQ("Hello World!", res->body);
  3311. EXPECT_EQ("/hi", res->location);
  3312. }
  3313. TEST_F(ServerTest, GetMethod404) {
  3314. auto res = cli_.Get("/invalid");
  3315. ASSERT_TRUE(res);
  3316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3317. }
  3318. TEST_F(ServerTest, HeadMethod200) {
  3319. auto res = cli_.Head("/hi");
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::OK_200, res->status);
  3322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. EXPECT_TRUE(res->body.empty());
  3324. }
  3325. TEST_F(ServerTest, HeadMethod200Static) {
  3326. auto res = cli_.Head("/mount/dir/index.html");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::OK_200, res->status);
  3329. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3330. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3331. EXPECT_TRUE(res->body.empty());
  3332. }
  3333. TEST_F(ServerTest, HeadMethod404) {
  3334. auto res = cli_.Head("/invalid");
  3335. ASSERT_TRUE(res);
  3336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3337. EXPECT_TRUE(res->body.empty());
  3338. }
  3339. TEST_F(ServerTest, GetMethodPersonJohn) {
  3340. auto res = cli_.Get("/person/john");
  3341. ASSERT_TRUE(res);
  3342. EXPECT_EQ(StatusCode::OK_200, res->status);
  3343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3344. EXPECT_EQ("programmer", res->body);
  3345. }
  3346. TEST_F(ServerTest, PostMethod1) {
  3347. auto res = cli_.Get("/person/john1");
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3350. res = cli_.Post("/person", "name=john1&note=coder",
  3351. "application/x-www-form-urlencoded");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. res = cli_.Get("/person/john1");
  3355. ASSERT_TRUE(res);
  3356. ASSERT_EQ(StatusCode::OK_200, res->status);
  3357. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3358. ASSERT_EQ("coder", res->body);
  3359. }
  3360. TEST_F(ServerTest, PostMethod2) {
  3361. auto res = cli_.Get("/person/john2");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3364. Params params;
  3365. params.emplace("name", "john2");
  3366. params.emplace("note", "coder");
  3367. res = cli_.Post("/person", params);
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. res = cli_.Get("/person/john2");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::OK_200, res->status);
  3373. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3374. ASSERT_EQ("coder", res->body);
  3375. }
  3376. TEST_F(ServerTest, PutMethod3) {
  3377. auto res = cli_.Get("/person/john3");
  3378. ASSERT_TRUE(res);
  3379. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3380. Params params;
  3381. params.emplace("name", "john3");
  3382. params.emplace("note", "coder");
  3383. res = cli_.Put("/person", params);
  3384. ASSERT_TRUE(res);
  3385. ASSERT_EQ(StatusCode::OK_200, res->status);
  3386. res = cli_.Get("/person/john3");
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::OK_200, res->status);
  3389. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3390. ASSERT_EQ("coder", res->body);
  3391. }
  3392. TEST_F(ServerTest, DeleteMethod1) {
  3393. auto res = cli_.Get("/person/john4");
  3394. ASSERT_TRUE(res);
  3395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3396. Params params;
  3397. params.emplace("name", "john4");
  3398. params.emplace("note", "coder");
  3399. res = cli_.Post("/person", params);
  3400. ASSERT_TRUE(res);
  3401. ASSERT_EQ(StatusCode::OK_200, res->status);
  3402. res = cli_.Get("/person/john4");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::OK_200, res->status);
  3405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. ASSERT_EQ("coder", res->body);
  3407. Params delete_params;
  3408. delete_params.emplace("name", "john4");
  3409. res = cli_.Delete("/person", delete_params);
  3410. ASSERT_TRUE(res);
  3411. ASSERT_EQ(StatusCode::OK_200, res->status);
  3412. ASSERT_EQ("DELETED", res->body);
  3413. res = cli_.Get("/person/john4");
  3414. ASSERT_TRUE(res);
  3415. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, DeleteMethod2) {
  3418. auto res = cli_.Get("/person/john5");
  3419. ASSERT_TRUE(res);
  3420. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3421. Params params;
  3422. params.emplace("name", "john5");
  3423. params.emplace("note", "developer");
  3424. res = cli_.Post("/person", params);
  3425. ASSERT_TRUE(res);
  3426. ASSERT_EQ(StatusCode::OK_200, res->status);
  3427. res = cli_.Get("/person/john5");
  3428. ASSERT_TRUE(res);
  3429. ASSERT_EQ(StatusCode::OK_200, res->status);
  3430. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3431. ASSERT_EQ("developer", res->body);
  3432. Params delete_params;
  3433. delete_params.emplace("name", "john5");
  3434. Headers headers;
  3435. headers.emplace("Custom-Header", "test-value");
  3436. res = cli_.Delete("/person", headers, delete_params);
  3437. ASSERT_TRUE(res);
  3438. ASSERT_EQ(StatusCode::OK_200, res->status);
  3439. ASSERT_EQ("DELETED", res->body);
  3440. res = cli_.Get("/person/john5");
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3443. }
  3444. TEST_F(ServerTest, DeleteMethod3) {
  3445. auto res = cli_.Get("/person/john6");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3448. Params params;
  3449. params.emplace("name", "john6");
  3450. params.emplace("note", "tester");
  3451. res = cli_.Post("/person", params);
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. res = cli_.Get("/person/john6");
  3455. ASSERT_TRUE(res);
  3456. ASSERT_EQ(StatusCode::OK_200, res->status);
  3457. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3458. ASSERT_EQ("tester", res->body);
  3459. Params delete_params;
  3460. delete_params.emplace("name", "john6");
  3461. Headers headers;
  3462. headers.emplace("Custom-Header", "test-value");
  3463. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. ASSERT_EQ("DELETED", res->body);
  3467. res = cli_.Get("/person/john6");
  3468. ASSERT_TRUE(res);
  3469. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3470. }
  3471. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3472. Params params;
  3473. params.emplace("json", JSON_DATA);
  3474. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3475. ASSERT_TRUE(res);
  3476. ASSERT_EQ(StatusCode::OK_200, res->status);
  3477. ASSERT_EQ(JSON_DATA, res->body);
  3478. }
  3479. TEST_F(ServerTest, PostEmptyContent) {
  3480. auto res = cli_.Post("/empty", "", "text/plain");
  3481. ASSERT_TRUE(res);
  3482. ASSERT_EQ(StatusCode::OK_200, res->status);
  3483. ASSERT_EQ("empty", res->body);
  3484. }
  3485. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3486. auto res = cli_.Post("/empty-no-content-type");
  3487. ASSERT_TRUE(res);
  3488. ASSERT_EQ(StatusCode::OK_200, res->status);
  3489. ASSERT_EQ("empty-no-content-type", res->body);
  3490. }
  3491. TEST_F(ServerTest, PostPathOnly) {
  3492. auto res = cli_.Post("/path-only");
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ("path-only", res->body);
  3496. }
  3497. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3498. auto res = cli_.Post("/path-headers-only",
  3499. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3500. ASSERT_TRUE(res);
  3501. ASSERT_EQ(StatusCode::OK_200, res->status);
  3502. ASSERT_EQ("path-headers-only", res->body);
  3503. }
  3504. TEST_F(ServerTest, PostLarge) {
  3505. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3506. ASSERT_TRUE(res);
  3507. ASSERT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ(LARGE_DATA, res->body);
  3509. }
  3510. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3511. auto res = cli_.Put("/empty-no-content-type");
  3512. ASSERT_TRUE(res);
  3513. ASSERT_EQ(StatusCode::OK_200, res->status);
  3514. ASSERT_EQ("empty-no-content-type", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDir) {
  3517. auto res = cli_.Get("/dir/");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. auto body = R"(<html>
  3522. <head>
  3523. </head>
  3524. <body>
  3525. <a href="/dir/test.html">Test</a>
  3526. <a href="/hi">hi</a>
  3527. </body>
  3528. </html>
  3529. )";
  3530. EXPECT_EQ(body, res->body);
  3531. }
  3532. TEST_F(ServerTest, GetMethodDirTest) {
  3533. auto res = cli_.Get("/dir/test.html");
  3534. ASSERT_TRUE(res);
  3535. EXPECT_EQ(StatusCode::OK_200, res->status);
  3536. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3537. EXPECT_EQ("test.html", res->body);
  3538. }
  3539. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3540. auto res = cli_.Get("/dir/../dir/test.html");
  3541. ASSERT_TRUE(res);
  3542. EXPECT_EQ(StatusCode::OK_200, res->status);
  3543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3544. EXPECT_EQ("test.html", res->body);
  3545. }
  3546. TEST_F(ServerTest, GetMethodInvalidPath) {
  3547. auto res = cli_.Get("/dir/../test.html");
  3548. ASSERT_TRUE(res);
  3549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3550. }
  3551. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3552. auto res = cli_.Get("/../www/dir/test.html");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3555. }
  3556. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3557. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3558. ASSERT_TRUE(res);
  3559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3560. }
  3561. TEST_F(ServerTest, GetMethodDirMountTest) {
  3562. auto res = cli_.Get("/mount/dir/test.html");
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3566. EXPECT_EQ("test.html", res->body);
  3567. }
  3568. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3569. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3570. ASSERT_TRUE(res);
  3571. EXPECT_EQ(StatusCode::OK_200, res->status);
  3572. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3573. EXPECT_EQ("test.html", res->body);
  3574. }
  3575. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3576. auto res = cli_.Get("/mount/dir/../test.html");
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3579. }
  3580. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3581. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3584. }
  3585. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3586. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3587. ASSERT_TRUE(res);
  3588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3589. }
  3590. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3591. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3596. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3599. }
  3600. TEST_F(ServerTest, PostMethod303) {
  3601. auto res = cli_.Post("/1", "body", "text/plain");
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3604. EXPECT_EQ("/2", res->get_header_value("Location"));
  3605. }
  3606. TEST_F(ServerTest, PostMethod303Redirect) {
  3607. cli_.set_follow_location(true);
  3608. auto res = cli_.Post("/1", "body", "text/plain");
  3609. ASSERT_TRUE(res);
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. EXPECT_EQ("redirected.", res->body);
  3612. EXPECT_EQ("/2", res->location);
  3613. }
  3614. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3615. auto res = cli_.Get("/dir/test.abcde");
  3616. ASSERT_TRUE(res);
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3619. EXPECT_EQ("abcde", res->body);
  3620. }
  3621. TEST_F(ServerTest, StaticFileRange) {
  3622. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3625. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3626. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3627. EXPECT_EQ(true, res->has_header("Content-Range"));
  3628. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3629. EXPECT_EQ(std::string("cd"), res->body);
  3630. }
  3631. TEST_F(ServerTest, StaticFileRanges) {
  3632. auto res =
  3633. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3634. ASSERT_TRUE(res);
  3635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3636. EXPECT_TRUE(
  3637. res->get_header_value("Content-Type")
  3638. .find(
  3639. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3640. 0);
  3641. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3642. }
  3643. TEST_F(ServerTest, StaticFileRangeHead) {
  3644. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3645. ASSERT_TRUE(res);
  3646. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3647. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3648. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3649. EXPECT_EQ(true, res->has_header("Content-Range"));
  3650. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3651. }
  3652. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3653. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3654. ASSERT_TRUE(res);
  3655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3657. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3658. EXPECT_EQ(true, res->has_header("Content-Range"));
  3659. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3660. res->get_header_value("Content-Range"));
  3661. EXPECT_EQ("LAST\n", res->body);
  3662. }
  3663. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3664. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3668. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3669. EXPECT_EQ(true, res->has_header("Content-Range"));
  3670. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3671. }
  3672. TEST_F(ServerTest, StaticFileBigFile) {
  3673. auto res = cli_.Get("/dir/1MB.txt");
  3674. ASSERT_TRUE(res);
  3675. EXPECT_EQ(StatusCode::OK_200, res->status);
  3676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3677. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3678. }
  3679. TEST_F(ServerTest, InvalidBaseDirMount) {
  3680. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3681. }
  3682. TEST_F(ServerTest, Binary) {
  3683. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3684. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3685. "application/octet-stream");
  3686. ASSERT_TRUE(res);
  3687. ASSERT_EQ(StatusCode::OK_200, res->status);
  3688. ASSERT_EQ(4U, res->body.size());
  3689. res = cli_.Put("/binary", binary.data(), binary.size(),
  3690. "application/octet-stream");
  3691. ASSERT_TRUE(res);
  3692. ASSERT_EQ(StatusCode::OK_200, res->status);
  3693. ASSERT_EQ(4U, res->body.size());
  3694. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3695. "application/octet-stream");
  3696. ASSERT_TRUE(res);
  3697. ASSERT_EQ(StatusCode::OK_200, res->status);
  3698. ASSERT_EQ(4U, res->body.size());
  3699. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3700. "application/octet-stream");
  3701. ASSERT_TRUE(res);
  3702. ASSERT_EQ(StatusCode::OK_200, res->status);
  3703. ASSERT_EQ(4U, res->body.size());
  3704. }
  3705. TEST_F(ServerTest, BinaryString) {
  3706. auto binary = std::string("\x00\x01\x02\x03", 4);
  3707. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ(4U, res->body.size());
  3711. res = cli_.Put("/binary", binary, "application/octet-stream");
  3712. ASSERT_TRUE(res);
  3713. ASSERT_EQ(StatusCode::OK_200, res->status);
  3714. ASSERT_EQ(4U, res->body.size());
  3715. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3716. ASSERT_TRUE(res);
  3717. ASSERT_EQ(StatusCode::OK_200, res->status);
  3718. ASSERT_EQ(4U, res->body.size());
  3719. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3720. ASSERT_TRUE(res);
  3721. ASSERT_EQ(StatusCode::OK_200, res->status);
  3722. ASSERT_EQ(4U, res->body.size());
  3723. }
  3724. TEST_F(ServerTest, EmptyRequest) {
  3725. auto res = cli_.Get("");
  3726. ASSERT_TRUE(!res);
  3727. EXPECT_EQ(Error::Connection, res.error());
  3728. }
  3729. TEST_F(ServerTest, LongRequest) {
  3730. std::string request;
  3731. for (size_t i = 0; i < 545; i++) {
  3732. request += "/TooLongRequest";
  3733. }
  3734. request += "OK";
  3735. auto res = cli_.Get(request.c_str());
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3738. }
  3739. TEST_F(ServerTest, TooLongRequest) {
  3740. std::string request;
  3741. for (size_t i = 0; i < 546; i++) {
  3742. request += "/TooLongRequest";
  3743. }
  3744. request += "_NG";
  3745. auto start = std::chrono::high_resolution_clock::now();
  3746. cli_.set_keep_alive(true);
  3747. auto res = cli_.Get(request.c_str());
  3748. auto end = std::chrono::high_resolution_clock::now();
  3749. auto elapsed =
  3750. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3751. .count();
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3754. EXPECT_LE(elapsed, 100);
  3755. EXPECT_EQ("close", res->get_header_value("Connection"));
  3756. EXPECT_FALSE(cli_.is_socket_open());
  3757. }
  3758. TEST_F(ServerTest, AlmostTooLongRequest) {
  3759. // test for #2046 - URI length check shouldn't include other content on req
  3760. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3761. // leading /, space, HTTP/1.1)
  3762. std::string request =
  3763. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3764. auto res = cli_.Get(request.c_str());
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3767. }
  3768. TEST_F(ServerTest, LongHeader) {
  3769. Request req;
  3770. req.method = "GET";
  3771. req.path = "/hi";
  3772. std::string host_and_port;
  3773. host_and_port += HOST;
  3774. host_and_port += ":";
  3775. host_and_port += std::to_string(PORT);
  3776. req.headers.emplace("Host", host_and_port.c_str());
  3777. req.headers.emplace("Accept", "*/*");
  3778. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3779. req.headers.emplace(
  3780. "Header-Name",
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@");
  3810. auto res = std::make_shared<Response>();
  3811. auto error = Error::Success;
  3812. auto ret = cli_.send(req, *res, error);
  3813. ASSERT_TRUE(ret);
  3814. EXPECT_EQ(StatusCode::OK_200, res->status);
  3815. }
  3816. TEST_F(ServerTest, LongQueryValue) {
  3817. auto start = std::chrono::high_resolution_clock::now();
  3818. cli_.set_keep_alive(true);
  3819. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3820. auto end = std::chrono::high_resolution_clock::now();
  3821. auto elapsed =
  3822. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3823. .count();
  3824. ASSERT_TRUE(res);
  3825. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3826. EXPECT_LE(elapsed, 100);
  3827. EXPECT_EQ("close", res->get_header_value("Connection"));
  3828. EXPECT_FALSE(cli_.is_socket_open());
  3829. }
  3830. TEST_F(ServerTest, TooLongQueryValue) {
  3831. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3832. ASSERT_FALSE(res);
  3833. EXPECT_EQ(Error::Read, res.error());
  3834. }
  3835. TEST_F(ServerTest, TooLongHeader) {
  3836. Request req;
  3837. req.method = "GET";
  3838. req.path = "/hi";
  3839. std::string host_and_port;
  3840. host_and_port += HOST;
  3841. host_and_port += ":";
  3842. host_and_port += std::to_string(PORT);
  3843. req.headers.emplace("Host", host_and_port.c_str());
  3844. req.headers.emplace("Accept", "*/*");
  3845. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3846. req.headers.emplace(
  3847. "Header-Name",
  3848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@");
  3877. auto res = std::make_shared<Response>();
  3878. auto error = Error::Success;
  3879. auto ret = cli_.send(req, *res, error);
  3880. ASSERT_TRUE(ret);
  3881. EXPECT_EQ(StatusCode::OK_200, res->status);
  3882. }
  3883. TEST_F(ServerTest, HeaderCountAtLimit) {
  3884. // Test with headers just under the 100 limit
  3885. httplib::Headers headers;
  3886. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3887. // This should keep us just under the 100 header limit
  3888. for (int i = 0; i < 95; i++) {
  3889. std::string name = "X-Test-Header-" + std::to_string(i);
  3890. std::string value = "value" + std::to_string(i);
  3891. headers.emplace(name, value);
  3892. }
  3893. // This should work fine as we're under the limit
  3894. auto res = cli_.Get("/hi", headers);
  3895. EXPECT_TRUE(res);
  3896. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3897. }
  3898. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3899. // Test with many headers to exceed the 100 limit
  3900. httplib::Headers headers;
  3901. // Add 150 headers to definitely exceed the 100 limit
  3902. for (int i = 0; i < 150; i++) {
  3903. std::string name = "X-Test-Header-" + std::to_string(i);
  3904. std::string value = "value" + std::to_string(i);
  3905. headers.emplace(name, value);
  3906. }
  3907. // This should fail due to exceeding header count limit
  3908. cli_.set_keep_alive(true);
  3909. auto res = cli_.Get("/hi", headers);
  3910. // The request should either fail or return 400 Bad Request
  3911. if (res) {
  3912. // If we get a response, it should be 400 Bad Request
  3913. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3914. } else {
  3915. // Or the request should fail entirely
  3916. EXPECT_FALSE(res);
  3917. }
  3918. EXPECT_EQ("close", res->get_header_value("Connection"));
  3919. EXPECT_FALSE(cli_.is_socket_open());
  3920. }
  3921. TEST_F(ServerTest, PercentEncoding) {
  3922. auto res = cli_.Get("/e%6edwith%");
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(StatusCode::OK_200, res->status);
  3925. }
  3926. TEST_F(ServerTest, PercentEncodingUnicode) {
  3927. auto res = cli_.Get("/e%u006edwith%");
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::OK_200, res->status);
  3930. }
  3931. TEST_F(ServerTest, InvalidPercentEncoding) {
  3932. auto res = cli_.Get("/%endwith%");
  3933. ASSERT_TRUE(res);
  3934. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3935. }
  3936. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3937. auto res = cli_.Get("/%uendwith%");
  3938. ASSERT_TRUE(res);
  3939. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3940. }
  3941. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3942. auto res = cli_.Get("/hello?aaa=bbb%");
  3943. ASSERT_TRUE(res);
  3944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3945. }
  3946. TEST_F(ServerTest, PlusSignEncoding) {
  3947. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ(StatusCode::OK_200, res->status);
  3950. EXPECT_EQ("a +b", res->body);
  3951. }
  3952. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3953. // This test simulates a potential DoS attack using many headers
  3954. // to verify our security fix prevents memory exhaustion
  3955. httplib::Headers attack_headers;
  3956. // Attempt to add many headers like an attacker would (200 headers to far
  3957. // exceed limit)
  3958. for (int i = 0; i < 200; i++) {
  3959. std::string name = "X-Attack-Header-" + std::to_string(i);
  3960. std::string value = "attack_payload_" + std::to_string(i);
  3961. attack_headers.emplace(name, value);
  3962. }
  3963. // Try to POST with excessive headers
  3964. cli_.set_keep_alive(true);
  3965. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3966. // Should either fail or return 400 Bad Request due to security limit
  3967. if (res) {
  3968. // If we get a response, it should be 400 Bad Request
  3969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3970. } else {
  3971. // Request failed, which is the expected behavior for DoS protection
  3972. EXPECT_FALSE(res);
  3973. }
  3974. EXPECT_EQ("close", res->get_header_value("Connection"));
  3975. EXPECT_FALSE(cli_.is_socket_open());
  3976. }
  3977. TEST_F(ServerTest, MultipartFormData) {
  3978. UploadFormDataItems items = {
  3979. {"text1", "text default", "", ""},
  3980. {"text2", "aωb", "", ""},
  3981. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3982. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3983. {"file3", "", "", "application/octet-stream"},
  3984. {"file4", "", "", " application/json tmp-string "}};
  3985. auto res = cli_.Post("/multipart", items);
  3986. ASSERT_TRUE(res);
  3987. EXPECT_EQ(StatusCode::OK_200, res->status);
  3988. }
  3989. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3990. UploadFormDataItems items = {
  3991. {"text", "default text", "", ""},
  3992. {"multi_text1", "aaaaa", "", ""},
  3993. {"multi_text1", "bbbbb", "", ""},
  3994. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3995. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3996. "application/json"},
  3997. };
  3998. auto res = cli_.Post("/multipart/multi_file_values", items);
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::OK_200, res->status);
  4001. }
  4002. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4003. auto res = cli_.Get("/hi");
  4004. ASSERT_TRUE(res);
  4005. EXPECT_EQ(StatusCode::OK_200, res->status);
  4006. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4007. EXPECT_EQ("Hello World!", res->body);
  4008. }
  4009. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4010. Request req;
  4011. req.method = "POST";
  4012. req.path = "/chunked";
  4013. std::string host_and_port;
  4014. host_and_port += HOST;
  4015. host_and_port += ":";
  4016. host_and_port += std::to_string(PORT);
  4017. req.headers.emplace("Host", host_and_port.c_str());
  4018. req.headers.emplace("Accept", "*/*");
  4019. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4020. req.headers.emplace("Content-Type", "text/plain");
  4021. req.headers.emplace("Content-Length", "0");
  4022. req.headers.emplace(
  4023. "Transfer-Encoding",
  4024. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4025. // Client does not chunk, so make a chunked body manually.
  4026. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4027. auto res = std::make_shared<Response>();
  4028. auto error = Error::Success;
  4029. auto ret = cli_.send(req, *res, error);
  4030. ASSERT_TRUE(ret);
  4031. EXPECT_EQ(StatusCode::OK_200, res->status);
  4032. }
  4033. TEST_F(ServerTest, GetStreamed2) {
  4034. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4038. EXPECT_EQ(true, res->has_header("Content-Range"));
  4039. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4040. EXPECT_EQ(std::string("ab"), res->body);
  4041. }
  4042. TEST_F(ServerTest, GetStreamed) {
  4043. auto res = cli_.Get("/streamed");
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::OK_200, res->status);
  4046. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(std::string("aaabbb"), res->body);
  4048. }
  4049. TEST_F(ServerTest, GetStreamedWithRange1) {
  4050. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("def"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetStreamedWithRange2) {
  4059. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4060. ASSERT_TRUE(res);
  4061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4062. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4063. EXPECT_EQ(true, res->has_header("Content-Range"));
  4064. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4065. EXPECT_EQ(std::string("bcdefg"), res->body);
  4066. }
  4067. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4068. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4071. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4072. EXPECT_EQ(true, res->has_header("Content-Range"));
  4073. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4074. EXPECT_EQ(std::string("efg"), res->body);
  4075. }
  4076. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4077. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4078. ASSERT_TRUE(res);
  4079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4081. EXPECT_EQ(false, res->has_header("Content-Range"));
  4082. EXPECT_EQ(0U, res->body.size());
  4083. }
  4084. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4085. auto res = cli_.Get("/streamed-with-range",
  4086. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4087. "92233720368547758079223372036854775807"}});
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4090. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4091. EXPECT_EQ(false, res->has_header("Content-Range"));
  4092. EXPECT_EQ(0U, res->body.size());
  4093. }
  4094. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4095. auto res = cli_.Get(
  4096. "/with-range",
  4097. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4098. {"Accept-Encoding", ""}});
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("abcdefg"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4107. auto res = cli_.Get("/with-range", {
  4108. {"Range", "bytes=0-"},
  4109. {"Accept-Encoding", ""},
  4110. });
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4113. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(true, res->has_header("Content-Range"));
  4115. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4116. EXPECT_EQ(std::string("abcdefg"), res->body);
  4117. }
  4118. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4119. auto res =
  4120. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4121. ASSERT_TRUE(res);
  4122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4123. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4124. EXPECT_EQ(false, res->has_header("Content-Range"));
  4125. EXPECT_EQ(267U, res->body.size());
  4126. // Check that both range contents are present
  4127. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4128. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4129. // Check that Content-Range headers are present for both ranges
  4130. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4131. std::string::npos);
  4132. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4133. std::string::npos);
  4134. }
  4135. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4136. Ranges ranges;
  4137. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4138. ranges.emplace_back(0, -1);
  4139. }
  4140. auto res =
  4141. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4142. ASSERT_TRUE(res);
  4143. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4144. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4145. EXPECT_EQ(false, res->has_header("Content-Range"));
  4146. EXPECT_EQ(0U, res->body.size());
  4147. }
  4148. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4149. auto res =
  4150. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4151. ASSERT_TRUE(res);
  4152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4153. EXPECT_EQ(5U, res->body.size());
  4154. // Check that overlapping ranges are coalesced into a single range
  4155. EXPECT_EQ("bcdef", res->body);
  4156. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4157. // Should be single range, not multipart
  4158. EXPECT_TRUE(res->has_header("Content-Range"));
  4159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4160. }
  4161. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4162. auto res =
  4163. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4164. ASSERT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4166. EXPECT_EQ(268U, res->body.size());
  4167. // Check that both range contents are present
  4168. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4169. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4170. // Check that Content-Range headers are present for both ranges
  4171. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4172. std::string::npos);
  4173. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4174. std::string::npos);
  4175. }
  4176. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4177. auto res =
  4178. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4181. EXPECT_EQ(269U, res->body.size());
  4182. // Check that both duplicate range contents are present
  4183. size_t first_abc = res->body.find("abc\r\n");
  4184. EXPECT_TRUE(first_abc != std::string::npos);
  4185. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4186. EXPECT_TRUE(second_abc != std::string::npos);
  4187. // Check that Content-Range headers are present for both ranges
  4188. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4189. EXPECT_TRUE(first_range != std::string::npos);
  4190. size_t second_range =
  4191. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4192. EXPECT_TRUE(second_range != std::string::npos);
  4193. }
  4194. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4195. auto res = cli_.Get("/streamed-with-range?error",
  4196. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4197. ASSERT_TRUE(res);
  4198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4199. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4200. EXPECT_EQ(false, res->has_header("Content-Range"));
  4201. EXPECT_EQ(0U, res->body.size());
  4202. }
  4203. TEST_F(ServerTest, GetStreamedEndless) {
  4204. uint64_t offset = 0;
  4205. auto res = cli_.Get("/streamed-cancel",
  4206. [&](const char * /*data*/, uint64_t data_length) {
  4207. if (offset < 100) {
  4208. offset += data_length;
  4209. return true;
  4210. }
  4211. return false;
  4212. });
  4213. ASSERT_TRUE(!res);
  4214. EXPECT_EQ(Error::Canceled, res.error());
  4215. }
  4216. TEST_F(ServerTest, ClientStop) {
  4217. std::atomic_size_t count{4};
  4218. std::vector<std::thread> threads;
  4219. for (auto i = count.load(); i != 0; --i) {
  4220. threads.emplace_back([&]() {
  4221. auto res = cli_.Get("/streamed-cancel",
  4222. [&](const char *, uint64_t) { return true; });
  4223. --count;
  4224. ASSERT_TRUE(!res);
  4225. EXPECT_TRUE(res.error() == Error::Canceled ||
  4226. res.error() == Error::Read || res.error() == Error::Write);
  4227. });
  4228. }
  4229. std::this_thread::sleep_for(std::chrono::seconds(2));
  4230. while (count != 0) {
  4231. cli_.stop();
  4232. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4233. }
  4234. for (auto &t : threads) {
  4235. t.join();
  4236. }
  4237. }
  4238. TEST_F(ServerTest, GetWithRange1) {
  4239. auto res = cli_.Get("/with-range", {
  4240. make_range_header({{3, 5}}),
  4241. {"Accept-Encoding", ""},
  4242. });
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4245. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4246. EXPECT_EQ(true, res->has_header("Content-Range"));
  4247. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4248. EXPECT_EQ(std::string("def"), res->body);
  4249. }
  4250. TEST_F(ServerTest, GetWithRange2) {
  4251. auto res = cli_.Get("/with-range", {
  4252. make_range_header({{1, -1}}),
  4253. {"Accept-Encoding", ""},
  4254. });
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4257. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4258. EXPECT_EQ(true, res->has_header("Content-Range"));
  4259. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4260. EXPECT_EQ(std::string("bcdefg"), res->body);
  4261. }
  4262. TEST_F(ServerTest, GetWithRange3) {
  4263. auto res = cli_.Get("/with-range", {
  4264. make_range_header({{0, 0}}),
  4265. {"Accept-Encoding", ""},
  4266. });
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4269. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(true, res->has_header("Content-Range"));
  4271. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4272. EXPECT_EQ(std::string("a"), res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRange4) {
  4275. auto res = cli_.Get("/with-range", {
  4276. make_range_header({{-1, 2}}),
  4277. {"Accept-Encoding", ""},
  4278. });
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4281. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4282. EXPECT_EQ(true, res->has_header("Content-Range"));
  4283. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4284. EXPECT_EQ(std::string("fg"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetWithRange5) {
  4287. auto res = cli_.Get("/with-range", {
  4288. make_range_header({{0, 5}}),
  4289. {"Accept-Encoding", ""},
  4290. });
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4293. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4294. EXPECT_EQ(true, res->has_header("Content-Range"));
  4295. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4296. EXPECT_EQ(std::string("abcdef"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4299. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4302. }
  4303. TEST_F(ServerTest, GetWithRangeMultipart) {
  4304. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4307. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4308. EXPECT_EQ(false, res->has_header("Content-Range"));
  4309. EXPECT_EQ(267U, res->body.size());
  4310. }
  4311. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4312. auto res =
  4313. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4314. ASSERT_TRUE(res);
  4315. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4316. }
  4317. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4318. auto res = cli_.Get("/with-range-customized-response",
  4319. {{make_range_header({{1, 2}})}});
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4322. EXPECT_EQ(true, res->has_header("Content-Length"));
  4323. EXPECT_EQ(false, res->has_header("Content-Range"));
  4324. EXPECT_EQ(JSON_DATA, res->body);
  4325. }
  4326. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4327. auto res = cli_.Get("/with-range-customized-response",
  4328. {{make_range_header({{1, 2}, {4, 5}})}});
  4329. ASSERT_TRUE(res);
  4330. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4331. EXPECT_EQ(true, res->has_header("Content-Length"));
  4332. EXPECT_EQ(false, res->has_header("Content-Range"));
  4333. EXPECT_EQ(JSON_DATA, res->body);
  4334. }
  4335. TEST_F(ServerTest, Issue1772) {
  4336. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4339. }
  4340. TEST_F(ServerTest, Issue609) {
  4341. auto res = cli_.Delete("/issue609");
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. EXPECT_EQ(std::string("ok"), res->body);
  4345. }
  4346. TEST_F(ServerTest, GetStreamedChunked) {
  4347. auto res = cli_.Get("/streamed-chunked");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ(std::string("123456789"), res->body);
  4351. }
  4352. TEST_F(ServerTest, GetStreamedChunked2) {
  4353. auto res = cli_.Get("/streamed-chunked2");
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::OK_200, res->status);
  4356. EXPECT_EQ(std::string("123456789"), res->body);
  4357. }
  4358. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4359. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. EXPECT_EQ(std::string("123456789"), res->body);
  4363. EXPECT_TRUE(res->has_header("Trailer"));
  4364. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4365. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4366. // Trailers are now stored separately from headers (security fix)
  4367. EXPECT_EQ(2U, res->trailers.size());
  4368. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4369. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4370. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4371. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4372. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4373. // Verify trailers are NOT in headers (security verification)
  4374. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4375. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4376. }
  4377. TEST_F(ServerTest, LargeChunkedPost) {
  4378. Request req;
  4379. req.method = "POST";
  4380. req.path = "/large-chunked";
  4381. std::string host_and_port;
  4382. host_and_port += HOST;
  4383. host_and_port += ":";
  4384. host_and_port += std::to_string(PORT);
  4385. req.headers.emplace("Host", host_and_port.c_str());
  4386. req.headers.emplace("Accept", "*/*");
  4387. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4388. req.headers.emplace("Content-Type", "text/plain");
  4389. req.headers.emplace("Content-Length", "0");
  4390. req.headers.emplace("Transfer-Encoding", "chunked");
  4391. std::string long_string(30 * 1024u, 'a');
  4392. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4393. // Attempt to make a large enough post to exceed OS buffers, to test that
  4394. // the server handles short reads if the full chunk data isn't available.
  4395. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4396. auto res = std::make_shared<Response>();
  4397. auto error = Error::Success;
  4398. auto ret = cli_.send(req, *res, error);
  4399. ASSERT_TRUE(ret);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4403. auto res = cli_.Get("/remote_addr");
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4407. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4408. }
  4409. TEST_F(ServerTest, GetMethodLocalAddr) {
  4410. auto res = cli_.Get("/local_addr");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4414. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4415. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4416. }
  4417. TEST_F(ServerTest, HTTPResponseSplitting) {
  4418. auto res = cli_.Get("/http_response_splitting");
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. }
  4422. TEST_F(ServerTest, SlowRequest) {
  4423. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4424. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4425. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4426. }
  4427. #if 0
  4428. TEST_F(ServerTest, SlowPost) {
  4429. char buffer[64 * 1024];
  4430. memset(buffer, 0x42, sizeof(buffer));
  4431. auto res = cli_.Post(
  4432. "/slowpost", 64 * 1024 * 1024,
  4433. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4434. auto ret = sink.write(buffer, sizeof(buffer));
  4435. EXPECT_TRUE(ret);
  4436. return true;
  4437. },
  4438. "text/plain");
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. }
  4442. TEST_F(ServerTest, SlowPostFail) {
  4443. char buffer[64 * 1024];
  4444. memset(buffer, 0x42, sizeof(buffer));
  4445. cli_.set_write_timeout(std::chrono::seconds(0));
  4446. auto res = cli_.Post(
  4447. "/slowpost", 64 * 1024 * 1024,
  4448. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4449. sink.write(buffer, sizeof(buffer));
  4450. return true;
  4451. },
  4452. "text/plain");
  4453. ASSERT_TRUE(!res);
  4454. EXPECT_EQ(Error::Write, res.error());
  4455. }
  4456. #endif
  4457. TEST_F(ServerTest, Put) {
  4458. auto res = cli_.Put("/put", "PUT", "text/plain");
  4459. ASSERT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. EXPECT_EQ("PUT", res->body);
  4462. }
  4463. TEST_F(ServerTest, PutWithContentProvider) {
  4464. auto res = cli_.Put(
  4465. "/put", 3,
  4466. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4467. sink.os << "PUT";
  4468. return true;
  4469. },
  4470. "text/plain");
  4471. ASSERT_TRUE(res);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("PUT", res->body);
  4474. }
  4475. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4476. auto res = cli_.Post(
  4477. "/post", 42,
  4478. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4479. return false;
  4480. },
  4481. "text/plain");
  4482. ASSERT_TRUE(!res);
  4483. EXPECT_EQ(Error::Canceled, res.error());
  4484. }
  4485. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4486. auto res = cli_.Put(
  4487. "/put",
  4488. [](size_t /*offset*/, DataSink &sink) {
  4489. sink.os << "PUT";
  4490. sink.done();
  4491. return true;
  4492. },
  4493. "text/plain");
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. EXPECT_EQ("PUT", res->body);
  4497. }
  4498. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4499. auto res = cli_.Post(
  4500. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4501. "text/plain");
  4502. ASSERT_TRUE(!res);
  4503. EXPECT_EQ(Error::Canceled, res.error());
  4504. }
  4505. TEST_F(ServerTest, PostLoopBack) {
  4506. std::string body;
  4507. auto res = cli_.Post(
  4508. "/post-loopback", 9,
  4509. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4510. EXPECT_EQ(9u, length);
  4511. sink.write("123", 3);
  4512. sink.write("456", 3);
  4513. sink.write("789", 3);
  4514. return true;
  4515. },
  4516. "text/plain",
  4517. [&body](const char *data, size_t data_length) {
  4518. body.append(data, data_length);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("123456789", body);
  4524. }
  4525. TEST_F(ServerTest, PutLoopBack) {
  4526. std::string body;
  4527. auto res = cli_.Put(
  4528. "/put-loopback", 9,
  4529. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4530. EXPECT_EQ(9u, length);
  4531. sink.write("123", 3);
  4532. sink.write("456", 3);
  4533. sink.write("789", 3);
  4534. return true;
  4535. },
  4536. "text/plain",
  4537. [&body](const char *data, size_t data_length) {
  4538. body.append(data, data_length);
  4539. return true;
  4540. });
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(StatusCode::OK_200, res->status);
  4543. EXPECT_EQ("123456789", body);
  4544. }
  4545. TEST_F(ServerTest, PatchLoopBack) {
  4546. std::string body;
  4547. auto res = cli_.Patch(
  4548. "/patch-loopback", 9,
  4549. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4550. EXPECT_EQ(9u, length);
  4551. sink.write("123", 3);
  4552. sink.write("456", 3);
  4553. sink.write("789", 3);
  4554. return true;
  4555. },
  4556. "text/plain",
  4557. [&body](const char *data, size_t data_length) {
  4558. body.append(data, data_length);
  4559. return true;
  4560. });
  4561. ASSERT_TRUE(res);
  4562. EXPECT_EQ(StatusCode::OK_200, res->status);
  4563. EXPECT_EQ("123456789", body);
  4564. }
  4565. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4566. std::string body;
  4567. auto res = cli_.Post(
  4568. "/post-loopback",
  4569. [](size_t /*offset*/, DataSink &sink) {
  4570. sink.write("123", 3);
  4571. sink.write("456", 3);
  4572. sink.write("789", 3);
  4573. sink.done();
  4574. return true;
  4575. },
  4576. "text/plain",
  4577. [&body](const char *data, size_t data_length) {
  4578. body.append(data, data_length);
  4579. return true;
  4580. });
  4581. ASSERT_TRUE(res);
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ("123456789", body);
  4584. }
  4585. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4586. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4587. cli_.set_compress(true);
  4588. auto res = cli_.Put(
  4589. "/put", 3,
  4590. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4591. sink.os << "PUT";
  4592. return true;
  4593. },
  4594. "text/plain");
  4595. ASSERT_TRUE(res);
  4596. EXPECT_EQ(StatusCode::OK_200, res->status);
  4597. EXPECT_EQ("PUT", res->body);
  4598. }
  4599. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4600. cli_.set_compress(true);
  4601. auto res = cli_.Post(
  4602. "/post", 42,
  4603. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4604. return false;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(!res);
  4608. EXPECT_EQ(Error::Canceled, res.error());
  4609. }
  4610. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4611. cli_.set_compress(true);
  4612. auto res = cli_.Put(
  4613. "/put",
  4614. [](size_t /*offset*/, DataSink &sink) {
  4615. sink.os << "PUT";
  4616. sink.done();
  4617. return true;
  4618. },
  4619. "text/plain");
  4620. ASSERT_TRUE(res);
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("PUT", res->body);
  4623. }
  4624. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4625. cli_.set_compress(true);
  4626. auto res = cli_.Post(
  4627. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4628. "text/plain");
  4629. ASSERT_TRUE(!res);
  4630. EXPECT_EQ(Error::Canceled, res.error());
  4631. }
  4632. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4633. cli_.set_compress(true);
  4634. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. EXPECT_EQ(LARGE_DATA, res->body);
  4638. }
  4639. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4640. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4641. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4642. Client cli(s.c_str());
  4643. cli.enable_server_certificate_verification(false);
  4644. #else
  4645. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4646. Client cli(s.c_str());
  4647. #endif
  4648. cli.set_compress(true);
  4649. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ(LARGE_DATA, res->body);
  4653. // The compressed size should be less than a 10th of the original. May vary
  4654. // depending on the zlib library.
  4655. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4656. static_cast<uint64_t>(10 * 1024 * 1024));
  4657. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4658. }
  4659. TEST_F(ServerTest, PutContentWithDeflate) {
  4660. cli_.set_compress(false);
  4661. Headers headers;
  4662. headers.emplace("Content-Encoding", "deflate");
  4663. // PUT in deflate format:
  4664. auto res = cli_.Put("/put", headers,
  4665. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("PUT", res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4671. Headers headers;
  4672. headers.emplace("Accept-Encoding", "gzip, deflate");
  4673. auto res = cli_.Get("/streamed-chunked", headers);
  4674. ASSERT_TRUE(res);
  4675. EXPECT_EQ(StatusCode::OK_200, res->status);
  4676. EXPECT_EQ(std::string("123456789"), res->body);
  4677. }
  4678. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4679. Headers headers;
  4680. headers.emplace("Accept-Encoding", "gzip, deflate");
  4681. auto res = cli_.Get("/streamed-chunked2", headers);
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ(std::string("123456789"), res->body);
  4685. }
  4686. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4687. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4688. ASSERT_TRUE(res);
  4689. EXPECT_EQ(StatusCode::OK_200, res->status);
  4690. }
  4691. TEST(GzipDecompressor, ChunkedDecompression) {
  4692. std::string data;
  4693. for (size_t i = 0; i < 32 * 1024; ++i) {
  4694. data.push_back(static_cast<char>('a' + i % 26));
  4695. }
  4696. std::string compressed_data;
  4697. {
  4698. httplib::detail::gzip_compressor compressor;
  4699. bool result = compressor.compress(
  4700. data.data(), data.size(),
  4701. /*last=*/true,
  4702. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4703. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4704. compressed_data_size);
  4705. return true;
  4706. });
  4707. ASSERT_TRUE(result);
  4708. }
  4709. std::string decompressed_data;
  4710. {
  4711. httplib::detail::gzip_decompressor decompressor;
  4712. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4713. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4714. size_t chunk_size = 130;
  4715. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4716. chunk_begin += chunk_size) {
  4717. size_t current_chunk_size =
  4718. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4719. bool result = decompressor.decompress(
  4720. compressed_data.data() + chunk_begin, current_chunk_size,
  4721. [&](const char *decompressed_data_chunk,
  4722. size_t decompressed_data_chunk_size) {
  4723. decompressed_data.insert(decompressed_data.size(),
  4724. decompressed_data_chunk,
  4725. decompressed_data_chunk_size);
  4726. return true;
  4727. });
  4728. ASSERT_TRUE(result);
  4729. }
  4730. }
  4731. ASSERT_EQ(data, decompressed_data);
  4732. }
  4733. TEST(GzipDecompressor, DeflateDecompression) {
  4734. std::string original_text = "Raw deflate without gzip";
  4735. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4736. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4737. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4738. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4739. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4740. std::string decompressed_data;
  4741. {
  4742. httplib::detail::gzip_decompressor decompressor;
  4743. bool result = decompressor.decompress(
  4744. compressed_data.data(), compressed_data.size(),
  4745. [&](const char *decompressed_data_chunk,
  4746. size_t decompressed_data_chunk_size) {
  4747. decompressed_data.insert(decompressed_data.size(),
  4748. decompressed_data_chunk,
  4749. decompressed_data_chunk_size);
  4750. return true;
  4751. });
  4752. ASSERT_TRUE(result);
  4753. }
  4754. ASSERT_EQ(original_text, decompressed_data);
  4755. }
  4756. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4757. std::string original_text = "Raw deflate without gzip";
  4758. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4759. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4760. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4761. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4762. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4763. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4764. std::string decompressed_data;
  4765. {
  4766. httplib::detail::gzip_decompressor decompressor;
  4767. bool result = decompressor.decompress(
  4768. compressed_data.data(), compressed_data.size(),
  4769. [&](const char *decompressed_data_chunk,
  4770. size_t decompressed_data_chunk_size) {
  4771. decompressed_data.insert(decompressed_data.size(),
  4772. decompressed_data_chunk,
  4773. decompressed_data_chunk_size);
  4774. return true;
  4775. });
  4776. ASSERT_TRUE(result);
  4777. }
  4778. ASSERT_EQ(original_text, decompressed_data);
  4779. }
  4780. #ifdef _WIN32
  4781. TEST(GzipDecompressor, LargeRandomData) {
  4782. // prepare large random data that is difficult to be compressed and is
  4783. // expected to have large size even when compressed
  4784. std::random_device seed_gen;
  4785. std::mt19937 random(seed_gen());
  4786. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4787. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4788. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4789. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4790. // compress data over 4GiB
  4791. std::string compressed_data;
  4792. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4793. httplib::detail::gzip_compressor compressor;
  4794. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4795. data.size() * sizeof(std::uint32_t), true,
  4796. [&](const char *data, size_t size) {
  4797. compressed_data.insert(
  4798. compressed_data.size(), data, size);
  4799. return true;
  4800. });
  4801. ASSERT_TRUE(result);
  4802. // FIXME: compressed data size is expected to be greater than 4GiB,
  4803. // but there is no guarantee
  4804. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4805. // decompress data over 4GiB
  4806. std::string decompressed_data;
  4807. decompressed_data.reserve(data_size);
  4808. httplib::detail::gzip_decompressor decompressor;
  4809. result = decompressor.decompress(
  4810. compressed_data.data(), compressed_data.size(),
  4811. [&](const char *data, size_t size) {
  4812. decompressed_data.insert(decompressed_data.size(), data, size);
  4813. return true;
  4814. });
  4815. ASSERT_TRUE(result);
  4816. // compare
  4817. ASSERT_EQ(data_size, decompressed_data.size());
  4818. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4819. 0);
  4820. }
  4821. #endif
  4822. #endif
  4823. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4824. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4825. Headers headers;
  4826. headers.emplace("Accept-Encoding", "br");
  4827. auto res = cli_.Get("/streamed-chunked", headers);
  4828. ASSERT_TRUE(res);
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. EXPECT_EQ(std::string("123456789"), res->body);
  4831. }
  4832. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4833. Headers headers;
  4834. headers.emplace("Accept-Encoding", "br");
  4835. auto res = cli_.Get("/streamed-chunked2", headers);
  4836. ASSERT_TRUE(res);
  4837. EXPECT_EQ(StatusCode::OK_200, res->status);
  4838. EXPECT_EQ(std::string("123456789"), res->body);
  4839. }
  4840. #endif
  4841. TEST_F(ServerTest, Patch) {
  4842. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4843. ASSERT_TRUE(res);
  4844. EXPECT_EQ(StatusCode::OK_200, res->status);
  4845. EXPECT_EQ("PATCH", res->body);
  4846. }
  4847. TEST_F(ServerTest, Delete) {
  4848. auto res = cli_.Delete("/delete");
  4849. ASSERT_TRUE(res);
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ("DELETE", res->body);
  4852. }
  4853. TEST_F(ServerTest, DeleteContentReceiver) {
  4854. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. EXPECT_EQ("content", res->body);
  4858. }
  4859. TEST_F(ServerTest, Options) {
  4860. auto res = cli_.Options("*");
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ(StatusCode::OK_200, res->status);
  4863. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4864. EXPECT_TRUE(res->body.empty());
  4865. }
  4866. TEST_F(ServerTest, URL) {
  4867. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. }
  4871. TEST_F(ServerTest, ArrayParam) {
  4872. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. }
  4876. TEST_F(ServerTest, NoMultipleHeaders) {
  4877. Headers headers = {{"Content-Length", "5"}};
  4878. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4879. "text/plain");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, PostContentReceiver) {
  4884. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4885. ASSERT_TRUE(res);
  4886. ASSERT_EQ(StatusCode::OK_200, res->status);
  4887. ASSERT_EQ("content", res->body);
  4888. }
  4889. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4890. UploadFormDataItems items = {
  4891. {"text1", "text default", "", ""},
  4892. {"text2", "aωb", "", ""},
  4893. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4894. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4895. {"file3", "", "", "application/octet-stream"},
  4896. };
  4897. auto res = cli_.Post("/content_receiver", items);
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. }
  4901. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4902. UploadFormDataItems items = {
  4903. {"text1", "text default", "", ""},
  4904. {"text2", "aωb", "", ""},
  4905. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4906. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4907. {"file3", "", "", "application/octet-stream"},
  4908. };
  4909. auto boundary = std::string("+++++");
  4910. std::string body;
  4911. for (const auto &item : items) {
  4912. body += "--" + boundary + "\r\n";
  4913. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4914. if (!item.filename.empty()) {
  4915. body += "; filename=\"" + item.filename + "\"";
  4916. }
  4917. body += "\r\n";
  4918. if (!item.content_type.empty()) {
  4919. body += "Content-Type: " + item.content_type + "\r\n";
  4920. }
  4921. body += "\r\n";
  4922. body += item.content + "\r\n";
  4923. }
  4924. body += "--" + boundary + "--\r\n";
  4925. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4926. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4927. ASSERT_TRUE(res);
  4928. EXPECT_EQ(StatusCode::OK_200, res->status);
  4929. }
  4930. TEST_F(ServerTest, PostContentReceiverGzip) {
  4931. cli_.set_compress(true);
  4932. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4933. ASSERT_TRUE(res);
  4934. ASSERT_EQ(StatusCode::OK_200, res->status);
  4935. ASSERT_EQ("content", res->body);
  4936. }
  4937. TEST_F(ServerTest, PutContentReceiver) {
  4938. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4939. ASSERT_TRUE(res);
  4940. ASSERT_EQ(StatusCode::OK_200, res->status);
  4941. ASSERT_EQ("content", res->body);
  4942. }
  4943. TEST_F(ServerTest, PatchContentReceiver) {
  4944. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4945. ASSERT_TRUE(res);
  4946. ASSERT_EQ(StatusCode::OK_200, res->status);
  4947. ASSERT_EQ("content", res->body);
  4948. }
  4949. template <typename ClientType>
  4950. void TestWithHeadersAndContentReceiver(
  4951. ClientType &cli,
  4952. std::function<Result(ClientType &, const std::string &, const Headers &,
  4953. const std::string &, const std::string &,
  4954. ContentReceiver, DownloadProgress)>
  4955. request_func) {
  4956. Headers headers;
  4957. headers.emplace("X-Custom-Header", "test-value");
  4958. std::string received_body;
  4959. auto res = request_func(
  4960. cli, "/content_receiver", headers, "content", "application/json",
  4961. [&](const char *data, size_t data_length) {
  4962. received_body.append(data, data_length);
  4963. return true;
  4964. },
  4965. nullptr);
  4966. ASSERT_TRUE(res);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. EXPECT_EQ("content", received_body);
  4969. }
  4970. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4972. using ClientT = SSLClient;
  4973. #else
  4974. using ClientT = Client;
  4975. #endif
  4976. TestWithHeadersAndContentReceiver<ClientT>(
  4977. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4978. const std::string &body, const std::string &content_type,
  4979. ContentReceiver receiver, DownloadProgress progress) {
  4980. return cli.Post(path, headers, body, content_type, receiver, progress);
  4981. });
  4982. }
  4983. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4985. using ClientT = SSLClient;
  4986. #else
  4987. using ClientT = Client;
  4988. #endif
  4989. TestWithHeadersAndContentReceiver<ClientT>(
  4990. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4991. const std::string &body, const std::string &content_type,
  4992. ContentReceiver receiver, DownloadProgress progress) {
  4993. return cli.Put(path, headers, body, content_type, receiver, progress);
  4994. });
  4995. }
  4996. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4998. using ClientT = SSLClient;
  4999. #else
  5000. using ClientT = Client;
  5001. #endif
  5002. TestWithHeadersAndContentReceiver<ClientT>(
  5003. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5004. const std::string &body, const std::string &content_type,
  5005. ContentReceiver receiver, DownloadProgress progress) {
  5006. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5007. });
  5008. }
  5009. template <typename ClientType>
  5010. void TestWithHeadersAndContentReceiverWithProgress(
  5011. ClientType &cli,
  5012. std::function<Result(ClientType &, const std::string &, const Headers &,
  5013. const std::string &, const std::string &,
  5014. ContentReceiver, DownloadProgress)>
  5015. request_func) {
  5016. Headers headers;
  5017. headers.emplace("X-Test-Header", "progress-test");
  5018. std::string received_body;
  5019. auto progress_called = false;
  5020. auto res = request_func(
  5021. cli, "/content_receiver", headers, "content", "text/plain",
  5022. [&](const char *data, size_t data_length) {
  5023. received_body.append(data, data_length);
  5024. return true;
  5025. },
  5026. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5027. progress_called = true;
  5028. return true;
  5029. });
  5030. ASSERT_TRUE(res);
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ("content", received_body);
  5033. EXPECT_TRUE(progress_called);
  5034. }
  5035. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5037. using ClientT = SSLClient;
  5038. #else
  5039. using ClientT = Client;
  5040. #endif
  5041. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5042. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5043. const std::string &body, const std::string &content_type,
  5044. ContentReceiver receiver, DownloadProgress progress) {
  5045. return cli.Post(path, headers, body, content_type, receiver, progress);
  5046. });
  5047. }
  5048. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5050. using ClientT = SSLClient;
  5051. #else
  5052. using ClientT = Client;
  5053. #endif
  5054. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5055. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5056. const std::string &body, const std::string &content_type,
  5057. ContentReceiver receiver, DownloadProgress progress) {
  5058. return cli.Put(path, headers, body, content_type, receiver, progress);
  5059. });
  5060. }
  5061. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5062. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5063. using ClientT = SSLClient;
  5064. #else
  5065. using ClientT = Client;
  5066. #endif
  5067. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5068. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5069. const std::string &body, const std::string &content_type,
  5070. ContentReceiver receiver, DownloadProgress progress) {
  5071. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5072. });
  5073. }
  5074. template <typename ClientType>
  5075. void TestWithHeadersAndContentReceiverError(
  5076. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5077. const Headers &, const std::string &,
  5078. const std::string &, ContentReceiver)>
  5079. request_func) {
  5080. Headers headers;
  5081. headers.emplace("X-Error-Test", "true");
  5082. std::string received_body;
  5083. auto receiver_failed = false;
  5084. auto res =
  5085. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5086. [&](const char *data, size_t data_length) {
  5087. received_body.append(data, data_length);
  5088. receiver_failed = true;
  5089. return false;
  5090. });
  5091. ASSERT_FALSE(res);
  5092. EXPECT_TRUE(receiver_failed);
  5093. }
  5094. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5095. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5096. using ClientT = SSLClient;
  5097. #else
  5098. using ClientT = Client;
  5099. #endif
  5100. TestWithHeadersAndContentReceiverError<ClientT>(
  5101. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5102. const std::string &body, const std::string &content_type,
  5103. ContentReceiver receiver) {
  5104. return cli.Post(path, headers, body, content_type, receiver);
  5105. });
  5106. }
  5107. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5108. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5109. using ClientT = SSLClient;
  5110. #else
  5111. using ClientT = Client;
  5112. #endif
  5113. TestWithHeadersAndContentReceiverError<ClientT>(
  5114. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5115. const std::string &body, const std::string &content_type,
  5116. ContentReceiver receiver) {
  5117. return cli.Put(path, headers, body, content_type, receiver);
  5118. });
  5119. }
  5120. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5122. using ClientT = SSLClient;
  5123. #else
  5124. using ClientT = Client;
  5125. #endif
  5126. TestWithHeadersAndContentReceiverError<ClientT>(
  5127. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5128. const std::string &body, const std::string &content_type,
  5129. ContentReceiver receiver) {
  5130. return cli.Patch(path, headers, body, content_type, receiver);
  5131. });
  5132. }
  5133. TEST_F(ServerTest, PostQueryStringAndBody) {
  5134. auto res =
  5135. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5136. ASSERT_TRUE(res);
  5137. ASSERT_EQ(StatusCode::OK_200, res->status);
  5138. }
  5139. TEST_F(ServerTest, HTTP2Magic) {
  5140. Request req;
  5141. req.method = "PRI";
  5142. req.path = "*";
  5143. req.body = "SM";
  5144. auto res = std::make_shared<Response>();
  5145. auto error = Error::Success;
  5146. auto ret = cli_.send(req, *res, error);
  5147. ASSERT_TRUE(ret);
  5148. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5149. }
  5150. TEST_F(ServerTest, KeepAlive) {
  5151. auto res = cli_.Get("/hi");
  5152. ASSERT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::OK_200, res->status);
  5154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5155. EXPECT_EQ("Hello World!", res->body);
  5156. res = cli_.Get("/hi");
  5157. ASSERT_TRUE(res);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5160. EXPECT_EQ("Hello World!", res->body);
  5161. res = cli_.Get("/hi");
  5162. ASSERT_TRUE(res);
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5165. EXPECT_EQ("Hello World!", res->body);
  5166. res = cli_.Get("/not-exist");
  5167. ASSERT_TRUE(res);
  5168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5169. res = cli_.Post("/empty", "", "text/plain");
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5173. EXPECT_EQ("empty", res->body);
  5174. EXPECT_EQ("close", res->get_header_value("Connection"));
  5175. res = cli_.Post(
  5176. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5177. "text/plain");
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5181. EXPECT_EQ("empty", res->body);
  5182. cli_.set_keep_alive(false);
  5183. res = cli_.Get("/last-request");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. }
  5188. TEST_F(ServerTest, TooManyRedirect) {
  5189. cli_.set_follow_location(true);
  5190. auto res = cli_.Get("/redirect/0");
  5191. ASSERT_TRUE(!res);
  5192. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5193. }
  5194. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5195. Request req;
  5196. req.method = "FOOBAR";
  5197. req.path = "/hi";
  5198. cli_.set_keep_alive(true);
  5199. auto res = cli_.send(req);
  5200. ASSERT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5202. EXPECT_EQ("close", res->get_header_value("Connection"));
  5203. EXPECT_FALSE(cli_.is_socket_open());
  5204. }
  5205. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5206. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5207. TEST_F(ServerTest, Gzip) {
  5208. Headers headers;
  5209. headers.emplace("Accept-Encoding", "gzip, deflate");
  5210. auto res = cli_.Get("/compress", headers);
  5211. ASSERT_TRUE(res);
  5212. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5214. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5215. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5216. "7890123456789012345678901234567890",
  5217. res->body);
  5218. EXPECT_EQ(StatusCode::OK_200, res->status);
  5219. }
  5220. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5221. Headers headers;
  5222. headers.emplace("Accept-Encoding", "");
  5223. auto res = cli_.Get("/compress", headers);
  5224. ASSERT_TRUE(res);
  5225. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5227. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5228. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5229. "7890123456789012345678901234567890",
  5230. res->body);
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. }
  5233. TEST_F(ServerTest, GzipWithContentReceiver) {
  5234. Headers headers;
  5235. headers.emplace("Accept-Encoding", "gzip, deflate");
  5236. std::string body;
  5237. auto res = cli_.Get("/compress", headers,
  5238. [&](const char *data, uint64_t data_length) {
  5239. EXPECT_EQ(100U, data_length);
  5240. body.append(data, data_length);
  5241. return true;
  5242. });
  5243. ASSERT_TRUE(res);
  5244. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5246. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5247. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5248. "7890123456789012345678901234567890",
  5249. body);
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. }
  5252. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5253. Headers headers;
  5254. headers.emplace("Accept-Encoding", "gzip, deflate");
  5255. cli_.set_decompress(false);
  5256. auto res = cli_.Get("/compress", headers);
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5260. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5261. EXPECT_EQ(33U, res->body.size());
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. }
  5264. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5265. Headers headers;
  5266. headers.emplace("Accept-Encoding", "");
  5267. std::string body;
  5268. auto res = cli_.Get("/compress", headers,
  5269. [&](const char *data, uint64_t data_length) {
  5270. EXPECT_EQ(100U, data_length);
  5271. body.append(data, data_length);
  5272. return true;
  5273. });
  5274. ASSERT_TRUE(res);
  5275. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5276. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5277. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5278. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5279. "7890123456789012345678901234567890",
  5280. body);
  5281. EXPECT_EQ(StatusCode::OK_200, res->status);
  5282. }
  5283. TEST_F(ServerTest, NoGzip) {
  5284. Headers headers;
  5285. headers.emplace("Accept-Encoding", "gzip, deflate");
  5286. auto res = cli_.Get("/nocompress", headers);
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5289. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5290. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5291. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5292. "7890123456789012345678901234567890",
  5293. res->body);
  5294. EXPECT_EQ(StatusCode::OK_200, res->status);
  5295. }
  5296. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5297. Headers headers;
  5298. headers.emplace("Accept-Encoding", "gzip, deflate");
  5299. std::string body;
  5300. auto res = cli_.Get("/nocompress", headers,
  5301. [&](const char *data, uint64_t data_length) {
  5302. EXPECT_EQ(100U, data_length);
  5303. body.append(data, data_length);
  5304. return true;
  5305. });
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5308. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5309. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5310. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5311. "7890123456789012345678901234567890",
  5312. body);
  5313. EXPECT_EQ(StatusCode::OK_200, res->status);
  5314. }
  5315. TEST_F(ServerTest, MultipartFormDataGzip) {
  5316. UploadFormDataItems items = {
  5317. {"key1", "test", "", ""},
  5318. {"key2", "--abcdefg123", "", ""},
  5319. };
  5320. cli_.set_compress(true);
  5321. auto res = cli_.Post("/compress-multipart", items);
  5322. ASSERT_TRUE(res);
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. }
  5325. #endif
  5326. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5327. TEST_F(ServerTest, Brotli) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "br");
  5330. auto res = cli_.Get("/compress", headers);
  5331. ASSERT_TRUE(res);
  5332. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5334. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5335. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5336. "7890123456789012345678901234567890",
  5337. res->body);
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. }
  5340. #endif
  5341. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5342. TEST_F(ServerTest, Zstd) {
  5343. Headers headers;
  5344. headers.emplace("Accept-Encoding", "zstd");
  5345. auto res = cli_.Get("/compress", headers);
  5346. ASSERT_TRUE(res);
  5347. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5350. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5351. "7890123456789012345678901234567890",
  5352. res->body);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. }
  5355. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5356. Headers headers;
  5357. headers.emplace("Accept-Encoding", "");
  5358. auto res = cli_.Get("/compress", headers);
  5359. ASSERT_TRUE(res);
  5360. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5362. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5363. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5364. "7890123456789012345678901234567890",
  5365. res->body);
  5366. EXPECT_EQ(StatusCode::OK_200, res->status);
  5367. }
  5368. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5369. Headers headers;
  5370. headers.emplace("Accept-Encoding", "zstd");
  5371. std::string body;
  5372. auto res = cli_.Get("/compress", headers,
  5373. [&](const char *data, uint64_t data_length) {
  5374. EXPECT_EQ(100U, data_length);
  5375. body.append(data, data_length);
  5376. return true;
  5377. });
  5378. ASSERT_TRUE(res);
  5379. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5381. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5382. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5383. "7890123456789012345678901234567890",
  5384. body);
  5385. EXPECT_EQ(StatusCode::OK_200, res->status);
  5386. }
  5387. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5388. Headers headers;
  5389. headers.emplace("Accept-Encoding", "zstd");
  5390. cli_.set_decompress(false);
  5391. auto res = cli_.Get("/compress", headers);
  5392. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5393. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5394. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5395. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. ASSERT_EQ(26U, res->body.size());
  5402. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5403. 0);
  5404. }
  5405. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5406. Headers headers;
  5407. headers.emplace("Accept-Encoding", "");
  5408. std::string body;
  5409. auto res = cli_.Get("/compress", headers,
  5410. [&](const char *data, uint64_t data_length) {
  5411. EXPECT_EQ(100U, data_length);
  5412. body.append(data, data_length);
  5413. return true;
  5414. });
  5415. ASSERT_TRUE(res);
  5416. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5418. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5420. "7890123456789012345678901234567890",
  5421. body);
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. }
  5424. TEST_F(ServerTest, NoZstd) {
  5425. Headers headers;
  5426. headers.emplace("Accept-Encoding", "zstd");
  5427. auto res = cli_.Get("/nocompress", headers);
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5430. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5431. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5433. "7890123456789012345678901234567890",
  5434. res->body);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. }
  5437. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5438. Headers headers;
  5439. headers.emplace("Accept-Encoding", "zstd");
  5440. std::string body;
  5441. auto res = cli_.Get("/nocompress", headers,
  5442. [&](const char *data, uint64_t data_length) {
  5443. EXPECT_EQ(100U, data_length);
  5444. body.append(data, data_length);
  5445. return true;
  5446. });
  5447. ASSERT_TRUE(res);
  5448. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5449. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5450. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5452. "7890123456789012345678901234567890",
  5453. body);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. }
  5456. // TODO: How to enable zstd ??
  5457. TEST_F(ServerTest, MultipartFormDataZstd) {
  5458. UploadFormDataItems items = {
  5459. {"key1", "test", "", ""},
  5460. {"key2", "--abcdefg123", "", ""},
  5461. };
  5462. Headers headers;
  5463. headers.emplace("Accept-Encoding", "zstd");
  5464. cli_.set_compress(true);
  5465. auto res = cli_.Post("/compress-multipart", headers, items);
  5466. ASSERT_TRUE(res);
  5467. EXPECT_EQ(StatusCode::OK_200, res->status);
  5468. }
  5469. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5470. Headers headers;
  5471. headers.emplace("Accept-Encoding", "zstd");
  5472. cli_.set_compress(true);
  5473. auto res = cli_.Put(
  5474. "/put", headers, 3,
  5475. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5476. sink.os << "PUT";
  5477. return true;
  5478. },
  5479. "text/plain");
  5480. ASSERT_TRUE(res);
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("PUT", res->body);
  5483. }
  5484. // Pre-compression logging tests
  5485. TEST_F(ServerTest, PreCompressionLogging) {
  5486. // Test data for compression (matches the actual /compress endpoint content)
  5487. const std::string test_content =
  5488. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5489. "3456789012345678901234567890";
  5490. // Variables to capture logging data
  5491. std::string pre_compression_body;
  5492. std::string pre_compression_content_type;
  5493. std::string pre_compression_content_encoding;
  5494. std::string post_compression_body;
  5495. std::string post_compression_content_type;
  5496. std::string post_compression_content_encoding;
  5497. // Set up pre-compression logger
  5498. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5499. const Response &res) {
  5500. pre_compression_body = res.body;
  5501. pre_compression_content_type = res.get_header_value("Content-Type");
  5502. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5503. });
  5504. // Set up post-compression logger
  5505. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5506. post_compression_body = res.body;
  5507. post_compression_content_type = res.get_header_value("Content-Type");
  5508. post_compression_content_encoding =
  5509. res.get_header_value("Content-Encoding");
  5510. });
  5511. // Test with gzip compression
  5512. Headers headers;
  5513. headers.emplace("Accept-Encoding", "gzip");
  5514. auto res = cli_.Get("/compress", headers);
  5515. // Verify response was compressed
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5519. // Verify pre-compression logger captured uncompressed content
  5520. EXPECT_EQ(test_content, pre_compression_body);
  5521. EXPECT_EQ("text/plain", pre_compression_content_type);
  5522. EXPECT_TRUE(pre_compression_content_encoding
  5523. .empty()); // No encoding header before compression
  5524. // Verify post-compression logger captured compressed content
  5525. EXPECT_NE(test_content,
  5526. post_compression_body); // Should be different after compression
  5527. EXPECT_EQ("text/plain", post_compression_content_type);
  5528. EXPECT_EQ("gzip", post_compression_content_encoding);
  5529. // Verify compressed content is smaller
  5530. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5531. }
  5532. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5533. const std::string test_content =
  5534. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5535. "3456789012345678901234567890";
  5536. std::string pre_compression_body;
  5537. std::string post_compression_body;
  5538. svr_.set_pre_compression_logger(
  5539. [&](const Request & /*req*/, const Response &res) {
  5540. pre_compression_body = res.body;
  5541. });
  5542. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5543. post_compression_body = res.body;
  5544. });
  5545. Headers headers;
  5546. headers.emplace("Accept-Encoding", "br");
  5547. auto res = cli_.Get("/compress", headers);
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5551. // Verify pre-compression content is uncompressed
  5552. EXPECT_EQ(test_content, pre_compression_body);
  5553. // Verify post-compression content is compressed
  5554. EXPECT_NE(test_content, post_compression_body);
  5555. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5556. }
  5557. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5558. const std::string test_content =
  5559. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5560. "3456789012345678901234567890";
  5561. std::string pre_compression_body;
  5562. std::string post_compression_body;
  5563. svr_.set_pre_compression_logger(
  5564. [&](const Request & /*req*/, const Response &res) {
  5565. pre_compression_body = res.body;
  5566. });
  5567. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5568. post_compression_body = res.body;
  5569. });
  5570. // Request without compression (use /nocompress endpoint)
  5571. Headers headers;
  5572. auto res = cli_.Get("/nocompress", headers);
  5573. ASSERT_TRUE(res);
  5574. EXPECT_EQ(StatusCode::OK_200, res->status);
  5575. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5576. // Pre-compression logger should not be called when no compression is applied
  5577. EXPECT_TRUE(
  5578. pre_compression_body.empty()); // Pre-compression logger not called
  5579. EXPECT_EQ(
  5580. test_content,
  5581. post_compression_body); // Post-compression logger captures final content
  5582. }
  5583. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5584. const std::string test_content =
  5585. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5586. "3456789012345678901234567890";
  5587. std::string pre_compression_body;
  5588. bool pre_logger_called = false;
  5589. // Set only pre-compression logger
  5590. svr_.set_pre_compression_logger(
  5591. [&](const Request & /*req*/, const Response &res) {
  5592. pre_compression_body = res.body;
  5593. pre_logger_called = true;
  5594. });
  5595. Headers headers;
  5596. headers.emplace("Accept-Encoding", "gzip");
  5597. auto res = cli_.Get("/compress", headers);
  5598. ASSERT_TRUE(res);
  5599. EXPECT_EQ(StatusCode::OK_200, res->status);
  5600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5601. // Verify pre-compression logger was called
  5602. EXPECT_TRUE(pre_logger_called);
  5603. EXPECT_EQ(test_content, pre_compression_body);
  5604. }
  5605. TEST(ZstdDecompressor, ChunkedDecompression) {
  5606. std::string data;
  5607. for (size_t i = 0; i < 32 * 1024; ++i) {
  5608. data.push_back(static_cast<char>('a' + i % 26));
  5609. }
  5610. std::string compressed_data;
  5611. {
  5612. httplib::detail::zstd_compressor compressor;
  5613. bool result = compressor.compress(
  5614. data.data(), data.size(),
  5615. /*last=*/true,
  5616. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5617. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5618. compressed_data_size);
  5619. return true;
  5620. });
  5621. ASSERT_TRUE(result);
  5622. }
  5623. std::string decompressed_data;
  5624. {
  5625. httplib::detail::zstd_decompressor decompressor;
  5626. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5627. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5628. size_t chunk_size = 130;
  5629. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5630. chunk_begin += chunk_size) {
  5631. size_t current_chunk_size =
  5632. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5633. bool result = decompressor.decompress(
  5634. compressed_data.data() + chunk_begin, current_chunk_size,
  5635. [&](const char *decompressed_data_chunk,
  5636. size_t decompressed_data_chunk_size) {
  5637. decompressed_data.insert(decompressed_data.size(),
  5638. decompressed_data_chunk,
  5639. decompressed_data_chunk_size);
  5640. return true;
  5641. });
  5642. ASSERT_TRUE(result);
  5643. }
  5644. }
  5645. ASSERT_EQ(data, decompressed_data);
  5646. }
  5647. TEST(ZstdDecompressor, Decompress) {
  5648. std::string original_text = "Compressed with ZSTD";
  5649. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5650. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5651. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5652. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5653. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5654. std::string decompressed_data;
  5655. {
  5656. httplib::detail::zstd_decompressor decompressor;
  5657. bool result = decompressor.decompress(
  5658. compressed_data.data(), compressed_data.size(),
  5659. [&](const char *decompressed_data_chunk,
  5660. size_t decompressed_data_chunk_size) {
  5661. decompressed_data.insert(decompressed_data.size(),
  5662. decompressed_data_chunk,
  5663. decompressed_data_chunk_size);
  5664. return true;
  5665. });
  5666. ASSERT_TRUE(result);
  5667. }
  5668. ASSERT_EQ(original_text, decompressed_data);
  5669. }
  5670. #endif
  5671. // Sends a raw request to a server listening at HOST:PORT.
  5672. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5673. std::string *resp = nullptr) {
  5674. auto error = Error::Success;
  5675. auto client_sock = detail::create_client_socket(
  5676. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5677. /*connection_timeout_sec=*/5, 0,
  5678. /*read_timeout_sec=*/5, 0,
  5679. /*write_timeout_sec=*/5, 0, std::string(), error);
  5680. if (client_sock == INVALID_SOCKET) { return false; }
  5681. auto ret = detail::process_client_socket(
  5682. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5683. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5684. if (req.size() !=
  5685. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5686. return false;
  5687. }
  5688. char buf[512];
  5689. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5690. while (line_reader.getline()) {
  5691. if (resp) { *resp += line_reader.ptr(); }
  5692. }
  5693. return true;
  5694. });
  5695. detail::close_socket(client_sock);
  5696. return ret;
  5697. }
  5698. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5699. Server svr;
  5700. std::string header_value;
  5701. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5702. header_value = req.get_header_value("foo");
  5703. res.set_content("ok", "text/plain");
  5704. });
  5705. thread t = thread([&] { svr.listen(HOST, PORT); });
  5706. auto se = detail::scope_exit([&] {
  5707. svr.stop();
  5708. t.join();
  5709. ASSERT_FALSE(svr.is_running());
  5710. });
  5711. svr.wait_until_ready();
  5712. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5713. // like characters are not treated the same - use vertical tab and escape.
  5714. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5715. "foo: \t \v bar \x1B\t \r\n"
  5716. "Connection: close\r\n"
  5717. "\r\n";
  5718. std::string res;
  5719. ASSERT_TRUE(send_request(5, req, &res));
  5720. EXPECT_EQ(header_value, "");
  5721. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5722. }
  5723. // Sends a raw request and verifies that there isn't a crash or exception.
  5724. static void test_raw_request(const std::string &req,
  5725. std::string *out = nullptr) {
  5726. Server svr;
  5727. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5728. res.set_content("ok", "text/plain");
  5729. });
  5730. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5731. res.set_content("ok", "text/plain");
  5732. });
  5733. svr.Get("/header_field_value_check",
  5734. [&](const Request & /*req*/, Response &res) {
  5735. res.set_content("ok", "text/plain");
  5736. });
  5737. // Server read timeout must be longer than the client read timeout for the
  5738. // bug to reproduce, probably to force the server to process a request
  5739. // without a trailing blank line.
  5740. const time_t client_read_timeout_sec = 1;
  5741. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5742. bool listen_thread_ok = false;
  5743. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5744. auto se = detail::scope_exit([&] {
  5745. svr.stop();
  5746. t.join();
  5747. ASSERT_FALSE(svr.is_running());
  5748. EXPECT_TRUE(listen_thread_ok);
  5749. });
  5750. svr.wait_until_ready();
  5751. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5752. }
  5753. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5754. // A certain header line causes an exception if the header property is parsed
  5755. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5756. test_raw_request(
  5757. "GET /hi HTTP/1.1\r\n"
  5758. " : "
  5759. " "
  5760. " ");
  5761. }
  5762. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5763. // A certain header line causes an exception if the header property *name* is
  5764. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5765. // greedy matcher and requires backtracking when there are a lot of ":"
  5766. // characters.
  5767. // This occurs with libc++ but not libstdc++.
  5768. test_raw_request(
  5769. "GET /hi HTTP/1.1\r\n"
  5770. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5771. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5772. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5773. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5774. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5775. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5776. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5777. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5778. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5779. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5780. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5781. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5782. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5783. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5784. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5785. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5786. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5787. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5788. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5789. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5790. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5791. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5792. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5793. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5794. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5795. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5796. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5797. "&&&%%%");
  5798. }
  5799. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5800. // Make sure this doesn't crash the server.
  5801. // In a previous version of the header line regex, the "\r" rendered the line
  5802. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5803. // a new position where the leading white space ended and the field value
  5804. // began.
  5805. // The crash occurs with libc++ but not libstdc++.
  5806. test_raw_request("GET /hi HTTP/1.1\r\n"
  5807. "a:" +
  5808. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5809. "\r\n"
  5810. "\r\n");
  5811. }
  5812. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5813. std::string out;
  5814. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5815. "Content-Type: text/plain\r\n"
  5816. "Transfer-Encoding: chunked\r\n"
  5817. "\r\n"
  5818. "nothex\r\n",
  5819. &out);
  5820. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5821. }
  5822. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5823. std::string out;
  5824. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5825. "Content-Type: text/plain\r\n"
  5826. "Transfer-Encoding: chunked\r\n"
  5827. "\r\n"
  5828. "3\r\n"
  5829. "xyz\r\n"
  5830. "NaN\r\n",
  5831. &out);
  5832. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5833. }
  5834. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5835. std::string out;
  5836. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5837. "Content-Type: text/plain\r\n"
  5838. "Transfer-Encoding: chunked\r\n"
  5839. "\r\n"
  5840. // Length is too large for 64 bits.
  5841. "1ffffffffffffffff\r\n"
  5842. "xyz\r\n",
  5843. &out);
  5844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5845. }
  5846. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5847. test_raw_request("GET /hi HTTP/1.1\r\n"
  5848. "Content-Type: text/plain\r\n\r");
  5849. }
  5850. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5851. std::string out;
  5852. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5853. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5854. }
  5855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5856. Server svr;
  5857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5858. EXPECT_TRUE(!req.remote_addr.empty());
  5859. });
  5860. thread t = thread([&] { svr.listen(HOST, PORT); });
  5861. auto se = detail::scope_exit([&] {
  5862. svr.stop();
  5863. t.join();
  5864. ASSERT_FALSE(svr.is_running());
  5865. });
  5866. svr.wait_until_ready();
  5867. // Send an invalid request line to trigger Bad Request
  5868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5869. std::string out;
  5870. ASSERT_TRUE(send_request(5, bad_req, &out));
  5871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5872. }
  5873. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5874. std::string out;
  5875. std::string request(
  5876. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5877. test_raw_request(request, &out);
  5878. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5879. }
  5880. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5881. std::string out;
  5882. std::string request(
  5883. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5884. test_raw_request(request, &out);
  5885. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5886. }
  5887. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5888. std::string out;
  5889. std::string request(
  5890. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5891. test_raw_request(request, &out);
  5892. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5893. }
  5894. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5895. std::string out;
  5896. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5897. "Test: \r\n\r\n",
  5898. &out);
  5899. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5900. }
  5901. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5902. Server svr;
  5903. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5904. res.set_header("Cache-Control", "no-cache");
  5905. res.set_chunked_content_provider(
  5906. "text/event-stream", [](size_t offset, DataSink &sink) {
  5907. std::string s = "data:";
  5908. s += std::to_string(offset);
  5909. s += "\n\n";
  5910. auto ret = sink.write(s.data(), s.size());
  5911. EXPECT_TRUE(ret);
  5912. std::this_thread::sleep_for(std::chrono::seconds(1));
  5913. return true;
  5914. });
  5915. });
  5916. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5917. svr.wait_until_ready();
  5918. Client client(HOST, PORT);
  5919. const Headers headers = {{"Accept", "text/event-stream"}};
  5920. auto get_thread = std::thread([&client, &headers]() {
  5921. auto res = client.Get(
  5922. "/events", headers,
  5923. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5924. });
  5925. auto se = detail::scope_exit([&] {
  5926. svr.stop();
  5927. get_thread.join();
  5928. listen_thread.join();
  5929. ASSERT_FALSE(svr.is_running());
  5930. });
  5931. // Give GET time to get a few messages.
  5932. std::this_thread::sleep_for(std::chrono::seconds(2));
  5933. }
  5934. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5935. httplib::Server svr;
  5936. svr.Post("/hi",
  5937. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5938. res.status = StatusCode::OK_200;
  5939. });
  5940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5941. svr.wait_until_ready();
  5942. Client cli(HOST, PORT);
  5943. auto res = cli.Post("/hi", "data", "text/plain");
  5944. ASSERT_TRUE(res);
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. svr.stop();
  5947. thread.join();
  5948. ASSERT_FALSE(svr.is_running());
  5949. res = cli.Post("/hi", "data", "text/plain");
  5950. ASSERT_FALSE(res);
  5951. }
  5952. TEST(ServerStopTest, ListenFailure) {
  5953. Server svr;
  5954. auto t = thread([&]() {
  5955. auto ret = svr.listen("????", PORT);
  5956. EXPECT_FALSE(ret);
  5957. });
  5958. svr.wait_until_ready();
  5959. svr.stop();
  5960. t.join();
  5961. }
  5962. TEST(ServerStopTest, Decommision) {
  5963. Server svr;
  5964. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5965. for (int i = 0; i < 4; i++) {
  5966. auto is_even = !(i % 2);
  5967. std::thread t{[&] {
  5968. try {
  5969. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5970. if (is_even) {
  5971. throw std::runtime_error("Some thing that happens to go wrong.");
  5972. }
  5973. svr.listen(HOST, PORT);
  5974. } catch (...) { svr.decommission(); }
  5975. }};
  5976. svr.wait_until_ready();
  5977. // Server is up
  5978. {
  5979. Client cli(HOST, PORT);
  5980. auto res = cli.Get("/hi");
  5981. if (is_even) {
  5982. EXPECT_FALSE(res);
  5983. } else {
  5984. EXPECT_TRUE(res);
  5985. EXPECT_EQ("hi...", res->body);
  5986. }
  5987. }
  5988. svr.stop();
  5989. t.join();
  5990. // Server is down...
  5991. {
  5992. Client cli(HOST, PORT);
  5993. auto res = cli.Get("/hi");
  5994. EXPECT_FALSE(res);
  5995. }
  5996. }
  5997. }
  5998. // Helper function for string body upload progress tests
  5999. template <typename SetupHandler, typename ClientCall>
  6000. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6001. ClientCall &&client_call,
  6002. const string &body) {
  6003. Server svr;
  6004. setup_handler(svr);
  6005. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6006. auto se = detail::scope_exit([&] {
  6007. svr.stop();
  6008. t.join();
  6009. });
  6010. svr.wait_until_ready();
  6011. Client cli(HOST, PORT);
  6012. vector<uint64_t> progress_values;
  6013. bool progress_called = false;
  6014. auto res =
  6015. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6016. progress_values.push_back(current);
  6017. progress_called = true;
  6018. return true;
  6019. });
  6020. ASSERT_TRUE(res);
  6021. EXPECT_EQ(200, res->status);
  6022. EXPECT_TRUE(progress_called);
  6023. }
  6024. TEST(UploadProgressTest, PostStringBodyBasic) {
  6025. TestStringBodyUploadProgress(
  6026. [](Server &svr) {
  6027. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6028. res.set_content("received", "text/plain");
  6029. });
  6030. },
  6031. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6032. return cli.Post("/test", body, "text/plain", progress_callback);
  6033. },
  6034. "test data for upload progress");
  6035. }
  6036. TEST(UploadProgressTest, PutStringBodyBasic) {
  6037. TestStringBodyUploadProgress(
  6038. [](Server &svr) {
  6039. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6040. res.set_content("put received", "text/plain");
  6041. });
  6042. },
  6043. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6044. return cli.Put("/test", body, "text/plain", progress_callback);
  6045. },
  6046. "put test data for upload progress");
  6047. }
  6048. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6049. TestStringBodyUploadProgress(
  6050. [](Server &svr) {
  6051. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6052. res.set_content("patch received", "text/plain");
  6053. });
  6054. },
  6055. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6056. return cli.Patch("/test", body, "text/plain", progress_callback);
  6057. },
  6058. "patch test data for upload progress");
  6059. }
  6060. // Helper function for content provider upload progress tests
  6061. template <typename SetupHandler, typename ClientCall>
  6062. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6063. ClientCall &&client_call) {
  6064. Server svr;
  6065. setup_handler(svr);
  6066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6067. auto se = detail::scope_exit([&] {
  6068. svr.stop();
  6069. t.join();
  6070. });
  6071. svr.wait_until_ready();
  6072. Client cli(HOST, PORT);
  6073. vector<uint64_t> progress_values;
  6074. auto res =
  6075. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6076. progress_values.push_back(current);
  6077. return true;
  6078. });
  6079. ASSERT_TRUE(res);
  6080. EXPECT_EQ(200, res->status);
  6081. EXPECT_FALSE(progress_values.empty());
  6082. }
  6083. TEST(UploadProgressTest, PostContentProviderProgress) {
  6084. TestContentProviderUploadProgress(
  6085. [](Server &svr) {
  6086. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6087. res.set_content("provider received", "text/plain");
  6088. });
  6089. },
  6090. [](Client &cli, UploadProgress progress_callback) {
  6091. return cli.Post(
  6092. "/test", 10,
  6093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6094. sink.os << "test data";
  6095. return true;
  6096. },
  6097. "text/plain", progress_callback);
  6098. });
  6099. }
  6100. // Helper function for multipart upload progress tests
  6101. template <typename SetupHandler, typename ClientCall>
  6102. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6103. ClientCall &&client_call,
  6104. const string &endpoint) {
  6105. Server svr;
  6106. setup_handler(svr);
  6107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6108. auto se = detail::scope_exit([&] {
  6109. svr.stop();
  6110. t.join();
  6111. });
  6112. svr.wait_until_ready();
  6113. Client cli(HOST, PORT);
  6114. vector<uint64_t> progress_values;
  6115. UploadFormDataItems items = {
  6116. {"field1", "value1", "", ""},
  6117. {"field2", "longer value for progress tracking test", "", ""},
  6118. {"file1", "file content data for upload progress", "test.txt",
  6119. "text/plain"}};
  6120. auto res = client_call(cli, endpoint, items,
  6121. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6122. progress_values.push_back(current);
  6123. return true;
  6124. });
  6125. ASSERT_TRUE(res);
  6126. EXPECT_EQ(200, res->status);
  6127. EXPECT_FALSE(progress_values.empty());
  6128. }
  6129. TEST(UploadProgressTest, PostMultipartProgress) {
  6130. TestMultipartUploadProgress(
  6131. [](Server &svr) {
  6132. svr.Post("/multipart", [](const Request &req, Response &res) {
  6133. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6134. res.set_content("multipart received", "text/plain");
  6135. });
  6136. },
  6137. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6138. UploadProgress progress_callback) {
  6139. return cli.Post(endpoint, items, progress_callback);
  6140. },
  6141. "/multipart");
  6142. }
  6143. // Helper function for basic download progress tests
  6144. template <typename SetupHandler, typename ClientCall>
  6145. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6146. ClientCall &&client_call, const string &endpoint,
  6147. size_t expected_content_size) {
  6148. Server svr;
  6149. setup_handler(svr);
  6150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6151. auto se = detail::scope_exit([&] {
  6152. svr.stop();
  6153. t.join();
  6154. });
  6155. svr.wait_until_ready();
  6156. Client cli(HOST, PORT);
  6157. vector<uint64_t> progress_values;
  6158. auto res = client_call(cli, endpoint,
  6159. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6160. progress_values.push_back(current);
  6161. return true;
  6162. });
  6163. ASSERT_TRUE(res);
  6164. EXPECT_EQ(200, res->status);
  6165. EXPECT_FALSE(progress_values.empty());
  6166. EXPECT_EQ(expected_content_size, res->body.size());
  6167. }
  6168. TEST(DownloadProgressTest, GetBasic) {
  6169. TestBasicDownloadProgress(
  6170. [](Server &svr) {
  6171. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6172. string content(1000, 'D');
  6173. res.set_content(content, "text/plain");
  6174. });
  6175. },
  6176. [](Client &cli, const string &endpoint,
  6177. DownloadProgress progress_callback) {
  6178. return cli.Get(endpoint, progress_callback);
  6179. },
  6180. "/download", 1000u);
  6181. }
  6182. // Helper function for content receiver download progress tests
  6183. template <typename SetupHandler, typename ClientCall>
  6184. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6185. ClientCall &&client_call,
  6186. const string &endpoint,
  6187. size_t expected_content_size) {
  6188. Server svr;
  6189. setup_handler(svr);
  6190. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6191. auto se = detail::scope_exit([&] {
  6192. svr.stop();
  6193. t.join();
  6194. });
  6195. svr.wait_until_ready();
  6196. Client cli(HOST, PORT);
  6197. vector<uint64_t> progress_values;
  6198. string received_body;
  6199. auto res = client_call(
  6200. cli, endpoint,
  6201. [&](const char *data, size_t data_length) -> bool {
  6202. received_body.append(data, data_length);
  6203. return true;
  6204. },
  6205. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6206. progress_values.push_back(current);
  6207. return true;
  6208. });
  6209. ASSERT_TRUE(res);
  6210. EXPECT_EQ(200, res->status);
  6211. EXPECT_FALSE(progress_values.empty());
  6212. EXPECT_EQ(expected_content_size, received_body.size());
  6213. EXPECT_TRUE(res->body.empty());
  6214. }
  6215. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6216. TestContentReceiverDownloadProgress(
  6217. [](Server &svr) {
  6218. svr.Get("/download-receiver",
  6219. [](const Request & /*req*/, Response &res) {
  6220. string content(2000, 'R');
  6221. res.set_content(content, "text/plain");
  6222. });
  6223. },
  6224. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6225. DownloadProgress progress_callback) {
  6226. return cli.Get(endpoint, content_receiver, progress_callback);
  6227. },
  6228. "/download-receiver", 2000u);
  6229. }
  6230. TEST(StreamingTest, NoContentLengthStreaming) {
  6231. Server svr;
  6232. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6233. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6234. if (offset < 6) {
  6235. sink.os << (offset < 3 ? "a" : "b");
  6236. } else {
  6237. sink.done();
  6238. }
  6239. return true;
  6240. });
  6241. });
  6242. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6243. auto listen_se = detail::scope_exit([&] {
  6244. svr.stop();
  6245. listen_thread.join();
  6246. ASSERT_FALSE(svr.is_running());
  6247. });
  6248. svr.wait_until_ready();
  6249. Client client(HOST, PORT);
  6250. auto get_thread = std::thread([&client]() {
  6251. std::string s;
  6252. auto res =
  6253. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6254. s += std::string(data, len);
  6255. return true;
  6256. });
  6257. ASSERT_TRUE(res);
  6258. EXPECT_EQ(StatusCode::OK_200, res->status);
  6259. EXPECT_EQ("aaabbb", s);
  6260. });
  6261. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6262. // Give GET time to get a few messages.
  6263. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6264. }
  6265. TEST(MountTest, Unmount) {
  6266. Server svr;
  6267. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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("localhost", PORT);
  6275. svr.set_mount_point("/mount2", "./www2");
  6276. auto res = cli.Get("/");
  6277. ASSERT_TRUE(res);
  6278. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6279. res = cli.Get("/mount2/dir/test.html");
  6280. ASSERT_TRUE(res);
  6281. EXPECT_EQ(StatusCode::OK_200, res->status);
  6282. svr.set_mount_point("/", "./www");
  6283. res = cli.Get("/dir/");
  6284. ASSERT_TRUE(res);
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. svr.remove_mount_point("/");
  6287. res = cli.Get("/dir/");
  6288. ASSERT_TRUE(res);
  6289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6290. svr.remove_mount_point("/mount2");
  6291. res = cli.Get("/mount2/dir/test.html");
  6292. ASSERT_TRUE(res);
  6293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6294. }
  6295. TEST(MountTest, Redicect) {
  6296. Server svr;
  6297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6298. auto se = detail::scope_exit([&] {
  6299. svr.stop();
  6300. listen_thread.join();
  6301. ASSERT_FALSE(svr.is_running());
  6302. });
  6303. svr.set_mount_point("/", "./www");
  6304. svr.wait_until_ready();
  6305. Client cli("localhost", PORT);
  6306. auto res = cli.Get("/dir/");
  6307. ASSERT_TRUE(res);
  6308. EXPECT_EQ(StatusCode::OK_200, res->status);
  6309. res = cli.Get("/dir");
  6310. ASSERT_TRUE(res);
  6311. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6312. res = cli.Get("/file");
  6313. ASSERT_TRUE(res);
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. res = cli.Get("/file/");
  6316. ASSERT_TRUE(res);
  6317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6318. cli.set_follow_location(true);
  6319. res = cli.Get("/dir");
  6320. ASSERT_TRUE(res);
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. }
  6323. TEST(MountTest, MultibytesPathName) {
  6324. Server svr;
  6325. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6326. auto se = detail::scope_exit([&] {
  6327. svr.stop();
  6328. listen_thread.join();
  6329. ASSERT_FALSE(svr.is_running());
  6330. });
  6331. svr.set_mount_point("/", "./www");
  6332. svr.wait_until_ready();
  6333. Client cli("localhost", PORT);
  6334. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6335. ASSERT_TRUE(res);
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6338. }
  6339. TEST(KeepAliveTest, ReadTimeout) {
  6340. Server svr;
  6341. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6342. std::this_thread::sleep_for(std::chrono::seconds(2));
  6343. res.set_content("a", "text/plain");
  6344. });
  6345. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6346. res.set_content("b", "text/plain");
  6347. });
  6348. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6349. auto se = detail::scope_exit([&] {
  6350. svr.stop();
  6351. listen_thread.join();
  6352. ASSERT_FALSE(svr.is_running());
  6353. });
  6354. svr.wait_until_ready();
  6355. Client cli("localhost", PORT);
  6356. cli.set_keep_alive(true);
  6357. cli.set_read_timeout(std::chrono::seconds(1));
  6358. auto resa = cli.Get("/a");
  6359. ASSERT_FALSE(resa);
  6360. EXPECT_EQ(Error::Read, resa.error());
  6361. auto resb = cli.Get("/b");
  6362. ASSERT_TRUE(resb);
  6363. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6364. EXPECT_EQ("b", resb->body);
  6365. }
  6366. TEST(KeepAliveTest, MaxCount) {
  6367. size_t keep_alive_max_count = 3;
  6368. Server svr;
  6369. svr.set_keep_alive_max_count(keep_alive_max_count);
  6370. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6371. res.set_content("Hello World!", "text/plain");
  6372. });
  6373. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6374. auto se = detail::scope_exit([&] {
  6375. svr.stop();
  6376. listen_thread.join();
  6377. ASSERT_FALSE(svr.is_running());
  6378. });
  6379. svr.wait_until_ready();
  6380. Client cli(HOST, PORT);
  6381. cli.set_keep_alive(true);
  6382. for (size_t i = 0; i < 5; i++) {
  6383. auto result = cli.Get("/hi");
  6384. ASSERT_TRUE(result);
  6385. EXPECT_EQ(StatusCode::OK_200, result->status);
  6386. if (i == keep_alive_max_count - 1) {
  6387. EXPECT_EQ("close", result->get_header_value("Connection"));
  6388. } else {
  6389. EXPECT_FALSE(result->has_header("Connection"));
  6390. }
  6391. }
  6392. }
  6393. TEST(KeepAliveTest, Issue1041) {
  6394. Server svr;
  6395. svr.set_keep_alive_timeout(3);
  6396. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6397. res.set_content("Hello World!", "text/plain");
  6398. });
  6399. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6400. auto se = detail::scope_exit([&] {
  6401. svr.stop();
  6402. listen_thread.join();
  6403. ASSERT_FALSE(svr.is_running());
  6404. });
  6405. svr.wait_until_ready();
  6406. Client cli(HOST, PORT);
  6407. cli.set_keep_alive(true);
  6408. auto result = cli.Get("/hi");
  6409. ASSERT_TRUE(result);
  6410. EXPECT_EQ(StatusCode::OK_200, result->status);
  6411. std::this_thread::sleep_for(std::chrono::seconds(5));
  6412. result = cli.Get("/hi");
  6413. ASSERT_TRUE(result);
  6414. EXPECT_EQ(StatusCode::OK_200, result->status);
  6415. }
  6416. TEST(KeepAliveTest, Issue1959) {
  6417. Server svr;
  6418. svr.set_keep_alive_timeout(5);
  6419. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6420. res.set_content("a", "text/plain");
  6421. });
  6422. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6423. auto se = detail::scope_exit([&] {
  6424. if (!svr.is_running()) return;
  6425. svr.stop();
  6426. listen_thread.join();
  6427. ASSERT_FALSE(svr.is_running());
  6428. });
  6429. svr.wait_until_ready();
  6430. Client cli("localhost", PORT);
  6431. cli.set_keep_alive(true);
  6432. using namespace std::chrono;
  6433. auto start = steady_clock::now();
  6434. cli.Get("/a");
  6435. svr.stop();
  6436. listen_thread.join();
  6437. auto end = steady_clock::now();
  6438. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6439. EXPECT_LT(elapsed, 5000);
  6440. }
  6441. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6442. TEST(KeepAliveTest, SSLClientReconnection) {
  6443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6444. ASSERT_TRUE(svr.is_valid());
  6445. svr.set_keep_alive_timeout(1);
  6446. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6447. res.set_content("Hello World!", "text/plain");
  6448. });
  6449. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6450. auto se = detail::scope_exit([&] {
  6451. svr.stop();
  6452. listen_thread.join();
  6453. ASSERT_FALSE(svr.is_running());
  6454. });
  6455. svr.wait_until_ready();
  6456. SSLClient cli(HOST, PORT);
  6457. cli.enable_server_certificate_verification(false);
  6458. cli.set_keep_alive(true);
  6459. auto result = cli.Get("/hi");
  6460. ASSERT_TRUE(result);
  6461. EXPECT_EQ(StatusCode::OK_200, result->status);
  6462. result = cli.Get("/hi");
  6463. ASSERT_TRUE(result);
  6464. EXPECT_EQ(StatusCode::OK_200, result->status);
  6465. std::this_thread::sleep_for(std::chrono::seconds(2));
  6466. // Recoonect
  6467. result = cli.Get("/hi");
  6468. ASSERT_TRUE(result);
  6469. EXPECT_EQ(StatusCode::OK_200, result->status);
  6470. result = cli.Get("/hi");
  6471. ASSERT_TRUE(result);
  6472. EXPECT_EQ(StatusCode::OK_200, result->status);
  6473. }
  6474. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6476. ASSERT_TRUE(svr.is_valid());
  6477. svr.set_keep_alive_timeout(1);
  6478. std::string content = "reconnect";
  6479. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6480. res.set_content("Hello World!", "text/plain");
  6481. });
  6482. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6483. auto se = detail::scope_exit([&] {
  6484. svr.stop();
  6485. listen_thread.join();
  6486. ASSERT_FALSE(svr.is_running());
  6487. });
  6488. svr.wait_until_ready();
  6489. SSLClient cli(HOST, PORT);
  6490. cli.enable_server_certificate_verification(false);
  6491. cli.set_keep_alive(true);
  6492. auto result = cli.Post(
  6493. "/hi", content.size(),
  6494. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6495. sink.write(content.c_str(), content.size());
  6496. return true;
  6497. },
  6498. "text/plain");
  6499. ASSERT_TRUE(result);
  6500. EXPECT_EQ(200, result->status);
  6501. std::this_thread::sleep_for(std::chrono::seconds(2));
  6502. // Recoonect
  6503. result = cli.Post(
  6504. "/hi", content.size(),
  6505. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6506. sink.write(content.c_str(), content.size());
  6507. return true;
  6508. },
  6509. "text/plain");
  6510. ASSERT_TRUE(result);
  6511. EXPECT_EQ(200, result->status);
  6512. result = cli.Post(
  6513. "/hi", content.size(),
  6514. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6515. sink.write(content.c_str(), content.size());
  6516. return true;
  6517. },
  6518. "text/plain");
  6519. ASSERT_TRUE(result);
  6520. EXPECT_EQ(200, result->status);
  6521. }
  6522. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6523. {
  6524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6525. ASSERT_TRUE(svr.is_valid());
  6526. svr.Get("/sni", [&](const Request &req, Response &res) {
  6527. std::string expected;
  6528. if (req.ssl) {
  6529. if (const char *sni =
  6530. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6531. expected = sni;
  6532. }
  6533. }
  6534. EXPECT_EQ(expected, req.get_param_value("expected"));
  6535. res.set_content("ok", "text/plain");
  6536. });
  6537. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6538. auto se = detail::scope_exit([&] {
  6539. svr.stop();
  6540. listen_thread.join();
  6541. ASSERT_FALSE(svr.is_running());
  6542. });
  6543. svr.wait_until_ready();
  6544. {
  6545. SSLClient cli("localhost", PORT);
  6546. cli.enable_server_certificate_verification(false);
  6547. auto res = cli.Get("/sni?expected=localhost");
  6548. ASSERT_TRUE(res);
  6549. }
  6550. {
  6551. SSLClient cli("::1", PORT);
  6552. cli.enable_server_certificate_verification(false);
  6553. auto res = cli.Get("/sni?expected=");
  6554. // NOTE: This may fail if the server is listening on IPv4 only
  6555. // (e.g., when localhost resolves to 127.0.0.1 only)
  6556. if (res) {
  6557. EXPECT_EQ(StatusCode::OK_200, res->status);
  6558. } else {
  6559. EXPECT_EQ(Error::Connection, res.error());
  6560. }
  6561. }
  6562. }
  6563. }
  6564. #endif
  6565. TEST(ClientProblemDetectionTest, ContentProvider) {
  6566. Server svr;
  6567. size_t content_length = 1024 * 1024;
  6568. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6569. res.set_content_provider(
  6570. content_length, "text/plain",
  6571. [&](size_t offset, size_t length, DataSink &sink) {
  6572. auto out_len = std::min(length, static_cast<size_t>(1024));
  6573. std::string out(out_len, '@');
  6574. sink.write(out.data(), out_len);
  6575. return offset < 4096;
  6576. },
  6577. [](bool success) { ASSERT_FALSE(success); });
  6578. });
  6579. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6580. res.set_content_provider(
  6581. 0, "text/plain",
  6582. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6583. EXPECT_TRUE(false);
  6584. return true;
  6585. },
  6586. [](bool success) { ASSERT_FALSE(success); });
  6587. });
  6588. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6589. auto se = detail::scope_exit([&] {
  6590. svr.stop();
  6591. listen_thread.join();
  6592. ASSERT_FALSE(svr.is_running());
  6593. });
  6594. svr.wait_until_ready();
  6595. Client cli("localhost", PORT);
  6596. {
  6597. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6598. size_t /*data_length*/) { return false; });
  6599. ASSERT_FALSE(res);
  6600. }
  6601. {
  6602. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6603. size_t /*data_length*/) { return false; });
  6604. ASSERT_TRUE(res);
  6605. }
  6606. }
  6607. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6608. Server svr;
  6609. svr.set_error_handler([](Request const &, Response &res) -> void {
  6610. res.set_chunked_content_provider(
  6611. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6612. sink.os << "hello";
  6613. sink.os << "world";
  6614. sink.done();
  6615. return true;
  6616. });
  6617. });
  6618. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6619. auto se = detail::scope_exit([&] {
  6620. svr.stop();
  6621. listen_thread.join();
  6622. ASSERT_FALSE(svr.is_running());
  6623. });
  6624. svr.wait_until_ready();
  6625. Client cli("localhost", PORT);
  6626. auto res = cli.Get("/");
  6627. ASSERT_TRUE(res);
  6628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6629. EXPECT_EQ("helloworld", res->body);
  6630. }
  6631. TEST(LongPollingTest, ClientCloseDetection) {
  6632. Server svr;
  6633. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6634. res.set_chunked_content_provider(
  6635. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6636. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6637. sink.os << "hello";
  6638. auto count = 10;
  6639. while (count > 0 && sink.is_writable()) {
  6640. this_thread::sleep_for(chrono::milliseconds(10));
  6641. count--;
  6642. }
  6643. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6644. return true;
  6645. });
  6646. });
  6647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6648. auto se = detail::scope_exit([&] {
  6649. svr.stop();
  6650. listen_thread.join();
  6651. ASSERT_FALSE(svr.is_running());
  6652. });
  6653. svr.wait_until_ready();
  6654. Client cli("localhost", PORT);
  6655. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6656. EXPECT_EQ("hello", string(data, data_length));
  6657. return false; // close the socket immediately.
  6658. });
  6659. ASSERT_FALSE(res);
  6660. }
  6661. TEST(GetWithParametersTest, GetWithParameters) {
  6662. Server svr;
  6663. svr.Get("/", [&](const Request &req, Response &) {
  6664. EXPECT_EQ("world", req.get_param_value("hello"));
  6665. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6666. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6667. });
  6668. svr.Get("/params", [&](const Request &req, Response &) {
  6669. EXPECT_EQ("world", req.get_param_value("hello"));
  6670. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6671. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6672. });
  6673. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6674. EXPECT_EQ("resource-id", req.matches[1]);
  6675. EXPECT_EQ("foo", req.get_param_value("param1"));
  6676. EXPECT_EQ("bar", req.get_param_value("param2"));
  6677. });
  6678. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6679. EXPECT_EQ("user-id", req.path_params.at("id"));
  6680. EXPECT_EQ("foo", req.get_param_value("param1"));
  6681. EXPECT_EQ("bar", req.get_param_value("param2"));
  6682. });
  6683. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6684. auto se = detail::scope_exit([&] {
  6685. svr.stop();
  6686. listen_thread.join();
  6687. ASSERT_FALSE(svr.is_running());
  6688. });
  6689. svr.wait_until_ready();
  6690. {
  6691. Client cli(HOST, PORT);
  6692. Params params;
  6693. params.emplace("hello", "world");
  6694. params.emplace("hello2", "world2");
  6695. params.emplace("hello3", "world3");
  6696. auto res = cli.Get("/", params, Headers{});
  6697. ASSERT_TRUE(res);
  6698. EXPECT_EQ(StatusCode::OK_200, res->status);
  6699. }
  6700. {
  6701. Client cli(HOST, PORT);
  6702. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6703. ASSERT_TRUE(res);
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. }
  6706. {
  6707. Client cli(HOST, PORT);
  6708. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6709. ASSERT_TRUE(res);
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. }
  6712. {
  6713. Client cli(HOST, PORT);
  6714. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6715. ASSERT_TRUE(res);
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. }
  6718. }
  6719. TEST(GetWithParametersTest, GetWithParameters2) {
  6720. Server svr;
  6721. svr.Get("/", [&](const Request &req, Response &res) {
  6722. auto text = req.get_param_value("hello");
  6723. res.set_content(text, "text/plain");
  6724. });
  6725. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6726. auto se = detail::scope_exit([&] {
  6727. svr.stop();
  6728. listen_thread.join();
  6729. ASSERT_FALSE(svr.is_running());
  6730. });
  6731. svr.wait_until_ready();
  6732. Client cli("localhost", PORT);
  6733. Params params;
  6734. params.emplace("hello", "world");
  6735. std::string body;
  6736. auto res = cli.Get("/", params, Headers{},
  6737. [&](const char *data, size_t data_length) {
  6738. body.append(data, data_length);
  6739. return true;
  6740. });
  6741. ASSERT_TRUE(res);
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("world", body);
  6744. }
  6745. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6746. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6747. auto host = "httpcan.org";
  6748. auto path = std::string{"/range/32"};
  6749. #else
  6750. auto host = "nghttp2.org";
  6751. auto path = std::string{"/httpbin/range/32"};
  6752. #endif
  6753. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6754. SSLClient cli(host);
  6755. #else
  6756. Client cli(host);
  6757. #endif
  6758. cli.set_default_headers({make_range_header({{1, 10}})});
  6759. cli.set_connection_timeout(5);
  6760. {
  6761. auto res = cli.Get(path);
  6762. ASSERT_TRUE(res);
  6763. EXPECT_EQ("bcdefghijk", res->body);
  6764. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6765. }
  6766. {
  6767. auto res = cli.Get(path);
  6768. ASSERT_TRUE(res);
  6769. EXPECT_EQ("bcdefghijk", res->body);
  6770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6771. }
  6772. }
  6773. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6774. Server svr;
  6775. svr.set_default_headers({{"Hello", "World"}});
  6776. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6777. res.set_content("ok", "text/plain");
  6778. });
  6779. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6780. auto se = detail::scope_exit([&] {
  6781. svr.stop();
  6782. listen_thread.join();
  6783. ASSERT_FALSE(svr.is_running());
  6784. });
  6785. svr.wait_until_ready();
  6786. Client cli("localhost", PORT);
  6787. auto res = cli.Get("/");
  6788. ASSERT_TRUE(res);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. EXPECT_EQ("ok", res->body);
  6791. EXPECT_EQ("World", res->get_header_value("Hello"));
  6792. }
  6793. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6794. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6796. ASSERT_TRUE(svr.is_valid());
  6797. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6798. std::this_thread::sleep_for(std::chrono::seconds(2));
  6799. res.set_content("a", "text/plain");
  6800. });
  6801. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6802. res.set_content("b", "text/plain");
  6803. });
  6804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6805. auto se = detail::scope_exit([&] {
  6806. svr.stop();
  6807. listen_thread.join();
  6808. ASSERT_FALSE(svr.is_running());
  6809. });
  6810. svr.wait_until_ready();
  6811. SSLClient cli("localhost", PORT);
  6812. cli.enable_server_certificate_verification(false);
  6813. cli.set_keep_alive(true);
  6814. cli.set_read_timeout(std::chrono::seconds(1));
  6815. auto resa = cli.Get("/a");
  6816. ASSERT_TRUE(!resa);
  6817. EXPECT_EQ(Error::Read, resa.error());
  6818. auto resb = cli.Get("/b");
  6819. ASSERT_TRUE(resb);
  6820. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6821. EXPECT_EQ("b", resb->body);
  6822. }
  6823. #endif
  6824. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6825. protected:
  6826. ServerTestWithAI_PASSIVE()
  6827. : cli_(HOST, PORT)
  6828. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6829. ,
  6830. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6831. #endif
  6832. {
  6833. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6834. cli_.enable_server_certificate_verification(false);
  6835. #endif
  6836. }
  6837. virtual void SetUp() {
  6838. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6839. res.set_content("Hello World!", "text/plain");
  6840. });
  6841. t_ = thread(
  6842. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6843. svr_.wait_until_ready();
  6844. }
  6845. virtual void TearDown() {
  6846. svr_.stop();
  6847. t_.join();
  6848. }
  6849. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6850. SSLClient cli_;
  6851. SSLServer svr_;
  6852. #else
  6853. Client cli_;
  6854. Server svr_;
  6855. #endif
  6856. thread t_;
  6857. };
  6858. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6859. auto res = cli_.Get("/hi");
  6860. ASSERT_TRUE(res);
  6861. EXPECT_EQ(StatusCode::OK_200, res->status);
  6862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6863. EXPECT_EQ("Hello World!", res->body);
  6864. }
  6865. class ServerUpDownTest : public ::testing::Test {
  6866. protected:
  6867. ServerUpDownTest() : cli_(HOST, PORT) {}
  6868. virtual void SetUp() {
  6869. t_ = thread([&]() {
  6870. svr_.bind_to_any_port(HOST);
  6871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6872. ASSERT_TRUE(svr_.listen_after_bind());
  6873. });
  6874. svr_.wait_until_ready();
  6875. }
  6876. virtual void TearDown() {
  6877. svr_.stop();
  6878. t_.join();
  6879. }
  6880. Client cli_;
  6881. Server svr_;
  6882. thread t_;
  6883. };
  6884. TEST_F(ServerUpDownTest, QuickStartStop) {
  6885. // Should not crash, especially when run with
  6886. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6887. }
  6888. class PayloadMaxLengthTest : public ::testing::Test {
  6889. protected:
  6890. PayloadMaxLengthTest()
  6891. : cli_(HOST, PORT)
  6892. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6893. ,
  6894. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6895. #endif
  6896. {
  6897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6898. cli_.enable_server_certificate_verification(false);
  6899. #endif
  6900. }
  6901. virtual void SetUp() {
  6902. svr_.set_payload_max_length(8);
  6903. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6904. res.set_content("test", "text/plain");
  6905. });
  6906. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6907. svr_.wait_until_ready();
  6908. }
  6909. virtual void TearDown() {
  6910. svr_.stop();
  6911. t_.join();
  6912. }
  6913. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6914. SSLClient cli_;
  6915. SSLServer svr_;
  6916. #else
  6917. Client cli_;
  6918. Server svr_;
  6919. #endif
  6920. thread t_;
  6921. };
  6922. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6923. auto res = cli_.Post("/test", "123456789", "text/plain");
  6924. ASSERT_TRUE(res);
  6925. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6926. res = cli_.Post("/test", "12345678", "text/plain");
  6927. ASSERT_TRUE(res);
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. }
  6930. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6931. // Test chunked encoding with payload exceeding the 8-byte limit
  6932. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6933. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6934. ASSERT_TRUE(res);
  6935. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6936. }
  6937. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6938. // Test chunked encoding with payload within the 8-byte limit
  6939. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6940. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6941. ASSERT_TRUE(res);
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. }
  6944. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6945. // Test using send_request to send chunked data exceeding payload limit
  6946. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6947. "Host: " +
  6948. std::string(HOST) + ":" + std::to_string(PORT) +
  6949. "\r\n"
  6950. "Transfer-Encoding: chunked\r\n"
  6951. "Connection: close\r\n"
  6952. "\r\n"
  6953. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6954. "0123456789\r\n"
  6955. "0\r\n" // End chunk
  6956. "\r\n";
  6957. std::string response;
  6958. bool result = send_request(1, chunked_request, &response);
  6959. if (!result) {
  6960. // If send_request fails, it might be because the server closed the
  6961. // connection due to payload limit enforcement, which is acceptable
  6962. SUCCEED()
  6963. << "Server rejected oversized chunked request (connection closed)";
  6964. } else {
  6965. // If we got a response, check if it's an error response or connection was
  6966. // closed early Short response length indicates connection was closed due to
  6967. // payload limit
  6968. if (response.length() <= 10) {
  6969. SUCCEED() << "Server closed connection for oversized chunked request";
  6970. } else {
  6971. // Check for error status codes
  6972. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6973. response.find("Payload Too Large") != std::string::npos ||
  6974. response.find("400") != std::string::npos);
  6975. }
  6976. }
  6977. }
  6978. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6979. // Test request without Content-Length header exceeding payload limit
  6980. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6981. "Host: " +
  6982. std::string(HOST) + ":" +
  6983. std::to_string(PORT) +
  6984. "\r\n"
  6985. "Connection: close\r\n"
  6986. "\r\n";
  6987. // Add payload exceeding the 8-byte limit
  6988. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6989. request_without_content_length += large_payload;
  6990. std::string response;
  6991. bool result = send_request(1, request_without_content_length, &response);
  6992. if (!result) {
  6993. // If send_request fails, server likely closed connection due to payload
  6994. // limit
  6995. SUCCEED() << "Server rejected oversized request without Content-Length "
  6996. "(connection closed)";
  6997. } else {
  6998. // Check if server responded with error or closed connection early
  6999. if (response.length() <= 10) {
  7000. SUCCEED() << "Server closed connection for oversized request without "
  7001. "Content-Length";
  7002. } else {
  7003. // Check for error status codes
  7004. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7005. response.find("Payload Too Large") != std::string::npos ||
  7006. response.find("400") != std::string::npos);
  7007. }
  7008. }
  7009. }
  7010. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7011. // Test request without Content-Length header within payload limit
  7012. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7013. "Host: " +
  7014. std::string(HOST) + ":" +
  7015. std::to_string(PORT) +
  7016. "\r\n"
  7017. "Connection: close\r\n"
  7018. "\r\n";
  7019. // Add payload within the 8-byte limit
  7020. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7021. request_without_content_length += small_payload;
  7022. std::string response;
  7023. bool result = send_request(1, request_without_content_length, &response);
  7024. // For requests without Content-Length, the server may have different behavior
  7025. // The key is that it should not reject due to payload limit for small
  7026. // payloads
  7027. if (result) {
  7028. // Check for any HTTP response (success or error, but not connection closed)
  7029. if (response.length() > 10) {
  7030. SUCCEED()
  7031. << "Server processed request without Content-Length within limit";
  7032. } else {
  7033. // Short response might indicate connection closed, which is acceptable
  7034. SUCCEED() << "Server closed connection for request without "
  7035. "Content-Length (acceptable behavior)";
  7036. }
  7037. } else {
  7038. // Connection failure might be due to protocol requirements
  7039. SUCCEED() << "Connection issue with request without Content-Length "
  7040. "(environment-specific)";
  7041. }
  7042. }
  7043. class LargePayloadMaxLengthTest : public ::testing::Test {
  7044. protected:
  7045. LargePayloadMaxLengthTest()
  7046. : cli_(HOST, PORT)
  7047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7048. ,
  7049. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7050. #endif
  7051. {
  7052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7053. cli_.enable_server_certificate_verification(false);
  7054. #endif
  7055. }
  7056. virtual void SetUp() {
  7057. // Set 10MB payload limit
  7058. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7059. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7060. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7061. res.set_content("Large payload test", "text/plain");
  7062. });
  7063. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7064. svr_.wait_until_ready();
  7065. }
  7066. virtual void TearDown() {
  7067. svr_.stop();
  7068. t_.join();
  7069. }
  7070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7071. SSLClient cli_;
  7072. SSLServer svr_;
  7073. #else
  7074. Client cli_;
  7075. Server svr_;
  7076. #endif
  7077. thread t_;
  7078. };
  7079. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7080. // Test chunked encoding with payload within 10MB limit
  7081. std::string medium_payload(5 * 1024 * 1024,
  7082. 'A'); // 5MB payload, within 10MB limit
  7083. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7084. ASSERT_TRUE(res);
  7085. EXPECT_EQ(StatusCode::OK_200, res->status);
  7086. }
  7087. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7088. // Test chunked encoding with payload exceeding 10MB limit
  7089. std::string large_payload(12 * 1024 * 1024,
  7090. 'B'); // 12MB payload, exceeds 10MB limit
  7091. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7092. ASSERT_TRUE(res);
  7093. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7094. }
  7095. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7096. // Test request without Content-Length header within 10MB limit
  7097. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7098. "Host: " +
  7099. std::string(HOST) + ":" +
  7100. std::to_string(PORT) +
  7101. "\r\n"
  7102. "Connection: close\r\n"
  7103. "\r\n";
  7104. // Add 1MB payload (within 10MB limit)
  7105. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7106. request_without_content_length += medium_payload;
  7107. std::string response;
  7108. bool result = send_request(5, request_without_content_length, &response);
  7109. if (result) {
  7110. // Should get a proper HTTP response for payloads within limit
  7111. if (response.length() > 10) {
  7112. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7113. "10MB limit";
  7114. } else {
  7115. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7116. "Content-Length)";
  7117. }
  7118. } else {
  7119. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7120. }
  7121. }
  7122. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7123. // Test request without Content-Length header exceeding 10MB limit
  7124. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7125. "Host: " +
  7126. std::string(HOST) + ":" +
  7127. std::to_string(PORT) +
  7128. "\r\n"
  7129. "Connection: close\r\n"
  7130. "\r\n";
  7131. // Add 12MB payload (exceeds 10MB limit)
  7132. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7133. request_without_content_length += large_payload;
  7134. std::string response;
  7135. bool result = send_request(10, request_without_content_length, &response);
  7136. if (!result) {
  7137. // Server should close connection due to payload limit
  7138. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7139. "(connection closed)";
  7140. } else {
  7141. // Check for error response
  7142. if (response.length() <= 10) {
  7143. SUCCEED()
  7144. << "Server closed connection for 12MB request exceeding 10MB limit";
  7145. } else {
  7146. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7147. response.find("Payload Too Large") != std::string::npos ||
  7148. response.find("400") != std::string::npos);
  7149. }
  7150. }
  7151. }
  7152. TEST(HostAndPortPropertiesTest, NoSSL) {
  7153. httplib::Client cli("www.google.com", 1234);
  7154. ASSERT_EQ("www.google.com", cli.host());
  7155. ASSERT_EQ(1234, cli.port());
  7156. }
  7157. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7158. httplib::Client cli("www.google.com:1234");
  7159. ASSERT_EQ("www.google.com", cli.host());
  7160. ASSERT_EQ(1234, cli.port());
  7161. }
  7162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7163. TEST(HostAndPortPropertiesTest, SSL) {
  7164. httplib::SSLClient cli("www.google.com");
  7165. ASSERT_EQ("www.google.com", cli.host());
  7166. ASSERT_EQ(443, cli.port());
  7167. }
  7168. #endif
  7169. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7170. TEST(SSLClientTest, UpdateCAStore) {
  7171. httplib::SSLClient httplib_client("www.google.com");
  7172. auto ca_store_1 = X509_STORE_new();
  7173. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7174. nullptr);
  7175. httplib_client.set_ca_cert_store(ca_store_1);
  7176. auto ca_store_2 = X509_STORE_new();
  7177. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7178. nullptr);
  7179. httplib_client.set_ca_cert_store(ca_store_2);
  7180. }
  7181. TEST(SSLClientTest, ServerNameIndication_Online) {
  7182. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7183. auto host = "httpcan.org";
  7184. auto path = std::string{"/get"};
  7185. #else
  7186. auto host = "nghttp2.org";
  7187. auto path = std::string{"/httpbin/get"};
  7188. #endif
  7189. SSLClient cli(host, 443);
  7190. auto res = cli.Get(path);
  7191. ASSERT_TRUE(res);
  7192. ASSERT_EQ(StatusCode::OK_200, res->status);
  7193. }
  7194. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7195. // Use a site that will cause SSL verification failure due to self-signed cert
  7196. SSLClient cli("self-signed.badssl.com", 443);
  7197. cli.enable_server_certificate_verification(true);
  7198. auto res = cli.Get("/");
  7199. ASSERT_TRUE(!res);
  7200. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7201. // For SSL server verification errors, ssl_error should be 0
  7202. EXPECT_EQ(0, res.ssl_error());
  7203. #if defined(_WIN32) && \
  7204. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7205. // On Windows Schannel, verify Windows certificate error is captured
  7206. EXPECT_NE(0UL, res.wincrypt_error());
  7207. // Common errors: CERT_E_UNTRUSTEDROOT, CERT_E_CHAINING
  7208. #else
  7209. // On OpenSSL, verify OpenSSL error is captured for SSLServerVerification
  7210. // This occurs when SSL_get_verify_result() returns a verification failure
  7211. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7212. res.ssl_openssl_error());
  7213. #endif
  7214. }
  7215. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7216. // Use a site where hostname doesn't match the certificate
  7217. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7218. SSLClient cli("wrong.host.badssl.com", 443);
  7219. cli.enable_server_certificate_verification(true);
  7220. cli.enable_server_hostname_verification(true);
  7221. auto res = cli.Get("/");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7224. // For SSL hostname verification errors, ssl_error should be 0
  7225. EXPECT_EQ(0, res.ssl_error());
  7226. #if defined(_WIN32) && \
  7227. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7228. // On Windows Schannel, verify Windows certificate error is captured
  7229. EXPECT_EQ(static_cast<unsigned long>(CERT_E_CN_NO_MATCH),
  7230. res.wincrypt_error());
  7231. #else
  7232. // On OpenSSL, verify OpenSSL error is captured for
  7233. // SSLServerHostnameVerification This occurs when verify_host() fails due to
  7234. // hostname mismatch
  7235. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7236. res.ssl_openssl_error());
  7237. #endif
  7238. }
  7239. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7240. Client cli("https://google.com");
  7241. auto res = cli.Get("/");
  7242. ASSERT_TRUE(res);
  7243. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7244. }
  7245. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7246. SSLClient cli("google.com");
  7247. cli.set_ca_cert_path(CA_CERT_FILE);
  7248. auto res = cli.Get("/");
  7249. ASSERT_TRUE(res);
  7250. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7251. }
  7252. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7253. SSLClient cli("google.com");
  7254. cli.enable_server_certificate_verification(true);
  7255. cli.set_ca_cert_path("hello");
  7256. auto res = cli.Get("/");
  7257. ASSERT_TRUE(!res);
  7258. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7259. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7260. // should be set
  7261. EXPECT_EQ(0, res.ssl_error());
  7262. // Verify OpenSSL error is captured for SSLLoadingCerts
  7263. // This error occurs when SSL_CTX_load_verify_locations() fails
  7264. // > openssl errstr 0x80000002
  7265. // error:80000002:system library::No such file or directory
  7266. // > openssl errstr 0xA000126
  7267. // error:0A000126:SSL routines::unexpected eof while reading
  7268. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7269. res.ssl_openssl_error() == 0xA000126);
  7270. }
  7271. TEST(SSLClientTest, ServerCertificateVerification4) {
  7272. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7273. ASSERT_TRUE(svr.is_valid());
  7274. svr.Get("/test", [&](const Request &, Response &res) {
  7275. res.set_content("test", "text/plain");
  7276. svr.stop();
  7277. ASSERT_TRUE(true);
  7278. });
  7279. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7280. auto se = detail::scope_exit([&] {
  7281. t.join();
  7282. ASSERT_FALSE(svr.is_running());
  7283. });
  7284. svr.wait_until_ready();
  7285. SSLClient cli("127.0.0.1", PORT);
  7286. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7287. cli.enable_server_certificate_verification(true);
  7288. cli.set_connection_timeout(30);
  7289. auto res = cli.Get("/test");
  7290. ASSERT_TRUE(res);
  7291. ASSERT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7294. std::string cert;
  7295. read_file(CA_CERT_FILE, cert);
  7296. SSLClient cli("google.com");
  7297. cli.load_ca_cert_store(cert.data(), cert.size());
  7298. const auto res = cli.Get("/");
  7299. ASSERT_TRUE(res);
  7300. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7301. }
  7302. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7303. // clang-format off
  7304. static constexpr char cert[] =
  7305. "GlobalSign Root CA\n"
  7306. "==================\n"
  7307. "-----BEGIN CERTIFICATE-----\n"
  7308. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7309. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7310. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7311. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7312. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7313. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7314. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7315. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7316. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7317. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7318. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7319. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7320. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7321. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7322. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7323. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7324. "-----END CERTIFICATE-----\n";
  7325. // clang-format on
  7326. SSLClient cli("google.com");
  7327. cli.load_ca_cert_store(cert, sizeof(cert));
  7328. const auto res = cli.Get("/");
  7329. ASSERT_TRUE(res);
  7330. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7331. }
  7332. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7333. SSLClient cli("www.youtube.com");
  7334. cli.set_ca_cert_path(CA_CERT_FILE);
  7335. cli.enable_server_certificate_verification(true);
  7336. cli.set_follow_location(true);
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. ASSERT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST(SSLClientTest, Issue2004_Online) {
  7342. Client client("https://google.com");
  7343. client.set_follow_location(true);
  7344. auto res = client.Get("/");
  7345. ASSERT_TRUE(res);
  7346. ASSERT_EQ(StatusCode::OK_200, res->status);
  7347. auto body = res->body;
  7348. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7349. }
  7350. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7351. // Create SSLClient with invalid cert/key to make is_valid() return false
  7352. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7353. "nonexistent_key.pem");
  7354. // is_valid() should be false due to cert loading failure
  7355. ASSERT_FALSE(cli.is_valid());
  7356. auto res = cli.Get("/");
  7357. ASSERT_FALSE(res);
  7358. EXPECT_EQ(Error::SSLConnection, res.error());
  7359. }
  7360. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7361. // Test for Issue #2251: SSL error not properly reported when client cert
  7362. // and key paths are swapped or mismatched
  7363. // This simulates the scenario where user accidentally swaps the cert and key
  7364. // files
  7365. // Using client cert file as private key and vice versa (completely wrong)
  7366. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7367. // Should fail validation due to cert/key mismatch
  7368. ASSERT_FALSE(cli.is_valid());
  7369. // Attempt to make a request should fail with proper error
  7370. auto res = cli.Get("/");
  7371. ASSERT_FALSE(res);
  7372. EXPECT_EQ(Error::SSLConnection, res.error());
  7373. // SSL error should be recorded in the Result object (this is the key fix for
  7374. // Issue #2251)
  7375. auto openssl_error = res.ssl_openssl_error();
  7376. EXPECT_NE(0u, openssl_error);
  7377. }
  7378. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7379. // Another variant: using valid file paths but with mismatched cert/key pair
  7380. // This tests the case where files exist but contain incompatible key material
  7381. // Using client cert with wrong key (cert2 key)
  7382. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7383. // Should fail validation
  7384. ASSERT_FALSE(cli.is_valid());
  7385. auto res = cli.Get("/");
  7386. ASSERT_FALSE(res);
  7387. // Must report error properly, not appear as success
  7388. EXPECT_EQ(Error::SSLConnection, res.error());
  7389. // OpenSSL error should be captured in Result
  7390. EXPECT_NE(0u, res.ssl_openssl_error());
  7391. }
  7392. #if 0
  7393. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7394. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7395. ASSERT_TRUE(cli != nullptr);
  7396. cli->set_address_family(AF_INET6);
  7397. cli->set_interface("en0");
  7398. auto res = cli->Get("/get");
  7399. ASSERT_TRUE(res);
  7400. ASSERT_EQ(StatusCode::OK_200, res->status);
  7401. }
  7402. #endif
  7403. void ClientCertPresent(
  7404. const std::string &client_cert_file,
  7405. const std::string &client_private_key_file,
  7406. const std::string &client_encrypted_private_key_pass = std::string()) {
  7407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7408. CLIENT_CA_CERT_DIR);
  7409. ASSERT_TRUE(svr.is_valid());
  7410. svr.Get("/test", [&](const Request &req, Response &res) {
  7411. res.set_content("test", "text/plain");
  7412. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7413. ASSERT_TRUE(peer_cert != nullptr);
  7414. auto subject_name = X509_get_subject_name(peer_cert);
  7415. ASSERT_TRUE(subject_name != nullptr);
  7416. std::string common_name;
  7417. {
  7418. char name[BUFSIZ];
  7419. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7420. name, sizeof(name));
  7421. common_name.assign(name, static_cast<size_t>(name_len));
  7422. }
  7423. EXPECT_EQ("Common Name", common_name);
  7424. X509_free(peer_cert);
  7425. });
  7426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7427. auto se = detail::scope_exit([&] {
  7428. svr.stop();
  7429. t.join();
  7430. ASSERT_FALSE(svr.is_running());
  7431. });
  7432. svr.wait_until_ready();
  7433. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7434. client_encrypted_private_key_pass);
  7435. cli.enable_server_certificate_verification(false);
  7436. cli.set_connection_timeout(30);
  7437. auto res = cli.Get("/test");
  7438. ASSERT_TRUE(res);
  7439. ASSERT_EQ(StatusCode::OK_200, res->status);
  7440. }
  7441. TEST(SSLClientServerTest, ClientCertPresent) {
  7442. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7443. }
  7444. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7445. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7446. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7447. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7448. }
  7449. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7450. void MemoryClientCertPresent(
  7451. const std::string &client_cert_file,
  7452. const std::string &client_private_key_file,
  7453. const std::string &client_encrypted_private_key_pass = std::string()) {
  7454. auto f = fopen(SERVER_CERT_FILE, "r+");
  7455. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7456. fclose(f);
  7457. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7458. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7459. fclose(f);
  7460. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7461. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7462. auto client_ca_cert_store = X509_STORE_new();
  7463. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7464. X509_free(client_cert);
  7465. fclose(f);
  7466. f = fopen(client_cert_file.c_str(), "r+");
  7467. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7468. fclose(f);
  7469. f = fopen(client_private_key_file.c_str(), "r+");
  7470. auto client_private_key = PEM_read_PrivateKey(
  7471. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7472. fclose(f);
  7473. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7474. ASSERT_TRUE(svr.is_valid());
  7475. svr.Get("/test", [&](const Request &req, Response &res) {
  7476. res.set_content("test", "text/plain");
  7477. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7478. ASSERT_TRUE(peer_cert != nullptr);
  7479. auto subject_name = X509_get_subject_name(peer_cert);
  7480. ASSERT_TRUE(subject_name != nullptr);
  7481. std::string common_name;
  7482. {
  7483. char name[BUFSIZ];
  7484. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7485. name, sizeof(name));
  7486. common_name.assign(name, static_cast<size_t>(name_len));
  7487. }
  7488. EXPECT_EQ("Common Name", common_name);
  7489. X509_free(peer_cert);
  7490. });
  7491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7492. auto se = detail::scope_exit([&] {
  7493. svr.stop();
  7494. t.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7499. client_encrypted_private_key_pass);
  7500. cli.enable_server_certificate_verification(false);
  7501. cli.set_connection_timeout(30);
  7502. auto res = cli.Get("/test");
  7503. ASSERT_TRUE(res);
  7504. ASSERT_EQ(StatusCode::OK_200, res->status);
  7505. X509_free(server_cert);
  7506. EVP_PKEY_free(server_private_key);
  7507. X509_free(client_cert);
  7508. EVP_PKEY_free(client_private_key);
  7509. }
  7510. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7511. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7512. }
  7513. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7514. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7515. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7516. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7517. }
  7518. #endif
  7519. TEST(SSLClientServerTest, ClientCertMissing) {
  7520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7521. CLIENT_CA_CERT_DIR);
  7522. ASSERT_TRUE(svr.is_valid());
  7523. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  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. SSLClient cli(HOST, PORT);
  7532. cli.set_connection_timeout(30);
  7533. auto res = cli.Get("/test");
  7534. ASSERT_TRUE(!res);
  7535. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7536. // For SSL server verification errors, ssl_error should be 0
  7537. EXPECT_EQ(0, res.ssl_error());
  7538. #if defined(_WIN32) && \
  7539. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7540. // On Windows Schannel, verify Windows certificate error is captured
  7541. EXPECT_NE(0UL, res.wincrypt_error());
  7542. #else
  7543. // Verify OpenSSL error is captured for SSLServerVerification
  7544. // Note: This test may have different error codes depending on the exact
  7545. // verification failure
  7546. EXPECT_NE(0UL, res.ssl_openssl_error());
  7547. #endif
  7548. }
  7549. TEST(SSLClientServerTest, TrustDirOptional) {
  7550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7551. ASSERT_TRUE(svr.is_valid());
  7552. svr.Get("/test", [&](const Request &, Response &res) {
  7553. res.set_content("test", "text/plain");
  7554. });
  7555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7556. auto se = detail::scope_exit([&] {
  7557. svr.stop();
  7558. t.join();
  7559. ASSERT_FALSE(svr.is_running());
  7560. });
  7561. svr.wait_until_ready();
  7562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7563. cli.enable_server_certificate_verification(false);
  7564. cli.set_connection_timeout(30);
  7565. auto res = cli.Get("/test");
  7566. ASSERT_TRUE(res);
  7567. ASSERT_EQ(StatusCode::OK_200, res->status);
  7568. }
  7569. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7570. class NoListenSSLServer : public SSLServer {
  7571. public:
  7572. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7573. const char *client_ca_cert_file_path,
  7574. const char *client_ca_cert_dir_path = nullptr)
  7575. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7576. client_ca_cert_dir_path),
  7577. stop_(false) {}
  7578. std::atomic_bool stop_;
  7579. private:
  7580. bool process_and_close_socket(socket_t /*sock*/) override {
  7581. // Don't create SSL context
  7582. while (!stop_.load()) {
  7583. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7584. }
  7585. return true;
  7586. }
  7587. };
  7588. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7589. CLIENT_CA_CERT_FILE);
  7590. ASSERT_TRUE(svr.is_valid());
  7591. svr.Get("/test", [&](const Request &, Response &res) {
  7592. res.set_content("test", "text/plain");
  7593. });
  7594. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7595. auto se = detail::scope_exit([&] {
  7596. svr.stop_ = true;
  7597. svr.stop();
  7598. t.join();
  7599. ASSERT_FALSE(svr.is_running());
  7600. });
  7601. svr.wait_until_ready();
  7602. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7603. cli.enable_server_certificate_verification(false);
  7604. cli.set_connection_timeout(1);
  7605. auto res = cli.Get("/test");
  7606. ASSERT_TRUE(!res);
  7607. EXPECT_EQ(Error::SSLConnection, res.error());
  7608. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7609. }
  7610. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7611. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7612. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7613. SSL_CTX_set_options(&ssl_ctx,
  7614. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7615. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7616. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7617. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7618. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7619. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7620. "ECDHE-DSS-AES128-SHA256:"
  7621. "ECDHE-RSA-AES256-SHA256:"
  7622. "ECDHE-DSS-AES256-SHA256:";
  7623. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7624. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7625. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7626. SSL_FILETYPE_PEM) != 1) {
  7627. return false;
  7628. }
  7629. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7630. CLIENT_CA_CERT_DIR);
  7631. SSL_CTX_set_verify(
  7632. &ssl_ctx,
  7633. SSL_VERIFY_PEER |
  7634. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7635. nullptr);
  7636. return true;
  7637. };
  7638. SSLServer svr(setup_ssl_ctx_callback);
  7639. ASSERT_TRUE(svr.is_valid());
  7640. svr.Get("/test", [&](const Request &req, Response &res) {
  7641. res.set_content("test", "text/plain");
  7642. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7643. ASSERT_TRUE(peer_cert != nullptr);
  7644. auto subject_name = X509_get_subject_name(peer_cert);
  7645. ASSERT_TRUE(subject_name != nullptr);
  7646. std::string common_name;
  7647. {
  7648. char name[BUFSIZ];
  7649. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7650. name, sizeof(name));
  7651. common_name.assign(name, static_cast<size_t>(name_len));
  7652. }
  7653. EXPECT_EQ("Common Name", common_name);
  7654. X509_free(peer_cert);
  7655. });
  7656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7657. auto se = detail::scope_exit([&] {
  7658. svr.stop();
  7659. t.join();
  7660. ASSERT_FALSE(svr.is_running());
  7661. });
  7662. svr.wait_until_ready();
  7663. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7664. cli.enable_server_certificate_verification(false);
  7665. cli.set_connection_timeout(30);
  7666. auto res = cli.Get("/test");
  7667. ASSERT_TRUE(res);
  7668. ASSERT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7672. ASSERT_TRUE(svr.is_valid());
  7673. // Set up a handler to verify client certificate is present
  7674. bool client_cert_verified = false;
  7675. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7676. // Verify that client certificate was provided
  7677. client_cert_verified = true;
  7678. res.set_content("success", "text/plain");
  7679. });
  7680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7681. auto se = detail::scope_exit([&] {
  7682. svr.stop();
  7683. t.join();
  7684. ASSERT_FALSE(svr.is_running());
  7685. });
  7686. svr.wait_until_ready();
  7687. // Client with certificate
  7688. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7689. cli.enable_server_certificate_verification(false);
  7690. cli.set_connection_timeout(30);
  7691. auto res = cli.Get("/test");
  7692. ASSERT_TRUE(res);
  7693. ASSERT_EQ(StatusCode::OK_200, res->status);
  7694. ASSERT_TRUE(client_cert_verified);
  7695. EXPECT_EQ("success", res->body);
  7696. }
  7697. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7698. // Test that when client CA cert file is provided,
  7699. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7700. // Create a server with client authentication
  7701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7702. ASSERT_TRUE(svr.is_valid());
  7703. // We can't directly access the SSL_CTX from SSLServer to verify,
  7704. // but we can test that the server properly requests client certificates
  7705. // and accepts valid ones from the specified CA
  7706. bool handler_called = false;
  7707. svr.Get("/test", [&](const Request &req, Response &res) {
  7708. handler_called = true;
  7709. // Verify that a client certificate was provided
  7710. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7711. ASSERT_TRUE(peer_cert != nullptr);
  7712. // Get the issuer name
  7713. auto issuer_name = X509_get_issuer_name(peer_cert);
  7714. ASSERT_TRUE(issuer_name != nullptr);
  7715. char issuer_buf[256];
  7716. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7717. // The client certificate should be issued by our test CA
  7718. std::string issuer_str(issuer_buf);
  7719. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7720. X509_free(peer_cert);
  7721. res.set_content("authenticated", "text/plain");
  7722. });
  7723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7724. auto se = detail::scope_exit([&] {
  7725. svr.stop();
  7726. t.join();
  7727. ASSERT_FALSE(svr.is_running());
  7728. });
  7729. svr.wait_until_ready();
  7730. // Connect with a client certificate issued by the CA
  7731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7732. cli.enable_server_certificate_verification(false);
  7733. cli.set_connection_timeout(30);
  7734. auto res = cli.Get("/test");
  7735. ASSERT_TRUE(res);
  7736. ASSERT_EQ(StatusCode::OK_200, res->status);
  7737. ASSERT_TRUE(handler_called);
  7738. EXPECT_EQ("authenticated", res->body);
  7739. }
  7740. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7741. // Test 1: Valid CA file - no error should be recorded
  7742. {
  7743. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7744. CLIENT_CA_CERT_FILE);
  7745. ASSERT_TRUE(svr.is_valid());
  7746. // With valid setup, last_ssl_error should be 0
  7747. EXPECT_EQ(0, svr.ssl_last_error());
  7748. }
  7749. // Test 2: Invalid CA file content
  7750. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7751. {
  7752. // Create a temporary file with completely invalid content
  7753. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7754. {
  7755. std::ofstream ofs(temp_invalid_ca);
  7756. ofs << "This is not a certificate file at all\n";
  7757. ofs << "Just plain text content\n";
  7758. }
  7759. // Create server with invalid CA file
  7760. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7761. // Clean up temporary file
  7762. std::remove(temp_invalid_ca);
  7763. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7764. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7765. // Note: SSL_CTX_load_verify_locations typically fails first,
  7766. // but our error handling code path is still exercised
  7767. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7768. }
  7769. }
  7770. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7771. // Test SSL server using X509_STORE constructor with client CA certificates
  7772. // This test verifies that Phase 2 implementation correctly extracts CA names
  7773. // from an X509_STORE and sets them in the SSL context
  7774. // Load the CA certificate into memory
  7775. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7776. ASSERT_NE(nullptr, bio);
  7777. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7778. BIO_free(bio);
  7779. ASSERT_NE(nullptr, ca_cert);
  7780. // Create an X509_STORE and add the CA certificate
  7781. auto store = X509_STORE_new();
  7782. ASSERT_NE(nullptr, store);
  7783. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7784. // Load server certificate and private key
  7785. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7786. ASSERT_NE(nullptr, cert_bio);
  7787. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7788. BIO_free(cert_bio);
  7789. ASSERT_NE(nullptr, server_cert);
  7790. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7791. ASSERT_NE(nullptr, key_bio);
  7792. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7793. BIO_free(key_bio);
  7794. ASSERT_NE(nullptr, server_key);
  7795. // Create SSLServer with X509_STORE constructor
  7796. // Note: X509_STORE ownership is transferred to SSL_CTX
  7797. SSLServer svr(server_cert, server_key, store);
  7798. ASSERT_TRUE(svr.is_valid());
  7799. // No SSL error should be recorded for valid setup
  7800. EXPECT_EQ(0, svr.ssl_last_error());
  7801. // Set up server endpoints
  7802. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7803. res.set_content("ok", "text/plain");
  7804. });
  7805. // Start server in a thread
  7806. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7807. svr.wait_until_ready();
  7808. // Connect with client certificate (using constructor with paths)
  7809. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7810. cli.enable_server_certificate_verification(false);
  7811. auto res = cli.Get("/test-x509store");
  7812. ASSERT_TRUE(res);
  7813. EXPECT_EQ(200, res->status);
  7814. EXPECT_EQ("ok", res->body);
  7815. // Clean up
  7816. X509_free(server_cert);
  7817. EVP_PKEY_free(server_key);
  7818. X509_free(ca_cert);
  7819. svr.stop();
  7820. server_thread.join();
  7821. }
  7822. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7823. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7824. // prepare large data
  7825. std::random_device seed_gen;
  7826. std::mt19937 random(seed_gen());
  7827. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7828. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7829. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7830. // server
  7831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7832. ASSERT_TRUE(svr.is_valid());
  7833. svr.Post("/binary", [&](const Request &req, Response &res) {
  7834. EXPECT_EQ(large_size_byte, req.body.size());
  7835. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7836. res.set_content(req.body, "application/octet-stream");
  7837. });
  7838. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7839. auto se = detail::scope_exit([&] {
  7840. svr.stop();
  7841. listen_thread.join();
  7842. ASSERT_FALSE(svr.is_running());
  7843. });
  7844. svr.wait_until_ready();
  7845. // client POST
  7846. SSLClient cli("localhost", PORT);
  7847. cli.enable_server_certificate_verification(false);
  7848. cli.set_read_timeout(std::chrono::seconds(100));
  7849. cli.set_write_timeout(std::chrono::seconds(100));
  7850. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7851. large_size_byte, "application/octet-stream");
  7852. // compare
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. EXPECT_EQ(large_size_byte, res->body.size());
  7855. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7856. }
  7857. #endif
  7858. #ifdef _WIN32
  7859. TEST(CleanupTest, WSACleanup) {
  7860. int ret = WSACleanup();
  7861. ASSERT_EQ(0, ret);
  7862. }
  7863. #endif
  7864. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7865. TEST(NoSSLSupport, SimpleInterface) {
  7866. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7867. }
  7868. #endif
  7869. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7870. TEST(InvalidScheme, SimpleInterface) {
  7871. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7872. }
  7873. #endif
  7874. TEST(NoScheme, SimpleInterface) {
  7875. Client cli("yahoo.com:80");
  7876. ASSERT_TRUE(cli.is_valid());
  7877. }
  7878. TEST(SendAPI, SimpleInterface_Online) {
  7879. Client cli("http://yahoo.com");
  7880. Request req;
  7881. req.method = "GET";
  7882. req.path = "/";
  7883. auto res = cli.send(req);
  7884. ASSERT_TRUE(res);
  7885. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7886. }
  7887. TEST(SendAPI, WithParamsInRequest) {
  7888. Server svr;
  7889. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7890. EXPECT_TRUE(req.has_param("test"));
  7891. EXPECT_EQ("test_value", req.get_param_value("test"));
  7892. });
  7893. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7894. auto se = detail::scope_exit([&] {
  7895. svr.stop();
  7896. t.join();
  7897. ASSERT_FALSE(svr.is_running());
  7898. });
  7899. svr.wait_until_ready();
  7900. Client cli(HOST, PORT);
  7901. {
  7902. Request req;
  7903. req.method = "GET";
  7904. req.path = "/";
  7905. req.params.emplace("test", "test_value");
  7906. auto res = cli.send(req);
  7907. ASSERT_TRUE(res);
  7908. }
  7909. {
  7910. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7911. ASSERT_TRUE(res);
  7912. }
  7913. }
  7914. TEST(ClientImplMethods, GetSocketTest) {
  7915. httplib::Server svr;
  7916. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7917. res.status = StatusCode::OK_200;
  7918. });
  7919. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. thread.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. {
  7927. httplib::Client cli("http://127.0.0.1:3333");
  7928. cli.set_keep_alive(true);
  7929. // Use the behavior of cpp-httplib of opening the connection
  7930. // only when the first request happens. If that changes,
  7931. // this test would be obsolete.
  7932. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7933. // This also implicitly tests the server. But other tests would fail much
  7934. // earlier than this one to be considered.
  7935. auto res = cli.Get("/");
  7936. ASSERT_TRUE(res);
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7939. }
  7940. }
  7941. // Disabled due to out-of-memory problem on GitHub Actions
  7942. #ifdef _WIN64
  7943. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7944. // allocate content size larger than 2GB in memory
  7945. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7946. char *content = (char *)malloc(content_size);
  7947. ASSERT_TRUE(content);
  7948. Server svr;
  7949. svr.Get("/foo",
  7950. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7951. res.set_content(content, content_size, "application/octet-stream");
  7952. });
  7953. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7954. auto se = detail::scope_exit([&] {
  7955. svr.stop();
  7956. listen_thread.join();
  7957. if (content) free(content);
  7958. ASSERT_FALSE(svr.is_running());
  7959. });
  7960. svr.wait_until_ready();
  7961. Client cli(HOST, PORT);
  7962. auto res = cli.Get("/foo");
  7963. ASSERT_TRUE(res);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_EQ(content_size, res->body.length());
  7966. }
  7967. #endif
  7968. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7969. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7970. Client cli("http://yahoo.com");
  7971. auto res = cli.Get("/");
  7972. ASSERT_TRUE(res);
  7973. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7974. cli.set_follow_location(true);
  7975. res = cli.Get("/");
  7976. ASSERT_TRUE(res);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7979. }
  7980. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7981. Client cli("https://yahoo.com");
  7982. auto res = cli.Get("/");
  7983. ASSERT_TRUE(res);
  7984. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7985. cli.set_follow_location(true);
  7986. res = cli.Get("/");
  7987. ASSERT_TRUE(res);
  7988. EXPECT_EQ(StatusCode::OK_200, res->status);
  7989. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7990. }
  7991. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7992. Client cli("https://yahoo.com");
  7993. auto res = cli.Get("/");
  7994. ASSERT_TRUE(res);
  7995. ASSERT_FALSE(!res);
  7996. ASSERT_TRUE(res);
  7997. ASSERT_FALSE(res == nullptr);
  7998. ASSERT_TRUE(res != nullptr);
  7999. EXPECT_EQ(Error::Success, res.error());
  8000. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8001. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8002. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8003. cli.set_follow_location(true);
  8004. res = cli.Get("/");
  8005. ASSERT_TRUE(res);
  8006. EXPECT_EQ(Error::Success, res.error());
  8007. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8008. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8009. EXPECT_EQ(StatusCode::OK_200, res->status);
  8010. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8011. }
  8012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8013. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8014. Client cli("https://cdnjs.cloudflare.com");
  8015. auto res =
  8016. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8017. ASSERT_TRUE(res);
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. EXPECT_EQ(287630U, res->body.size());
  8020. EXPECT_EQ("application/javascript; charset=utf-8",
  8021. res->get_header_value("Content-Type"));
  8022. }
  8023. #endif
  8024. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8025. #undef REDIR_HOST // Silence compiler warning
  8026. #define REDIR_HOST "https://httpbingo.org"
  8027. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8028. Client cli(REDIR_HOST);
  8029. cli.set_follow_location(true);
  8030. auto res =
  8031. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8032. ASSERT_TRUE(res);
  8033. EXPECT_EQ(StatusCode::OK_200, res->status);
  8034. }
  8035. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8036. Client cli(REDIR_HOST);
  8037. cli.set_follow_location(true);
  8038. Params params;
  8039. params.emplace("url", "http://example.com");
  8040. params.emplace("status_code", "302");
  8041. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8042. ASSERT_TRUE(res);
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. }
  8045. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8046. Client cli(REDIR_HOST);
  8047. cli.set_follow_location(true);
  8048. Params params;
  8049. params.emplace("url", "http://example.com");
  8050. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8051. ASSERT_TRUE(res);
  8052. EXPECT_EQ(StatusCode::OK_200, res->status);
  8053. }
  8054. TEST(HttpToHttpsRedirectTest, CertFile) {
  8055. Server svr;
  8056. ASSERT_TRUE(svr.is_valid());
  8057. svr.Get("/index", [&](const Request &, Response &res) {
  8058. res.set_redirect("https://127.0.0.1:1235/index");
  8059. svr.stop();
  8060. });
  8061. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8062. ASSERT_TRUE(ssl_svr.is_valid());
  8063. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8064. res.set_content("test", "text/plain");
  8065. ssl_svr.stop();
  8066. });
  8067. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8068. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8069. auto se = detail::scope_exit([&] {
  8070. t2.join();
  8071. t.join();
  8072. ASSERT_FALSE(svr.is_running());
  8073. });
  8074. svr.wait_until_ready();
  8075. ssl_svr.wait_until_ready();
  8076. Client cli("127.0.0.1", PORT);
  8077. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8078. cli.enable_server_certificate_verification(true);
  8079. cli.set_follow_location(true);
  8080. cli.set_connection_timeout(30);
  8081. auto res = cli.Get("/index");
  8082. ASSERT_TRUE(res);
  8083. ASSERT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. TEST(SSLClientRedirectTest, CertFile) {
  8086. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8087. ASSERT_TRUE(ssl_svr1.is_valid());
  8088. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8089. res.set_redirect("https://127.0.0.1:1235/index");
  8090. ssl_svr1.stop();
  8091. });
  8092. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8093. ASSERT_TRUE(ssl_svr2.is_valid());
  8094. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8095. res.set_content("test", "text/plain");
  8096. ssl_svr2.stop();
  8097. });
  8098. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8099. thread t2 =
  8100. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8101. auto se = detail::scope_exit([&] {
  8102. t2.join();
  8103. t.join();
  8104. ASSERT_FALSE(ssl_svr1.is_running());
  8105. });
  8106. ssl_svr1.wait_until_ready();
  8107. ssl_svr2.wait_until_ready();
  8108. SSLClient cli("127.0.0.1", PORT);
  8109. std::string cert;
  8110. read_file(SERVER_CERT2_FILE, cert);
  8111. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8112. cli.enable_server_certificate_verification(true);
  8113. cli.set_follow_location(true);
  8114. cli.set_connection_timeout(30);
  8115. auto res = cli.Get("/index");
  8116. ASSERT_TRUE(res);
  8117. ASSERT_EQ(StatusCode::OK_200, res->status);
  8118. }
  8119. TEST(MultipartFormDataTest, LargeData) {
  8120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8121. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8122. const ContentReader &content_reader) {
  8123. if (req.is_multipart_form_data()) {
  8124. std::vector<FormData> items;
  8125. content_reader(
  8126. [&](const FormData &file) {
  8127. items.push_back(file);
  8128. return true;
  8129. },
  8130. [&](const char *data, size_t data_length) {
  8131. items.back().content.append(data, data_length);
  8132. return true;
  8133. });
  8134. EXPECT_TRUE(std::string(items[0].name) == "document");
  8135. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8136. EXPECT_TRUE(items[0].filename == "2MB_data");
  8137. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8138. EXPECT_TRUE(items[1].name == "hello");
  8139. EXPECT_TRUE(items[1].content == "world");
  8140. EXPECT_TRUE(items[1].filename == "");
  8141. EXPECT_TRUE(items[1].content_type == "");
  8142. } else {
  8143. std::string body;
  8144. content_reader([&](const char *data, size_t data_length) {
  8145. body.append(data, data_length);
  8146. return true;
  8147. });
  8148. }
  8149. });
  8150. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8151. auto se = detail::scope_exit([&] {
  8152. svr.stop();
  8153. t.join();
  8154. ASSERT_FALSE(svr.is_running());
  8155. });
  8156. svr.wait_until_ready();
  8157. {
  8158. std::string data(1024 * 1024 * 2, '.');
  8159. std::stringstream buffer;
  8160. buffer << data;
  8161. Client cli("https://localhost:8080");
  8162. cli.enable_server_certificate_verification(false);
  8163. UploadFormDataItems items{
  8164. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8165. {"hello", "world", "", ""},
  8166. };
  8167. auto res = cli.Post("/post", items);
  8168. ASSERT_TRUE(res);
  8169. ASSERT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. }
  8172. TEST(MultipartFormDataTest, DataProviderItems) {
  8173. std::random_device seed_gen;
  8174. std::mt19937 random(seed_gen());
  8175. std::string rand1;
  8176. rand1.resize(1000);
  8177. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8178. std::string rand2;
  8179. rand2.resize(3000);
  8180. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8182. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8183. const ContentReader &content_reader) {
  8184. ASSERT_FALSE(req.is_multipart_form_data());
  8185. std::string body;
  8186. content_reader([&](const char *data, size_t data_length) {
  8187. body.append(data, data_length);
  8188. return true;
  8189. });
  8190. EXPECT_EQ(body, "");
  8191. });
  8192. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8193. const ContentReader &content_reader) {
  8194. ASSERT_TRUE(req.is_multipart_form_data());
  8195. std::vector<FormData> items;
  8196. content_reader(
  8197. [&](const FormData &file) {
  8198. items.push_back(file);
  8199. return true;
  8200. },
  8201. [&](const char *data, size_t data_length) {
  8202. items.back().content.append(data, data_length);
  8203. return true;
  8204. });
  8205. ASSERT_TRUE(items.size() == 2);
  8206. EXPECT_EQ(std::string(items[0].name), "name1");
  8207. EXPECT_EQ(items[0].content, "Testing123");
  8208. EXPECT_EQ(items[0].filename, "filename1");
  8209. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8210. EXPECT_EQ(items[1].name, "name2");
  8211. EXPECT_EQ(items[1].content, "Testing456");
  8212. EXPECT_EQ(items[1].filename, "");
  8213. EXPECT_EQ(items[1].content_type, "");
  8214. });
  8215. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8216. const ContentReader &content_reader) {
  8217. ASSERT_TRUE(req.is_multipart_form_data());
  8218. std::vector<FormData> items;
  8219. content_reader(
  8220. [&](const FormData &file) {
  8221. items.push_back(file);
  8222. return true;
  8223. },
  8224. [&](const char *data, size_t data_length) {
  8225. items.back().content.append(data, data_length);
  8226. return true;
  8227. });
  8228. ASSERT_TRUE(items.size() == 2);
  8229. EXPECT_EQ(items[0].name, "name3");
  8230. EXPECT_EQ(items[0].content, rand1);
  8231. EXPECT_EQ(items[0].filename, "filename3");
  8232. EXPECT_EQ(items[0].content_type, "");
  8233. EXPECT_EQ(items[1].name, "name4");
  8234. EXPECT_EQ(items[1].content, rand2);
  8235. EXPECT_EQ(items[1].filename, "filename4");
  8236. EXPECT_EQ(items[1].content_type, "");
  8237. });
  8238. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8239. const ContentReader &content_reader) {
  8240. ASSERT_TRUE(req.is_multipart_form_data());
  8241. std::vector<FormData> items;
  8242. content_reader(
  8243. [&](const FormData &file) {
  8244. items.push_back(file);
  8245. return true;
  8246. },
  8247. [&](const char *data, size_t data_length) {
  8248. items.back().content.append(data, data_length);
  8249. return true;
  8250. });
  8251. ASSERT_TRUE(items.size() == 4);
  8252. EXPECT_EQ(std::string(items[0].name), "name1");
  8253. EXPECT_EQ(items[0].content, "Testing123");
  8254. EXPECT_EQ(items[0].filename, "filename1");
  8255. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8256. EXPECT_EQ(items[1].name, "name2");
  8257. EXPECT_EQ(items[1].content, "Testing456");
  8258. EXPECT_EQ(items[1].filename, "");
  8259. EXPECT_EQ(items[1].content_type, "");
  8260. EXPECT_EQ(items[2].name, "name3");
  8261. EXPECT_EQ(items[2].content, rand1);
  8262. EXPECT_EQ(items[2].filename, "filename3");
  8263. EXPECT_EQ(items[2].content_type, "");
  8264. EXPECT_EQ(items[3].name, "name4");
  8265. EXPECT_EQ(items[3].content, rand2);
  8266. EXPECT_EQ(items[3].filename, "filename4");
  8267. EXPECT_EQ(items[3].content_type, "");
  8268. });
  8269. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8270. auto se = detail::scope_exit([&] {
  8271. svr.stop();
  8272. t.join();
  8273. ASSERT_FALSE(svr.is_running());
  8274. });
  8275. svr.wait_until_ready();
  8276. {
  8277. Client cli("https://localhost:8080");
  8278. cli.enable_server_certificate_verification(false);
  8279. UploadFormDataItems items{
  8280. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8281. {"name2", "Testing456", "", ""}, // not a file
  8282. };
  8283. {
  8284. auto res = cli.Post("/post-none", {}, {}, {});
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. }
  8288. FormDataProviderItems providers;
  8289. {
  8290. auto res =
  8291. cli.Post("/post-items", {}, items, providers); // empty providers
  8292. ASSERT_TRUE(res);
  8293. ASSERT_EQ(StatusCode::OK_200, res->status);
  8294. }
  8295. providers.push_back({"name3",
  8296. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8297. // test the offset is given correctly at each step
  8298. if (!offset)
  8299. sink.os.write(rand1.data(), 30);
  8300. else if (offset == 30)
  8301. sink.os.write(rand1.data() + 30, 300);
  8302. else if (offset == 330)
  8303. sink.os.write(rand1.data() + 330, 670);
  8304. else if (offset == rand1.size())
  8305. sink.done();
  8306. return true;
  8307. },
  8308. "filename3",
  8309. {}});
  8310. providers.push_back({"name4",
  8311. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8312. // test the offset is given correctly at each step
  8313. if (!offset)
  8314. sink.os.write(rand2.data(), 2000);
  8315. else if (offset == 2000)
  8316. sink.os.write(rand2.data() + 2000, 1);
  8317. else if (offset == 2001)
  8318. sink.os.write(rand2.data() + 2001, 999);
  8319. else if (offset == rand2.size())
  8320. sink.done();
  8321. return true;
  8322. },
  8323. "filename4",
  8324. {}});
  8325. {
  8326. auto res = cli.Post("/post-providers", {}, {}, providers);
  8327. ASSERT_TRUE(res);
  8328. ASSERT_EQ(StatusCode::OK_200, res->status);
  8329. }
  8330. {
  8331. auto res = cli.Post("/post-both", {}, items, providers);
  8332. ASSERT_TRUE(res);
  8333. ASSERT_EQ(StatusCode::OK_200, res->status);
  8334. }
  8335. }
  8336. }
  8337. TEST(MultipartFormDataTest, BadHeader) {
  8338. Server svr;
  8339. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8340. res.set_content("ok", "text/plain");
  8341. });
  8342. thread t = thread([&] { svr.listen(HOST, PORT); });
  8343. auto se = detail::scope_exit([&] {
  8344. svr.stop();
  8345. t.join();
  8346. ASSERT_FALSE(svr.is_running());
  8347. });
  8348. svr.wait_until_ready();
  8349. const std::string body =
  8350. "This is the preamble. It is to be ignored, though it\r\n"
  8351. "is a handy place for composition agents to include an\r\n"
  8352. "explanatory note to non-MIME conformant readers.\r\n"
  8353. "\r\n"
  8354. "\r\n"
  8355. "--simple boundary\r\n"
  8356. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8357. ": BAD...\r\n"
  8358. "\r\n"
  8359. "value1\r\n"
  8360. "--simple boundary\r\n"
  8361. "Content-Disposition: form-data; name=\"field2\"; "
  8362. "filename=\"example.txt\"\r\n"
  8363. "\r\n"
  8364. "value2\r\n"
  8365. "--simple boundary--\r\n"
  8366. "This is the epilogue. It is also to be ignored.\r\n";
  8367. std::string content_type =
  8368. R"(multipart/form-data; boundary="simple boundary")";
  8369. Client cli(HOST, PORT);
  8370. auto res = cli.Post("/post", body, content_type.c_str());
  8371. ASSERT_TRUE(res);
  8372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8373. }
  8374. TEST(MultipartFormDataTest, WithPreamble) {
  8375. Server svr;
  8376. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8377. res.set_content("ok", "text/plain");
  8378. });
  8379. thread t = thread([&] { svr.listen(HOST, PORT); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. t.join();
  8383. ASSERT_FALSE(svr.is_running());
  8384. });
  8385. svr.wait_until_ready();
  8386. const std::string body =
  8387. "This is the preamble. It is to be ignored, though it\r\n"
  8388. "is a handy place for composition agents to include an\r\n"
  8389. "explanatory note to non-MIME conformant readers.\r\n"
  8390. "\r\n"
  8391. "\r\n"
  8392. "--simple boundary\r\n"
  8393. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8394. "\r\n"
  8395. "value1\r\n"
  8396. "--simple boundary\r\n"
  8397. "Content-Disposition: form-data; name=\"field2\"; "
  8398. "filename=\"example.txt\"\r\n"
  8399. "\r\n"
  8400. "value2\r\n"
  8401. "--simple boundary--\r\n"
  8402. "This is the epilogue. It is also to be ignored.\r\n";
  8403. std::string content_type =
  8404. R"(multipart/form-data; boundary="simple boundary")";
  8405. Client cli(HOST, PORT);
  8406. auto res = cli.Post("/post", body, content_type.c_str());
  8407. ASSERT_TRUE(res);
  8408. EXPECT_EQ(StatusCode::OK_200, res->status);
  8409. }
  8410. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8412. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8413. const ContentReader &content_reader) {
  8414. if (req.is_multipart_form_data()) {
  8415. std::vector<FormData> items;
  8416. content_reader(
  8417. [&](const FormData &file) {
  8418. items.push_back(file);
  8419. return true;
  8420. },
  8421. [&](const char *data, size_t data_length) {
  8422. items.back().content.append(data, data_length);
  8423. return true;
  8424. });
  8425. EXPECT_TRUE(std::string(items[0].name) == "document");
  8426. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8427. EXPECT_TRUE(items[0].filename == "2MB_data");
  8428. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8429. EXPECT_TRUE(items[1].name == "hello");
  8430. EXPECT_TRUE(items[1].content == "world");
  8431. EXPECT_TRUE(items[1].filename == "");
  8432. EXPECT_TRUE(items[1].content_type == "");
  8433. } else {
  8434. std::string body;
  8435. content_reader([&](const char *data, size_t data_length) {
  8436. body.append(data, data_length);
  8437. return true;
  8438. });
  8439. }
  8440. });
  8441. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8442. auto se = detail::scope_exit([&] {
  8443. svr.stop();
  8444. t.join();
  8445. ASSERT_FALSE(svr.is_running());
  8446. });
  8447. svr.wait_until_ready();
  8448. {
  8449. std::string data(1024 * 1024 * 2, '.');
  8450. std::stringstream buffer;
  8451. buffer << data;
  8452. Client cli("https://localhost:8080");
  8453. cli.enable_server_certificate_verification(false);
  8454. UploadFormDataItems items{
  8455. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8456. {"hello", "world", "", ""},
  8457. };
  8458. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8459. ASSERT_TRUE(res);
  8460. ASSERT_EQ(StatusCode::OK_200, res->status);
  8461. }
  8462. }
  8463. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8464. std::string data(1024 * 1024 * 2, '&');
  8465. std::stringstream buffer;
  8466. buffer << data;
  8467. Client cli("https://localhost:8080");
  8468. UploadFormDataItems items{
  8469. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8470. {"hello", "world", "", ""},
  8471. };
  8472. for (const char &c : " \t\r\n") {
  8473. auto res =
  8474. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8475. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8476. ASSERT_FALSE(res);
  8477. }
  8478. }
  8479. TEST(MultipartFormDataTest, PutFormData) {
  8480. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8481. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8482. const ContentReader &content_reader) {
  8483. if (req.is_multipart_form_data()) {
  8484. std::vector<FormData> items;
  8485. content_reader(
  8486. [&](const FormData &file) {
  8487. items.push_back(file);
  8488. return true;
  8489. },
  8490. [&](const char *data, size_t data_length) {
  8491. items.back().content.append(data, data_length);
  8492. return true;
  8493. });
  8494. EXPECT_TRUE(std::string(items[0].name) == "document");
  8495. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8496. EXPECT_TRUE(items[0].filename == "2MB_data");
  8497. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8498. EXPECT_TRUE(items[1].name == "hello");
  8499. EXPECT_TRUE(items[1].content == "world");
  8500. EXPECT_TRUE(items[1].filename == "");
  8501. EXPECT_TRUE(items[1].content_type == "");
  8502. } else {
  8503. std::string body;
  8504. content_reader([&](const char *data, size_t data_length) {
  8505. body.append(data, data_length);
  8506. return true;
  8507. });
  8508. }
  8509. });
  8510. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8511. auto se = detail::scope_exit([&] {
  8512. svr.stop();
  8513. t.join();
  8514. ASSERT_FALSE(svr.is_running());
  8515. });
  8516. svr.wait_until_ready();
  8517. {
  8518. std::string data(1024 * 1024 * 2, '&');
  8519. std::stringstream buffer;
  8520. buffer << data;
  8521. Client cli("https://localhost:8080");
  8522. cli.enable_server_certificate_verification(false);
  8523. UploadFormDataItems items{
  8524. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8525. {"hello", "world", "", ""},
  8526. };
  8527. auto res = cli.Put("/put", items);
  8528. ASSERT_TRUE(res);
  8529. ASSERT_EQ(StatusCode::OK_200, res->status);
  8530. }
  8531. }
  8532. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8534. svr.Put("/put_customboundary",
  8535. [&](const Request &req, const Response & /*res*/,
  8536. const ContentReader &content_reader) {
  8537. if (req.is_multipart_form_data()) {
  8538. std::vector<FormData> items;
  8539. content_reader(
  8540. [&](const FormData &file) {
  8541. items.push_back(file);
  8542. return true;
  8543. },
  8544. [&](const char *data, size_t data_length) {
  8545. items.back().content.append(data, data_length);
  8546. return true;
  8547. });
  8548. EXPECT_TRUE(std::string(items[0].name) == "document");
  8549. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8550. EXPECT_TRUE(items[0].filename == "2MB_data");
  8551. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8552. EXPECT_TRUE(items[1].name == "hello");
  8553. EXPECT_TRUE(items[1].content == "world");
  8554. EXPECT_TRUE(items[1].filename == "");
  8555. EXPECT_TRUE(items[1].content_type == "");
  8556. } else {
  8557. std::string body;
  8558. content_reader([&](const char *data, size_t data_length) {
  8559. body.append(data, data_length);
  8560. return true;
  8561. });
  8562. }
  8563. });
  8564. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8565. auto se = detail::scope_exit([&] {
  8566. svr.stop();
  8567. t.join();
  8568. ASSERT_FALSE(svr.is_running());
  8569. });
  8570. svr.wait_until_ready();
  8571. {
  8572. std::string data(1024 * 1024 * 2, '&');
  8573. std::stringstream buffer;
  8574. buffer << data;
  8575. Client cli("https://localhost:8080");
  8576. cli.enable_server_certificate_verification(false);
  8577. UploadFormDataItems items{
  8578. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8579. {"hello", "world", "", ""},
  8580. };
  8581. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8582. ASSERT_TRUE(res);
  8583. ASSERT_EQ(StatusCode::OK_200, res->status);
  8584. }
  8585. }
  8586. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8587. std::string data(1024 * 1024 * 2, '&');
  8588. std::stringstream buffer;
  8589. buffer << data;
  8590. Client cli("https://localhost:8080");
  8591. cli.enable_server_certificate_verification(false);
  8592. UploadFormDataItems items{
  8593. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8594. {"hello", "world", "", ""},
  8595. };
  8596. for (const char &c : " \t\r\n") {
  8597. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8598. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8599. ASSERT_FALSE(res);
  8600. }
  8601. }
  8602. TEST(MultipartFormDataTest, AlternateFilename) {
  8603. auto handled = false;
  8604. Server svr;
  8605. svr.Post("/test", [&](const Request &req, Response &res) {
  8606. ASSERT_EQ(2u, req.form.files.size());
  8607. ASSERT_EQ(1u, req.form.fields.size());
  8608. // Test files
  8609. const auto &file1 = req.form.get_file("file1");
  8610. ASSERT_EQ("file1", file1.name);
  8611. ASSERT_EQ("A.txt", file1.filename);
  8612. ASSERT_EQ("text/plain", file1.content_type);
  8613. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8614. const auto &file2 = req.form.get_file("file2");
  8615. ASSERT_EQ("file2", file2.name);
  8616. ASSERT_EQ("a.html", file2.filename);
  8617. ASSERT_EQ("text/html", file2.content_type);
  8618. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8619. file2.content);
  8620. // Test text field
  8621. const auto &text = req.form.get_field("text");
  8622. ASSERT_EQ("text default", text);
  8623. res.set_content("ok", "text/plain");
  8624. handled = true;
  8625. });
  8626. thread t = thread([&] { svr.listen(HOST, PORT); });
  8627. auto se = detail::scope_exit([&] {
  8628. svr.stop();
  8629. t.join();
  8630. ASSERT_FALSE(svr.is_running());
  8631. ASSERT_TRUE(handled);
  8632. });
  8633. svr.wait_until_ready();
  8634. auto req = "POST /test HTTP/1.1\r\n"
  8635. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8636. "Content-Length: 399\r\n"
  8637. "\r\n"
  8638. "----------\r\n"
  8639. "Content-Disposition: form-data; name=\"text\"\r\n"
  8640. "\r\n"
  8641. "text default\r\n"
  8642. "----------\r\n"
  8643. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8644. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8645. "Content-Type: text/plain\r\n"
  8646. "\r\n"
  8647. "Content of a.txt.\r\n"
  8648. "\r\n"
  8649. "----------\r\n"
  8650. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8651. "\"a.html\"\r\n"
  8652. "Content-Type: text/html\r\n"
  8653. "\r\n"
  8654. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8655. "\r\n"
  8656. "------------\r\n";
  8657. ASSERT_TRUE(send_request(1, req));
  8658. }
  8659. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8660. auto handled = false;
  8661. Server svr;
  8662. svr.Post("/test", [&](const Request &req, Response &) {
  8663. ASSERT_EQ(2u, req.form.fields.size());
  8664. const auto &text1 = req.form.get_field("text1");
  8665. ASSERT_EQ("text1", text1);
  8666. const auto &text2 = req.form.get_field("text2");
  8667. ASSERT_EQ("text2", text2);
  8668. handled = true;
  8669. });
  8670. thread t = thread([&] { svr.listen(HOST, PORT); });
  8671. auto se = detail::scope_exit([&] {
  8672. svr.stop();
  8673. t.join();
  8674. ASSERT_FALSE(svr.is_running());
  8675. ASSERT_TRUE(handled);
  8676. });
  8677. svr.wait_until_ready();
  8678. auto req = "POST /test HTTP/1.1\r\n"
  8679. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8680. "Content-Length: 146\r\n"
  8681. "\r\n----------\r\n"
  8682. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8683. "\r\n"
  8684. "text1"
  8685. "\r\n----------\r\n"
  8686. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8687. "\r\n"
  8688. "text2"
  8689. "\r\n------------";
  8690. std::string response;
  8691. ASSERT_TRUE(send_request(1, req, &response));
  8692. ASSERT_EQ("200", response.substr(9, 3));
  8693. }
  8694. TEST(MultipartFormDataTest, ContentLength) {
  8695. auto handled = false;
  8696. Server svr;
  8697. svr.Post("/test", [&](const Request &req, Response &) {
  8698. ASSERT_EQ(2u, req.form.fields.size());
  8699. const auto &text1 = req.form.get_field("text1");
  8700. ASSERT_EQ("text1", text1);
  8701. const auto &text2 = req.form.get_field("text2");
  8702. ASSERT_EQ("text2", text2);
  8703. handled = true;
  8704. });
  8705. thread t = thread([&] { svr.listen(HOST, PORT); });
  8706. auto se = detail::scope_exit([&] {
  8707. svr.stop();
  8708. t.join();
  8709. ASSERT_FALSE(svr.is_running());
  8710. ASSERT_TRUE(handled);
  8711. });
  8712. svr.wait_until_ready();
  8713. auto req = "POST /test HTTP/1.1\r\n"
  8714. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8715. "Content-Length: 167\r\n"
  8716. "\r\n----------\r\n"
  8717. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8718. "Content-Length: 5\r\n"
  8719. "\r\n"
  8720. "text1"
  8721. "\r\n----------\r\n"
  8722. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8723. "\r\n"
  8724. "text2"
  8725. "\r\n------------\r\n";
  8726. std::string response;
  8727. ASSERT_TRUE(send_request(1, req, &response));
  8728. ASSERT_EQ("200", response.substr(9, 3));
  8729. }
  8730. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8731. auto handled = false;
  8732. Server svr;
  8733. svr.Post("/test", [&](const Request &req, Response &) {
  8734. ASSERT_EQ(2u, req.form.fields.size());
  8735. const auto &text1 = req.form.get_field("text1");
  8736. ASSERT_EQ("text1", text1);
  8737. // TODO: Add header access for text fields if needed
  8738. const auto &text2 = req.form.get_field("text2");
  8739. ASSERT_EQ("text2", text2);
  8740. // TODO: Header access for text fields needs to be implemented
  8741. // auto &headers = it->second.headers;
  8742. // ASSERT_EQ(3U, headers.size());
  8743. // auto custom_header = headers.find("x-whatever");
  8744. // ASSERT_TRUE(custom_header != headers.end());
  8745. // ASSERT_NE("customvalue", custom_header->second);
  8746. // ASSERT_EQ("CustomValue", custom_header->second);
  8747. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8748. handled = true;
  8749. });
  8750. thread t = thread([&] { svr.listen(HOST, PORT); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. ASSERT_FALSE(svr.is_running());
  8755. ASSERT_TRUE(handled);
  8756. });
  8757. svr.wait_until_ready();
  8758. auto req = "POST /test HTTP/1.1\r\n"
  8759. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8760. "Content-Length: 232\r\n"
  8761. "\r\n----------\r\n"
  8762. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8763. "Content-Length: 5\r\n"
  8764. "X-Test: 1\r\n"
  8765. "\r\n"
  8766. "text1"
  8767. "\r\n----------\r\n"
  8768. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8769. "Content-Type: text/plain\r\n"
  8770. "X-Whatever: CustomValue\r\n"
  8771. "\r\n"
  8772. "text2"
  8773. "\r\n------------\r\n"
  8774. "That should be disregarded. Not even read";
  8775. std::string response;
  8776. ASSERT_TRUE(send_request(1, req, &response));
  8777. ASSERT_EQ("200", response.substr(9, 3));
  8778. }
  8779. #endif
  8780. TEST(MultipartFormDataTest, LargeHeader) {
  8781. auto handled = false;
  8782. Server svr;
  8783. svr.Post("/test", [&](const Request &req, Response &) {
  8784. ASSERT_EQ(1u, req.form.fields.size());
  8785. const auto &text = req.form.get_field("name1");
  8786. ASSERT_EQ("text1", text);
  8787. handled = true;
  8788. });
  8789. thread t = thread([&] { svr.listen(HOST, PORT); });
  8790. auto se = detail::scope_exit([&] {
  8791. svr.stop();
  8792. t.join();
  8793. ASSERT_FALSE(svr.is_running());
  8794. ASSERT_TRUE(handled);
  8795. });
  8796. svr.wait_until_ready();
  8797. auto boundary = std::string("cpp-httplib-multipart-data");
  8798. std::string content = "--" + boundary +
  8799. "\r\n"
  8800. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8801. "\r\n"
  8802. "text1\r\n"
  8803. "--" +
  8804. boundary + "--\r\n";
  8805. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8806. "Content-Type: multipart/form-data;boundary=" +
  8807. boundary +
  8808. "\r\n"
  8809. "Content-Length: " +
  8810. std::to_string(content.size()) +
  8811. "\r\n"
  8812. "Dummy-Header: ";
  8813. std::string header_suffix = "\r\n"
  8814. "\r\n";
  8815. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8816. size_t header_dummy_size =
  8817. read_buff_size -
  8818. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8819. auto header_dummy = std::string(header_dummy_size, '@');
  8820. auto req = header_prefix + header_dummy + header_suffix + content;
  8821. std::string response;
  8822. ASSERT_TRUE(send_request(1, req, &response));
  8823. ASSERT_EQ("200", response.substr(9, 3));
  8824. }
  8825. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8826. static constexpr unsigned int number_of_tasks{1000000};
  8827. std::atomic_uint count{0};
  8828. std::unique_ptr<TaskQueue> task_queue{
  8829. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8830. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8831. auto queued = task_queue->enqueue(
  8832. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8833. EXPECT_TRUE(queued);
  8834. }
  8835. EXPECT_NO_THROW(task_queue->shutdown());
  8836. EXPECT_EQ(number_of_tasks, count.load());
  8837. }
  8838. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8839. static constexpr unsigned int number_of_tasks{1000000};
  8840. static constexpr unsigned int qlimit{2};
  8841. unsigned int queued_count{0};
  8842. std::atomic_uint count{0};
  8843. std::unique_ptr<TaskQueue> task_queue{
  8844. new ThreadPool{/*num_threads=*/1, qlimit}};
  8845. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8846. if (task_queue->enqueue(
  8847. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8848. queued_count++;
  8849. }
  8850. }
  8851. EXPECT_NO_THROW(task_queue->shutdown());
  8852. EXPECT_EQ(queued_count, count.load());
  8853. EXPECT_TRUE(queued_count <= number_of_tasks);
  8854. EXPECT_TRUE(queued_count >= qlimit);
  8855. }
  8856. TEST(TaskQueueTest, MaxQueuedRequests) {
  8857. static constexpr unsigned int qlimit{3};
  8858. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8859. std::condition_variable sem_cv;
  8860. std::mutex sem_mtx;
  8861. int credits = 0;
  8862. bool queued;
  8863. /* Fill up the queue with tasks that will block until we give them credits to
  8864. * complete. */
  8865. for (unsigned int n = 0; n <= qlimit;) {
  8866. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8867. std::unique_lock<std::mutex> lock(sem_mtx);
  8868. while (credits <= 0) {
  8869. sem_cv.wait(lock);
  8870. }
  8871. /* Consume the credit and signal the test code if they are all gone. */
  8872. if (--credits == 0) { sem_cv.notify_one(); }
  8873. });
  8874. if (n < qlimit) {
  8875. /* The first qlimit enqueues must succeed. */
  8876. EXPECT_TRUE(queued);
  8877. } else {
  8878. /* The last one will succeed only when the worker thread
  8879. * starts and dequeues the first blocking task. Although
  8880. * not necessary for the correctness of this test, we sleep for
  8881. * a short while to avoid busy waiting. */
  8882. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8883. }
  8884. if (queued) { n++; }
  8885. }
  8886. /* Further enqueues must fail since the queue is full. */
  8887. for (auto i = 0; i < 4; i++) {
  8888. queued = task_queue->enqueue([] {});
  8889. EXPECT_FALSE(queued);
  8890. }
  8891. /* Give the credits to allow the previous tasks to complete. */
  8892. {
  8893. std::unique_lock<std::mutex> lock(sem_mtx);
  8894. credits += qlimit + 1;
  8895. }
  8896. sem_cv.notify_all();
  8897. /* Wait for all the credits to be consumed. */
  8898. {
  8899. std::unique_lock<std::mutex> lock(sem_mtx);
  8900. while (credits > 0) {
  8901. sem_cv.wait(lock);
  8902. }
  8903. }
  8904. /* Check that we are able again to enqueue at least qlimit tasks. */
  8905. for (unsigned int i = 0; i < qlimit; i++) {
  8906. queued = task_queue->enqueue([] {});
  8907. EXPECT_TRUE(queued);
  8908. }
  8909. EXPECT_NO_THROW(task_queue->shutdown());
  8910. }
  8911. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8912. Server svr;
  8913. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8914. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8915. });
  8916. svr.Get("/hello", [](const Request &req, Response &res) {
  8917. res.set_content(req.get_param_value("key"), "text/plain");
  8918. });
  8919. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. thread.join();
  8923. ASSERT_FALSE(svr.is_running());
  8924. });
  8925. svr.wait_until_ready();
  8926. {
  8927. Client cli(HOST, PORT);
  8928. cli.set_follow_location(true);
  8929. auto res = cli.Get("/");
  8930. ASSERT_TRUE(res);
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. EXPECT_EQ("val&key2=val2", res->body);
  8933. }
  8934. }
  8935. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8936. Server svr;
  8937. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8938. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8939. });
  8940. svr.Get("/hello", [](const Request &req, Response &res) {
  8941. res.set_content(req.get_param_value("key"), "text/plain");
  8942. });
  8943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8944. auto se = detail::scope_exit([&] {
  8945. svr.stop();
  8946. thread.join();
  8947. ASSERT_FALSE(svr.is_running());
  8948. });
  8949. svr.wait_until_ready();
  8950. {
  8951. Client cli(HOST, PORT);
  8952. cli.set_follow_location(true);
  8953. auto res = cli.Get("/");
  8954. ASSERT_TRUE(res);
  8955. EXPECT_EQ(StatusCode::OK_200, res->status);
  8956. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8957. }
  8958. }
  8959. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8960. TEST(RedirectTest, Issue2185_Online) {
  8961. SSLClient client("github.com");
  8962. client.set_follow_location(true);
  8963. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8964. "Coollab-Windows.zip");
  8965. ASSERT_TRUE(res);
  8966. EXPECT_EQ(StatusCode::OK_200, res->status);
  8967. EXPECT_EQ(9920427U, res->body.size());
  8968. }
  8969. #endif
  8970. TEST(VulnerabilityTest, CRLFInjection) {
  8971. Server svr;
  8972. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8973. res.set_content("Hello 1", "text/plain");
  8974. });
  8975. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8976. res.set_content("Hello 2", "text/plain");
  8977. });
  8978. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8979. res.set_content("Hello 3", "text/plain");
  8980. });
  8981. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8982. res.set_content("Hello 4", "text/plain");
  8983. });
  8984. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8985. for (const auto &x : req.headers) {
  8986. auto key = x.first;
  8987. EXPECT_STRNE("evil", key.c_str());
  8988. }
  8989. });
  8990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8991. auto se = detail::scope_exit([&] {
  8992. svr.stop();
  8993. thread.join();
  8994. ASSERT_FALSE(svr.is_running());
  8995. });
  8996. svr.wait_until_ready();
  8997. {
  8998. Client cli(HOST, PORT);
  8999. cli.Post("/test1", "A=B",
  9000. "application/x-www-form-urlencoded\r\nevil: hello1");
  9001. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9002. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9003. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9004. }
  9005. }
  9006. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9007. auto server_thread = std::thread([] {
  9008. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9009. default_socket_options(srv);
  9010. sockaddr_in addr{};
  9011. addr.sin_family = AF_INET;
  9012. addr.sin_port = htons(PORT + 1);
  9013. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9014. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9015. ::listen(srv, 1);
  9016. sockaddr_in cli_addr{};
  9017. socklen_t cli_len = sizeof(cli_addr);
  9018. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9019. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9020. std::string buf_all;
  9021. char buf[2048];
  9022. ssize_t n;
  9023. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9024. buf_all.append(buf, static_cast<size_t>(n));
  9025. size_t pos;
  9026. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9027. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9028. auto e = request_block.find("\r\n");
  9029. if (e != std::string::npos) {
  9030. auto request_line = request_block.substr(0, e);
  9031. std::string msg =
  9032. "CRLF injection detected in request line: '" + request_line + "'";
  9033. EXPECT_FALSE(true) << msg;
  9034. }
  9035. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9036. ::send(cli, resp.c_str(), resp.size(), 0);
  9037. buf_all.erase(0, pos + 4);
  9038. }
  9039. }
  9040. detail::close_socket(cli);
  9041. detail::close_socket(srv);
  9042. });
  9043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9044. auto cli = Client("127.0.0.1", PORT + 1);
  9045. auto headers = Headers{
  9046. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9047. {"Connection", "keep-alive"}};
  9048. auto res = cli.Get("/hi", headers);
  9049. EXPECT_FALSE(res);
  9050. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9051. server_thread.join();
  9052. }
  9053. TEST(PathParamsTest, StaticMatch) {
  9054. const auto pattern = "/users/all";
  9055. detail::PathParamsMatcher matcher(pattern);
  9056. Request request;
  9057. request.path = "/users/all";
  9058. ASSERT_TRUE(matcher.match(request));
  9059. std::unordered_map<std::string, std::string> expected_params = {};
  9060. EXPECT_EQ(request.path_params, expected_params);
  9061. }
  9062. TEST(PathParamsTest, StaticMismatch) {
  9063. const auto pattern = "/users/all";
  9064. detail::PathParamsMatcher matcher(pattern);
  9065. Request request;
  9066. request.path = "/users/1";
  9067. ASSERT_FALSE(matcher.match(request));
  9068. }
  9069. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9070. const auto pattern = "/users/:id/subscriptions";
  9071. detail::PathParamsMatcher matcher(pattern);
  9072. Request request;
  9073. request.path = "/users/42/subscriptions";
  9074. ASSERT_TRUE(matcher.match(request));
  9075. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9076. EXPECT_EQ(request.path_params, expected_params);
  9077. }
  9078. TEST(PathParamsTest, SingleParamInTheEnd) {
  9079. const auto pattern = "/users/:id";
  9080. detail::PathParamsMatcher matcher(pattern);
  9081. Request request;
  9082. request.path = "/users/24";
  9083. ASSERT_TRUE(matcher.match(request));
  9084. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9085. EXPECT_EQ(request.path_params, expected_params);
  9086. }
  9087. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9088. const auto pattern = "/users/:id/";
  9089. detail::PathParamsMatcher matcher(pattern);
  9090. Request request;
  9091. request.path = "/users/42/";
  9092. ASSERT_TRUE(matcher.match(request));
  9093. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9094. EXPECT_EQ(request.path_params, expected_params);
  9095. }
  9096. TEST(PathParamsTest, EmptyParam) {
  9097. const auto pattern = "/users/:id/";
  9098. detail::PathParamsMatcher matcher(pattern);
  9099. Request request;
  9100. request.path = "/users//";
  9101. ASSERT_TRUE(matcher.match(request));
  9102. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9103. EXPECT_EQ(request.path_params, expected_params);
  9104. }
  9105. TEST(PathParamsTest, FragmentMismatch) {
  9106. const auto pattern = "/users/:id/";
  9107. detail::PathParamsMatcher matcher(pattern);
  9108. Request request;
  9109. request.path = "/admins/24/";
  9110. ASSERT_FALSE(matcher.match(request));
  9111. }
  9112. TEST(PathParamsTest, ExtraFragments) {
  9113. const auto pattern = "/users/:id";
  9114. detail::PathParamsMatcher matcher(pattern);
  9115. Request request;
  9116. request.path = "/users/42/subscriptions";
  9117. ASSERT_FALSE(matcher.match(request));
  9118. }
  9119. TEST(PathParamsTest, MissingTrailingParam) {
  9120. const auto pattern = "/users/:id";
  9121. detail::PathParamsMatcher matcher(pattern);
  9122. Request request;
  9123. request.path = "/users";
  9124. ASSERT_FALSE(matcher.match(request));
  9125. }
  9126. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9127. const auto pattern = "/users/:id/subscriptions";
  9128. detail::PathParamsMatcher matcher(pattern);
  9129. Request request;
  9130. request.path = "/users/subscriptions";
  9131. ASSERT_FALSE(matcher.match(request));
  9132. }
  9133. TEST(PathParamsTest, MultipleParams) {
  9134. const auto pattern = "/users/:userid/subscriptions/:subid";
  9135. detail::PathParamsMatcher matcher(pattern);
  9136. Request request;
  9137. request.path = "/users/42/subscriptions/2";
  9138. ASSERT_TRUE(matcher.match(request));
  9139. std::unordered_map<std::string, std::string> expected_params = {
  9140. {"userid", "42"}, {"subid", "2"}};
  9141. EXPECT_EQ(request.path_params, expected_params);
  9142. }
  9143. TEST(PathParamsTest, SequenceOfParams) {
  9144. const auto pattern = "/values/:x/:y/:z";
  9145. detail::PathParamsMatcher matcher(pattern);
  9146. Request request;
  9147. request.path = "/values/1/2/3";
  9148. ASSERT_TRUE(matcher.match(request));
  9149. std::unordered_map<std::string, std::string> expected_params = {
  9150. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9151. EXPECT_EQ(request.path_params, expected_params);
  9152. }
  9153. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9154. const auto pattern = "/prefix:suffix";
  9155. detail::PathParamsMatcher matcher(pattern);
  9156. Request request;
  9157. request.path = "/prefix:suffix";
  9158. ASSERT_TRUE(matcher.match(request));
  9159. const std::unordered_map<std::string, std::string> expected_params = {};
  9160. EXPECT_EQ(request.path_params, expected_params);
  9161. }
  9162. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9163. // If ipv6 regex working, regex match codepath is taken.
  9164. // else port will default to 80 in Client impl
  9165. int clientImplMagicPort = 80;
  9166. int port = 4321;
  9167. // above ports must be different to avoid false negative
  9168. EXPECT_NE(clientImplMagicPort, port);
  9169. std::string ipV6TestURL = "http://[ff06::c3]";
  9170. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9171. CLIENT_PRIVATE_KEY_FILE);
  9172. EXPECT_EQ(cli.port(), port);
  9173. }
  9174. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9175. auto file_path = "./www/dir/index.html";
  9176. auto dir_path = "./www/dir";
  9177. detail::FileStat stat_file(file_path);
  9178. EXPECT_TRUE(stat_file.is_file());
  9179. EXPECT_FALSE(stat_file.is_dir());
  9180. detail::FileStat stat_dir(dir_path);
  9181. EXPECT_FALSE(stat_dir.is_file());
  9182. EXPECT_TRUE(stat_dir.is_dir());
  9183. }
  9184. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9185. // IPv4 with default HTTP port (80)
  9186. EXPECT_EQ("example.com",
  9187. detail::make_host_and_port_string("example.com", 80, false));
  9188. // IPv4 with default HTTPS port (443)
  9189. EXPECT_EQ("example.com",
  9190. detail::make_host_and_port_string("example.com", 443, true));
  9191. // IPv4 with non-default HTTP port
  9192. EXPECT_EQ("example.com:8080",
  9193. detail::make_host_and_port_string("example.com", 8080, false));
  9194. // IPv4 with non-default HTTPS port
  9195. EXPECT_EQ("example.com:8443",
  9196. detail::make_host_and_port_string("example.com", 8443, true));
  9197. // IPv6 with default HTTP port (80)
  9198. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9199. // IPv6 with default HTTPS port (443)
  9200. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9201. // IPv6 with non-default HTTP port
  9202. EXPECT_EQ("[::1]:8080",
  9203. detail::make_host_and_port_string("::1", 8080, false));
  9204. // IPv6 with non-default HTTPS port
  9205. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9206. // IPv6 full address with default port
  9207. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9208. detail::make_host_and_port_string(
  9209. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9210. // IPv6 full address with non-default port
  9211. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9212. detail::make_host_and_port_string(
  9213. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9214. // IPv6 localhost with non-default port
  9215. EXPECT_EQ("[::1]:3000",
  9216. detail::make_host_and_port_string("::1", 3000, false));
  9217. // IPv6 with zone ID (link-local address) with default port
  9218. EXPECT_EQ("[fe80::1%eth0]",
  9219. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9220. // IPv6 with zone ID (link-local address) with non-default port
  9221. EXPECT_EQ("[fe80::1%eth0]:8080",
  9222. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9223. // Edge case: Port 443 with is_ssl=false (should add port)
  9224. EXPECT_EQ("example.com:443",
  9225. detail::make_host_and_port_string("example.com", 443, false));
  9226. // Edge case: Port 80 with is_ssl=true (should add port)
  9227. EXPECT_EQ("example.com:80",
  9228. detail::make_host_and_port_string("example.com", 80, true));
  9229. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9230. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9231. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9232. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9233. // Security fix: Already bracketed IPv6 should not get double brackets
  9234. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9235. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9236. EXPECT_EQ("[::1]:8080",
  9237. detail::make_host_and_port_string("[::1]", 8080, false));
  9238. EXPECT_EQ("[2001:db8::1]:8080",
  9239. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9240. EXPECT_EQ("[fe80::1%eth0]",
  9241. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9242. EXPECT_EQ("[fe80::1%eth0]:8080",
  9243. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9244. // Edge case: Empty host (should return as-is)
  9245. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9246. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9247. // This is a known limitation but shouldn't crash
  9248. EXPECT_EQ("[host:name]",
  9249. detail::make_host_and_port_string("host:name", 80, false));
  9250. // Port number edge cases (no validation, but should not crash)
  9251. EXPECT_EQ("example.com:0",
  9252. detail::make_host_and_port_string("example.com", 0, false));
  9253. EXPECT_EQ("example.com:-1",
  9254. detail::make_host_and_port_string("example.com", -1, false));
  9255. EXPECT_EQ("example.com:65535",
  9256. detail::make_host_and_port_string("example.com", 65535, false));
  9257. EXPECT_EQ("example.com:65536",
  9258. detail::make_host_and_port_string("example.com", 65536, false));
  9259. }
  9260. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9261. TEST(SSLClientHostHeaderTest, Issue2301) {
  9262. httplib::SSLClient cli("roblox.com", 443);
  9263. cli.set_follow_location(true);
  9264. auto res = cli.Get("/");
  9265. ASSERT_TRUE(res);
  9266. EXPECT_EQ(StatusCode::OK_200, res->status);
  9267. }
  9268. #endif
  9269. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9270. Server svr;
  9271. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9272. EXPECT_EQ(res.status, 400);
  9273. });
  9274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9275. auto se = detail::scope_exit([&] {
  9276. svr.stop();
  9277. thread.join();
  9278. ASSERT_FALSE(svr.is_running());
  9279. });
  9280. svr.wait_until_ready();
  9281. Client cli(HOST, PORT);
  9282. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9283. }
  9284. TEST(InvalidHeaderCharsTest, is_field_name) {
  9285. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9286. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9287. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9288. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9289. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9290. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9291. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9292. EXPECT_FALSE(detail::fields::is_field_name(""));
  9293. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9294. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9295. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9296. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9297. }
  9298. TEST(InvalidHeaderCharsTest, is_field_value) {
  9299. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9300. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9301. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9302. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9303. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9304. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9305. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9306. EXPECT_TRUE(detail::fields::is_field_value(""));
  9307. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9308. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9309. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9310. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9311. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9312. }
  9313. TEST(InvalidHeaderCharsTest, OnServer) {
  9314. Server svr;
  9315. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9316. std::string header = "Not Set";
  9317. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9318. res.set_header(header, "value");
  9319. res.set_content("Page Content Page Content", "text/plain");
  9320. });
  9321. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9322. std::string header = "Not Set";
  9323. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9324. res.set_header("X-Test", header);
  9325. res.set_content("Page Content Page Content", "text/plain");
  9326. });
  9327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. thread.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. Client cli(HOST, PORT);
  9335. {
  9336. auto res = cli.Get(
  9337. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9338. ASSERT_TRUE(res);
  9339. EXPECT_EQ("Page Content Page Content", res->body);
  9340. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9341. }
  9342. {
  9343. auto res = cli.Get(
  9344. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9345. ASSERT_TRUE(res);
  9346. EXPECT_EQ("Page Content Page Content", res->body);
  9347. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9348. }
  9349. }
  9350. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9351. auto handled = false;
  9352. Server svr;
  9353. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9354. thread t = thread([&] { svr.listen(HOST, PORT); });
  9355. auto se = detail::scope_exit([&] {
  9356. svr.stop();
  9357. t.join();
  9358. ASSERT_FALSE(svr.is_running());
  9359. ASSERT_FALSE(handled);
  9360. });
  9361. svr.wait_until_ready();
  9362. auto req = "POST /test HTTP/1.1\r\n"
  9363. "Content-Length: x\r\n"
  9364. "\r\n";
  9365. std::string response;
  9366. ASSERT_TRUE(send_request(1, req, &response));
  9367. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9368. response.substr(0, response.find("\r\n")));
  9369. }
  9370. #ifndef _WIN32
  9371. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9372. static constexpr char reject[] = "Unauthorized";
  9373. static constexpr char accept[] = "Upload accepted";
  9374. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9375. Server svr;
  9376. svr.set_expect_100_continue_handler(
  9377. [](const Request & /*req*/, Response &res) {
  9378. res.status = StatusCode::Unauthorized_401;
  9379. res.set_content(reject, "text/plain");
  9380. return res.status;
  9381. });
  9382. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9383. res.set_content(accept, "text/plain");
  9384. });
  9385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. thread.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. svr.wait_until_ready();
  9392. {
  9393. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9394. curl_easy_init(), &curl_easy_cleanup};
  9395. ASSERT_NE(curl, nullptr);
  9396. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9397. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9398. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9399. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9400. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9401. &curl_slist_free_all};
  9402. ASSERT_NE(list, nullptr);
  9403. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9404. struct read_data {
  9405. size_t read_size;
  9406. size_t total_size;
  9407. } data = {0, total_size};
  9408. using read_callback_t =
  9409. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9410. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9411. void *userdata) -> size_t {
  9412. read_data *data = (read_data *)userdata;
  9413. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9414. std::fill_n(ptr, size * nmemb, 'A');
  9415. data->read_size += size * nmemb;
  9416. return size * nmemb;
  9417. };
  9418. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9419. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9420. std::vector<char> buffer;
  9421. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9422. using write_callback_t =
  9423. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9424. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9425. void *userdata) -> size_t {
  9426. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9427. buffer->reserve(buffer->size() + size * nmemb + 1);
  9428. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9429. return size * nmemb;
  9430. };
  9431. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9432. {
  9433. const auto res = curl_easy_perform(curl.get());
  9434. ASSERT_EQ(res, CURLE_OK);
  9435. }
  9436. {
  9437. auto response_code = long{};
  9438. const auto res =
  9439. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9440. ASSERT_EQ(res, CURLE_OK);
  9441. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9442. }
  9443. {
  9444. auto dl = curl_off_t{};
  9445. const auto res =
  9446. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9447. ASSERT_EQ(res, CURLE_OK);
  9448. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9449. }
  9450. {
  9451. buffer.push_back('\0');
  9452. ASSERT_STRCASEEQ(buffer.data(), reject);
  9453. }
  9454. }
  9455. }
  9456. #endif
  9457. template <typename S, typename C>
  9458. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9459. svr.Get("/stream", [&](const Request &, Response &res) {
  9460. auto data = new std::string("01234567890123456789");
  9461. res.set_content_provider(
  9462. data->size(), "text/plain",
  9463. [&, data](size_t offset, size_t length, DataSink &sink) {
  9464. const size_t DATA_CHUNK_SIZE = 4;
  9465. const auto &d = *data;
  9466. std::this_thread::sleep_for(std::chrono::seconds(1));
  9467. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9468. return true;
  9469. },
  9470. [data](bool success) {
  9471. EXPECT_FALSE(success);
  9472. delete data;
  9473. });
  9474. });
  9475. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9476. auto i = new size_t(0);
  9477. res.set_content_provider(
  9478. "text/plain",
  9479. [i](size_t, DataSink &sink) {
  9480. if (*i < 5) {
  9481. std::this_thread::sleep_for(std::chrono::seconds(1));
  9482. sink.write("abcd", 4);
  9483. (*i)++;
  9484. } else {
  9485. sink.done();
  9486. }
  9487. return true;
  9488. },
  9489. [i](bool success) {
  9490. EXPECT_FALSE(success);
  9491. delete i;
  9492. });
  9493. });
  9494. svr.Get("/chunked", [&](const Request &, Response &res) {
  9495. auto i = new size_t(0);
  9496. res.set_chunked_content_provider(
  9497. "text/plain",
  9498. [i](size_t, DataSink &sink) {
  9499. if (*i < 5) {
  9500. std::this_thread::sleep_for(std::chrono::seconds(1));
  9501. sink.os << "abcd";
  9502. (*i)++;
  9503. } else {
  9504. sink.done();
  9505. }
  9506. return true;
  9507. },
  9508. [i](bool success) {
  9509. EXPECT_FALSE(success);
  9510. delete i;
  9511. });
  9512. });
  9513. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9514. auto se = detail::scope_exit([&] {
  9515. svr.stop();
  9516. listen_thread.join();
  9517. ASSERT_FALSE(svr.is_running());
  9518. });
  9519. svr.wait_until_ready();
  9520. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9521. {
  9522. auto start = std::chrono::steady_clock::now();
  9523. auto res = cli.Get("/stream");
  9524. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9525. std::chrono::steady_clock::now() - start)
  9526. .count();
  9527. ASSERT_FALSE(res);
  9528. EXPECT_EQ(Error::Read, res.error());
  9529. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9530. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9531. }
  9532. {
  9533. auto start = std::chrono::steady_clock::now();
  9534. auto res = cli.Get("/stream_without_length");
  9535. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9536. std::chrono::steady_clock::now() - start)
  9537. .count();
  9538. ASSERT_FALSE(res);
  9539. EXPECT_EQ(Error::Read, res.error());
  9540. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9541. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9542. }
  9543. {
  9544. auto start = std::chrono::steady_clock::now();
  9545. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9546. EXPECT_EQ("abcd", string(data, data_length));
  9547. return true;
  9548. });
  9549. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9550. std::chrono::steady_clock::now() - start)
  9551. .count();
  9552. ASSERT_FALSE(res);
  9553. EXPECT_EQ(Error::Read, res.error());
  9554. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9555. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9556. }
  9557. }
  9558. TEST(MaxTimeoutTest, ContentStream) {
  9559. time_t timeout = 2000;
  9560. time_t threshold = 200;
  9561. Server svr;
  9562. Client cli("localhost", PORT);
  9563. max_timeout_test(svr, cli, timeout, threshold);
  9564. }
  9565. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9566. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9567. time_t timeout = 2000;
  9568. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9570. SSLClient cli("localhost", PORT);
  9571. cli.enable_server_certificate_verification(false);
  9572. max_timeout_test(svr, cli, timeout, threshold);
  9573. }
  9574. #endif
  9575. class EventDispatcher {
  9576. public:
  9577. EventDispatcher() {}
  9578. bool wait_event(DataSink *sink) {
  9579. unique_lock<mutex> lk(m_);
  9580. int id = id_;
  9581. // Wait with timeout to prevent hanging if client disconnects
  9582. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9583. [&] { return cid_ == id; })) {
  9584. return false; // Timeout occurred
  9585. }
  9586. sink->write(message_.data(), message_.size());
  9587. return true;
  9588. }
  9589. void send_event(const string &message) {
  9590. lock_guard<mutex> lk(m_);
  9591. cid_ = id_++;
  9592. message_ = message;
  9593. cv_.notify_all();
  9594. }
  9595. private:
  9596. mutex m_;
  9597. condition_variable cv_;
  9598. atomic_int id_{0};
  9599. atomic_int cid_{-1};
  9600. string message_;
  9601. };
  9602. TEST(ClientInThreadTest, Issue2068) {
  9603. EventDispatcher ed;
  9604. Server svr;
  9605. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9606. res.set_chunked_content_provider("text/event-stream",
  9607. [&](size_t /*offset*/, DataSink &sink) {
  9608. return ed.wait_event(&sink);
  9609. });
  9610. });
  9611. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9612. svr.wait_until_ready();
  9613. thread event_thread([&] {
  9614. int id = 0;
  9615. while (svr.is_running()) {
  9616. this_thread::sleep_for(chrono::milliseconds(500));
  9617. std::stringstream ss;
  9618. ss << "data: " << id << "\n\n";
  9619. ed.send_event(ss.str());
  9620. id++;
  9621. }
  9622. });
  9623. auto se = detail::scope_exit([&] {
  9624. svr.stop();
  9625. listen_thread.join();
  9626. event_thread.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. {
  9630. auto client = detail::make_unique<Client>(HOST, PORT);
  9631. client->set_read_timeout(std::chrono::minutes(10));
  9632. std::atomic<bool> stop{false};
  9633. std::thread t([&] {
  9634. client->Get("/event1",
  9635. [&](const char *, size_t) -> bool { return !stop; });
  9636. });
  9637. std::this_thread::sleep_for(std::chrono::seconds(2));
  9638. stop = true;
  9639. client->stop();
  9640. t.join();
  9641. // Reset client after thread has finished
  9642. client.reset();
  9643. }
  9644. }
  9645. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9646. Server svr;
  9647. svr.Get("/", [](const Request &req, Response &res) {
  9648. EXPECT_EQ(2U, req.trailers.size());
  9649. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9650. // Denied
  9651. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9652. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9653. // Accepted
  9654. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9655. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9656. EXPECT_TRUE(req.has_trailer("X-World"));
  9657. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9658. res.set_content("ok", "text/plain");
  9659. });
  9660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9661. auto se = detail::scope_exit([&] {
  9662. svr.stop();
  9663. t.join();
  9664. ASSERT_FALSE(svr.is_running());
  9665. });
  9666. svr.wait_until_ready();
  9667. const std::string req = "GET / HTTP/1.1\r\n"
  9668. "Transfer-Encoding: chunked\r\n"
  9669. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9670. "\r\n"
  9671. "0\r\n"
  9672. "Content-Length: 10\r\n"
  9673. "Host: internal.local\r\n"
  9674. "Content-Type: malicious/content\r\n"
  9675. "Cookie: any\r\n"
  9676. "Set-Cookie: any\r\n"
  9677. "X-Forwarded-For: attacker.com\r\n"
  9678. "X-Real-Ip: 1.1.1.1\r\n"
  9679. "X-Hello: hello\r\n"
  9680. "X-World: world\r\n"
  9681. "\r\n";
  9682. std::string res;
  9683. ASSERT_TRUE(send_request(1, req, &res));
  9684. }
  9685. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9686. Server svr;
  9687. std::string observed_remote_addr;
  9688. std::string observed_xff;
  9689. svr.Get("/ip", [&](const Request &req, Response &res) {
  9690. observed_remote_addr = req.remote_addr;
  9691. observed_xff = req.get_header_value("X-Forwarded-For");
  9692. res.set_content("ok", "text/plain");
  9693. });
  9694. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. t.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. Client cli(HOST, PORT);
  9702. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9703. ASSERT_TRUE(res);
  9704. EXPECT_EQ(StatusCode::OK_200, res->status);
  9705. EXPECT_EQ(observed_xff, "203.0.113.66");
  9706. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9707. observed_remote_addr == "127.0.0.1");
  9708. }
  9709. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9710. Server svr;
  9711. svr.set_trusted_proxies({"203.0.113.66"});
  9712. std::string observed_remote_addr;
  9713. std::string observed_xff;
  9714. svr.Get("/ip", [&](const Request &req, Response &res) {
  9715. observed_remote_addr = req.remote_addr;
  9716. observed_xff = req.get_header_value("X-Forwarded-For");
  9717. res.set_content("ok", "text/plain");
  9718. });
  9719. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9720. auto se = detail::scope_exit([&] {
  9721. svr.stop();
  9722. t.join();
  9723. ASSERT_FALSE(svr.is_running());
  9724. });
  9725. svr.wait_until_ready();
  9726. Client cli(HOST, PORT);
  9727. auto res = cli.Get("/ip");
  9728. ASSERT_TRUE(res);
  9729. EXPECT_EQ(StatusCode::OK_200, res->status);
  9730. EXPECT_EQ(observed_xff, "");
  9731. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9732. observed_remote_addr == "127.0.0.1");
  9733. }
  9734. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9735. Server svr;
  9736. svr.set_trusted_proxies({"203.0.113.66"});
  9737. std::string observed_remote_addr;
  9738. std::string observed_xff;
  9739. svr.Get("/ip", [&](const Request &req, Response &res) {
  9740. observed_remote_addr = req.remote_addr;
  9741. observed_xff = req.get_header_value("X-Forwarded-For");
  9742. res.set_content("ok", "text/plain");
  9743. });
  9744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. t.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. Client cli(HOST, PORT);
  9752. auto res =
  9753. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9754. ASSERT_TRUE(res);
  9755. EXPECT_EQ(StatusCode::OK_200, res->status);
  9756. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9757. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9758. }
  9759. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9760. Server svr;
  9761. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9762. std::string observed_remote_addr;
  9763. std::string observed_xff;
  9764. svr.Get("/ip", [&](const Request &req, Response &res) {
  9765. observed_remote_addr = req.remote_addr;
  9766. observed_xff = req.get_header_value("X-Forwarded-For");
  9767. res.set_content("ok", "text/plain");
  9768. });
  9769. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9770. auto se = detail::scope_exit([&] {
  9771. svr.stop();
  9772. t.join();
  9773. ASSERT_FALSE(svr.is_running());
  9774. });
  9775. svr.wait_until_ready();
  9776. Client cli(HOST, PORT);
  9777. auto res = cli.Get(
  9778. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9779. ASSERT_TRUE(res);
  9780. EXPECT_EQ(StatusCode::OK_200, res->status);
  9781. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9782. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9783. }
  9784. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9785. Server svr;
  9786. svr.set_trusted_proxies({"192.0.2.45"});
  9787. std::string observed_remote_addr;
  9788. std::string observed_xff;
  9789. svr.Get("/ip", [&](const Request &req, Response &res) {
  9790. observed_remote_addr = req.remote_addr;
  9791. observed_xff = req.get_header_value("X-Forwarded-For");
  9792. res.set_content("ok", "text/plain");
  9793. });
  9794. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. t.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. Client cli(HOST, PORT);
  9802. auto res =
  9803. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9804. ASSERT_TRUE(res);
  9805. EXPECT_EQ(StatusCode::OK_200, res->status);
  9806. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9807. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9808. }
  9809. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9810. Server svr;
  9811. svr.set_trusted_proxies({"192.0.2.45"});
  9812. std::string observed_remote_addr;
  9813. std::string observed_xff;
  9814. svr.Get("/ip", [&](const Request &req, Response &res) {
  9815. observed_remote_addr = req.remote_addr;
  9816. observed_xff = req.get_header_value("X-Forwarded-For");
  9817. res.set_content("ok", "text/plain");
  9818. });
  9819. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9820. auto se = detail::scope_exit([&] {
  9821. svr.stop();
  9822. t.join();
  9823. ASSERT_FALSE(svr.is_running());
  9824. });
  9825. svr.wait_until_ready();
  9826. Client cli(HOST, PORT);
  9827. auto res = cli.Get(
  9828. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9829. ASSERT_TRUE(res);
  9830. EXPECT_EQ(StatusCode::OK_200, res->status);
  9831. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9832. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9833. }
  9834. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9835. Server svr;
  9836. svr.set_trusted_proxies({"192.0.2.45"});
  9837. std::string observed_remote_addr;
  9838. std::string observed_xff;
  9839. svr.Get("/ip", [&](const Request &req, Response &res) {
  9840. observed_remote_addr = req.remote_addr;
  9841. observed_xff = req.get_header_value("X-Forwarded-For");
  9842. res.set_content("ok", "text/plain");
  9843. });
  9844. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9845. auto se = detail::scope_exit([&] {
  9846. svr.stop();
  9847. t.join();
  9848. ASSERT_FALSE(svr.is_running());
  9849. });
  9850. svr.wait_until_ready();
  9851. std::string raw_req =
  9852. "GET /ip HTTP/1.1\r\n"
  9853. "Host: localhost\r\n"
  9854. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9855. "Connection: close\r\n"
  9856. "\r\n";
  9857. std::string out;
  9858. ASSERT_TRUE(send_request(5, raw_req, &out));
  9859. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9860. // Header parser trims surrounding whitespace of the header value
  9861. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9862. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9863. }
  9864. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9865. Server svr;
  9866. svr.Post("/post", [&](const Request &req, Response &res) {
  9867. res.set_content(req.body, "text/plain");
  9868. });
  9869. svr.Put("/put", [&](const Request &req, Response &res) {
  9870. res.set_content(req.body, "text/plain");
  9871. });
  9872. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9873. res.set_content(req.body, "text/plain");
  9874. });
  9875. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9876. res.set_content(req.body, "text/plain");
  9877. });
  9878. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. t.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. std::string resp;
  9886. // POST without Content-Length
  9887. ASSERT_TRUE(send_request(5,
  9888. "POST /post HTTP/1.1\r\n"
  9889. "Host: localhost\r\n"
  9890. "Connection: close\r\n"
  9891. "\r\n",
  9892. &resp));
  9893. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9894. // PUT without Content-Length
  9895. resp.clear();
  9896. ASSERT_TRUE(send_request(5,
  9897. "PUT /put HTTP/1.1\r\n"
  9898. "Host: localhost\r\n"
  9899. "Connection: close\r\n"
  9900. "\r\n",
  9901. &resp));
  9902. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9903. // PATCH without Content-Length
  9904. resp.clear();
  9905. ASSERT_TRUE(send_request(5,
  9906. "PATCH /patch HTTP/1.1\r\n"
  9907. "Host: localhost\r\n"
  9908. "Connection: close\r\n"
  9909. "\r\n",
  9910. &resp));
  9911. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9912. // DELETE without Content-Length
  9913. resp.clear();
  9914. ASSERT_TRUE(send_request(5,
  9915. "DELETE /delete HTTP/1.1\r\n"
  9916. "Host: localhost\r\n"
  9917. "Connection: close\r\n"
  9918. "\r\n",
  9919. &resp));
  9920. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9921. }
  9922. //==============================================================================
  9923. // open_stream() Tests
  9924. //==============================================================================
  9925. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9926. std::string result;
  9927. char buf[8192];
  9928. ssize_t n;
  9929. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9930. result.append(buf, static_cast<size_t>(n));
  9931. }
  9932. return result;
  9933. }
  9934. // Mock stream for unit tests
  9935. class MockStream : public Stream {
  9936. public:
  9937. std::string data;
  9938. size_t pos = 0;
  9939. ssize_t error_after = -1; // -1 = no error
  9940. explicit MockStream(const std::string &d, ssize_t err = -1)
  9941. : data(d), error_after(err) {}
  9942. bool is_readable() const override { return true; }
  9943. bool wait_readable() const override { return true; }
  9944. bool wait_writable() const override { return true; }
  9945. ssize_t read(char *ptr, size_t size) override {
  9946. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9947. if (pos >= data.size()) return 0;
  9948. size_t limit =
  9949. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9950. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9951. std::memcpy(ptr, data.data() + pos, to_read);
  9952. pos += to_read;
  9953. return static_cast<ssize_t>(to_read);
  9954. }
  9955. ssize_t write(const char *, size_t) override { return -1; }
  9956. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9957. ip = "127.0.0.1";
  9958. port = 0;
  9959. }
  9960. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9961. ip = "127.0.0.1";
  9962. port = 0;
  9963. }
  9964. socket_t socket() const override { return INVALID_SOCKET; }
  9965. time_t duration() const override { return 0; }
  9966. };
  9967. TEST(StreamHandleTest, Basic) {
  9968. ClientImpl::StreamHandle handle;
  9969. EXPECT_FALSE(handle.is_valid());
  9970. handle.response = detail::make_unique<Response>();
  9971. handle.error = Error::Connection;
  9972. EXPECT_FALSE(handle.is_valid());
  9973. handle.error = Error::Success;
  9974. EXPECT_TRUE(handle.is_valid());
  9975. }
  9976. TEST(BodyReaderTest, Basic) {
  9977. MockStream stream("Hello, World!");
  9978. detail::BodyReader reader;
  9979. reader.stream = &stream;
  9980. reader.content_length = 13;
  9981. char buf[32];
  9982. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9983. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9984. EXPECT_TRUE(reader.eof);
  9985. }
  9986. TEST(BodyReaderTest, NoStream) {
  9987. detail::BodyReader reader;
  9988. char buf[32];
  9989. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9990. EXPECT_EQ(Error::Connection, reader.last_error);
  9991. }
  9992. TEST(BodyReaderTest, Error) {
  9993. MockStream stream("Hello, World!", 5);
  9994. detail::BodyReader reader;
  9995. reader.stream = &stream;
  9996. reader.content_length = 13;
  9997. char buf[32];
  9998. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9999. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10000. EXPECT_EQ(Error::Read, reader.last_error);
  10001. }
  10002. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10003. // Mock-based StreamHandle tests relying on private internals are removed.
  10004. class OpenStreamTest : public ::testing::Test {
  10005. protected:
  10006. void SetUp() override {
  10007. svr_.Get("/hello", [](const Request &, Response &res) {
  10008. res.set_content("Hello World!", "text/plain");
  10009. });
  10010. svr_.Get("/large", [](const Request &, Response &res) {
  10011. res.set_content(std::string(10000, 'X'), "text/plain");
  10012. });
  10013. svr_.Get("/chunked", [](const Request &, Response &res) {
  10014. res.set_chunked_content_provider("text/plain",
  10015. [](size_t offset, DataSink &sink) {
  10016. if (offset < 15) {
  10017. sink.write("chunk", 5);
  10018. return true;
  10019. }
  10020. sink.done();
  10021. return true;
  10022. });
  10023. });
  10024. svr_.Get("/compressible", [](const Request &, Response &res) {
  10025. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10026. DataSink &sink) {
  10027. if (offset < 100 * 1024) {
  10028. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10029. sink.write(chunk.data(), chunk.size());
  10030. return true;
  10031. }
  10032. sink.done();
  10033. return true;
  10034. });
  10035. });
  10036. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10037. [](const Request & /*req*/, Response &res) {
  10038. auto i = new int(0);
  10039. res.set_header("Trailer", "Content-Length, X-Allowed");
  10040. res.set_chunked_content_provider(
  10041. "text/plain",
  10042. [i](size_t /*offset*/, DataSink &sink) {
  10043. switch (*i) {
  10044. case 0: sink.os << "123"; break;
  10045. case 1: sink.os << "456"; break;
  10046. case 2: sink.os << "789"; break;
  10047. case 3: {
  10048. sink.done_with_trailer(
  10049. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10050. } break;
  10051. }
  10052. (*i)++;
  10053. return true;
  10054. },
  10055. [i](bool success) {
  10056. EXPECT_TRUE(success);
  10057. delete i;
  10058. });
  10059. });
  10060. // Echo headers endpoint for header-related tests
  10061. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10062. std::string body;
  10063. for (const auto &h : req.headers) {
  10064. body.append(h.first);
  10065. body.push_back(':');
  10066. body.append(h.second);
  10067. body.push_back('\n');
  10068. }
  10069. res.set_content(body, "text/plain");
  10070. });
  10071. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10072. std::string body;
  10073. for (const auto &h : req.headers) {
  10074. body.append(h.first);
  10075. body.push_back(':');
  10076. body.append(h.second);
  10077. body.push_back('\n');
  10078. }
  10079. res.set_content(body, "text/plain");
  10080. });
  10081. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10082. svr_.wait_until_ready();
  10083. }
  10084. void TearDown() override {
  10085. svr_.stop();
  10086. if (thread_.joinable()) thread_.join();
  10087. }
  10088. Server svr_;
  10089. std::thread thread_;
  10090. };
  10091. TEST_F(OpenStreamTest, Basic) {
  10092. Client cli("127.0.0.1", 8787);
  10093. auto handle = cli.open_stream("GET", "/hello");
  10094. EXPECT_TRUE(handle.is_valid());
  10095. EXPECT_EQ("Hello World!", read_all(handle));
  10096. }
  10097. TEST_F(OpenStreamTest, SmallBuffer) {
  10098. Client cli("127.0.0.1", 8787);
  10099. auto handle = cli.open_stream("GET", "/hello");
  10100. std::string result;
  10101. char buf[4];
  10102. ssize_t n;
  10103. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10104. result.append(buf, static_cast<size_t>(n));
  10105. EXPECT_EQ("Hello World!", result);
  10106. }
  10107. TEST_F(OpenStreamTest, DefaultHeaders) {
  10108. Client cli("127.0.0.1", 8787);
  10109. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10110. {
  10111. auto handle = cli.open_stream("GET", "/echo-headers");
  10112. ASSERT_TRUE(handle.is_valid());
  10113. auto body = read_all(handle);
  10114. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10115. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10116. std::string::npos);
  10117. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10118. }
  10119. // open_stream POST with body and no explicit content_type should NOT add
  10120. // text/plain Content-Type (behavior differs from non-streaming path), but
  10121. // should include Content-Length
  10122. {
  10123. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10124. ASSERT_TRUE(handle.is_valid());
  10125. auto body = read_all(handle);
  10126. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10127. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10128. }
  10129. // open_stream POST with explicit Content-Type should preserve it
  10130. {
  10131. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10132. {{"Content-Type", "application/custom"}},
  10133. "{}", "application/custom");
  10134. ASSERT_TRUE(handle.is_valid());
  10135. auto body = read_all(handle);
  10136. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10137. }
  10138. // User-specified User-Agent must not be overwritten for stream API
  10139. {
  10140. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10141. {{"User-Agent", "MyAgent/1.2"}});
  10142. ASSERT_TRUE(handle.is_valid());
  10143. auto body = read_all(handle);
  10144. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10145. }
  10146. }
  10147. TEST_F(OpenStreamTest, Large) {
  10148. Client cli("127.0.0.1", 8787);
  10149. auto handle = cli.open_stream("GET", "/large");
  10150. EXPECT_EQ(10000u, read_all(handle).size());
  10151. }
  10152. TEST_F(OpenStreamTest, ConnectionError) {
  10153. Client cli("127.0.0.1", 9999);
  10154. auto handle = cli.open_stream("GET", "/hello");
  10155. EXPECT_FALSE(handle.is_valid());
  10156. }
  10157. TEST_F(OpenStreamTest, Chunked) {
  10158. Client cli("127.0.0.1", 8787);
  10159. auto handle = cli.open_stream("GET", "/chunked");
  10160. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10161. "Transfer-Encoding") == "chunked");
  10162. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10163. }
  10164. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10165. Client cli("127.0.0.1", 8787);
  10166. auto handle =
  10167. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10168. ASSERT_TRUE(handle.is_valid());
  10169. // Consume body to allow trailers to be received/parsed
  10170. auto body = read_all(handle);
  10171. // Explicitly parse trailers (ensure trailers are available for assertion)
  10172. handle.parse_trailers_if_needed();
  10173. EXPECT_EQ(std::string("123456789"), body);
  10174. // The response should include a Trailer header declaring both names
  10175. ASSERT_TRUE(handle.response);
  10176. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10177. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10178. handle.response->get_header_value("Trailer"));
  10179. // Prohibited trailer must not be present
  10180. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10181. // Allowed trailer should be present
  10182. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10183. EXPECT_EQ(std::string("yes"),
  10184. handle.response->get_trailer_value("X-Allowed"));
  10185. // Verify trailers are NOT present as regular headers
  10186. EXPECT_EQ(std::string(""),
  10187. handle.response->get_header_value("Content-Length"));
  10188. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10189. }
  10190. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10191. TEST_F(OpenStreamTest, Gzip) {
  10192. Client cli("127.0.0.1", 8787);
  10193. auto handle = cli.open_stream("GET", "/compressible", {},
  10194. {{"Accept-Encoding", "gzip"}});
  10195. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10196. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10197. }
  10198. #endif
  10199. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10200. TEST_F(OpenStreamTest, Brotli) {
  10201. Client cli("127.0.0.1", 8787);
  10202. auto handle =
  10203. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10204. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10205. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10206. }
  10207. #endif
  10208. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10209. TEST_F(OpenStreamTest, Zstd) {
  10210. Client cli("127.0.0.1", 8787);
  10211. auto handle = cli.open_stream("GET", "/compressible", {},
  10212. {{"Accept-Encoding", "zstd"}});
  10213. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10214. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10215. }
  10216. #endif
  10217. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10218. class SSLOpenStreamTest : public ::testing::Test {
  10219. protected:
  10220. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10221. void SetUp() override {
  10222. svr_.Get("/hello", [](const Request &, Response &res) {
  10223. res.set_content("Hello SSL World!", "text/plain");
  10224. });
  10225. svr_.Get("/chunked", [](const Request &, Response &res) {
  10226. res.set_chunked_content_provider("text/plain",
  10227. [](size_t offset, DataSink &sink) {
  10228. if (offset < 15) {
  10229. sink.write("chunk", 5);
  10230. return true;
  10231. }
  10232. sink.done();
  10233. return true;
  10234. });
  10235. });
  10236. svr_.Post("/echo", [](const Request &req, Response &res) {
  10237. res.set_content(req.body, req.get_header_value("Content-Type"));
  10238. });
  10239. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10240. std::string body = req.body;
  10241. res.set_chunked_content_provider(
  10242. "text/plain", [body](size_t offset, DataSink &sink) {
  10243. if (offset < body.size()) {
  10244. sink.write(body.data() + offset, body.size() - offset);
  10245. }
  10246. sink.done();
  10247. return true;
  10248. });
  10249. });
  10250. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10251. svr_.wait_until_ready();
  10252. }
  10253. void TearDown() override {
  10254. svr_.stop();
  10255. if (thread_.joinable()) thread_.join();
  10256. }
  10257. SSLServer svr_;
  10258. std::thread thread_;
  10259. };
  10260. TEST_F(SSLOpenStreamTest, Basic) {
  10261. SSLClient cli("127.0.0.1", 8788);
  10262. cli.enable_server_certificate_verification(false);
  10263. auto handle = cli.open_stream("GET", "/hello");
  10264. ASSERT_TRUE(handle.is_valid());
  10265. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10266. }
  10267. TEST_F(SSLOpenStreamTest, Chunked) {
  10268. SSLClient cli("127.0.0.1", 8788);
  10269. cli.enable_server_certificate_verification(false);
  10270. auto handle = cli.open_stream("GET", "/chunked");
  10271. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10272. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10273. "Transfer-Encoding") == "chunked");
  10274. auto body = read_all(handle);
  10275. EXPECT_EQ("chunkchunkchunk", body);
  10276. }
  10277. TEST_F(SSLOpenStreamTest, Post) {
  10278. SSLClient cli("127.0.0.1", 8788);
  10279. cli.enable_server_certificate_verification(false);
  10280. auto handle =
  10281. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10282. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10283. EXPECT_EQ(200, handle.response->status);
  10284. auto body = read_all(handle);
  10285. EXPECT_EQ("Hello SSL POST", body);
  10286. }
  10287. TEST_F(SSLOpenStreamTest, PostChunked) {
  10288. SSLClient cli("127.0.0.1", 8788);
  10289. cli.enable_server_certificate_verification(false);
  10290. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10291. "Chunked SSL Data", "text/plain");
  10292. ASSERT_TRUE(handle.is_valid());
  10293. EXPECT_EQ(200, handle.response->status);
  10294. auto body = read_all(handle);
  10295. EXPECT_EQ("Chunked SSL Data", body);
  10296. }
  10297. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10298. //==============================================================================
  10299. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10300. // results for various scenarios.
  10301. //==============================================================================
  10302. TEST(ParityTest, GetVsOpenStream) {
  10303. Server svr;
  10304. const std::string path = "/parity";
  10305. const std::string content = "Parity test content: hello world";
  10306. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10307. res.set_content(content, "text/plain");
  10308. });
  10309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10310. auto se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. t.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli(HOST, PORT);
  10317. // Non-stream path
  10318. auto r1 = cli.Get(path);
  10319. ASSERT_TRUE(r1);
  10320. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10321. // Stream path
  10322. auto h = cli.open_stream("GET", path);
  10323. ASSERT_TRUE(h.is_valid());
  10324. EXPECT_EQ(r1->body, read_all(h));
  10325. }
  10326. // Helper to compress data with provided compressor type T
  10327. template <typename Compressor>
  10328. static std::string compress_payload_for_parity(const std::string &in) {
  10329. std::string out;
  10330. Compressor compressor;
  10331. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10332. [&](const char *data, size_t n) {
  10333. out.append(data, n);
  10334. return true;
  10335. });
  10336. EXPECT_TRUE(ok);
  10337. return out;
  10338. }
  10339. // Helper function for compression parity tests
  10340. template <typename Compressor>
  10341. static void test_compression_parity(const std::string &original,
  10342. const std::string &path,
  10343. const std::string &encoding) {
  10344. const std::string compressed =
  10345. compress_payload_for_parity<Compressor>(original);
  10346. Server svr;
  10347. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10348. res.set_content(compressed, "application/octet-stream");
  10349. res.set_header("Content-Encoding", encoding);
  10350. });
  10351. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10352. auto se = detail::scope_exit([&] {
  10353. svr.stop();
  10354. t.join();
  10355. ASSERT_FALSE(svr.is_running());
  10356. });
  10357. svr.wait_until_ready();
  10358. Client cli(HOST, PORT);
  10359. // Non-streaming
  10360. {
  10361. auto res = cli.Get(path);
  10362. ASSERT_TRUE(res);
  10363. EXPECT_EQ(StatusCode::OK_200, res->status);
  10364. EXPECT_EQ(original, res->body);
  10365. }
  10366. // Streaming
  10367. {
  10368. auto h = cli.open_stream("GET", path);
  10369. ASSERT_TRUE(h.is_valid());
  10370. EXPECT_EQ(original, read_all(h));
  10371. }
  10372. }
  10373. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10374. TEST(ParityTest, Gzip) {
  10375. test_compression_parity<detail::gzip_compressor>(
  10376. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10377. }
  10378. #endif
  10379. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10380. TEST(ParityTest, Brotli) {
  10381. test_compression_parity<detail::brotli_compressor>(
  10382. "Hello, brotli parity test payload", "/parity-br", "br");
  10383. }
  10384. #endif
  10385. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10386. TEST(ParityTest, Zstd) {
  10387. test_compression_parity<detail::zstd_compressor>(
  10388. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10389. }
  10390. #endif
  10391. //==============================================================================
  10392. // New Stream API Tests
  10393. //==============================================================================
  10394. inline std::string read_body(httplib::stream::Result &result) {
  10395. std::string body;
  10396. while (result.next()) {
  10397. body.append(result.data(), result.size());
  10398. }
  10399. return body;
  10400. }
  10401. TEST(ClientConnectionTest, Basic) {
  10402. httplib::ClientConnection conn;
  10403. EXPECT_FALSE(conn.is_open());
  10404. conn.sock = 1;
  10405. EXPECT_TRUE(conn.is_open());
  10406. httplib::ClientConnection conn2(std::move(conn));
  10407. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10408. conn2.sock = INVALID_SOCKET;
  10409. }
  10410. // Unified test server for all stream::* tests
  10411. class StreamApiTest : public ::testing::Test {
  10412. protected:
  10413. void SetUp() override {
  10414. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10415. res.set_content("Hello World!", "text/plain");
  10416. });
  10417. svr_.Get("/echo-params",
  10418. [](const httplib::Request &req, httplib::Response &res) {
  10419. std::string r;
  10420. for (const auto &p : req.params) {
  10421. if (!r.empty()) r += "&";
  10422. r += p.first + "=" + p.second;
  10423. }
  10424. res.set_content(r, "text/plain");
  10425. });
  10426. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10427. res.set_content(req.body, req.get_header_value("Content-Type"));
  10428. });
  10429. svr_.Post("/echo-headers",
  10430. [](const httplib::Request &req, httplib::Response &res) {
  10431. std::string r;
  10432. for (const auto &h : req.headers)
  10433. r += h.first + ": " + h.second + "\n";
  10434. res.set_content(r, "text/plain");
  10435. });
  10436. svr_.Post("/echo-params",
  10437. [](const httplib::Request &req, httplib::Response &res) {
  10438. std::string r = "params:";
  10439. for (const auto &p : req.params)
  10440. r += p.first + "=" + p.second + ";";
  10441. res.set_content(r + " body:" + req.body, "text/plain");
  10442. });
  10443. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10444. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10445. });
  10446. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10447. res.set_content("PUT:" + req.body, "text/plain");
  10448. });
  10449. svr_.Patch("/echo",
  10450. [](const httplib::Request &req, httplib::Response &res) {
  10451. res.set_content("PATCH:" + req.body, "text/plain");
  10452. });
  10453. svr_.Delete(
  10454. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10455. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10456. "text/plain");
  10457. });
  10458. svr_.Get("/head-test",
  10459. [](const httplib::Request &, httplib::Response &res) {
  10460. res.set_content("body for HEAD", "text/plain");
  10461. });
  10462. svr_.Options("/options",
  10463. [](const httplib::Request &, httplib::Response &res) {
  10464. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10465. });
  10466. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10467. svr_.wait_until_ready();
  10468. }
  10469. void TearDown() override {
  10470. svr_.stop();
  10471. if (thread_.joinable()) thread_.join();
  10472. }
  10473. httplib::Server svr_;
  10474. std::thread thread_;
  10475. };
  10476. // stream::Get tests
  10477. TEST_F(StreamApiTest, GetBasic) {
  10478. httplib::Client cli(HOST, PORT);
  10479. auto result = httplib::stream::Get(cli, "/hello");
  10480. ASSERT_TRUE(result.is_valid());
  10481. EXPECT_EQ(200, result.status());
  10482. EXPECT_EQ("Hello World!", read_body(result));
  10483. }
  10484. TEST_F(StreamApiTest, GetWithParams) {
  10485. httplib::Client cli(HOST, PORT);
  10486. httplib::Params params{{"foo", "bar"}};
  10487. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10488. ASSERT_TRUE(result.is_valid());
  10489. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10490. }
  10491. TEST_F(StreamApiTest, GetConnectionError) {
  10492. httplib::Client cli(HOST, 9999);
  10493. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10494. }
  10495. TEST_F(StreamApiTest, Get404) {
  10496. httplib::Client cli(HOST, PORT);
  10497. auto result = httplib::stream::Get(cli, "/nonexistent");
  10498. EXPECT_TRUE(result.is_valid());
  10499. EXPECT_EQ(404, result.status());
  10500. }
  10501. // stream::Post tests
  10502. TEST_F(StreamApiTest, PostBasic) {
  10503. httplib::Client cli(HOST, PORT);
  10504. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10505. "application/json");
  10506. ASSERT_TRUE(result.is_valid());
  10507. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10508. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10509. }
  10510. TEST_F(StreamApiTest, PostWithHeaders) {
  10511. httplib::Client cli(HOST, PORT);
  10512. httplib::Headers headers{{"X-Custom", "value"}};
  10513. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10514. "text/plain");
  10515. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10516. }
  10517. TEST_F(StreamApiTest, PostWithParams) {
  10518. httplib::Client cli(HOST, PORT);
  10519. httplib::Params params{{"k", "v"}};
  10520. auto result =
  10521. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10522. auto body = read_body(result);
  10523. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10524. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10525. }
  10526. TEST_F(StreamApiTest, PostLarge) {
  10527. httplib::Client cli(HOST, PORT);
  10528. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10529. size_t total = 0;
  10530. while (result.next()) {
  10531. total += result.size();
  10532. }
  10533. EXPECT_EQ(100u * 1024u, total);
  10534. }
  10535. // stream::Put/Patch tests
  10536. TEST_F(StreamApiTest, PutAndPatch) {
  10537. httplib::Client cli(HOST, PORT);
  10538. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10539. EXPECT_EQ("PUT:test", read_body(put));
  10540. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10541. EXPECT_EQ("PATCH:test", read_body(patch));
  10542. }
  10543. // stream::Delete tests
  10544. TEST_F(StreamApiTest, Delete) {
  10545. httplib::Client cli(HOST, PORT);
  10546. auto del1 = httplib::stream::Delete(cli, "/resource");
  10547. EXPECT_EQ("Deleted", read_body(del1));
  10548. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10549. EXPECT_EQ("Deleted:data", read_body(del2));
  10550. }
  10551. // stream::Head/Options tests
  10552. TEST_F(StreamApiTest, HeadAndOptions) {
  10553. httplib::Client cli(HOST, PORT);
  10554. auto head = httplib::stream::Head(cli, "/head-test");
  10555. EXPECT_TRUE(head.is_valid());
  10556. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10557. auto opts = httplib::stream::Options(cli, "/options");
  10558. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10559. }
  10560. // SSL stream::* tests
  10561. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10562. class SSLStreamApiTest : public ::testing::Test {
  10563. protected:
  10564. void SetUp() override {
  10565. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10566. res.set_content("Hello SSL!", "text/plain");
  10567. });
  10568. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10569. res.set_content(req.body, "text/plain");
  10570. });
  10571. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10572. svr_.wait_until_ready();
  10573. }
  10574. void TearDown() override {
  10575. svr_.stop();
  10576. if (thread_.joinable()) thread_.join();
  10577. }
  10578. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10579. std::thread thread_;
  10580. };
  10581. TEST_F(SSLStreamApiTest, GetAndPost) {
  10582. httplib::SSLClient cli("127.0.0.1", 8803);
  10583. cli.enable_server_certificate_verification(false);
  10584. auto get = httplib::stream::Get(cli, "/hello");
  10585. EXPECT_EQ("Hello SSL!", read_body(get));
  10586. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10587. EXPECT_EQ("test", read_body(post));
  10588. }
  10589. #endif
  10590. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10591. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10592. // BodyReader
  10593. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10594. // Test that read timeout during streaming is detected
  10595. // Use a large content-length response where server delays mid-stream
  10596. Server svr;
  10597. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10598. // Send a large response with delay in the middle
  10599. res.set_content_provider(
  10600. 1000, // content_length
  10601. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10602. if (offset < 100) {
  10603. // Send first 100 bytes immediately
  10604. std::string data(100, 'A');
  10605. sink.write(data.c_str(), data.size());
  10606. return true;
  10607. }
  10608. // Then delay longer than client timeout
  10609. std::this_thread::sleep_for(std::chrono::seconds(3));
  10610. std::string data(900, 'B');
  10611. sink.write(data.c_str(), data.size());
  10612. return true;
  10613. });
  10614. });
  10615. auto port = 8091;
  10616. std::thread t([&]() { svr.listen("localhost", port); });
  10617. svr.wait_until_ready();
  10618. Client cli("localhost", port);
  10619. cli.set_read_timeout(1, 0); // 1 second timeout
  10620. auto handle = cli.open_stream("GET", "/slow-stream");
  10621. ASSERT_TRUE(handle.is_valid());
  10622. char buf[256];
  10623. ssize_t total = 0;
  10624. ssize_t n;
  10625. bool got_error = false;
  10626. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10627. total += n;
  10628. }
  10629. if (n < 0) {
  10630. got_error = true;
  10631. // Should be timeout or read error
  10632. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10633. handle.get_read_error() == Error::Read)
  10634. << "Actual error: " << to_string(handle.get_read_error());
  10635. }
  10636. // Either we got an error, or we got less data than expected
  10637. EXPECT_TRUE(got_error || total < 1000)
  10638. << "Expected timeout but got all " << total << " bytes";
  10639. svr.stop();
  10640. t.join();
  10641. }
  10642. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10643. // Test connection closed detection via BodyReader
  10644. Server svr;
  10645. std::atomic<bool> close_now{false};
  10646. svr.Get("/will-close", [&](const Request &, Response &res) {
  10647. res.set_content_provider(
  10648. 10000, // Large content_length that we won't fully send
  10649. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10650. if (offset < 100) {
  10651. std::string data(100, 'X');
  10652. sink.write(data.c_str(), data.size());
  10653. return true;
  10654. }
  10655. // Wait for signal then abort
  10656. while (!close_now) {
  10657. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10658. }
  10659. return false; // Abort - server will close connection
  10660. });
  10661. });
  10662. auto port = 8092;
  10663. std::thread t([&]() { svr.listen("localhost", port); });
  10664. svr.wait_until_ready();
  10665. Client cli("localhost", port);
  10666. auto handle = cli.open_stream("GET", "/will-close");
  10667. ASSERT_TRUE(handle.is_valid());
  10668. char buf[256];
  10669. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10670. EXPECT_GT(n, 0) << "First read should succeed";
  10671. // Signal server to close
  10672. close_now = true;
  10673. // Keep reading until error or EOF
  10674. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10675. // Keep reading
  10676. }
  10677. // Should get an error since content_length wasn't satisfied
  10678. if (n < 0) {
  10679. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10680. handle.get_read_error() == Error::Read)
  10681. << "Actual error: " << to_string(handle.get_read_error());
  10682. }
  10683. svr.stop();
  10684. t.join();
  10685. }
  10686. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10687. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10688. // Test that read timeout during SSL streaming is detected
  10689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10690. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10691. res.set_content_provider(
  10692. 1000, "text/plain",
  10693. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10694. if (offset < 100) {
  10695. std::string data(100, 'A');
  10696. sink.write(data.c_str(), data.size());
  10697. return true;
  10698. }
  10699. std::this_thread::sleep_for(std::chrono::seconds(3));
  10700. std::string data(900, 'B');
  10701. sink.write(data.c_str(), data.size());
  10702. return true;
  10703. });
  10704. });
  10705. auto port = 8093;
  10706. std::thread t([&]() { svr.listen("localhost", port); });
  10707. svr.wait_until_ready();
  10708. SSLClient cli("localhost", port);
  10709. cli.enable_server_certificate_verification(false);
  10710. cli.set_read_timeout(1, 0); // 1 second timeout
  10711. auto handle = cli.open_stream("GET", "/slow-stream");
  10712. ASSERT_TRUE(handle.is_valid());
  10713. char buf[256];
  10714. ssize_t total = 0;
  10715. ssize_t n;
  10716. bool got_error = false;
  10717. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10718. total += n;
  10719. }
  10720. if (n < 0) {
  10721. got_error = true;
  10722. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10723. handle.get_read_error() == Error::Read)
  10724. << "Actual error: " << to_string(handle.get_read_error());
  10725. }
  10726. EXPECT_TRUE(got_error || total < 1000)
  10727. << "Expected timeout but got all " << total << " bytes";
  10728. svr.stop();
  10729. t.join();
  10730. }
  10731. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10732. // Test SSL connection closed detection
  10733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10734. std::atomic<bool> close_now{false};
  10735. svr.Get("/will-close", [&](const Request &, Response &res) {
  10736. res.set_content_provider(
  10737. 10000, "text/plain",
  10738. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10739. if (offset < 100) {
  10740. std::string data(100, 'X');
  10741. sink.write(data.c_str(), data.size());
  10742. return true;
  10743. }
  10744. while (!close_now) {
  10745. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10746. }
  10747. return false;
  10748. });
  10749. });
  10750. auto port = 8094;
  10751. std::thread t([&]() { svr.listen("localhost", port); });
  10752. svr.wait_until_ready();
  10753. SSLClient cli("localhost", port);
  10754. cli.enable_server_certificate_verification(false);
  10755. auto handle = cli.open_stream("GET", "/will-close");
  10756. ASSERT_TRUE(handle.is_valid());
  10757. char buf[256];
  10758. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10759. EXPECT_GT(n, 0);
  10760. // Signal server to close
  10761. close_now = true;
  10762. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10763. // Keep reading
  10764. }
  10765. if (n < 0) {
  10766. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10767. handle.get_read_error() == Error::Read)
  10768. << "Actual error: " << to_string(handle.get_read_error());
  10769. }
  10770. svr.stop();
  10771. t.join();
  10772. }
  10773. #endif
  10774. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10775. using namespace httplib;
  10776. // Create a test file
  10777. const char *fname = "etag_testfile.txt";
  10778. const char *content = "etag-content";
  10779. {
  10780. std::ofstream ofs(fname);
  10781. ofs << content;
  10782. ASSERT_TRUE(ofs.good());
  10783. }
  10784. Server svr;
  10785. svr.set_mount_point("/static", ".");
  10786. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, PORT);
  10789. // First request: should get 200 with ETag header
  10790. auto res1 = cli.Get("/static/etag_testfile.txt");
  10791. ASSERT_TRUE(res1);
  10792. ASSERT_EQ(200, res1->status);
  10793. ASSERT_TRUE(res1->has_header("ETag"));
  10794. std::string etag = res1->get_header_value("ETag");
  10795. EXPECT_FALSE(etag.empty());
  10796. // Verify ETag format: W/"hex-hex"
  10797. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10798. EXPECT_EQ('W', etag[0]);
  10799. EXPECT_EQ('/', etag[1]);
  10800. EXPECT_EQ('"', etag[2]);
  10801. EXPECT_EQ('"', etag.back());
  10802. // Exact match: expect 304 Not Modified
  10803. Headers h2 = {{"If-None-Match", etag}};
  10804. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10805. ASSERT_TRUE(res2);
  10806. EXPECT_EQ(304, res2->status);
  10807. // Wildcard match: expect 304 Not Modified
  10808. Headers h3 = {{"If-None-Match", "*"}};
  10809. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10810. ASSERT_TRUE(res3);
  10811. EXPECT_EQ(304, res3->status);
  10812. // Non-matching ETag: expect 200
  10813. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10814. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10815. ASSERT_TRUE(res4);
  10816. EXPECT_EQ(200, res4->status);
  10817. // Multiple ETags with one matching: expect 304
  10818. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10819. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10820. ASSERT_TRUE(res5);
  10821. EXPECT_EQ(304, res5->status);
  10822. svr.stop();
  10823. t.join();
  10824. std::remove(fname);
  10825. }
  10826. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10827. using namespace httplib;
  10828. Server svr;
  10829. svr.set_mount_point("/static", ".");
  10830. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. // Send If-None-Match: * to a non-existent file
  10834. Headers h = {{"If-None-Match", "*"}};
  10835. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10836. ASSERT_TRUE(res);
  10837. EXPECT_EQ(404, res->status);
  10838. svr.stop();
  10839. t.join();
  10840. }
  10841. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10842. using namespace httplib;
  10843. // Create a test file
  10844. const char *fname = "ims_testfile.txt";
  10845. const char *content = "if-modified-since-test";
  10846. {
  10847. std::ofstream ofs(fname);
  10848. ofs << content;
  10849. ASSERT_TRUE(ofs.good());
  10850. }
  10851. Server svr;
  10852. svr.set_mount_point("/static", ".");
  10853. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10854. svr.wait_until_ready();
  10855. Client cli(HOST, PORT);
  10856. // First request: should get 200 with Last-Modified header
  10857. auto res1 = cli.Get("/static/ims_testfile.txt");
  10858. ASSERT_TRUE(res1);
  10859. ASSERT_EQ(200, res1->status);
  10860. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10861. std::string last_modified = res1->get_header_value("Last-Modified");
  10862. EXPECT_FALSE(last_modified.empty());
  10863. // If-Modified-Since with same time: expect 304
  10864. Headers h2 = {{"If-Modified-Since", last_modified}};
  10865. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10866. ASSERT_TRUE(res2);
  10867. EXPECT_EQ(304, res2->status);
  10868. // If-Modified-Since with future time: expect 304
  10869. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10870. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10871. ASSERT_TRUE(res3);
  10872. EXPECT_EQ(304, res3->status);
  10873. // If-Modified-Since with past time: expect 200
  10874. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10875. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10876. ASSERT_TRUE(res4);
  10877. EXPECT_EQ(200, res4->status);
  10878. // If-None-Match takes precedence over If-Modified-Since
  10879. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10880. ASSERT_TRUE(res1->has_header("ETag"));
  10881. std::string etag = res1->get_header_value("ETag");
  10882. Headers h5 = {{"If-None-Match", etag},
  10883. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10884. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10885. ASSERT_TRUE(res5);
  10886. EXPECT_EQ(304, res5->status);
  10887. svr.stop();
  10888. t.join();
  10889. std::remove(fname);
  10890. }
  10891. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10892. using namespace httplib;
  10893. Server svr;
  10894. // Endpoint that returns compressible content
  10895. svr.Get("/compressible", [](const Request &, Response &res) {
  10896. // Return a large enough body to trigger compression
  10897. std::string body(1000, 'a');
  10898. res.set_content(body, "text/plain");
  10899. });
  10900. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10901. svr.wait_until_ready();
  10902. Client cli(HOST, PORT);
  10903. // Request with gzip support: should get Vary header when compressed
  10904. cli.set_compress(true);
  10905. auto res1 = cli.Get("/compressible");
  10906. ASSERT_TRUE(res1);
  10907. EXPECT_EQ(200, res1->status);
  10908. // If Content-Encoding is set, Vary should also be set
  10909. if (res1->has_header("Content-Encoding")) {
  10910. EXPECT_TRUE(res1->has_header("Vary"));
  10911. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10912. }
  10913. // Request without Accept-Encoding header: should not have compression
  10914. Headers h_no_compress;
  10915. auto res2 = cli.Get("/compressible", h_no_compress);
  10916. ASSERT_TRUE(res2);
  10917. EXPECT_EQ(200, res2->status);
  10918. // Verify Vary header is present when compression is applied
  10919. // (the exact behavior depends on server configuration)
  10920. svr.stop();
  10921. t.join();
  10922. }
  10923. TEST(ETagTest, IfRangeWithETag) {
  10924. using namespace httplib;
  10925. // Create a test file with known content
  10926. const char *fname = "if_range_testfile.txt";
  10927. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10928. {
  10929. std::ofstream ofs(fname);
  10930. ofs << content;
  10931. ASSERT_TRUE(ofs.good());
  10932. }
  10933. Server svr;
  10934. svr.set_mount_point("/static", ".");
  10935. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10936. svr.wait_until_ready();
  10937. Client cli(HOST, PORT);
  10938. // First request: get ETag
  10939. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10940. ASSERT_TRUE(res1);
  10941. ASSERT_EQ(200, res1->status);
  10942. ASSERT_TRUE(res1->has_header("ETag"));
  10943. std::string etag = res1->get_header_value("ETag");
  10944. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10945. // Since our server generates weak ETags (W/"..."), If-Range with our
  10946. // ETag should NOT result in partial content - it should return full content.
  10947. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10948. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10949. ASSERT_TRUE(res2);
  10950. // Weak ETag in If-Range -> full content (200), not partial (206)
  10951. EXPECT_EQ(200, res2->status);
  10952. EXPECT_EQ(content, res2->body);
  10953. EXPECT_FALSE(res2->has_header("Content-Range"));
  10954. // Range request with non-matching If-Range (ETag): should get 200 (full
  10955. // content)
  10956. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10957. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10958. ASSERT_TRUE(res3);
  10959. EXPECT_EQ(200, res3->status);
  10960. EXPECT_EQ(content, res3->body);
  10961. EXPECT_FALSE(res3->has_header("Content-Range"));
  10962. // Range request with strong ETag (hypothetical - our server doesn't generate
  10963. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10964. // should return full content)
  10965. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10966. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10967. ASSERT_TRUE(res4);
  10968. EXPECT_EQ(200, res4->status);
  10969. EXPECT_EQ(content, res4->body);
  10970. EXPECT_FALSE(res4->has_header("Content-Range"));
  10971. svr.stop();
  10972. t.join();
  10973. std::remove(fname);
  10974. }
  10975. TEST(ETagTest, IfRangeWithDate) {
  10976. using namespace httplib;
  10977. // Create a test file
  10978. const char *fname = "if_range_date_testfile.txt";
  10979. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10980. {
  10981. std::ofstream ofs(fname);
  10982. ofs << content;
  10983. ASSERT_TRUE(ofs.good());
  10984. }
  10985. Server svr;
  10986. svr.set_mount_point("/static", ".");
  10987. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10988. svr.wait_until_ready();
  10989. Client cli(HOST, PORT);
  10990. // First request: get Last-Modified
  10991. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10992. ASSERT_TRUE(res1);
  10993. ASSERT_EQ(200, res1->status);
  10994. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10995. std::string last_modified = res1->get_header_value("Last-Modified");
  10996. // Range request with matching If-Range (date): should get 206
  10997. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10998. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10999. ASSERT_TRUE(res2);
  11000. EXPECT_EQ(206, res2->status);
  11001. EXPECT_EQ("FGHIJ", res2->body);
  11002. // Range request with old If-Range date: should get 200 (full content)
  11003. Headers h3 = {{"Range", "bytes=5-9"},
  11004. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11005. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11006. ASSERT_TRUE(res3);
  11007. EXPECT_EQ(200, res3->status);
  11008. EXPECT_EQ(content, res3->body);
  11009. // Range request with future If-Range date: should get 206
  11010. Headers h4 = {{"Range", "bytes=0-4"},
  11011. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11012. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11013. ASSERT_TRUE(res4);
  11014. EXPECT_EQ(206, res4->status);
  11015. EXPECT_EQ("ABCDE", res4->body);
  11016. svr.stop();
  11017. t.join();
  11018. std::remove(fname);
  11019. }
  11020. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11021. using namespace httplib;
  11022. const char *fname = "etag_malformed.txt";
  11023. const char *content = "malformed-etag";
  11024. {
  11025. std::ofstream ofs(fname);
  11026. ofs << content;
  11027. ASSERT_TRUE(ofs.good());
  11028. }
  11029. Server svr;
  11030. svr.set_mount_point("/static", ".");
  11031. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11032. svr.wait_until_ready();
  11033. Client cli(HOST, PORT);
  11034. // baseline: should get 200 and an ETag
  11035. auto res1 = cli.Get("/static/etag_malformed.txt");
  11036. ASSERT_TRUE(res1);
  11037. ASSERT_EQ(200, res1->status);
  11038. ASSERT_TRUE(res1->has_header("ETag"));
  11039. // Malformed ETag value (missing quotes) should be treated as non-matching
  11040. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11041. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11042. ASSERT_TRUE(res_bad);
  11043. EXPECT_EQ(200, res_bad->status);
  11044. // Whitespace-only header value should be considered invalid / non-matching
  11045. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11046. "Host: localhost\r\n"
  11047. "If-None-Match: \r\n"
  11048. "Connection: close\r\n"
  11049. "\r\n";
  11050. std::string out;
  11051. ASSERT_TRUE(send_request(5, raw_req, &out));
  11052. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11053. svr.stop();
  11054. t.join();
  11055. std::remove(fname);
  11056. }
  11057. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11058. using namespace httplib;
  11059. const char *fname = "ims_invalid_format.txt";
  11060. const char *content = "ims-bad-format";
  11061. {
  11062. std::ofstream ofs(fname);
  11063. ofs << content;
  11064. ASSERT_TRUE(ofs.good());
  11065. }
  11066. Server svr;
  11067. svr.set_mount_point("/static", ".");
  11068. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11069. svr.wait_until_ready();
  11070. Client cli(HOST, PORT);
  11071. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11072. ASSERT_TRUE(res1);
  11073. ASSERT_EQ(200, res1->status);
  11074. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11075. // If-Modified-Since with invalid format should not result in 304
  11076. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11077. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11078. ASSERT_TRUE(res_bad);
  11079. EXPECT_EQ(200, res_bad->status);
  11080. // If-Range with invalid date format should be treated as mismatch -> full
  11081. // content (200)
  11082. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11083. {"If-Range", "invalid-date"}};
  11084. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11085. ASSERT_TRUE(res_ifrange);
  11086. EXPECT_EQ(200, res_ifrange->status);
  11087. svr.stop();
  11088. t.join();
  11089. std::remove(fname);
  11090. }
  11091. TEST(ETagTest, IfRangeWithMalformedETag) {
  11092. using namespace httplib;
  11093. const char *fname = "ifrange_malformed.txt";
  11094. const std::string content = "0123456789";
  11095. {
  11096. std::ofstream ofs(fname);
  11097. ofs << content;
  11098. ASSERT_TRUE(ofs.good());
  11099. }
  11100. Server svr;
  11101. svr.set_mount_point("/static", ".");
  11102. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11103. svr.wait_until_ready();
  11104. Client cli(HOST, PORT);
  11105. // First request: get ETag
  11106. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11107. ASSERT_TRUE(res1);
  11108. ASSERT_EQ(200, res1->status);
  11109. ASSERT_TRUE(res1->has_header("ETag"));
  11110. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11111. // full content (200)
  11112. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11113. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11114. ASSERT_TRUE(res2);
  11115. EXPECT_EQ(200, res2->status);
  11116. EXPECT_EQ(content, res2->body);
  11117. svr.stop();
  11118. t.join();
  11119. std::remove(fname);
  11120. }
  11121. TEST(ETagTest, ExtremeLargeDateValues) {
  11122. using namespace httplib;
  11123. const char *fname = "ims_extreme_date.txt";
  11124. const char *content = "ims-extreme-date";
  11125. {
  11126. std::ofstream ofs(fname);
  11127. ofs << content;
  11128. ASSERT_TRUE(ofs.good());
  11129. }
  11130. Server svr;
  11131. svr.set_mount_point("/static", ".");
  11132. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11133. svr.wait_until_ready();
  11134. Client cli(HOST, PORT);
  11135. auto res1 = cli.Get(std::string("/static/") + fname);
  11136. ASSERT_TRUE(res1);
  11137. ASSERT_EQ(200, res1->status);
  11138. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11139. // Extremely large year that may overflow date parsing routines.
  11140. Headers h_large_date = {
  11141. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11142. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11143. ASSERT_TRUE(res_bad);
  11144. // Expect server to treat this as invalid/mismatch and return full content
  11145. EXPECT_EQ(200, res_bad->status);
  11146. // If-Range with extremely large date should be treated as mismatch -> full
  11147. // content (200)
  11148. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11149. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11150. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11151. ASSERT_TRUE(res_ifrange);
  11152. EXPECT_EQ(200, res_ifrange->status);
  11153. svr.stop();
  11154. t.join();
  11155. std::remove(fname);
  11156. }
  11157. TEST(ETagTest, NegativeFileModificationTime) {
  11158. using namespace httplib;
  11159. const char *fname = "ims_negative_mtime.txt";
  11160. const std::string content = "negative-mtime";
  11161. {
  11162. std::ofstream ofs(fname);
  11163. ofs << content;
  11164. ASSERT_TRUE(ofs.good());
  11165. }
  11166. // Try to set file mtime to a negative value. This may fail on some
  11167. // platforms/filesystems; if it fails, the test will still verify server
  11168. // behaves safely by performing a regular conditional request.
  11169. #if defined(__APPLE__) || defined(__linux__)
  11170. bool set_negative = false;
  11171. do {
  11172. struct timeval times[2];
  11173. // access time: now
  11174. times[0].tv_sec = time(nullptr);
  11175. times[0].tv_usec = 0;
  11176. // modification time: negative (e.g., -1)
  11177. times[1].tv_sec = -1;
  11178. times[1].tv_usec = 0;
  11179. if (utimes(fname, times) == 0) { set_negative = true; }
  11180. } while (0);
  11181. #else
  11182. bool set_negative = false;
  11183. #endif
  11184. Server svr;
  11185. svr.set_mount_point("/static", ".");
  11186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11187. svr.wait_until_ready();
  11188. Client cli(HOST, PORT);
  11189. auto res1 = cli.Get(std::string("/static/") + fname);
  11190. ASSERT_TRUE(res1);
  11191. ASSERT_EQ(200, res1->status);
  11192. bool has_last_modified = res1->has_header("Last-Modified");
  11193. std::string last_modified;
  11194. if (has_last_modified) {
  11195. last_modified = res1->get_header_value("Last-Modified");
  11196. }
  11197. if (set_negative) {
  11198. // If we successfully set a negative mtime, ensure server returns a
  11199. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11200. // with an old date and ensure server handles it without crash.
  11201. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11202. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11203. ASSERT_TRUE(res2);
  11204. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11205. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11206. } else {
  11207. // Could not set negative mtime on this platform; fall back to verifying
  11208. // that normal invalid/malformed dates are treated safely (non-304).
  11209. Headers h_bad_date = {
  11210. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11211. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11212. ASSERT_TRUE(res_bad);
  11213. EXPECT_EQ(200, res_bad->status);
  11214. }
  11215. svr.stop();
  11216. t.join();
  11217. std::remove(fname);
  11218. }
  11219. //==============================================================================
  11220. // SSE Parsing Tests
  11221. //==============================================================================
  11222. class SSEParsingTest : public ::testing::Test {
  11223. protected:
  11224. // Test helper that mimics SSE parsing behavior
  11225. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11226. int &retry_ms) {
  11227. // Blank line signals end of event
  11228. if (line.empty() || line == "\r") { return true; }
  11229. // Lines starting with ':' are comments (ignored)
  11230. if (!line.empty() && line[0] == ':') { return false; }
  11231. // Find the colon separator
  11232. auto colon_pos = line.find(':');
  11233. if (colon_pos == std::string::npos) {
  11234. // Line with no colon is treated as field name with empty value
  11235. return false;
  11236. }
  11237. std::string field = line.substr(0, colon_pos);
  11238. std::string value;
  11239. // Value starts after colon, skip optional single space
  11240. if (colon_pos + 1 < line.size()) {
  11241. size_t value_start = colon_pos + 1;
  11242. if (line[value_start] == ' ') { value_start++; }
  11243. value = line.substr(value_start);
  11244. // Remove trailing \r if present
  11245. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11246. }
  11247. // Handle known fields
  11248. if (field == "event") {
  11249. msg.event = value;
  11250. } else if (field == "data") {
  11251. // Multiple data lines are concatenated with newlines
  11252. if (!msg.data.empty()) { msg.data += "\n"; }
  11253. msg.data += value;
  11254. } else if (field == "id") {
  11255. // Empty id is valid (clears the last event ID)
  11256. msg.id = value;
  11257. } else if (field == "retry") {
  11258. // Parse retry interval in milliseconds
  11259. try {
  11260. retry_ms = std::stoi(value);
  11261. } catch (...) {
  11262. // Invalid retry value, ignore
  11263. }
  11264. }
  11265. // Unknown fields are ignored per SSE spec
  11266. return false;
  11267. }
  11268. };
  11269. // Test: Single-line data
  11270. TEST_F(SSEParsingTest, SingleLineData) {
  11271. sse::SSEMessage msg;
  11272. int retry_ms = 3000;
  11273. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11274. EXPECT_EQ(msg.data, "hello");
  11275. EXPECT_EQ(msg.event, "message");
  11276. // Blank line ends event
  11277. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11278. }
  11279. // Test: Multi-line data
  11280. TEST_F(SSEParsingTest, MultiLineData) {
  11281. sse::SSEMessage msg;
  11282. int retry_ms = 3000;
  11283. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11284. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11285. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11286. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11287. }
  11288. // Test: Custom event types
  11289. TEST_F(SSEParsingTest, CustomEventType) {
  11290. sse::SSEMessage msg;
  11291. int retry_ms = 3000;
  11292. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11293. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11294. EXPECT_EQ(msg.event, "update");
  11295. EXPECT_EQ(msg.data, "payload");
  11296. }
  11297. // Test: Event ID handling
  11298. TEST_F(SSEParsingTest, EventIdHandling) {
  11299. sse::SSEMessage msg;
  11300. int retry_ms = 3000;
  11301. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11302. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11303. EXPECT_EQ(msg.id, "12345");
  11304. }
  11305. // Test: Empty event ID (clears last event ID)
  11306. TEST_F(SSEParsingTest, EmptyEventId) {
  11307. sse::SSEMessage msg;
  11308. msg.id = "previous";
  11309. int retry_ms = 3000;
  11310. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11311. EXPECT_EQ(msg.id, "");
  11312. }
  11313. // Test: Retry field parsing
  11314. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11315. sse::SSEMessage msg;
  11316. int retry_ms = 3000;
  11317. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11318. EXPECT_EQ(retry_ms, 5000);
  11319. }
  11320. // Test: Invalid retry value
  11321. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11322. sse::SSEMessage msg;
  11323. int retry_ms = 3000;
  11324. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11325. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11326. }
  11327. // Test: Comments (lines starting with :)
  11328. TEST_F(SSEParsingTest, CommentsIgnored) {
  11329. sse::SSEMessage msg;
  11330. int retry_ms = 3000;
  11331. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11332. EXPECT_EQ(msg.data, "");
  11333. EXPECT_EQ(msg.event, "message");
  11334. }
  11335. // Test: Colon in value
  11336. TEST_F(SSEParsingTest, ColonInValue) {
  11337. sse::SSEMessage msg;
  11338. int retry_ms = 3000;
  11339. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11340. EXPECT_EQ(msg.data, "hello:world:test");
  11341. }
  11342. // Test: Line with no colon (field name only)
  11343. TEST_F(SSEParsingTest, FieldNameOnly) {
  11344. sse::SSEMessage msg;
  11345. int retry_ms = 3000;
  11346. // According to SSE spec, this is treated as field name with empty value
  11347. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11348. // Since we don't recognize "data" without colon, data should be empty
  11349. EXPECT_EQ(msg.data, "");
  11350. }
  11351. // Test: Trailing \r handling
  11352. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11353. sse::SSEMessage msg;
  11354. int retry_ms = 3000;
  11355. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11356. EXPECT_EQ(msg.data, "hello");
  11357. }
  11358. // Test: Unknown fields ignored
  11359. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11360. sse::SSEMessage msg;
  11361. int retry_ms = 3000;
  11362. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11363. EXPECT_EQ(msg.data, "");
  11364. EXPECT_EQ(msg.event, "message");
  11365. }
  11366. // Test: Space after colon is optional
  11367. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11368. sse::SSEMessage msg1, msg2;
  11369. int retry_ms = 3000;
  11370. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11371. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11372. EXPECT_EQ(msg1.data, "hello");
  11373. EXPECT_EQ(msg2.data, "hello");
  11374. }
  11375. // Test: SSEMessage clear
  11376. TEST_F(SSEParsingTest, MessageClear) {
  11377. sse::SSEMessage msg;
  11378. msg.event = "custom";
  11379. msg.data = "some data";
  11380. msg.id = "123";
  11381. msg.clear();
  11382. EXPECT_EQ(msg.event, "message");
  11383. EXPECT_EQ(msg.data, "");
  11384. EXPECT_EQ(msg.id, "");
  11385. }
  11386. // Test: Complete event parsing
  11387. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11388. sse::SSEMessage msg;
  11389. int retry_ms = 3000;
  11390. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11391. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11392. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11393. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11394. // Blank line ends event
  11395. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11396. EXPECT_EQ(msg.event, "notification");
  11397. EXPECT_EQ(msg.id, "evt-42");
  11398. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11399. EXPECT_EQ(retry_ms, 1000);
  11400. }
  11401. //==============================================================================
  11402. // Integration Tests with Server
  11403. //==============================================================================
  11404. class SSEIntegrationTest : public ::testing::Test {
  11405. protected:
  11406. void SetUp() override {
  11407. stop_server_.store(false);
  11408. events_.clear();
  11409. server_ = httplib::detail::make_unique<Server>();
  11410. setup_server();
  11411. start_server();
  11412. }
  11413. void TearDown() override {
  11414. stop_server_.store(true);
  11415. event_cv_.notify_all();
  11416. server_->stop();
  11417. if (server_thread_.joinable()) { server_thread_.join(); }
  11418. }
  11419. void setup_server() {
  11420. // Simple SSE endpoint
  11421. server_->Get("/events", [this](const Request &req, Response &res) {
  11422. auto last_id = req.get_header_value("Last-Event-ID");
  11423. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11424. res.set_chunked_content_provider(
  11425. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11426. std::unique_lock<std::mutex> lock(event_mutex_);
  11427. if (event_cv_.wait_for(
  11428. lock, std::chrono::milliseconds(200), [this] {
  11429. return !events_.empty() || stop_server_.load();
  11430. })) {
  11431. if (stop_server_.load()) { return false; }
  11432. if (!events_.empty()) {
  11433. std::string event = events_.front();
  11434. events_.erase(events_.begin());
  11435. sink.write(event.data(), event.size());
  11436. return true;
  11437. }
  11438. }
  11439. return !stop_server_.load();
  11440. });
  11441. });
  11442. // Endpoint that returns error
  11443. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11444. res.status = 500;
  11445. res.set_content("Internal Server Error", "text/plain");
  11446. });
  11447. // Endpoint for custom event types
  11448. server_->Get("/custom-events", [](const Request &, Response &res) {
  11449. res.set_chunked_content_provider(
  11450. "text/event-stream", [](size_t offset, DataSink &sink) {
  11451. if (offset == 0) {
  11452. std::string event = "event: update\ndata: updated\n\n"
  11453. "event: delete\ndata: deleted\n\n";
  11454. sink.write(event.data(), event.size());
  11455. }
  11456. return false; // End stream after sending
  11457. });
  11458. });
  11459. }
  11460. void start_server() {
  11461. port_ = server_->bind_to_any_port(HOST);
  11462. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11463. // Wait for server to start
  11464. while (!server_->is_running()) {
  11465. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11466. }
  11467. }
  11468. int get_port() const { return port_; }
  11469. void send_event(const std::string &event) {
  11470. std::lock_guard<std::mutex> lock(event_mutex_);
  11471. events_.push_back(event);
  11472. event_cv_.notify_all();
  11473. }
  11474. std::unique_ptr<Server> server_;
  11475. std::thread server_thread_;
  11476. std::mutex event_mutex_;
  11477. std::condition_variable event_cv_;
  11478. std::vector<std::string> events_;
  11479. std::atomic<bool> stop_server_{false};
  11480. std::string last_received_event_id_;
  11481. int port_ = 0;
  11482. };
  11483. // Test: Successful connection and on_open callback
  11484. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11485. // Add a simple endpoint that sends one event and closes
  11486. server_->Get("/simple-event", [](const Request &, Response &res) {
  11487. res.set_chunked_content_provider(
  11488. "text/event-stream", [](size_t offset, DataSink &sink) {
  11489. if (offset == 0) {
  11490. std::string event = "data: hello\n\n";
  11491. sink.write(event.data(), event.size());
  11492. }
  11493. return false; // Close stream after sending
  11494. });
  11495. });
  11496. Client client("localhost", get_port());
  11497. sse::SSEClient sse(client, "/simple-event");
  11498. std::atomic<bool> open_called{false};
  11499. std::atomic<bool> message_received{false};
  11500. sse.on_open([&open_called]() { open_called.store(true); });
  11501. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11502. if (msg.data == "hello") { message_received.store(true); }
  11503. });
  11504. sse.set_reconnect_interval(100);
  11505. sse.set_max_reconnect_attempts(1);
  11506. // Start async
  11507. sse.start_async();
  11508. // Wait for message to be processed
  11509. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11510. sse.stop();
  11511. EXPECT_TRUE(open_called.load());
  11512. EXPECT_TRUE(message_received.load());
  11513. }
  11514. // Test: on_message callback
  11515. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11516. // Endpoint that sends multiple events then closes
  11517. server_->Get("/multi-event", [](const Request &, Response &res) {
  11518. res.set_chunked_content_provider(
  11519. "text/event-stream", [](size_t offset, DataSink &sink) {
  11520. if (offset == 0) {
  11521. std::string events = "data: message1\n\ndata: message2\n\n";
  11522. sink.write(events.data(), events.size());
  11523. }
  11524. return false;
  11525. });
  11526. });
  11527. Client client("localhost", get_port());
  11528. sse::SSEClient sse(client, "/multi-event");
  11529. std::vector<std::string> received_messages;
  11530. std::mutex messages_mutex;
  11531. sse.on_message([&](const sse::SSEMessage &msg) {
  11532. std::lock_guard<std::mutex> lock(messages_mutex);
  11533. received_messages.push_back(msg.data);
  11534. });
  11535. sse.set_reconnect_interval(100);
  11536. sse.set_max_reconnect_attempts(1);
  11537. sse.start_async();
  11538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11539. sse.stop();
  11540. std::lock_guard<std::mutex> lock(messages_mutex);
  11541. EXPECT_GE(received_messages.size(), 2u);
  11542. if (received_messages.size() >= 2) {
  11543. EXPECT_EQ(received_messages[0], "message1");
  11544. EXPECT_EQ(received_messages[1], "message2");
  11545. }
  11546. }
  11547. // Test: on_event for specific types
  11548. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11549. Client client("localhost", get_port());
  11550. sse::SSEClient sse(client, "/custom-events");
  11551. std::atomic<bool> update_received{false};
  11552. std::atomic<bool> delete_received{false};
  11553. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11554. if (msg.data == "updated") { update_received.store(true); }
  11555. });
  11556. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11557. if (msg.data == "deleted") { delete_received.store(true); }
  11558. });
  11559. sse.set_max_reconnect_attempts(1);
  11560. sse.start_async();
  11561. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11562. sse.stop();
  11563. EXPECT_TRUE(update_received.load());
  11564. EXPECT_TRUE(delete_received.load());
  11565. }
  11566. // Test: on_error callback on connection failure
  11567. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11568. // Connect to a non-existent port
  11569. Client client("localhost", 59999);
  11570. sse::SSEClient sse(client, "/events");
  11571. std::atomic<bool> error_called{false};
  11572. Error received_error = Error::Success;
  11573. sse.on_error([&](Error err) {
  11574. error_called.store(true);
  11575. received_error = err;
  11576. });
  11577. sse.set_reconnect_interval(50);
  11578. sse.set_max_reconnect_attempts(1);
  11579. sse.start_async();
  11580. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11581. sse.stop();
  11582. EXPECT_TRUE(error_called.load());
  11583. EXPECT_NE(received_error, Error::Success);
  11584. }
  11585. // Test: Last-Event-ID header sent on reconnect
  11586. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11587. // Endpoint that sends event with ID
  11588. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11589. res.set_chunked_content_provider(
  11590. "text/event-stream", [](size_t offset, DataSink &sink) {
  11591. if (offset == 0) {
  11592. std::string event = "id: evt-123\ndata: test\n\n";
  11593. sink.write(event.data(), event.size());
  11594. }
  11595. return false;
  11596. });
  11597. });
  11598. Client client("localhost", get_port());
  11599. sse::SSEClient sse(client, "/event-with-id");
  11600. std::atomic<bool> id_received{false};
  11601. sse.on_message([&](const sse::SSEMessage &msg) {
  11602. if (!msg.id.empty()) { id_received.store(true); }
  11603. });
  11604. sse.set_reconnect_interval(100);
  11605. sse.set_max_reconnect_attempts(1);
  11606. sse.start_async();
  11607. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11608. sse.stop();
  11609. EXPECT_TRUE(id_received.load());
  11610. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11611. }
  11612. // Test: Manual stop
  11613. TEST_F(SSEIntegrationTest, ManualStop) {
  11614. // Endpoint that sends one event and stays open briefly
  11615. std::atomic<bool> handler_running{true};
  11616. server_->Get("/stay-open", [&handler_running](const Request &,
  11617. Response &res) {
  11618. res.set_chunked_content_provider(
  11619. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11620. if (offset == 0) {
  11621. std::string event = "data: connected\n\n";
  11622. sink.write(event.data(), event.size());
  11623. }
  11624. // Keep connection open while handler_running is true
  11625. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11626. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11627. }
  11628. return false;
  11629. });
  11630. });
  11631. Client client("localhost", get_port());
  11632. sse::SSEClient sse(client, "/stay-open");
  11633. std::atomic<bool> connected{false};
  11634. sse.on_open([&connected]() { connected.store(true); });
  11635. sse.set_reconnect_interval(100);
  11636. sse.set_max_reconnect_attempts(1);
  11637. sse.start_async();
  11638. // Wait for connection to establish
  11639. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11640. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11641. }
  11642. EXPECT_TRUE(connected.load());
  11643. EXPECT_TRUE(sse.is_connected());
  11644. // Signal handler to stop
  11645. handler_running.store(false);
  11646. // Stop SSE client
  11647. sse.stop();
  11648. EXPECT_FALSE(sse.is_connected());
  11649. }
  11650. // Test: SSEClient with custom headers
  11651. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11652. // Setup a server endpoint that checks for custom header
  11653. std::atomic<bool> header_received{false};
  11654. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11655. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11656. header_received.store(true);
  11657. }
  11658. res.set_chunked_content_provider("text/event-stream",
  11659. [](size_t, DataSink &) { return false; });
  11660. });
  11661. Client client("localhost", get_port());
  11662. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11663. sse::SSEClient sse(client, "/header-check", headers);
  11664. sse.set_max_reconnect_attempts(1);
  11665. sse.start_async();
  11666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11667. sse.stop();
  11668. EXPECT_TRUE(header_received.load());
  11669. }
  11670. // Test: Reconnect interval configuration
  11671. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11672. Client client("localhost", get_port());
  11673. sse::SSEClient sse(client, "/events");
  11674. auto &result = sse.set_reconnect_interval(500);
  11675. // Builder pattern should return reference to self
  11676. EXPECT_EQ(&result, &sse);
  11677. }
  11678. // Test: Max reconnect attempts
  11679. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11680. // Connect to non-existent port to force reconnects
  11681. Client client("localhost", 59998);
  11682. sse::SSEClient sse(client, "/events");
  11683. std::atomic<int> error_count{0};
  11684. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11685. sse.set_reconnect_interval(50);
  11686. sse.set_max_reconnect_attempts(2);
  11687. auto start = std::chrono::steady_clock::now();
  11688. sse.start(); // Blocking call
  11689. auto end = std::chrono::steady_clock::now();
  11690. // Should have stopped after 2 failed attempts
  11691. EXPECT_GE(error_count.load(), 2);
  11692. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11693. auto duration =
  11694. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11695. #ifdef _WIN32
  11696. // Windows is much slower for socket connection failures
  11697. EXPECT_LT(duration.count(), 7000);
  11698. #else
  11699. EXPECT_LT(duration.count(), 1000);
  11700. #endif
  11701. }
  11702. // Test: Multi-line data in integration
  11703. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11704. // Endpoint with multi-line data
  11705. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11706. res.set_chunked_content_provider(
  11707. "text/event-stream", [](size_t offset, DataSink &sink) {
  11708. if (offset == 0) {
  11709. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11710. sink.write(event.data(), event.size());
  11711. }
  11712. return false;
  11713. });
  11714. });
  11715. Client client("localhost", get_port());
  11716. sse::SSEClient sse(client, "/multiline-data");
  11717. std::string received_data;
  11718. std::mutex data_mutex;
  11719. sse.on_message([&](const sse::SSEMessage &msg) {
  11720. std::lock_guard<std::mutex> lock(data_mutex);
  11721. received_data = msg.data;
  11722. });
  11723. sse.set_reconnect_interval(100);
  11724. sse.set_max_reconnect_attempts(1);
  11725. sse.start_async();
  11726. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11727. sse.stop();
  11728. std::lock_guard<std::mutex> lock(data_mutex);
  11729. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11730. }
  11731. // Test: Auto-reconnect after server disconnection
  11732. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11733. std::atomic<int> connection_count{0};
  11734. std::atomic<int> message_count{0};
  11735. // Endpoint that sends one event and closes, forcing reconnect
  11736. server_->Get("/reconnect-test",
  11737. [&connection_count](const Request &, Response &res) {
  11738. connection_count.fetch_add(1);
  11739. res.set_chunked_content_provider(
  11740. "text/event-stream", [](size_t offset, DataSink &sink) {
  11741. if (offset == 0) {
  11742. std::string event = "data: hello\n\n";
  11743. sink.write(event.data(), event.size());
  11744. }
  11745. return false; // Close connection after sending
  11746. });
  11747. });
  11748. Client client("localhost", get_port());
  11749. sse::SSEClient sse(client, "/reconnect-test");
  11750. sse.on_message([&message_count](const sse::SSEMessage &) {
  11751. message_count.fetch_add(1);
  11752. });
  11753. sse.set_reconnect_interval(100);
  11754. sse.set_max_reconnect_attempts(3);
  11755. sse.start_async();
  11756. // Wait long enough for multiple reconnects
  11757. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11758. sse.stop();
  11759. // Should have connected multiple times (initial + reconnects)
  11760. EXPECT_GE(connection_count.load(), 2);
  11761. // Should have received messages from multiple connections
  11762. EXPECT_GE(message_count.load(), 2);
  11763. }
  11764. // Test: Last-Event-ID sent on reconnect
  11765. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11766. std::atomic<int> connection_count{0};
  11767. std::vector<std::string> received_last_event_ids;
  11768. std::mutex id_mutex;
  11769. // Endpoint that checks Last-Event-ID header and sends event with ID
  11770. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11771. int conn = connection_count.fetch_add(1);
  11772. // Capture the Last-Event-ID header from each connection
  11773. {
  11774. std::lock_guard<std::mutex> lock(id_mutex);
  11775. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11776. }
  11777. res.set_chunked_content_provider(
  11778. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11779. if (offset == 0) {
  11780. std::string event =
  11781. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11782. sink.write(event.data(), event.size());
  11783. }
  11784. return false;
  11785. });
  11786. });
  11787. Client client("localhost", get_port());
  11788. sse::SSEClient sse(client, "/reconnect-with-id");
  11789. sse.set_reconnect_interval(100);
  11790. sse.set_max_reconnect_attempts(3);
  11791. sse.start_async();
  11792. // Wait for at least 2 connections
  11793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11794. sse.stop();
  11795. // Verify behavior
  11796. std::lock_guard<std::mutex> lock(id_mutex);
  11797. EXPECT_GE(received_last_event_ids.size(), 2u);
  11798. // First connection should have no Last-Event-ID
  11799. if (!received_last_event_ids.empty()) {
  11800. EXPECT_EQ(received_last_event_ids[0], "");
  11801. }
  11802. // Second connection should have Last-Event-ID from first connection
  11803. if (received_last_event_ids.size() >= 2) {
  11804. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11805. }
  11806. }
  11807. TEST(Issue2318Test, EmptyHostString) {
  11808. {
  11809. httplib::Client cli_empty("", PORT);
  11810. auto res = cli_empty.Get("/");
  11811. ASSERT_FALSE(res);
  11812. EXPECT_EQ(httplib::Error::Connection, res.error());
  11813. }
  11814. {
  11815. httplib::Client cli(" ", PORT);
  11816. auto res = cli.Get("/");
  11817. ASSERT_FALSE(res);
  11818. EXPECT_EQ(httplib::Error::Connection, res.error());
  11819. }
  11820. }