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. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  120. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  121. class UnixSocketTest : public ::testing::Test {
  122. protected:
  123. void TearDown() override { std::remove(pathname_.c_str()); }
  124. void client_GET(const std::string &addr) {
  125. httplib::Client cli{addr};
  126. cli.set_address_family(AF_UNIX);
  127. ASSERT_TRUE(cli.is_valid());
  128. const auto &result = cli.Get(pattern_);
  129. ASSERT_TRUE(result) << "error: " << result.error();
  130. const auto &resp = result.value();
  131. EXPECT_EQ(resp.status, StatusCode::OK_200);
  132. EXPECT_EQ(resp.body, content_);
  133. }
  134. const std::string pathname_{"./httplib-server.sock"};
  135. const std::string pattern_{"/hi"};
  136. const std::string content_{"Hello World!"};
  137. };
  138. TEST_F(UnixSocketTest, pathname) {
  139. httplib::Server svr;
  140. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  141. res.set_content(content_, "text/plain");
  142. });
  143. std::thread t{[&] {
  144. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  145. }};
  146. auto se = detail::scope_exit([&] {
  147. svr.stop();
  148. t.join();
  149. ASSERT_FALSE(svr.is_running());
  150. });
  151. svr.wait_until_ready();
  152. ASSERT_TRUE(svr.is_running());
  153. client_GET(pathname_);
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_EQ(0, close(fds[1]));
  246. EXPECT_FALSE(s0.wait_writable());
  247. return true;
  248. });
  249. EXPECT_EQ(0, close(fds[0]));
  250. }
  251. TEST(SocketStream, wait_writable_INET) {
  252. sockaddr_in addr;
  253. memset(&addr, 0, sizeof(addr));
  254. addr.sin_family = AF_INET;
  255. addr.sin_port = htons(PORT + 1);
  256. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  257. int disconnected_svr_sock = -1;
  258. std::thread svr{[&] {
  259. const int s = socket(AF_INET, SOCK_STREAM, 0);
  260. ASSERT_LE(0, s);
  261. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  262. ASSERT_EQ(0, listen(s, 1));
  263. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  264. ASSERT_EQ(0, close(s));
  265. }};
  266. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  267. std::thread cli{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. cli.join();
  274. svr.join();
  275. ASSERT_NE(disconnected_svr_sock, -1);
  276. const auto asSocketStream = [&](socket_t fd,
  277. std::function<bool(Stream &)> func) {
  278. return detail::process_client_socket(
  279. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  280. };
  281. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  282. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  283. EXPECT_FALSE(ss.wait_writable());
  284. return true;
  285. });
  286. ASSERT_EQ(0, close(disconnected_svr_sock));
  287. }
  288. #endif // #ifndef _WIN32
  289. TEST(ClientTest, MoveConstructible) {
  290. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  291. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  292. }
  293. TEST(ClientTest, MoveAssignable) {
  294. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  295. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  296. }
  297. #ifdef _WIN32
  298. TEST(StartupTest, WSAStartup) {
  299. WSADATA wsaData;
  300. int ret = WSAStartup(0x0002, &wsaData);
  301. ASSERT_EQ(0, ret);
  302. }
  303. #endif
  304. TEST(DecodePathTest, PercentCharacter) {
  305. EXPECT_EQ(
  306. decode_path_component(
  307. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  308. u8"descrip=Gastos áéíóúñÑ 6");
  309. }
  310. TEST(DecodePathTest, PercentCharacterNUL) {
  311. string expected;
  312. expected.push_back('x');
  313. expected.push_back('\0');
  314. expected.push_back('x');
  315. EXPECT_EQ(decode_path_component("x%00x"), expected);
  316. }
  317. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  318. string unescapedCharacters = "-_.!~*'()";
  319. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  320. }
  321. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  322. string reservedCharacters = ";,/?:@&=+$";
  323. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  324. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  325. }
  326. TEST(ClientQueryOrder, PreserveOrder) {
  327. // This test reproduces Issue #2259: client may reorder query parameters
  328. // when sending a GET request. The expected behavior is that the client
  329. // preserves the original query string order when the caller supplied it
  330. // as part of the path.
  331. Server svr;
  332. svr.Get("/", [&](const Request &req, Response &res) {
  333. // Echo back the raw target so the test can assert ordering
  334. res.set_content(req.target, "text/plain");
  335. });
  336. std::thread t{[&] { svr.listen(HOST, PORT); }};
  337. auto se = detail::scope_exit([&] {
  338. svr.stop();
  339. t.join();
  340. ASSERT_FALSE(svr.is_running());
  341. });
  342. svr.wait_until_ready();
  343. Client cli(HOST, PORT);
  344. ASSERT_TRUE(cli.is_valid());
  345. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  346. auto res = cli.Get(original);
  347. ASSERT_TRUE(res);
  348. // Expect the echoed target to exactly match the original path (order
  349. // preserved)
  350. EXPECT_EQ(res->body, original);
  351. }
  352. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  353. string chineseCharacters = u8"中国語";
  354. string russianCharacters = u8"дом";
  355. string brazilianCharacters = u8"óculos";
  356. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  357. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  358. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  359. "%D0%B4%D0%BE%D0%BC");
  360. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  361. }
  362. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  363. string unescapedCharacters = "-_.!~*'()";
  364. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  365. }
  366. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  367. string reservedCharacters = ";,/?:@&=+$";
  368. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  369. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  370. }
  371. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  372. string chineseCharacters = u8"中国語";
  373. string russianCharacters = u8"дом";
  374. string brazilianCharacters = u8"óculos";
  375. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  376. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  377. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  378. "%D0%B4%D0%BE%D0%BC");
  379. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  380. }
  381. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  382. // Issue #2082 use case: encoding path component with ampersand
  383. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  384. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  385. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  386. }
  387. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  388. string unescapedCharacters = "-_.!~*'()";
  389. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  390. }
  391. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  392. string reservedCharacters = ";,/?:@&=+$#";
  393. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  394. }
  395. TEST(EncodeUriTest, TestUTF8Characters) {
  396. string chineseCharacters = u8"中国語";
  397. string russianCharacters = u8"дом";
  398. string brazilianCharacters = u8"óculos";
  399. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  400. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  401. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriTest, TestCompleteUri) {
  405. string uri =
  406. "https://example.com/path/to/resource?query=value&param=test#fragment";
  407. EXPECT_EQ(
  408. httplib::encode_uri(uri),
  409. "https://example.com/path/to/resource?query=value&param=test#fragment");
  410. }
  411. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  412. string uri =
  413. "https://example.com/path with spaces/file name.html?q=hello world";
  414. EXPECT_EQ(httplib::encode_uri(uri),
  415. "https://example.com/path%20with%20spaces/"
  416. "file%20name.html?q=hello%20world");
  417. }
  418. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  419. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  420. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  421. }
  422. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  423. string unescapedCharacters = "-_.!~*'()";
  424. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  425. }
  426. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  427. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  428. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  429. string encodedBrazilian = "%C3%B3culos";
  430. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  431. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  433. }
  434. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  435. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  436. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  437. "Piri Tommy Villiers - on & on");
  438. }
  439. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  440. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  441. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  442. }
  443. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  445. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  446. }
  447. TEST(DecodeUriTest, TestUTF8Characters) {
  448. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  449. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  450. string encodedBrazilian = "%C3%B3culos";
  451. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  452. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  453. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  454. }
  455. TEST(DecodeUriTest, TestCompleteUri) {
  456. string encodedUri = "https://example.com/path%20with%20spaces/"
  457. "file%20name.html?q=hello%20world";
  458. EXPECT_EQ(
  459. httplib::decode_uri(encodedUri),
  460. "https://example.com/path with spaces/file name.html?q=hello world");
  461. }
  462. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  463. string original =
  464. "https://example.com/path with spaces/file name.html?q=hello world";
  465. string encoded = httplib::encode_uri(original);
  466. string decoded = httplib::decode_uri(encoded);
  467. EXPECT_EQ(decoded, original);
  468. }
  469. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  470. string original = "Piri Tommy Villiers - on & on";
  471. string encoded = httplib::encode_uri_component(original);
  472. string decoded = httplib::decode_uri_component(encoded);
  473. EXPECT_EQ(decoded, original);
  474. }
  475. TEST(TrimTests, TrimStringTests) {
  476. EXPECT_EQ("abc", detail::trim_copy("abc"));
  477. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  478. EXPECT_TRUE(detail::trim_copy("").empty());
  479. }
  480. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  481. // Simple case without quality values
  482. std::vector<std::string> result1;
  483. EXPECT_TRUE(detail::parse_accept_header(
  484. "text/html,application/json,text/plain", result1));
  485. EXPECT_EQ(result1.size(), 3U);
  486. EXPECT_EQ(result1[0], "text/html");
  487. EXPECT_EQ(result1[1], "application/json");
  488. EXPECT_EQ(result1[2], "text/plain");
  489. // With quality values
  490. std::vector<std::string> result2;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  493. EXPECT_EQ(result2.size(), 3U);
  494. EXPECT_EQ(result2[0], "application/json"); // highest q value
  495. EXPECT_EQ(result2[1], "text/html");
  496. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  497. }
  498. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  499. // Mixed with and without quality values
  500. std::vector<std::string> result;
  501. EXPECT_TRUE(detail::parse_accept_header(
  502. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  503. EXPECT_EQ(result.size(), 3U);
  504. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  505. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  506. EXPECT_EQ(result[2], "application/json"); // q=0.5
  507. }
  508. TEST(ParseAcceptHeaderTest, EdgeCases) {
  509. // Empty header
  510. std::vector<std::string> empty_result;
  511. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  512. EXPECT_TRUE(empty_result.empty());
  513. // Single type
  514. std::vector<std::string> single_result;
  515. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  516. EXPECT_EQ(single_result.size(), 1U);
  517. EXPECT_EQ(single_result[0], "application/json");
  518. // Wildcard types
  519. std::vector<std::string> wildcard_result;
  520. EXPECT_TRUE(detail::parse_accept_header(
  521. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  522. EXPECT_EQ(wildcard_result.size(), 3U);
  523. EXPECT_EQ(wildcard_result[0], "application/json");
  524. EXPECT_EQ(wildcard_result[1], "text/*");
  525. EXPECT_EQ(wildcard_result[2], "*/*");
  526. }
  527. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  528. // Common browser Accept header
  529. std::vector<std::string> browser_result;
  530. EXPECT_TRUE(
  531. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  532. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  533. browser_result));
  534. EXPECT_EQ(browser_result.size(), 6U);
  535. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  536. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  540. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  541. // API client header
  542. std::vector<std::string> api_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  545. api_result));
  546. EXPECT_EQ(api_result.size(), 3U);
  547. EXPECT_EQ(api_result[0], "application/json");
  548. EXPECT_EQ(api_result[1], "application/xml");
  549. EXPECT_EQ(api_result[2], "text/plain");
  550. }
  551. TEST(ParseAcceptHeaderTest, SpecialCases) {
  552. // Quality value with 3 decimal places
  553. std::vector<std::string> decimal_result;
  554. EXPECT_TRUE(detail::parse_accept_header(
  555. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  556. EXPECT_EQ(decimal_result.size(), 2U);
  557. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  558. EXPECT_EQ(decimal_result[1], "text/html");
  559. // Zero quality (should still be included but with lowest priority)
  560. std::vector<std::string> zero_q_result;
  561. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  562. zero_q_result));
  563. EXPECT_EQ(zero_q_result.size(), 2U);
  564. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  565. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  566. // No spaces around commas
  567. std::vector<std::string> no_space_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  570. no_space_result));
  571. EXPECT_EQ(no_space_result.size(), 3U);
  572. EXPECT_EQ(no_space_result[0], "text/html");
  573. EXPECT_EQ(no_space_result[1], "application/json");
  574. EXPECT_EQ(no_space_result[2], "text/plain");
  575. }
  576. TEST(ParseAcceptHeaderTest, InvalidCases) {
  577. std::vector<std::string> result;
  578. // Invalid quality value (> 1.0)
  579. EXPECT_FALSE(
  580. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  581. // Invalid quality value (< 0.0)
  582. EXPECT_FALSE(
  583. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  584. // Invalid quality value (not a number)
  585. EXPECT_FALSE(detail::parse_accept_header(
  586. "text/html;q=invalid,application/json", result));
  587. // Empty quality value
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=,application/json", result));
  590. // Invalid media type format (no slash and not wildcard)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("invalidtype,application/json", result));
  593. // Empty media type
  594. result.clear();
  595. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  596. // Only commas
  597. result.clear();
  598. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  599. // Valid cases should still work
  600. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  601. EXPECT_EQ(result.size(), 1U);
  602. EXPECT_EQ(result[0], "*/*");
  603. EXPECT_TRUE(detail::parse_accept_header("*", result));
  604. EXPECT_EQ(result.size(), 1U);
  605. EXPECT_EQ(result[0], "*");
  606. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  607. EXPECT_EQ(result.size(), 1U);
  608. EXPECT_EQ(result[0], "text/*");
  609. }
  610. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  611. Server svr;
  612. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  613. EXPECT_EQ(req.accept_content_types.size(), 3U);
  614. EXPECT_EQ(req.accept_content_types[0], "application/json");
  615. EXPECT_EQ(req.accept_content_types[1], "text/html");
  616. EXPECT_EQ(req.accept_content_types[2], "*/*");
  617. res.set_content("ok", "text/plain");
  618. });
  619. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  620. EXPECT_TRUE(false);
  621. res.set_content("bad request", "text/plain");
  622. });
  623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  624. auto se = detail::scope_exit([&] {
  625. svr.stop();
  626. listen_thread.join();
  627. ASSERT_FALSE(svr.is_running());
  628. });
  629. svr.wait_until_ready();
  630. Client cli("localhost", PORT);
  631. {
  632. auto res =
  633. cli.Get("/accept_ok",
  634. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  635. ASSERT_TRUE(res);
  636. EXPECT_EQ(StatusCode::OK_200, res->status);
  637. }
  638. {
  639. auto res = cli.Get("/accept_bad_request",
  640. {{"Accept", "text/html;q=abc,application/json"}});
  641. ASSERT_TRUE(res);
  642. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  643. }
  644. }
  645. TEST(DivideTest, DivideStringTests) {
  646. auto divide = [](const std::string &str, char d) {
  647. std::string lhs;
  648. std::string rhs;
  649. detail::divide(str, d,
  650. [&](const char *lhs_data, std::size_t lhs_size,
  651. const char *rhs_data, std::size_t rhs_size) {
  652. lhs.assign(lhs_data, lhs_size);
  653. rhs.assign(rhs_data, rhs_size);
  654. });
  655. return std::make_pair(std::move(lhs), std::move(rhs));
  656. };
  657. {
  658. const auto res = divide("", '=');
  659. EXPECT_EQ(res.first, "");
  660. EXPECT_EQ(res.second, "");
  661. }
  662. {
  663. const auto res = divide("=", '=');
  664. EXPECT_EQ(res.first, "");
  665. EXPECT_EQ(res.second, "");
  666. }
  667. {
  668. const auto res = divide(" ", '=');
  669. EXPECT_EQ(res.first, " ");
  670. EXPECT_EQ(res.second, "");
  671. }
  672. {
  673. const auto res = divide("a", '=');
  674. EXPECT_EQ(res.first, "a");
  675. EXPECT_EQ(res.second, "");
  676. }
  677. {
  678. const auto res = divide("a=", '=');
  679. EXPECT_EQ(res.first, "a");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=b", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "b");
  686. }
  687. {
  688. const auto res = divide("a=b", '=');
  689. EXPECT_EQ(res.first, "a");
  690. EXPECT_EQ(res.second, "b");
  691. }
  692. {
  693. const auto res = divide("a=b=", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "b=");
  696. }
  697. {
  698. const auto res = divide("a=b=c", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "b=c");
  701. }
  702. }
  703. TEST(SplitTest, ParseQueryString) {
  704. string s = "key1=val1&key2=val2&key3=val3";
  705. Params dic;
  706. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  707. [&](const char *b, const char *e) {
  708. string key, val;
  709. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  710. if (key.empty()) {
  711. key.assign(b2, e2);
  712. } else {
  713. val.assign(b2, e2);
  714. }
  715. });
  716. dic.emplace(key, val);
  717. });
  718. EXPECT_EQ("val1", dic.find("key1")->second);
  719. EXPECT_EQ("val2", dic.find("key2")->second);
  720. EXPECT_EQ("val3", dic.find("key3")->second);
  721. }
  722. TEST(SplitTest, ParseInvalidQueryTests) {
  723. {
  724. string s = " ";
  725. Params dict;
  726. detail::parse_query_text(s, dict);
  727. EXPECT_TRUE(dict.empty());
  728. }
  729. {
  730. string s = " = =";
  731. Params dict;
  732. detail::parse_query_text(s, dict);
  733. EXPECT_TRUE(dict.empty());
  734. }
  735. }
  736. TEST(ParseQueryTest, ParseQueryString) {
  737. {
  738. std::string s = "key1=val1&key2=val2&key3=val3";
  739. Params dic;
  740. detail::parse_query_text(s, dic);
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. {
  746. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("", dic.find("key1")->second);
  750. EXPECT_EQ("val1", dic.find("key2")->second);
  751. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  752. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  753. }
  754. }
  755. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  756. Params dic;
  757. EXPECT_EQ(detail::params_to_query_str(dic), "");
  758. dic.emplace("key1", "val1");
  759. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  760. dic.emplace("key2", "val2");
  761. dic.emplace("key3", "val3");
  762. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  763. }
  764. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  765. string content_type = "multipart/form-data; boundary=something";
  766. string boundary;
  767. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  768. EXPECT_TRUE(ret);
  769. EXPECT_EQ(boundary, "something");
  770. }
  771. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  772. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  773. string boundary;
  774. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  777. }
  778. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  779. string content_type =
  780. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  793. }
  794. TEST(GetHeaderValueTest, DefaultValue) {
  795. Headers headers = {{"Dummy", "Dummy"}};
  796. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  797. EXPECT_STREQ("text/plain", val);
  798. }
  799. TEST(GetHeaderValueTest, DefaultValueInt) {
  800. Headers headers = {{"Dummy", "Dummy"}};
  801. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  802. EXPECT_EQ(100ull, val);
  803. }
  804. TEST(GetHeaderValueTest, RegularValue) {
  805. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  806. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  807. EXPECT_STREQ("text/html", val);
  808. }
  809. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  810. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  811. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  812. EXPECT_STREQ("text/html", val);
  813. }
  814. TEST(GetHeaderValueTest, SetContent) {
  815. Response res;
  816. res.set_content("html", "text/html");
  817. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  818. res.set_content("text", "text/plain");
  819. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  820. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  821. }
  822. TEST(GetHeaderValueTest, RegularValueInt) {
  823. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  828. Headers headers = {{"Content-Length", "x"}};
  829. auto is_invalid_value = false;
  830. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  831. is_invalid_value);
  832. EXPECT_EQ(0ull, val);
  833. EXPECT_TRUE(is_invalid_value);
  834. }
  835. TEST(GetHeaderValueTest, Range) {
  836. {
  837. Headers headers = {make_range_header({{1, -1}})};
  838. auto val = detail::get_header_value(headers, "Range", 0, 0);
  839. EXPECT_STREQ("bytes=1-", val);
  840. }
  841. {
  842. Headers headers = {make_range_header({{-1, 1}})};
  843. auto val = detail::get_header_value(headers, "Range", 0, 0);
  844. EXPECT_STREQ("bytes=-1", val);
  845. }
  846. {
  847. Headers headers = {make_range_header({{1, 10}})};
  848. auto val = detail::get_header_value(headers, "Range", 0, 0);
  849. EXPECT_STREQ("bytes=1-10", val);
  850. }
  851. {
  852. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  853. auto val = detail::get_header_value(headers, "Range", 0, 0);
  854. EXPECT_STREQ("bytes=1-10, 100-", val);
  855. }
  856. {
  857. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-10, 100-200", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=0-0, -1", val);
  865. }
  866. }
  867. TEST(ParseHeaderValueTest, Range) {
  868. {
  869. Ranges ranges;
  870. auto ret = detail::parse_range_header("bytes=1-", ranges);
  871. EXPECT_TRUE(ret);
  872. EXPECT_EQ(1u, ranges.size());
  873. EXPECT_EQ(1u, ranges[0].first);
  874. EXPECT_EQ(-1, ranges[0].second);
  875. }
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=-1", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(-1, ranges[0].first);
  882. EXPECT_EQ(1u, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(1u, ranges[0].first);
  890. EXPECT_EQ(10u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  895. EXPECT_FALSE(ret);
  896. }
  897. {
  898. Ranges ranges;
  899. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  900. EXPECT_TRUE(ret);
  901. EXPECT_EQ(2u, ranges.size());
  902. EXPECT_EQ(1u, ranges[0].first);
  903. EXPECT_EQ(10u, ranges[0].second);
  904. EXPECT_EQ(100u, ranges[1].first);
  905. EXPECT_EQ(-1, ranges[1].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret =
  910. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  911. EXPECT_TRUE(ret);
  912. EXPECT_EQ(3u, ranges.size());
  913. EXPECT_EQ(1u, ranges[0].first);
  914. EXPECT_EQ(10u, ranges[0].second);
  915. EXPECT_EQ(100u, ranges[1].first);
  916. EXPECT_EQ(200u, ranges[1].second);
  917. EXPECT_EQ(300u, ranges[2].first);
  918. EXPECT_EQ(400u, ranges[2].second);
  919. }
  920. {
  921. Ranges ranges;
  922. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  923. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  926. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  927. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  928. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  929. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  935. EXPECT_TRUE(ranges.empty());
  936. }
  937. }
  938. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  939. Request req;
  940. req.set_header("Accept-Encoding", "gzip");
  941. Response res;
  942. res.set_header("Content-Type", "text/plain");
  943. auto ret = detail::encoding_type(req, res);
  944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  945. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  946. #else
  947. EXPECT_TRUE(ret == detail::EncodingType::None);
  948. #endif
  949. }
  950. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  951. Request req;
  952. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  953. Response res;
  954. res.set_header("Content-Type", "text/plain");
  955. auto ret = detail::encoding_type(req, res);
  956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  957. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  958. #elif CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #elif CPPHTTPLIB_ZSTD_SUPPORT
  961. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  962. #else
  963. EXPECT_TRUE(ret == detail::EncodingType::None);
  964. #endif
  965. }
  966. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  967. Request req;
  968. req.set_header("Accept-Encoding",
  969. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  970. Response res;
  971. res.set_header("Content-Type", "text/plain");
  972. auto ret = detail::encoding_type(req, res);
  973. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  974. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  975. #elif CPPHTTPLIB_ZLIB_SUPPORT
  976. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  977. #elif CPPHTTPLIB_ZSTD_SUPPORT
  978. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  979. #else
  980. EXPECT_TRUE(ret == detail::EncodingType::None);
  981. #endif
  982. }
  983. TEST(BufferStreamTest, read) {
  984. detail::BufferStream strm1;
  985. Stream &strm = strm1;
  986. EXPECT_EQ(5, strm.write("hello"));
  987. char buf[512];
  988. EXPECT_EQ(2, strm.read(buf, 2));
  989. EXPECT_EQ('h', buf[0]);
  990. EXPECT_EQ('e', buf[1]);
  991. EXPECT_EQ(2, strm.read(buf, 2));
  992. EXPECT_EQ('l', buf[0]);
  993. EXPECT_EQ('l', buf[1]);
  994. EXPECT_EQ(1, strm.read(buf, 1));
  995. EXPECT_EQ('o', buf[0]);
  996. EXPECT_EQ(0, strm.read(buf, 1));
  997. }
  998. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  999. auto host = "www.httpwatch.com";
  1000. auto ip = hosted_at(host);
  1001. EXPECT_EQ("23.96.13.243", ip);
  1002. std::vector<std::string> addrs;
  1003. hosted_at(host, addrs);
  1004. EXPECT_EQ(1u, addrs.size());
  1005. }
  1006. #if 0 // It depends on each test environment...
  1007. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1008. auto host = "www.youtube.com";
  1009. std::vector<std::string> addrs;
  1010. hosted_at(host, addrs);
  1011. EXPECT_EQ(20u, addrs.size());
  1012. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1013. EXPECT_TRUE(it != addrs.end());
  1014. }
  1015. #endif
  1016. class ChunkedEncodingTest : public ::testing::Test {
  1017. protected:
  1018. ChunkedEncodingTest()
  1019. : cli_(HOST, PORT)
  1020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1021. ,
  1022. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1023. #endif
  1024. {
  1025. cli_.set_connection_timeout(2);
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. cli_.enable_server_certificate_verification(false);
  1028. #endif
  1029. }
  1030. virtual void SetUp() {
  1031. read_file("./image.jpg", image_data_);
  1032. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1033. res.set_content("Hello World!", "text/plain");
  1034. });
  1035. svr_.Get(
  1036. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1037. res.set_chunked_content_provider(
  1038. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1039. size_t remaining = image_data_.size() - offset;
  1040. if (remaining == 0) {
  1041. sink.done();
  1042. } else {
  1043. constexpr size_t CHUNK_SIZE = 1024;
  1044. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1045. sink.write(&image_data_[offset], send_size);
  1046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1047. }
  1048. return true;
  1049. });
  1050. });
  1051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1052. svr_.wait_until_ready();
  1053. }
  1054. virtual void TearDown() {
  1055. svr_.stop();
  1056. if (!request_threads_.empty()) {
  1057. std::this_thread::sleep_for(std::chrono::seconds(1));
  1058. for (auto &t : request_threads_) {
  1059. t.join();
  1060. }
  1061. }
  1062. t_.join();
  1063. }
  1064. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1065. SSLClient cli_;
  1066. SSLServer svr_;
  1067. #else
  1068. Client cli_;
  1069. Server svr_;
  1070. #endif
  1071. thread t_;
  1072. std::vector<thread> request_threads_;
  1073. std::string image_data_;
  1074. };
  1075. TEST_F(ChunkedEncodingTest, NormalGet) {
  1076. auto res = cli_.Get("/chunked");
  1077. ASSERT_TRUE(res);
  1078. std::string out;
  1079. read_file("./image.jpg", out);
  1080. EXPECT_EQ(StatusCode::OK_200, res->status);
  1081. EXPECT_EQ(out, res->body);
  1082. }
  1083. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1084. std::string body;
  1085. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1086. body.append(data, data_length);
  1087. return true;
  1088. });
  1089. ASSERT_TRUE(res);
  1090. std::string out;
  1091. read_file("./image.jpg", out);
  1092. EXPECT_EQ(StatusCode::OK_200, res->status);
  1093. EXPECT_EQ(out, body);
  1094. }
  1095. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1096. std::string body;
  1097. auto res = cli_.Get(
  1098. "/chunked",
  1099. [&](const Response &response) {
  1100. EXPECT_EQ(StatusCode::OK_200, response.status);
  1101. return true;
  1102. },
  1103. [&](const char *data, size_t data_length) {
  1104. body.append(data, data_length);
  1105. return true;
  1106. });
  1107. ASSERT_TRUE(res);
  1108. std::string out;
  1109. read_file("./image.jpg", out);
  1110. EXPECT_EQ(StatusCode::OK_200, res->status);
  1111. EXPECT_EQ(out, body);
  1112. }
  1113. TEST(RangeTest, FromHTTPBin_Online) {
  1114. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1115. auto host = "httpcan.org";
  1116. auto path = std::string{"/range/32"};
  1117. #else
  1118. auto host = "nghttp2.org";
  1119. auto path = std::string{"/httpbin/range/32"};
  1120. #endif
  1121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1122. auto port = 443;
  1123. SSLClient cli(host, port);
  1124. #else
  1125. auto port = 80;
  1126. Client cli(host, port);
  1127. #endif
  1128. cli.set_connection_timeout(5);
  1129. {
  1130. auto res = cli.Get(path);
  1131. ASSERT_TRUE(res);
  1132. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. }
  1135. {
  1136. Headers headers = {make_range_header({{1, -1}})};
  1137. auto res = cli.Get(path, headers);
  1138. ASSERT_TRUE(res);
  1139. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1141. }
  1142. {
  1143. Headers headers = {make_range_header({{1, 10}})};
  1144. auto res = cli.Get(path, headers);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("bcdefghijk", res->body);
  1147. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{0, 31}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{0, -1}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 32}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1168. }
  1169. }
  1170. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1171. auto host = "unresolvableaddress.local";
  1172. auto path = std::string{"/"};
  1173. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1174. auto port = 443;
  1175. SSLClient cli(host, port);
  1176. #else
  1177. auto port = 80;
  1178. Client cli(host, port);
  1179. #endif
  1180. cli.set_connection_timeout(1);
  1181. {
  1182. auto res = cli.Get(path);
  1183. ASSERT_FALSE(res);
  1184. }
  1185. std::this_thread::sleep_for(std::chrono::seconds(8));
  1186. }
  1187. TEST(ConnectionErrorTest, InvalidHost) {
  1188. auto host = "-abcde.com";
  1189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1190. auto port = 443;
  1191. SSLClient cli(host, port);
  1192. #else
  1193. auto port = 80;
  1194. Client cli(host, port);
  1195. #endif
  1196. cli.set_connection_timeout(std::chrono::seconds(2));
  1197. auto res = cli.Get("/");
  1198. ASSERT_TRUE(!res);
  1199. EXPECT_EQ(Error::Connection, res.error());
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost2) {
  1202. auto host = "httpcan.org/";
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host);
  1205. #else
  1206. Client cli(host);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_EQ(Error::Connection, res.error());
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1214. auto host = "httpcan.org/";
  1215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1216. SSLClient cli(host);
  1217. #else
  1218. Client cli(host);
  1219. #endif
  1220. cli.set_connection_timeout(std::chrono::seconds(2));
  1221. auto res = cli.Get("/");
  1222. ASSERT_TRUE(!res);
  1223. stringstream s;
  1224. s << "error code: " << res.error();
  1225. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidPort) {
  1228. auto host = "localhost";
  1229. auto port = 44380;
  1230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1231. SSLClient cli(host, port);
  1232. #else
  1233. Client cli(host, port);
  1234. #endif
  1235. cli.set_connection_timeout(std::chrono::seconds(2));
  1236. auto res = cli.Get("/");
  1237. ASSERT_TRUE(!res);
  1238. EXPECT_TRUE(Error::Connection == res.error() ||
  1239. Error::ConnectionTimeout == res.error());
  1240. }
  1241. TEST(ConnectionErrorTest, Timeout_Online) {
  1242. auto host = "google.com";
  1243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1244. auto port = 44380;
  1245. SSLClient cli(host, port);
  1246. #else
  1247. auto port = 8080;
  1248. Client cli(host, port);
  1249. #endif
  1250. cli.set_connection_timeout(std::chrono::seconds(2));
  1251. // only probe one address type so that the error reason
  1252. // correlates to the timed-out IPv4, not the unsupported
  1253. // IPv6 connection attempt
  1254. cli.set_address_family(AF_INET);
  1255. auto res = cli.Get("/");
  1256. ASSERT_TRUE(!res);
  1257. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1258. }
  1259. TEST(CancelTest, NoCancel_Online) {
  1260. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1261. auto host = "httpcan.org";
  1262. auto path = std::string{"/range/32"};
  1263. #else
  1264. auto host = "nghttp2.org";
  1265. auto path = std::string{"/httpbin/range/32"};
  1266. #endif
  1267. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1268. auto port = 443;
  1269. SSLClient cli(host, port);
  1270. #else
  1271. auto port = 80;
  1272. Client cli(host, port);
  1273. #endif
  1274. cli.set_connection_timeout(std::chrono::seconds(5));
  1275. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1278. EXPECT_EQ(StatusCode::OK_200, res->status);
  1279. }
  1280. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1281. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1282. auto host = "httpcan.org";
  1283. auto path = std::string{"/range/32"};
  1284. #else
  1285. auto host = "nghttp2.org";
  1286. auto path = std::string{"/httpbin/range/32"};
  1287. #endif
  1288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1289. auto port = 443;
  1290. SSLClient cli(host, port);
  1291. #else
  1292. auto port = 80;
  1293. Client cli(host, port);
  1294. #endif
  1295. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1296. cli.set_connection_timeout(std::chrono::seconds(5));
  1297. ASSERT_TRUE(!res);
  1298. EXPECT_EQ(Error::Canceled, res.error());
  1299. }
  1300. TEST(CancelTest, WithCancelLargePayload_Online) {
  1301. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1302. auto host = "httpcan.org";
  1303. auto path = std::string{"/range/65536"};
  1304. #else
  1305. auto host = "nghttp2.org";
  1306. auto path = std::string{"/httpbin/range/65536"};
  1307. #endif
  1308. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(std::chrono::seconds(5));
  1316. uint32_t count = 0;
  1317. auto res =
  1318. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1319. ASSERT_TRUE(!res);
  1320. EXPECT_EQ(Error::Canceled, res.error());
  1321. }
  1322. TEST(CancelTest, NoCancelPost) {
  1323. Server svr;
  1324. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1325. res.set_content("Hello World!", "text/plain");
  1326. });
  1327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. thread.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. Client cli(HOST, PORT);
  1335. cli.set_connection_timeout(std::chrono::seconds(5));
  1336. auto res =
  1337. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1338. "application/json", [](uint64_t, uint64_t) { return true; });
  1339. ASSERT_TRUE(res);
  1340. EXPECT_EQ("Hello World!", res->body);
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. }
  1343. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1344. Server svr;
  1345. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1346. res.set_content("Hello World!", "text/plain");
  1347. });
  1348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1349. auto se = detail::scope_exit([&] {
  1350. svr.stop();
  1351. thread.join();
  1352. ASSERT_FALSE(svr.is_running());
  1353. });
  1354. svr.wait_until_ready();
  1355. Client cli(HOST, PORT);
  1356. cli.set_connection_timeout(std::chrono::seconds(5));
  1357. auto res =
  1358. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1359. "application/json", [](uint64_t, uint64_t) { return false; });
  1360. ASSERT_TRUE(!res);
  1361. EXPECT_EQ(Error::Canceled, res.error());
  1362. }
  1363. TEST(CancelTest, WithCancelLargePayloadPost) {
  1364. Server svr;
  1365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1366. res.set_content(LARGE_DATA, "text/plain");
  1367. });
  1368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. thread.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. Client cli(HOST, PORT);
  1376. cli.set_connection_timeout(std::chrono::seconds(5));
  1377. auto res =
  1378. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1379. "application/json", [](uint64_t, uint64_t) { return false; });
  1380. ASSERT_TRUE(!res);
  1381. EXPECT_EQ(Error::Canceled, res.error());
  1382. }
  1383. TEST(CancelTest, NoCancelPut) {
  1384. Server svr;
  1385. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1386. res.set_content("Hello World!", "text/plain");
  1387. });
  1388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. thread.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, PORT);
  1396. cli.set_connection_timeout(std::chrono::seconds(5));
  1397. auto res =
  1398. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1399. "application/json", [](uint64_t, uint64_t) { return true; });
  1400. ASSERT_TRUE(res);
  1401. EXPECT_EQ("Hello World!", res->body);
  1402. EXPECT_EQ(StatusCode::OK_200, res->status);
  1403. }
  1404. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1405. Server svr;
  1406. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1407. res.set_content("Hello World!", "text/plain");
  1408. });
  1409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1410. auto se = detail::scope_exit([&] {
  1411. svr.stop();
  1412. thread.join();
  1413. ASSERT_FALSE(svr.is_running());
  1414. });
  1415. svr.wait_until_ready();
  1416. Client cli(HOST, PORT);
  1417. cli.set_connection_timeout(std::chrono::seconds(5));
  1418. auto res =
  1419. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1420. "application/json", [](uint64_t, uint64_t) { return false; });
  1421. ASSERT_TRUE(!res);
  1422. EXPECT_EQ(Error::Canceled, res.error());
  1423. }
  1424. TEST(CancelTest, WithCancelLargePayloadPut) {
  1425. Server svr;
  1426. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1427. res.set_content(LARGE_DATA, "text/plain");
  1428. });
  1429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1430. auto se = detail::scope_exit([&] {
  1431. svr.stop();
  1432. thread.join();
  1433. ASSERT_FALSE(svr.is_running());
  1434. });
  1435. svr.wait_until_ready();
  1436. Client cli(HOST, PORT);
  1437. cli.set_connection_timeout(std::chrono::seconds(5));
  1438. auto res =
  1439. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1440. "application/json", [](uint64_t, uint64_t) { return false; });
  1441. ASSERT_TRUE(!res);
  1442. EXPECT_EQ(Error::Canceled, res.error());
  1443. }
  1444. TEST(CancelTest, NoCancelPatch) {
  1445. Server svr;
  1446. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1447. res.set_content("Hello World!", "text/plain");
  1448. });
  1449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. thread.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. Client cli(HOST, PORT);
  1457. cli.set_connection_timeout(std::chrono::seconds(5));
  1458. auto res =
  1459. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1460. "application/json", [](uint64_t, uint64_t) { return true; });
  1461. ASSERT_TRUE(res);
  1462. EXPECT_EQ("Hello World!", res->body);
  1463. EXPECT_EQ(StatusCode::OK_200, res->status);
  1464. }
  1465. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1466. Server svr;
  1467. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1468. res.set_content("Hello World!", "text/plain");
  1469. });
  1470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1471. auto se = detail::scope_exit([&] {
  1472. svr.stop();
  1473. thread.join();
  1474. ASSERT_FALSE(svr.is_running());
  1475. });
  1476. svr.wait_until_ready();
  1477. Client cli(HOST, PORT);
  1478. cli.set_connection_timeout(std::chrono::seconds(5));
  1479. auto res =
  1480. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1481. "application/json", [](uint64_t, uint64_t) { return false; });
  1482. ASSERT_TRUE(!res);
  1483. EXPECT_EQ(Error::Canceled, res.error());
  1484. }
  1485. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1486. Server svr;
  1487. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1488. res.set_content(LARGE_DATA, "text/plain");
  1489. });
  1490. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. thread.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. Client cli(HOST, PORT);
  1498. cli.set_connection_timeout(std::chrono::seconds(5));
  1499. auto res =
  1500. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1501. "application/json", [](uint64_t, uint64_t) { return false; });
  1502. ASSERT_TRUE(!res);
  1503. EXPECT_EQ(Error::Canceled, res.error());
  1504. }
  1505. TEST(CancelTest, NoCancelDelete) {
  1506. Server svr;
  1507. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1508. res.set_content("Hello World!", "text/plain");
  1509. });
  1510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1511. auto se = detail::scope_exit([&] {
  1512. svr.stop();
  1513. thread.join();
  1514. ASSERT_FALSE(svr.is_running());
  1515. });
  1516. svr.wait_until_ready();
  1517. Client cli(HOST, PORT);
  1518. cli.set_connection_timeout(std::chrono::seconds(5));
  1519. auto res =
  1520. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1521. "application/json", [](uint64_t, uint64_t) { return true; });
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ("Hello World!", res->body);
  1524. EXPECT_EQ(StatusCode::OK_200, res->status);
  1525. }
  1526. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1527. Server svr;
  1528. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1529. res.set_content("Hello World!", "text/plain");
  1530. });
  1531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. thread.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. Client cli(HOST, PORT);
  1539. cli.set_connection_timeout(std::chrono::seconds(5));
  1540. auto res =
  1541. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1542. "application/json", [](uint64_t, uint64_t) { return false; });
  1543. ASSERT_TRUE(!res);
  1544. EXPECT_EQ(Error::Canceled, res.error());
  1545. }
  1546. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1547. Server svr;
  1548. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_connection_timeout(std::chrono::seconds(5));
  1560. auto res =
  1561. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1562. "application/json", [](uint64_t, uint64_t) { return false; });
  1563. ASSERT_TRUE(!res);
  1564. EXPECT_EQ(Error::Canceled, res.error());
  1565. }
  1566. static std::string remove_whitespace(const std::string &input) {
  1567. std::string output;
  1568. output.reserve(input.size());
  1569. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1570. [](unsigned char c) { return !std::isspace(c); });
  1571. return output;
  1572. }
  1573. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1574. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1575. auto host = "httpcan.org";
  1576. auto path = std::string{"/basic-auth/hello/world"};
  1577. #else
  1578. auto host = "nghttp2.org";
  1579. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1580. #endif
  1581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1582. auto port = 443;
  1583. SSLClient cli(host, port);
  1584. #else
  1585. auto port = 80;
  1586. Client cli(host, port);
  1587. #endif
  1588. {
  1589. auto res = cli.Get(path);
  1590. ASSERT_TRUE(res);
  1591. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1592. }
  1593. {
  1594. auto res =
  1595. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1596. ASSERT_TRUE(res);
  1597. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1598. remove_whitespace(res->body));
  1599. EXPECT_EQ(StatusCode::OK_200, res->status);
  1600. }
  1601. {
  1602. cli.set_basic_auth("hello", "world");
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "bad");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("bad", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1620. }
  1621. }
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1624. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1625. auto host = "httpcan.org";
  1626. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1627. auto paths = std::vector<std::string>{
  1628. "/digest-auth/auth/hello/world/MD5",
  1629. "/digest-auth/auth/hello/world/SHA-256",
  1630. "/digest-auth/auth/hello/world/SHA-512",
  1631. };
  1632. #else
  1633. auto host = "nghttp2.org";
  1634. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/httpbin/digest-auth/auth/hello/world/MD5",
  1637. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1638. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1639. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1640. };
  1641. #endif
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. {
  1645. auto res = cli.Get(unauth_path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_digest_auth("hello", "world");
  1651. for (const auto &path : paths) {
  1652. auto res = cli.Get(path.c_str());
  1653. ASSERT_TRUE(res);
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. std::string algo(path.substr(path.rfind('/') + 1));
  1656. EXPECT_EQ(
  1657. remove_whitespace("{\"algorithm\":\"" + algo +
  1658. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1659. remove_whitespace(res->body));
  1660. #else
  1661. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1662. remove_whitespace(res->body));
  1663. #endif
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. }
  1666. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1667. cli.set_digest_auth("hello", "bad");
  1668. for (const auto &path : paths) {
  1669. auto res = cli.Get(path.c_str());
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. #endif
  1674. }
  1675. }
  1676. #endif
  1677. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1678. auto host = "google.com";
  1679. auto another_host = "example.com";
  1680. auto wrong_ip = "0.0.0.0";
  1681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1682. SSLClient cli(host);
  1683. #else
  1684. Client cli(host);
  1685. #endif
  1686. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1687. auto res = cli.Get("/");
  1688. ASSERT_TRUE(res);
  1689. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1690. }
  1691. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1692. auto host = "google.com";
  1693. auto wrong_ip = "0.0.0.0";
  1694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1695. SSLClient cli(host);
  1696. #else
  1697. Client cli(host);
  1698. #endif
  1699. cli.set_hostname_addr_map({{host, wrong_ip}});
  1700. auto res = cli.Get("/");
  1701. ASSERT_TRUE(!res);
  1702. EXPECT_EQ(Error::Connection, res.error());
  1703. }
  1704. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1705. auto host = "nghttp2.org";
  1706. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1707. SSLClient cli(host);
  1708. #else
  1709. Client cli(host);
  1710. #endif
  1711. cli.set_follow_location(true);
  1712. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(StatusCode::OK_200, res->status);
  1715. }
  1716. TEST(RedirectTest, Redirect_Online) {
  1717. auto host = "nghttp2.org";
  1718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1719. SSLClient cli(host);
  1720. #else
  1721. Client cli(host);
  1722. #endif
  1723. cli.set_follow_location(true);
  1724. auto res = cli.Get("/httpbin/redirect/3");
  1725. ASSERT_TRUE(res);
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. TEST(RelativeRedirectTest, Redirect_Online) {
  1729. auto host = "nghttp2.org";
  1730. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1731. SSLClient cli(host);
  1732. #else
  1733. Client cli(host);
  1734. #endif
  1735. cli.set_follow_location(true);
  1736. auto res = cli.Get("/httpbin/relative-redirect/3");
  1737. ASSERT_TRUE(res);
  1738. EXPECT_EQ(StatusCode::OK_200, res->status);
  1739. }
  1740. TEST(TooManyRedirectTest, Redirect_Online) {
  1741. auto host = "nghttp2.org";
  1742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1743. SSLClient cli(host);
  1744. #else
  1745. Client cli(host);
  1746. #endif
  1747. cli.set_follow_location(true);
  1748. auto res = cli.Get("/httpbin/redirect/21");
  1749. ASSERT_TRUE(!res);
  1750. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1751. }
  1752. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1753. TEST(YahooRedirectTest, Redirect_Online) {
  1754. Client cli("yahoo.com");
  1755. auto res = cli.Get("/");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1758. cli.set_follow_location(true);
  1759. res = cli.Get("/");
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1763. }
  1764. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1765. #define REDIR_HOST "httpbingo.org"
  1766. #define REDIR_PATH "/redirect-to"
  1767. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1768. SSLClient cli(REDIR_HOST);
  1769. cli.set_follow_location(true);
  1770. auto res =
  1771. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. Params params;
  1779. params.emplace("url", "http://example.com");
  1780. params.emplace("status_code", "302");
  1781. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. }
  1794. TEST(UrlWithSpace, Redirect_Online) {
  1795. SSLClient cli("edge.forgecdn.net");
  1796. cli.set_follow_location(true);
  1797. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1798. ASSERT_TRUE(res);
  1799. EXPECT_EQ(StatusCode::OK_200, res->status);
  1800. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1801. }
  1802. #endif
  1803. #if !defined(_WIN32) && !defined(_WIN64)
  1804. TEST(ReceiveSignals, Signal) {
  1805. auto setupSignalHandlers = []() {
  1806. struct sigaction act;
  1807. sigemptyset(&act.sa_mask);
  1808. act.sa_flags = SA_SIGINFO;
  1809. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1810. switch (sig) {
  1811. case SIGINT:
  1812. default: break;
  1813. }
  1814. };
  1815. ::sigaction(SIGINT, &act, nullptr);
  1816. };
  1817. Server svr;
  1818. int port = 0;
  1819. auto thread = std::thread([&]() {
  1820. setupSignalHandlers();
  1821. port = svr.bind_to_any_port(HOST);
  1822. svr.listen_after_bind();
  1823. });
  1824. auto se = detail::scope_exit([&] {
  1825. svr.stop();
  1826. thread.join();
  1827. ASSERT_FALSE(svr.is_running());
  1828. });
  1829. svr.wait_until_ready();
  1830. ASSERT_TRUE(svr.is_running());
  1831. pthread_kill(thread.native_handle(), SIGINT);
  1832. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1833. ASSERT_TRUE(svr.is_running());
  1834. }
  1835. #endif
  1836. TEST(RedirectToDifferentPort, Redirect) {
  1837. Server svr1;
  1838. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1839. res.set_content("Hello World!", "text/plain");
  1840. });
  1841. int svr1_port = 0;
  1842. auto thread1 = std::thread([&]() {
  1843. svr1_port = svr1.bind_to_any_port(HOST);
  1844. svr1.listen_after_bind();
  1845. });
  1846. Server svr2;
  1847. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1848. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1849. });
  1850. int svr2_port = 0;
  1851. auto thread2 = std::thread([&]() {
  1852. svr2_port = svr2.bind_to_any_port(HOST);
  1853. svr2.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr2.stop();
  1857. thread2.join();
  1858. svr1.stop();
  1859. thread1.join();
  1860. ASSERT_FALSE(svr2.is_running());
  1861. ASSERT_FALSE(svr1.is_running());
  1862. });
  1863. svr1.wait_until_ready();
  1864. svr2.wait_until_ready();
  1865. Client cli("localhost", svr2_port);
  1866. cli.set_follow_location(true);
  1867. auto res = cli.Get("/2");
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", res->body);
  1871. }
  1872. TEST(RedirectFromPageWithContent, Redirect) {
  1873. Server svr;
  1874. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("___", "text/plain");
  1876. res.set_redirect("/2");
  1877. });
  1878. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!", "text/plain");
  1880. });
  1881. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. th.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. {
  1889. Client cli("localhost", PORT);
  1890. cli.set_follow_location(true);
  1891. std::string body;
  1892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1893. body.append(data, data_length);
  1894. return true;
  1895. });
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::OK_200, res->status);
  1898. EXPECT_EQ("Hello World!", body);
  1899. }
  1900. {
  1901. Client cli("localhost", PORT);
  1902. std::string body;
  1903. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1904. body.append(data, data_length);
  1905. return true;
  1906. });
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::Found_302, res->status);
  1909. EXPECT_EQ("___", body);
  1910. }
  1911. }
  1912. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1913. Server svr;
  1914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1915. res.set_content("___", "text/plain");
  1916. // res.set_redirect("/2");
  1917. res.set_redirect("http://[::1]:1234/2");
  1918. });
  1919. svr.Get("/2", [&](const Request &req, Response &res) {
  1920. auto host_header = req.headers.find("Host");
  1921. ASSERT_TRUE(host_header != req.headers.end());
  1922. EXPECT_EQ("[::1]:1234", host_header->second);
  1923. res.set_content("Hello World!", "text/plain");
  1924. });
  1925. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. th.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1932. // actually starts anything, so the condition !svr.is_running() will
  1933. // always remain true, and the loop never stops.
  1934. // This basically counts how many milliseconds have passed since the
  1935. // call to svr.listen(), and if after 5 seconds nothing started yet
  1936. // aborts the test.
  1937. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1938. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1939. ASSERT_LT(milliseconds, 5000U);
  1940. }
  1941. {
  1942. Client cli("http://[::1]:1234");
  1943. cli.set_follow_location(true);
  1944. std::string body;
  1945. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(StatusCode::OK_200, res->status);
  1951. EXPECT_EQ("Hello World!", body);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. std::string body;
  1956. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::Found_302, res->status);
  1962. EXPECT_EQ("___", body);
  1963. }
  1964. }
  1965. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1966. Server svr;
  1967. svr.Get("/foo", [](const Request &req, Response &res) {
  1968. auto a = req.params.find("a");
  1969. if (a != req.params.end()) {
  1970. res.set_content((*a).second, "text/plain");
  1971. res.status = StatusCode::OK_200;
  1972. } else {
  1973. res.status = StatusCode::BadRequest_400;
  1974. }
  1975. });
  1976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1977. auto se = detail::scope_exit([&] {
  1978. svr.stop();
  1979. thread.join();
  1980. ASSERT_FALSE(svr.is_running());
  1981. });
  1982. svr.wait_until_ready();
  1983. {
  1984. Client cli(HOST, PORT);
  1985. cli.set_path_encode(false);
  1986. auto res = cli.Get("/foo?a=explicitly+encoded");
  1987. ASSERT_TRUE(res);
  1988. EXPECT_EQ(StatusCode::OK_200, res->status);
  1989. // This expects it back with a space, as the `+` won't have been
  1990. // url-encoded, and server-side the params get decoded turning `+`
  1991. // into spaces.
  1992. EXPECT_EQ("explicitly encoded", res->body);
  1993. }
  1994. }
  1995. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1996. Server svr;
  1997. svr.Get("/", [](const Request &req, Response &) {
  1998. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1999. });
  2000. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2001. auto se = detail::scope_exit([&] {
  2002. svr.stop();
  2003. thread.join();
  2004. ASSERT_FALSE(svr.is_running());
  2005. });
  2006. svr.wait_until_ready();
  2007. {
  2008. Client cli(HOST, PORT);
  2009. cli.set_path_encode(false);
  2010. auto res = cli.Get("/?something=%0A");
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. }
  2014. }
  2015. TEST(BindServerTest, DISABLED_BindDualStack) {
  2016. Server svr;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. {
  2028. Client cli("127.0.0.1", PORT);
  2029. auto res = cli.Get("/1");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::OK_200, res->status);
  2032. EXPECT_EQ("Hello World!", res->body);
  2033. }
  2034. {
  2035. Client cli("::1", PORT);
  2036. auto res = cli.Get("/1");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("Hello World!", res->body);
  2040. }
  2041. }
  2042. TEST(BindServerTest, BindAndListenSeparately) {
  2043. Server svr;
  2044. int port = svr.bind_to_any_port("0.0.0.0");
  2045. ASSERT_TRUE(svr.is_valid());
  2046. ASSERT_TRUE(port > 0);
  2047. svr.stop();
  2048. }
  2049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2050. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2052. CLIENT_CA_CERT_DIR);
  2053. int port = svr.bind_to_any_port("0.0.0.0");
  2054. ASSERT_TRUE(svr.is_valid());
  2055. ASSERT_TRUE(port > 0);
  2056. svr.stop();
  2057. }
  2058. #endif
  2059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2060. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2061. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2062. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2063. int port = svr.bind_to_any_port("0.0.0.0");
  2064. ASSERT_TRUE(svr.is_valid());
  2065. ASSERT_TRUE(port > 0);
  2066. svr.stop();
  2067. }
  2068. #endif
  2069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2070. X509 *readCertificate(const std::string &strFileName) {
  2071. std::ifstream inStream(strFileName);
  2072. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2073. std::istreambuf_iterator<char>());
  2074. if (strCertPEM.empty()) return (nullptr);
  2075. BIO *pbCert = BIO_new(BIO_s_mem());
  2076. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2077. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2078. BIO_free(pbCert);
  2079. return (pCert);
  2080. }
  2081. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2082. std::ifstream inStream(strFileName);
  2083. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2084. std::istreambuf_iterator<char>());
  2085. if (strPrivateKeyPEM.empty()) return (nullptr);
  2086. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2087. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2088. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2089. BIO_free(pbPrivKey);
  2090. return (pPrivateKey);
  2091. }
  2092. TEST(BindServerTest, UpdateCerts) {
  2093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2094. int port = svr.bind_to_any_port("0.0.0.0");
  2095. ASSERT_TRUE(svr.is_valid());
  2096. ASSERT_TRUE(port > 0);
  2097. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2098. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2099. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2100. ASSERT_TRUE(cert != nullptr);
  2101. ASSERT_TRUE(ca_cert != nullptr);
  2102. ASSERT_TRUE(key != nullptr);
  2103. X509_STORE *cert_store = X509_STORE_new();
  2104. X509_STORE_add_cert(cert_store, ca_cert);
  2105. svr.update_certs(cert, key, cert_store);
  2106. ASSERT_TRUE(svr.is_valid());
  2107. svr.stop();
  2108. X509_free(cert);
  2109. X509_free(ca_cert);
  2110. EVP_PKEY_free(key);
  2111. }
  2112. #endif
  2113. TEST(ErrorHandlerTest, ContentLength) {
  2114. Server svr;
  2115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2116. res.status = StatusCode::OK_200;
  2117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2118. "text/html"); // <= Content-Length still 13
  2119. });
  2120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!\n", "text/plain");
  2122. res.status = 524;
  2123. });
  2124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2125. auto se = detail::scope_exit([&] {
  2126. svr.stop();
  2127. thread.join();
  2128. ASSERT_FALSE(svr.is_running());
  2129. });
  2130. svr.wait_until_ready();
  2131. {
  2132. Client cli(HOST, PORT);
  2133. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2139. }
  2140. }
  2141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2142. TEST(ExceptionTest, WithoutExceptionHandler) {
  2143. Server svr;
  2144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2145. throw std::runtime_error("exception...");
  2146. });
  2147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2148. throw std::runtime_error("exception\r\n...");
  2149. });
  2150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. listen_thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. Client cli("localhost", PORT);
  2158. {
  2159. auto res = cli.Get("/exception");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2163. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2164. }
  2165. {
  2166. auto res = cli.Get("/unknown");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2169. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2170. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2171. }
  2172. }
  2173. TEST(ExceptionTest, WithExceptionHandler) {
  2174. Server svr;
  2175. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2176. std::exception_ptr ep) {
  2177. EXPECT_FALSE(ep == nullptr);
  2178. try {
  2179. std::rethrow_exception(ep);
  2180. } catch (std::exception &e) {
  2181. EXPECT_EQ("abc", std::string(e.what()));
  2182. } catch (...) {}
  2183. res.status = StatusCode::InternalServerError_500;
  2184. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2185. "text/html"); // <= Content-Length still 13 at this point
  2186. });
  2187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2188. res.set_content("Hello World!\n", "text/plain");
  2189. throw std::runtime_error("abc");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. for (size_t i = 0; i < 10; i++) {
  2199. Client cli(HOST, PORT);
  2200. for (size_t j = 0; j < 100; j++) {
  2201. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2205. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2206. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2207. }
  2208. cli.set_keep_alive(true);
  2209. for (size_t j = 0; j < 100; j++) {
  2210. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2216. }
  2217. }
  2218. }
  2219. TEST(ExceptionTest, AndErrorHandler) {
  2220. Server svr;
  2221. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2222. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2223. });
  2224. svr.set_exception_handler(
  2225. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2226. EXPECT_FALSE(ep == nullptr);
  2227. try {
  2228. std::rethrow_exception(ep);
  2229. } catch (std::exception &e) {
  2230. res.set_content(e.what(), "text/html");
  2231. } catch (...) {}
  2232. res.status = StatusCode::InternalServerError_500;
  2233. });
  2234. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2235. throw std::runtime_error("EXCEPTION");
  2236. });
  2237. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2238. res.set_content("ERROR", "text/html");
  2239. res.status = StatusCode::InternalServerError_500;
  2240. });
  2241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2242. auto se = detail::scope_exit([&] {
  2243. svr.stop();
  2244. thread.join();
  2245. ASSERT_FALSE(svr.is_running());
  2246. });
  2247. svr.wait_until_ready();
  2248. Client cli(HOST, PORT);
  2249. {
  2250. auto res = cli.Get("/exception");
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2253. EXPECT_EQ("EXCEPTION", res->body);
  2254. }
  2255. {
  2256. auto res = cli.Get("/error");
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2259. EXPECT_EQ("ERROR", res->body);
  2260. }
  2261. {
  2262. auto res = cli.Get("/invalid");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("NOT_FOUND", res->body);
  2266. }
  2267. }
  2268. #endif
  2269. TEST(NoContentTest, ContentLength) {
  2270. Server svr;
  2271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2272. res.status = StatusCode::NoContent_204;
  2273. });
  2274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. {
  2282. Client cli(HOST, PORT);
  2283. auto res = cli.Get("/hi");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2287. }
  2288. }
  2289. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2292. ASSERT_TRUE(svr.is_valid());
  2293. #else
  2294. Server svr;
  2295. #endif
  2296. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2297. if (req.path == "/routing_handler") {
  2298. res.set_header("PRE_ROUTING", "on");
  2299. res.set_content("Routing Handler", "text/plain");
  2300. return httplib::Server::HandlerResponse::Handled;
  2301. }
  2302. return httplib::Server::HandlerResponse::Unhandled;
  2303. });
  2304. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2305. res.set_content("Error", "text/html");
  2306. });
  2307. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2308. if (req.path == "/routing_handler") {
  2309. res.set_header("POST_ROUTING", "on");
  2310. }
  2311. });
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.set_content("Hello World!\n", "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2324. SSLClient cli(HOST, PORT);
  2325. cli.enable_server_certificate_verification(false);
  2326. #else
  2327. Client cli(HOST, PORT);
  2328. #endif
  2329. auto res = cli.Get("/routing_handler");
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::OK_200, res->status);
  2332. EXPECT_EQ("Routing Handler", res->body);
  2333. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2334. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2335. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2336. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2337. }
  2338. {
  2339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2340. SSLClient cli(HOST, PORT);
  2341. cli.enable_server_certificate_verification(false);
  2342. #else
  2343. Client cli(HOST, PORT);
  2344. #endif
  2345. auto res = cli.Get("/hi");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(StatusCode::OK_200, res->status);
  2348. EXPECT_EQ("Hello World!\n", res->body);
  2349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2351. }
  2352. {
  2353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2354. SSLClient cli(HOST, PORT);
  2355. cli.enable_server_certificate_verification(false);
  2356. #else
  2357. Client cli(HOST, PORT);
  2358. #endif
  2359. auto res = cli.Get("/aaa");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2362. EXPECT_EQ("Error", res->body);
  2363. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2364. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2365. }
  2366. }
  2367. TEST(RequestHandlerTest, PreRequestHandler) {
  2368. auto route_path = "/user/:user";
  2369. Server svr;
  2370. svr.Get("/hi", [](const Request &, Response &res) {
  2371. res.set_content("hi", "text/plain");
  2372. });
  2373. svr.Get(route_path, [](const Request &req, Response &res) {
  2374. res.set_content(req.path_params.at("user"), "text/plain");
  2375. });
  2376. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2377. if (req.matched_route == route_path) {
  2378. auto user = req.path_params.at("user");
  2379. if (user != "john") {
  2380. res.status = StatusCode::Forbidden_403;
  2381. res.set_content("error", "text/html");
  2382. return Server::HandlerResponse::Handled;
  2383. }
  2384. }
  2385. return Server::HandlerResponse::Unhandled;
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. Client cli(HOST, PORT);
  2395. {
  2396. auto res = cli.Get("/hi");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ("hi", res->body);
  2400. }
  2401. {
  2402. auto res = cli.Get("/user/john");
  2403. ASSERT_TRUE(res);
  2404. EXPECT_EQ(StatusCode::OK_200, res->status);
  2405. EXPECT_EQ("john", res->body);
  2406. }
  2407. {
  2408. auto res = cli.Get("/user/invalid-user");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2411. EXPECT_EQ("error", res->body);
  2412. }
  2413. }
  2414. TEST(InvalidFormatTest, StatusCode) {
  2415. Server svr;
  2416. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2417. res.set_content("Hello World!\n", "text/plain");
  2418. res.status = 9999; // Status should be a three-digit code...
  2419. });
  2420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2421. auto se = detail::scope_exit([&] {
  2422. svr.stop();
  2423. thread.join();
  2424. ASSERT_FALSE(svr.is_running());
  2425. });
  2426. svr.wait_until_ready();
  2427. {
  2428. Client cli(HOST, PORT);
  2429. auto res = cli.Get("/hi");
  2430. ASSERT_FALSE(res);
  2431. }
  2432. }
  2433. TEST(URLFragmentTest, WithFragment) {
  2434. Server svr;
  2435. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2436. EXPECT_TRUE(req.target == "/hi");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. {
  2446. Client cli(HOST, PORT);
  2447. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2448. EXPECT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::OK_200, res->status);
  2450. res = cli.Get("/hi%23key1=val1=key2=val2");
  2451. EXPECT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2453. }
  2454. }
  2455. TEST(HeaderWriter, SetHeaderWriter) {
  2456. Server svr;
  2457. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2458. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2459. return detail::write_headers(strm, hdrs);
  2460. });
  2461. svr.Get("/hi", [](const Request &req, Response &res) {
  2462. auto it = req.headers.find("CustomClientHeader");
  2463. EXPECT_TRUE(it != req.headers.end());
  2464. EXPECT_EQ(it->second, "CustomClientValue");
  2465. res.set_content("Hello World!\n", "text/plain");
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. {
  2475. Client cli(HOST, PORT);
  2476. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2477. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2478. return detail::write_headers(strm, hdrs);
  2479. });
  2480. auto res = cli.Get("/hi");
  2481. EXPECT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::OK_200, res->status);
  2483. auto it = res->headers.find("CustomServerHeader");
  2484. EXPECT_TRUE(it != res->headers.end());
  2485. EXPECT_EQ(it->second, "CustomServerValue");
  2486. }
  2487. }
  2488. class ServerTest : public ::testing::Test {
  2489. protected:
  2490. ServerTest()
  2491. : cli_(HOST, PORT)
  2492. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2493. ,
  2494. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2495. #endif
  2496. {
  2497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2498. cli_.enable_server_certificate_verification(false);
  2499. #endif
  2500. }
  2501. virtual void SetUp() {
  2502. svr_.set_mount_point("/", "./www");
  2503. svr_.set_mount_point("/mount", "./www2");
  2504. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2505. svr_.Get("/hi",
  2506. [&](const Request & /*req*/, Response &res) {
  2507. res.set_content("Hello World!", "text/plain");
  2508. })
  2509. .Get("/file_content",
  2510. [&](const Request & /*req*/, Response &res) {
  2511. res.set_file_content("./www/dir/test.html");
  2512. })
  2513. .Get("/file_content_with_content_type",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_file_content("./www/file", "text/plain");
  2516. })
  2517. .Get("/invalid_file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/invalid_file_path");
  2520. })
  2521. .Get("/http_response_splitting",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2524. EXPECT_EQ(0U, res.headers.size());
  2525. EXPECT_FALSE(res.has_header("a"));
  2526. res.set_header("a", "1\nSet-Cookie: a=1");
  2527. EXPECT_EQ(0U, res.headers.size());
  2528. EXPECT_FALSE(res.has_header("a"));
  2529. res.set_header("a", "1\rSet-Cookie: a=1");
  2530. EXPECT_EQ(0U, res.headers.size());
  2531. EXPECT_FALSE(res.has_header("a"));
  2532. res.set_header("a\r\nb", "0");
  2533. EXPECT_EQ(0U, res.headers.size());
  2534. EXPECT_FALSE(res.has_header("a"));
  2535. res.set_header("a\rb", "0");
  2536. EXPECT_EQ(0U, res.headers.size());
  2537. EXPECT_FALSE(res.has_header("a"));
  2538. res.set_header("a\nb", "0");
  2539. EXPECT_EQ(0U, res.headers.size());
  2540. EXPECT_FALSE(res.has_header("a"));
  2541. res.set_redirect("1\r\nSet-Cookie: a=1");
  2542. EXPECT_EQ(0U, res.headers.size());
  2543. EXPECT_FALSE(res.has_header("Location"));
  2544. })
  2545. .Get("/slow",
  2546. [&](const Request & /*req*/, Response &res) {
  2547. std::this_thread::sleep_for(std::chrono::seconds(2));
  2548. res.set_content("slow", "text/plain");
  2549. })
  2550. #if 0
  2551. .Post("/slowpost",
  2552. [&](const Request & /*req*/, Response &res) {
  2553. std::this_thread::sleep_for(std::chrono::seconds(2));
  2554. res.set_content("slow", "text/plain");
  2555. })
  2556. #endif
  2557. .Get("/remote_addr",
  2558. [&](const Request &req, Response &res) {
  2559. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2560. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2561. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2562. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2563. res.set_content(req.remote_addr, "text/plain");
  2564. })
  2565. .Get("/local_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2568. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2571. auto local_addr = req.local_addr;
  2572. auto local_port = std::to_string(req.local_port);
  2573. res.set_content(local_addr.append(":").append(local_port),
  2574. "text/plain");
  2575. })
  2576. .Get("/endwith%",
  2577. [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. })
  2580. .Get("/a\\+\\+b",
  2581. [&](const Request &req, Response &res) {
  2582. ASSERT_TRUE(req.has_param("a +b"));
  2583. auto val = req.get_param_value("a +b");
  2584. res.set_content(val, "text/plain");
  2585. })
  2586. .Get("/", [&](const Request & /*req*/,
  2587. Response &res) { res.set_redirect("/hi"); })
  2588. .Post("/1",
  2589. [](const Request & /*req*/, Response &res) {
  2590. res.set_redirect("/2", StatusCode::SeeOther_303);
  2591. })
  2592. .Get("/2",
  2593. [](const Request & /*req*/, Response &res) {
  2594. res.set_content("redirected.", "text/plain");
  2595. res.status = StatusCode::OK_200;
  2596. })
  2597. .Post("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name") && req.has_param("note")) {
  2600. persons_[req.get_param_value("name")] =
  2601. req.get_param_value("note");
  2602. } else {
  2603. res.status = StatusCode::BadRequest_400;
  2604. }
  2605. })
  2606. .Put("/person",
  2607. [&](const Request &req, Response &res) {
  2608. if (req.has_param("name") && req.has_param("note")) {
  2609. persons_[req.get_param_value("name")] =
  2610. req.get_param_value("note");
  2611. } else {
  2612. res.status = StatusCode::BadRequest_400;
  2613. }
  2614. })
  2615. .Get("/person/(.*)",
  2616. [&](const Request &req, Response &res) {
  2617. string name = req.matches[1];
  2618. if (persons_.find(name) != persons_.end()) {
  2619. auto note = persons_[name];
  2620. res.set_content(note, "text/plain");
  2621. } else {
  2622. res.status = StatusCode::NotFound_404;
  2623. }
  2624. })
  2625. .Delete("/person",
  2626. [&](const Request &req, Response &res) {
  2627. if (req.has_param("name")) {
  2628. string name = req.get_param_value("name");
  2629. if (persons_.find(name) != persons_.end()) {
  2630. persons_.erase(name);
  2631. res.set_content("DELETED", "text/plain");
  2632. } else {
  2633. res.status = StatusCode::NotFound_404;
  2634. }
  2635. } else {
  2636. res.status = StatusCode::BadRequest_400;
  2637. }
  2638. })
  2639. .Post("/x-www-form-urlencoded-json",
  2640. [&](const Request &req, Response &res) {
  2641. auto json = req.get_param_value("json");
  2642. ASSERT_EQ(JSON_DATA, json);
  2643. res.set_content(json, "appliation/json");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Get("/streamed-chunked",
  2647. [&](const Request & /*req*/, Response &res) {
  2648. res.set_chunked_content_provider(
  2649. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2650. sink.os << "123";
  2651. sink.os << "456";
  2652. sink.os << "789";
  2653. sink.done();
  2654. return true;
  2655. });
  2656. })
  2657. .Get("/streamed-chunked-with-prohibited-trailer",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. auto i = new int(0);
  2660. // Declare both a prohibited trailer (Content-Length) and an
  2661. // allowed one
  2662. res.set_header("Trailer", "Content-Length, X-Allowed");
  2663. res.set_chunked_content_provider(
  2664. "text/plain",
  2665. [i](size_t /*offset*/, DataSink &sink) {
  2666. switch (*i) {
  2667. case 0: sink.os << "123"; break;
  2668. case 1: sink.os << "456"; break;
  2669. case 2: sink.os << "789"; break;
  2670. case 3: {
  2671. sink.done_with_trailer(
  2672. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2673. } break;
  2674. }
  2675. (*i)++;
  2676. return true;
  2677. },
  2678. [i](bool success) {
  2679. EXPECT_TRUE(success);
  2680. delete i;
  2681. });
  2682. })
  2683. .Get("/streamed-chunked2",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. auto i = new int(0);
  2686. res.set_chunked_content_provider(
  2687. "text/plain",
  2688. [i](size_t /*offset*/, DataSink &sink) {
  2689. switch (*i) {
  2690. case 0: sink.os << "123"; break;
  2691. case 1: sink.os << "456"; break;
  2692. case 2: sink.os << "789"; break;
  2693. case 3: sink.done(); break;
  2694. }
  2695. (*i)++;
  2696. return true;
  2697. },
  2698. [i](bool success) {
  2699. EXPECT_TRUE(success);
  2700. delete i;
  2701. });
  2702. })
  2703. .Get("/streamed-chunked-with-trailer",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. auto i = new int(0);
  2706. res.set_header("Trailer", "Dummy1, Dummy2");
  2707. res.set_chunked_content_provider(
  2708. "text/plain",
  2709. [i](size_t /*offset*/, DataSink &sink) {
  2710. switch (*i) {
  2711. case 0: sink.os << "123"; break;
  2712. case 1: sink.os << "456"; break;
  2713. case 2: sink.os << "789"; break;
  2714. case 3: {
  2715. sink.done_with_trailer(
  2716. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2717. } break;
  2718. }
  2719. (*i)++;
  2720. return true;
  2721. },
  2722. [i](bool success) {
  2723. EXPECT_TRUE(success);
  2724. delete i;
  2725. });
  2726. })
  2727. .Get("/streamed",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_content_provider(
  2730. 6, "text/plain",
  2731. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2732. sink.os << (offset < 3 ? "a" : "b");
  2733. return true;
  2734. });
  2735. })
  2736. .Get("/streamed-with-range",
  2737. [&](const Request &req, Response &res) {
  2738. auto data = new std::string("abcdefg");
  2739. res.set_content_provider(
  2740. data->size(), "text/plain",
  2741. [data](size_t offset, size_t length, DataSink &sink) {
  2742. size_t DATA_CHUNK_SIZE = 4;
  2743. const auto &d = *data;
  2744. auto out_len =
  2745. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2746. auto ret =
  2747. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2748. EXPECT_TRUE(ret);
  2749. return true;
  2750. },
  2751. [data, &req](bool success) {
  2752. EXPECT_EQ(success, !req.has_param("error"));
  2753. delete data;
  2754. });
  2755. })
  2756. .Get("/streamed-cancel",
  2757. [&](const Request & /*req*/, Response &res) {
  2758. res.set_content_provider(
  2759. size_t(-1), "text/plain",
  2760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2761. sink.os << "data_chunk";
  2762. return true;
  2763. });
  2764. })
  2765. .Get("/regex-with-delimiter",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. ASSERT_TRUE(req.has_param("key"));
  2768. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2769. })
  2770. .Get("/with-range",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_content("abcdefg", "text/plain");
  2773. })
  2774. .Get("/test-start-time",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_NE(req.start_time_,
  2777. std::chrono::steady_clock::time_point::min());
  2778. })
  2779. .Get("/with-range-customized-response",
  2780. [&](const Request & /*req*/, Response &res) {
  2781. res.status = StatusCode::BadRequest_400;
  2782. res.set_content(JSON_DATA, "application/json");
  2783. })
  2784. .Post("/chunked",
  2785. [&](const Request &req, Response & /*res*/) {
  2786. EXPECT_EQ(req.body, "dechunked post body");
  2787. })
  2788. .Post("/large-chunked",
  2789. [&](const Request &req, Response & /*res*/) {
  2790. std::string expected(6 * 30 * 1024u, 'a');
  2791. EXPECT_EQ(req.body, expected);
  2792. })
  2793. .Post("/multipart",
  2794. [&](const Request &req, Response & /*res*/) {
  2795. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2796. req.form.get_field_count("text2") +
  2797. req.form.get_field_count("file3") +
  2798. req.form.get_field_count("file4"));
  2799. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2800. req.form.get_file_count("file2"));
  2801. ASSERT_TRUE(!req.form.has_file("???"));
  2802. ASSERT_TRUE(!req.form.has_field("???"));
  2803. ASSERT_TRUE(req.body.empty());
  2804. {
  2805. const auto &text = req.form.get_field("text1");
  2806. EXPECT_EQ("text default", text);
  2807. }
  2808. {
  2809. const auto &text = req.form.get_field("text2");
  2810. EXPECT_EQ("aωb", text);
  2811. }
  2812. {
  2813. const auto &file = req.form.get_file("file1");
  2814. EXPECT_EQ("hello.txt", file.filename);
  2815. EXPECT_EQ("text/plain", file.content_type);
  2816. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2817. }
  2818. {
  2819. const auto &file = req.form.get_file("file2");
  2820. EXPECT_EQ("world.json", file.filename);
  2821. EXPECT_EQ("application/json", file.content_type);
  2822. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2823. }
  2824. {
  2825. const auto &text = req.form.get_field("file3");
  2826. EXPECT_EQ(0u, text.size());
  2827. }
  2828. {
  2829. const auto &text = req.form.get_field("file4");
  2830. EXPECT_EQ(0u, text.size());
  2831. }
  2832. })
  2833. .Post("/multipart/multi_file_values",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2836. req.form.get_field_count("multi_text1"));
  2837. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2838. ASSERT_TRUE(!req.form.has_file("???"));
  2839. ASSERT_TRUE(!req.form.has_field("???"));
  2840. ASSERT_TRUE(req.body.empty());
  2841. {
  2842. const auto &text = req.form.get_field("text");
  2843. EXPECT_EQ("default text", text);
  2844. }
  2845. {
  2846. const auto &text1_values = req.form.get_fields("multi_text1");
  2847. EXPECT_EQ(2u, text1_values.size());
  2848. EXPECT_EQ("aaaaa", text1_values[0]);
  2849. EXPECT_EQ("bbbbb", text1_values[1]);
  2850. }
  2851. {
  2852. const auto &file1_values = req.form.get_files("multi_file1");
  2853. EXPECT_EQ(2u, file1_values.size());
  2854. auto file1 = file1_values[0];
  2855. EXPECT_EQ(file1.filename, "hello.txt");
  2856. EXPECT_EQ(file1.content_type, "text/plain");
  2857. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2858. auto file2 = file1_values[1];
  2859. EXPECT_EQ(file2.filename, "world.json");
  2860. EXPECT_EQ(file2.content_type, "application/json");
  2861. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2862. }
  2863. })
  2864. .Post("/empty",
  2865. [&](const Request &req, Response &res) {
  2866. EXPECT_EQ(req.body, "");
  2867. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2869. res.set_content("empty", "text/plain");
  2870. })
  2871. .Post("/empty-no-content-type",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "");
  2874. EXPECT_FALSE(req.has_header("Content-Type"));
  2875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2876. res.set_content("empty-no-content-type", "text/plain");
  2877. })
  2878. .Post("/path-only",
  2879. [&](const Request &req, Response &res) {
  2880. EXPECT_EQ(req.body, "");
  2881. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2882. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2883. res.set_content("path-only", "text/plain");
  2884. })
  2885. .Post("/path-headers-only",
  2886. [&](const Request &req, Response &res) {
  2887. EXPECT_EQ(req.body, "");
  2888. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2889. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2890. EXPECT_EQ("world", req.get_header_value("hello"));
  2891. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2892. res.set_content("path-headers-only", "text/plain");
  2893. })
  2894. .Post("/post-large",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(req.body, LARGE_DATA);
  2897. res.set_content(req.body, "text/plain");
  2898. })
  2899. .Post("/post-loopback",
  2900. [&](const Request &, Response &res,
  2901. ContentReader const &content_reader) {
  2902. std::string body;
  2903. content_reader([&](const char *data, size_t data_length) {
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. res.set_content(body, "text/plain");
  2908. })
  2909. .Put("/put-loopback",
  2910. [&](const Request &, Response &res,
  2911. ContentReader const &content_reader) {
  2912. std::string body;
  2913. content_reader([&](const char *data, size_t data_length) {
  2914. body.append(data, data_length);
  2915. return true;
  2916. });
  2917. res.set_content(body, "text/plain");
  2918. })
  2919. .Patch("/patch-loopback",
  2920. [&](const Request &, Response &res,
  2921. ContentReader const &content_reader) {
  2922. std::string body;
  2923. content_reader([&](const char *data, size_t data_length) {
  2924. body.append(data, data_length);
  2925. return true;
  2926. });
  2927. res.set_content(body, "text/plain");
  2928. })
  2929. .Put("/empty-no-content-type",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "");
  2932. EXPECT_FALSE(req.has_header("Content-Type"));
  2933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2934. res.set_content("empty-no-content-type", "text/plain");
  2935. })
  2936. .Put("/put",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "PUT");
  2939. res.set_content(req.body, "text/plain");
  2940. })
  2941. .Put("/put-large",
  2942. [&](const Request &req, Response &res) {
  2943. EXPECT_EQ(req.body, LARGE_DATA);
  2944. res.set_content(req.body, "text/plain");
  2945. })
  2946. .Patch("/patch",
  2947. [&](const Request &req, Response &res) {
  2948. EXPECT_EQ(req.body, "PATCH");
  2949. res.set_content(req.body, "text/plain");
  2950. })
  2951. .Delete("/delete",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_content("DELETE", "text/plain");
  2954. })
  2955. .Delete("/delete-body",
  2956. [&](const Request &req, Response &res) {
  2957. EXPECT_EQ(req.body, "content");
  2958. res.set_content(req.body, "text/plain");
  2959. })
  2960. .Options(R"(\*)",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2963. })
  2964. .Get("/request-target",
  2965. [&](const Request &req, Response & /*res*/) {
  2966. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2967. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2968. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2969. })
  2970. .Get("/long-query-value",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2973. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2974. })
  2975. .Get("/too-long-query-value",
  2976. [&](const Request &req, Response & /*res*/) {
  2977. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2978. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2979. })
  2980. .Get("/array-param",
  2981. [&](const Request &req, Response & /*res*/) {
  2982. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2983. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2984. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2985. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2986. })
  2987. .Post("/validate-no-multiple-headers",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2990. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2991. })
  2992. .Post("/content_receiver",
  2993. [&](const Request &req, Response &res,
  2994. const ContentReader &content_reader) {
  2995. if (req.is_multipart_form_data()) {
  2996. std::vector<FormData> items;
  2997. content_reader(
  2998. [&](const FormData &file) {
  2999. items.push_back(file);
  3000. return true;
  3001. },
  3002. [&](const char *data, size_t data_length) {
  3003. items.back().content.append(data, data_length);
  3004. return true;
  3005. });
  3006. EXPECT_EQ(5u, items.size());
  3007. {
  3008. const auto &file = get_file_value(items, "text1");
  3009. EXPECT_TRUE(file.filename.empty());
  3010. EXPECT_EQ("text default", file.content);
  3011. }
  3012. {
  3013. const auto &file = get_file_value(items, "text2");
  3014. EXPECT_TRUE(file.filename.empty());
  3015. EXPECT_EQ("aωb", file.content);
  3016. }
  3017. {
  3018. const auto &file = get_file_value(items, "file1");
  3019. EXPECT_EQ("hello.txt", file.filename);
  3020. EXPECT_EQ("text/plain", file.content_type);
  3021. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3022. }
  3023. {
  3024. const auto &file = get_file_value(items, "file2");
  3025. EXPECT_EQ("world.json", file.filename);
  3026. EXPECT_EQ("application/json", file.content_type);
  3027. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3028. }
  3029. {
  3030. const auto &file = get_file_value(items, "file3");
  3031. EXPECT_TRUE(file.filename.empty());
  3032. EXPECT_EQ("application/octet-stream", file.content_type);
  3033. EXPECT_EQ(0u, file.content.size());
  3034. }
  3035. } else {
  3036. std::string body;
  3037. content_reader([&](const char *data, size_t data_length) {
  3038. EXPECT_EQ(7U, data_length);
  3039. body.append(data, data_length);
  3040. return true;
  3041. });
  3042. EXPECT_EQ(body, "content");
  3043. res.set_content(body, "text/plain");
  3044. }
  3045. })
  3046. .Put("/content_receiver",
  3047. [&](const Request & /*req*/, Response &res,
  3048. const ContentReader &content_reader) {
  3049. std::string body;
  3050. content_reader([&](const char *data, size_t data_length) {
  3051. body.append(data, data_length);
  3052. return true;
  3053. });
  3054. EXPECT_EQ(body, "content");
  3055. res.set_content(body, "text/plain");
  3056. })
  3057. .Patch("/content_receiver",
  3058. [&](const Request & /*req*/, Response &res,
  3059. const ContentReader &content_reader) {
  3060. std::string body;
  3061. content_reader([&](const char *data, size_t data_length) {
  3062. body.append(data, data_length);
  3063. return true;
  3064. });
  3065. EXPECT_EQ(body, "content");
  3066. res.set_content(body, "text/plain");
  3067. })
  3068. .Post("/query-string-and-body",
  3069. [&](const Request &req, Response & /*res*/) {
  3070. ASSERT_TRUE(req.has_param("key"));
  3071. EXPECT_EQ(req.get_param_value("key"), "value");
  3072. EXPECT_EQ(req.body, "content");
  3073. })
  3074. .Get("/last-request",
  3075. [&](const Request &req, Response & /*res*/) {
  3076. EXPECT_EQ("close", req.get_header_value("Connection"));
  3077. })
  3078. .Get(R"(/redirect/(\d+))",
  3079. [&](const Request &req, Response &res) {
  3080. auto num = std::stoi(req.matches[1]) + 1;
  3081. std::string url = "/redirect/" + std::to_string(num);
  3082. res.set_redirect(url);
  3083. })
  3084. .Post("/binary",
  3085. [&](const Request &req, Response &res) {
  3086. EXPECT_EQ(4U, req.body.size());
  3087. EXPECT_EQ("application/octet-stream",
  3088. req.get_header_value("Content-Type"));
  3089. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3090. res.set_content(req.body, "application/octet-stream");
  3091. })
  3092. .Put("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Patch("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Delete("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Get("/issue1772",
  3117. [&](const Request & /*req*/, Response &res) {
  3118. res.status = 401;
  3119. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3120. })
  3121. .Delete("/issue609",
  3122. [](const httplib::Request &, httplib::Response &res,
  3123. const httplib::ContentReader &) {
  3124. res.set_content("ok", "text/plain");
  3125. })
  3126. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3127. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3128. .Get("/compress",
  3129. [&](const Request & /*req*/, Response &res) {
  3130. res.set_content(
  3131. "12345678901234567890123456789012345678901234567890123456789"
  3132. "01234567890123456789012345678901234567890",
  3133. "text/plain");
  3134. })
  3135. .Get("/nocompress",
  3136. [&](const Request & /*req*/, Response &res) {
  3137. res.set_content(
  3138. "12345678901234567890123456789012345678901234567890123456789"
  3139. "01234567890123456789012345678901234567890",
  3140. "application/octet-stream");
  3141. })
  3142. .Post("/compress-multipart",
  3143. [&](const Request &req, Response & /*res*/) {
  3144. EXPECT_EQ(2u, req.form.fields.size());
  3145. ASSERT_TRUE(!req.form.has_field("???"));
  3146. {
  3147. const auto &text = req.form.get_field("key1");
  3148. EXPECT_EQ("test", text);
  3149. }
  3150. {
  3151. const auto &text = req.form.get_field("key2");
  3152. EXPECT_EQ("--abcdefg123", text);
  3153. }
  3154. })
  3155. #endif
  3156. ;
  3157. persons_["john"] = "programmer";
  3158. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3159. svr_.wait_until_ready();
  3160. }
  3161. virtual void TearDown() {
  3162. svr_.stop();
  3163. if (!request_threads_.empty()) {
  3164. std::this_thread::sleep_for(std::chrono::seconds(1));
  3165. for (auto &t : request_threads_) {
  3166. t.join();
  3167. }
  3168. }
  3169. t_.join();
  3170. }
  3171. map<string, string> persons_;
  3172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3173. SSLClient cli_;
  3174. SSLServer svr_;
  3175. #else
  3176. Client cli_;
  3177. Server svr_;
  3178. #endif
  3179. thread t_;
  3180. std::vector<thread> request_threads_;
  3181. };
  3182. TEST_F(ServerTest, GetMethod200) {
  3183. auto res = cli_.Get("/hi");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ("HTTP/1.1", res->version);
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. EXPECT_EQ("OK", res->reason);
  3188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3190. EXPECT_EQ("Hello World!", res->body);
  3191. }
  3192. TEST_F(ServerTest, GetEmptyFile) {
  3193. auto res = cli_.Get("/empty_file");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3198. EXPECT_EQ("", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetFileContent) {
  3201. auto res = cli_.Get("/file_content");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("test.html", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContentWithRange) {
  3209. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3214. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3215. EXPECT_EQ("est", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetFileContentWithContentType) {
  3218. auto res = cli_.Get("/file_content_with_content_type");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("file\n", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetInvalidFileContent) {
  3226. auto res = cli_.Get("/invalid_file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3231. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ("HTTP/1.1", res->version);
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3236. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. TEST_F(ServerTest, GetMethod302) {
  3240. auto res = cli_.Get("/");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::Found_302, res->status);
  3243. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3244. }
  3245. TEST_F(ServerTest, GetMethod302Redirect) {
  3246. cli_.set_follow_location(true);
  3247. auto res = cli_.Get("/");
  3248. ASSERT_TRUE(res);
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. EXPECT_EQ("Hello World!", res->body);
  3251. EXPECT_EQ("/hi", res->location);
  3252. }
  3253. TEST_F(ServerTest, GetMethod404) {
  3254. auto res = cli_.Get("/invalid");
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3257. }
  3258. TEST_F(ServerTest, HeadMethod200) {
  3259. auto res = cli_.Head("/hi");
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. EXPECT_TRUE(res->body.empty());
  3264. }
  3265. TEST_F(ServerTest, HeadMethod200Static) {
  3266. auto res = cli_.Head("/mount/dir/index.html");
  3267. ASSERT_TRUE(res);
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3270. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod404) {
  3274. auto res = cli_.Head("/invalid");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3277. EXPECT_TRUE(res->body.empty());
  3278. }
  3279. TEST_F(ServerTest, GetMethodPersonJohn) {
  3280. auto res = cli_.Get("/person/john");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("programmer", res->body);
  3285. }
  3286. TEST_F(ServerTest, PostMethod1) {
  3287. auto res = cli_.Get("/person/john1");
  3288. ASSERT_TRUE(res);
  3289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3290. res = cli_.Post("/person", "name=john1&note=coder",
  3291. "application/x-www-form-urlencoded");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::OK_200, res->status);
  3294. res = cli_.Get("/person/john1");
  3295. ASSERT_TRUE(res);
  3296. ASSERT_EQ(StatusCode::OK_200, res->status);
  3297. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3298. ASSERT_EQ("coder", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostMethod2) {
  3301. auto res = cli_.Get("/person/john2");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john2");
  3306. params.emplace("note", "coder");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john2");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("coder", res->body);
  3315. }
  3316. TEST_F(ServerTest, PutMethod3) {
  3317. auto res = cli_.Get("/person/john3");
  3318. ASSERT_TRUE(res);
  3319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3320. Params params;
  3321. params.emplace("name", "john3");
  3322. params.emplace("note", "coder");
  3323. res = cli_.Put("/person", params);
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::OK_200, res->status);
  3326. res = cli_.Get("/person/john3");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3330. ASSERT_EQ("coder", res->body);
  3331. }
  3332. TEST_F(ServerTest, DeleteMethod1) {
  3333. auto res = cli_.Get("/person/john4");
  3334. ASSERT_TRUE(res);
  3335. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3336. Params params;
  3337. params.emplace("name", "john4");
  3338. params.emplace("note", "coder");
  3339. res = cli_.Post("/person", params);
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. res = cli_.Get("/person/john4");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3346. ASSERT_EQ("coder", res->body);
  3347. Params delete_params;
  3348. delete_params.emplace("name", "john4");
  3349. res = cli_.Delete("/person", delete_params);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john4");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod2) {
  3358. auto res = cli_.Get("/person/john5");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john5");
  3363. params.emplace("note", "developer");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john5");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("developer", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john5");
  3374. Headers headers;
  3375. headers.emplace("Custom-Header", "test-value");
  3376. res = cli_.Delete("/person", headers, delete_params);
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::OK_200, res->status);
  3379. ASSERT_EQ("DELETED", res->body);
  3380. res = cli_.Get("/person/john5");
  3381. ASSERT_TRUE(res);
  3382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3383. }
  3384. TEST_F(ServerTest, DeleteMethod3) {
  3385. auto res = cli_.Get("/person/john6");
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3388. Params params;
  3389. params.emplace("name", "john6");
  3390. params.emplace("note", "tester");
  3391. res = cli_.Post("/person", params);
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. res = cli_.Get("/person/john6");
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. ASSERT_EQ("tester", res->body);
  3399. Params delete_params;
  3400. delete_params.emplace("name", "john6");
  3401. Headers headers;
  3402. headers.emplace("Custom-Header", "test-value");
  3403. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3404. ASSERT_TRUE(res);
  3405. ASSERT_EQ(StatusCode::OK_200, res->status);
  3406. ASSERT_EQ("DELETED", res->body);
  3407. res = cli_.Get("/person/john6");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3412. Params params;
  3413. params.emplace("json", JSON_DATA);
  3414. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ(JSON_DATA, res->body);
  3418. }
  3419. TEST_F(ServerTest, PostEmptyContent) {
  3420. auto res = cli_.Post("/empty", "", "text/plain");
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::OK_200, res->status);
  3423. ASSERT_EQ("empty", res->body);
  3424. }
  3425. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3426. auto res = cli_.Post("/empty-no-content-type");
  3427. ASSERT_TRUE(res);
  3428. ASSERT_EQ(StatusCode::OK_200, res->status);
  3429. ASSERT_EQ("empty-no-content-type", res->body);
  3430. }
  3431. TEST_F(ServerTest, PostPathOnly) {
  3432. auto res = cli_.Post("/path-only");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::OK_200, res->status);
  3435. ASSERT_EQ("path-only", res->body);
  3436. }
  3437. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3438. auto res = cli_.Post("/path-headers-only",
  3439. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("path-headers-only", res->body);
  3443. }
  3444. TEST_F(ServerTest, PostLarge) {
  3445. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ(LARGE_DATA, res->body);
  3449. }
  3450. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3451. auto res = cli_.Put("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetMethodDir) {
  3457. auto res = cli_.Get("/dir/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. auto body = R"(<html>
  3462. <head>
  3463. </head>
  3464. <body>
  3465. <a href="/dir/test.html">Test</a>
  3466. <a href="/hi">hi</a>
  3467. </body>
  3468. </html>
  3469. )";
  3470. EXPECT_EQ(body, res->body);
  3471. }
  3472. TEST_F(ServerTest, GetMethodDirTest) {
  3473. auto res = cli_.Get("/dir/test.html");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("test.html", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3480. auto res = cli_.Get("/dir/../dir/test.html");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3484. EXPECT_EQ("test.html", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethodInvalidPath) {
  3487. auto res = cli_.Get("/dir/../test.html");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3490. }
  3491. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3492. auto res = cli_.Get("/../www/dir/test.html");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3495. }
  3496. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3497. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3500. }
  3501. TEST_F(ServerTest, GetMethodDirMountTest) {
  3502. auto res = cli_.Get("/mount/dir/test.html");
  3503. ASSERT_TRUE(res);
  3504. EXPECT_EQ(StatusCode::OK_200, res->status);
  3505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3506. EXPECT_EQ("test.html", res->body);
  3507. }
  3508. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3509. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("test.html", res->body);
  3514. }
  3515. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3516. auto res = cli_.Get("/mount/dir/../test.html");
  3517. ASSERT_TRUE(res);
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3521. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. }
  3525. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3526. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3527. ASSERT_TRUE(res);
  3528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3529. }
  3530. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3531. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3534. }
  3535. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3536. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, PostMethod303) {
  3541. auto res = cli_.Post("/1", "body", "text/plain");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3544. EXPECT_EQ("/2", res->get_header_value("Location"));
  3545. }
  3546. TEST_F(ServerTest, PostMethod303Redirect) {
  3547. cli_.set_follow_location(true);
  3548. auto res = cli_.Post("/1", "body", "text/plain");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ(StatusCode::OK_200, res->status);
  3551. EXPECT_EQ("redirected.", res->body);
  3552. EXPECT_EQ("/2", res->location);
  3553. }
  3554. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3555. auto res = cli_.Get("/dir/test.abcde");
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3559. EXPECT_EQ("abcde", res->body);
  3560. }
  3561. TEST_F(ServerTest, StaticFileRange) {
  3562. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3565. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3566. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3567. EXPECT_EQ(true, res->has_header("Content-Range"));
  3568. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3569. EXPECT_EQ(std::string("cd"), res->body);
  3570. }
  3571. TEST_F(ServerTest, StaticFileRanges) {
  3572. auto res =
  3573. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3576. EXPECT_TRUE(
  3577. res->get_header_value("Content-Type")
  3578. .find(
  3579. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3580. 0);
  3581. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3582. }
  3583. TEST_F(ServerTest, StaticFileRangeHead) {
  3584. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3585. ASSERT_TRUE(res);
  3586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3587. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3589. EXPECT_EQ(true, res->has_header("Content-Range"));
  3590. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3591. }
  3592. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3593. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3597. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3598. EXPECT_EQ(true, res->has_header("Content-Range"));
  3599. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3600. res->get_header_value("Content-Range"));
  3601. EXPECT_EQ("LAST\n", res->body);
  3602. }
  3603. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3604. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3609. EXPECT_EQ(true, res->has_header("Content-Range"));
  3610. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3611. }
  3612. TEST_F(ServerTest, StaticFileBigFile) {
  3613. auto res = cli_.Get("/dir/1MB.txt");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3617. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3618. }
  3619. TEST_F(ServerTest, InvalidBaseDirMount) {
  3620. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3621. }
  3622. TEST_F(ServerTest, Binary) {
  3623. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3624. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3625. "application/octet-stream");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ(4U, res->body.size());
  3629. res = cli_.Put("/binary", binary.data(), binary.size(),
  3630. "application/octet-stream");
  3631. ASSERT_TRUE(res);
  3632. ASSERT_EQ(StatusCode::OK_200, res->status);
  3633. ASSERT_EQ(4U, res->body.size());
  3634. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3635. "application/octet-stream");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ(4U, res->body.size());
  3639. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3640. "application/octet-stream");
  3641. ASSERT_TRUE(res);
  3642. ASSERT_EQ(StatusCode::OK_200, res->status);
  3643. ASSERT_EQ(4U, res->body.size());
  3644. }
  3645. TEST_F(ServerTest, BinaryString) {
  3646. auto binary = std::string("\x00\x01\x02\x03", 4);
  3647. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. ASSERT_EQ(4U, res->body.size());
  3651. res = cli_.Put("/binary", binary, "application/octet-stream");
  3652. ASSERT_TRUE(res);
  3653. ASSERT_EQ(StatusCode::OK_200, res->status);
  3654. ASSERT_EQ(4U, res->body.size());
  3655. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. }
  3664. TEST_F(ServerTest, EmptyRequest) {
  3665. auto res = cli_.Get("");
  3666. ASSERT_TRUE(!res);
  3667. EXPECT_EQ(Error::Connection, res.error());
  3668. }
  3669. TEST_F(ServerTest, LongRequest) {
  3670. std::string request;
  3671. for (size_t i = 0; i < 545; i++) {
  3672. request += "/TooLongRequest";
  3673. }
  3674. request += "OK";
  3675. auto res = cli_.Get(request.c_str());
  3676. ASSERT_TRUE(res);
  3677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3678. }
  3679. TEST_F(ServerTest, TooLongRequest) {
  3680. std::string request;
  3681. for (size_t i = 0; i < 546; i++) {
  3682. request += "/TooLongRequest";
  3683. }
  3684. request += "_NG";
  3685. auto start = std::chrono::high_resolution_clock::now();
  3686. cli_.set_keep_alive(true);
  3687. auto res = cli_.Get(request.c_str());
  3688. auto end = std::chrono::high_resolution_clock::now();
  3689. auto elapsed =
  3690. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3691. .count();
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3694. EXPECT_LE(elapsed, 100);
  3695. EXPECT_EQ("close", res->get_header_value("Connection"));
  3696. EXPECT_FALSE(cli_.is_socket_open());
  3697. }
  3698. TEST_F(ServerTest, AlmostTooLongRequest) {
  3699. // test for #2046 - URI length check shouldn't include other content on req
  3700. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3701. // leading /, space, HTTP/1.1)
  3702. std::string request =
  3703. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3704. auto res = cli_.Get(request.c_str());
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3707. }
  3708. TEST_F(ServerTest, LongHeader) {
  3709. Request req;
  3710. req.method = "GET";
  3711. req.path = "/hi";
  3712. std::string host_and_port;
  3713. host_and_port += HOST;
  3714. host_and_port += ":";
  3715. host_and_port += std::to_string(PORT);
  3716. req.headers.emplace("Host", host_and_port.c_str());
  3717. req.headers.emplace("Accept", "*/*");
  3718. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3719. req.headers.emplace(
  3720. "Header-Name",
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@");
  3750. auto res = std::make_shared<Response>();
  3751. auto error = Error::Success;
  3752. auto ret = cli_.send(req, *res, error);
  3753. ASSERT_TRUE(ret);
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST_F(ServerTest, LongQueryValue) {
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3760. auto end = std::chrono::high_resolution_clock::now();
  3761. auto elapsed =
  3762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3763. .count();
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3766. EXPECT_LE(elapsed, 100);
  3767. EXPECT_EQ("close", res->get_header_value("Connection"));
  3768. EXPECT_FALSE(cli_.is_socket_open());
  3769. }
  3770. TEST_F(ServerTest, TooLongQueryValue) {
  3771. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3772. ASSERT_FALSE(res);
  3773. EXPECT_EQ(Error::Read, res.error());
  3774. }
  3775. TEST_F(ServerTest, TooLongHeader) {
  3776. Request req;
  3777. req.method = "GET";
  3778. req.path = "/hi";
  3779. std::string host_and_port;
  3780. host_and_port += HOST;
  3781. host_and_port += ":";
  3782. host_and_port += std::to_string(PORT);
  3783. req.headers.emplace("Host", host_and_port.c_str());
  3784. req.headers.emplace("Accept", "*/*");
  3785. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3786. req.headers.emplace(
  3787. "Header-Name",
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@");
  3817. auto res = std::make_shared<Response>();
  3818. auto error = Error::Success;
  3819. auto ret = cli_.send(req, *res, error);
  3820. ASSERT_TRUE(ret);
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. TEST_F(ServerTest, HeaderCountAtLimit) {
  3824. // Test with headers just under the 100 limit
  3825. httplib::Headers headers;
  3826. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3827. // This should keep us just under the 100 header limit
  3828. for (int i = 0; i < 95; i++) {
  3829. std::string name = "X-Test-Header-" + std::to_string(i);
  3830. std::string value = "value" + std::to_string(i);
  3831. headers.emplace(name, value);
  3832. }
  3833. // This should work fine as we're under the limit
  3834. auto res = cli_.Get("/hi", headers);
  3835. EXPECT_TRUE(res);
  3836. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3837. }
  3838. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3839. // Test with many headers to exceed the 100 limit
  3840. httplib::Headers headers;
  3841. // Add 150 headers to definitely exceed the 100 limit
  3842. for (int i = 0; i < 150; i++) {
  3843. std::string name = "X-Test-Header-" + std::to_string(i);
  3844. std::string value = "value" + std::to_string(i);
  3845. headers.emplace(name, value);
  3846. }
  3847. // This should fail due to exceeding header count limit
  3848. cli_.set_keep_alive(true);
  3849. auto res = cli_.Get("/hi", headers);
  3850. // The request should either fail or return 400 Bad Request
  3851. if (res) {
  3852. // If we get a response, it should be 400 Bad Request
  3853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3854. } else {
  3855. // Or the request should fail entirely
  3856. EXPECT_FALSE(res);
  3857. }
  3858. EXPECT_EQ("close", res->get_header_value("Connection"));
  3859. EXPECT_FALSE(cli_.is_socket_open());
  3860. }
  3861. TEST_F(ServerTest, PercentEncoding) {
  3862. auto res = cli_.Get("/e%6edwith%");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, PercentEncodingUnicode) {
  3867. auto res = cli_.Get("/e%u006edwith%");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, InvalidPercentEncoding) {
  3872. auto res = cli_.Get("/%endwith%");
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3875. }
  3876. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3877. auto res = cli_.Get("/%uendwith%");
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3880. }
  3881. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3882. auto res = cli_.Get("/hello?aaa=bbb%");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3885. }
  3886. TEST_F(ServerTest, PlusSignEncoding) {
  3887. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. EXPECT_EQ("a +b", res->body);
  3891. }
  3892. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3893. // This test simulates a potential DoS attack using many headers
  3894. // to verify our security fix prevents memory exhaustion
  3895. httplib::Headers attack_headers;
  3896. // Attempt to add many headers like an attacker would (200 headers to far
  3897. // exceed limit)
  3898. for (int i = 0; i < 200; i++) {
  3899. std::string name = "X-Attack-Header-" + std::to_string(i);
  3900. std::string value = "attack_payload_" + std::to_string(i);
  3901. attack_headers.emplace(name, value);
  3902. }
  3903. // Try to POST with excessive headers
  3904. cli_.set_keep_alive(true);
  3905. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3906. // Should either fail or return 400 Bad Request due to security limit
  3907. if (res) {
  3908. // If we get a response, it should be 400 Bad Request
  3909. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3910. } else {
  3911. // Request failed, which is the expected behavior for DoS protection
  3912. EXPECT_FALSE(res);
  3913. }
  3914. EXPECT_EQ("close", res->get_header_value("Connection"));
  3915. EXPECT_FALSE(cli_.is_socket_open());
  3916. }
  3917. TEST_F(ServerTest, MultipartFormData) {
  3918. UploadFormDataItems items = {
  3919. {"text1", "text default", "", ""},
  3920. {"text2", "aωb", "", ""},
  3921. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3922. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3923. {"file3", "", "", "application/octet-stream"},
  3924. {"file4", "", "", " application/json tmp-string "}};
  3925. auto res = cli_.Post("/multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3930. UploadFormDataItems items = {
  3931. {"text", "default text", "", ""},
  3932. {"multi_text1", "aaaaa", "", ""},
  3933. {"multi_text1", "bbbbb", "", ""},
  3934. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3935. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3936. "application/json"},
  3937. };
  3938. auto res = cli_.Post("/multipart/multi_file_values", items);
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::OK_200, res->status);
  3941. }
  3942. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3943. auto res = cli_.Get("/hi");
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3947. EXPECT_EQ("Hello World!", res->body);
  3948. }
  3949. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3950. Request req;
  3951. req.method = "POST";
  3952. req.path = "/chunked";
  3953. std::string host_and_port;
  3954. host_and_port += HOST;
  3955. host_and_port += ":";
  3956. host_and_port += std::to_string(PORT);
  3957. req.headers.emplace("Host", host_and_port.c_str());
  3958. req.headers.emplace("Accept", "*/*");
  3959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3960. req.headers.emplace("Content-Type", "text/plain");
  3961. req.headers.emplace("Content-Length", "0");
  3962. req.headers.emplace(
  3963. "Transfer-Encoding",
  3964. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3965. // Client does not chunk, so make a chunked body manually.
  3966. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3967. auto res = std::make_shared<Response>();
  3968. auto error = Error::Success;
  3969. auto ret = cli_.send(req, *res, error);
  3970. ASSERT_TRUE(ret);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, GetStreamed2) {
  3974. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(true, res->has_header("Content-Range"));
  3979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3980. EXPECT_EQ(std::string("ab"), res->body);
  3981. }
  3982. TEST_F(ServerTest, GetStreamed) {
  3983. auto res = cli_.Get("/streamed");
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::OK_200, res->status);
  3986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3987. EXPECT_EQ(std::string("aaabbb"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedWithRange1) {
  3990. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3994. EXPECT_EQ(true, res->has_header("Content-Range"));
  3995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3996. EXPECT_EQ(std::string("def"), res->body);
  3997. }
  3998. TEST_F(ServerTest, GetStreamedWithRange2) {
  3999. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("bcdefg"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4008. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4011. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(true, res->has_header("Content-Range"));
  4013. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4014. EXPECT_EQ(std::string("efg"), res->body);
  4015. }
  4016. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4017. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4020. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4021. EXPECT_EQ(false, res->has_header("Content-Range"));
  4022. EXPECT_EQ(0U, res->body.size());
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4025. auto res = cli_.Get("/streamed-with-range",
  4026. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4027. "92233720368547758079223372036854775807"}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4035. auto res = cli_.Get(
  4036. "/with-range",
  4037. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4038. {"Accept-Encoding", ""}});
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4042. EXPECT_EQ(true, res->has_header("Content-Range"));
  4043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4044. EXPECT_EQ(std::string("abcdefg"), res->body);
  4045. }
  4046. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4047. auto res = cli_.Get("/with-range", {
  4048. {"Range", "bytes=0-"},
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("abcdefg"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4059. auto res =
  4060. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4063. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4064. EXPECT_EQ(false, res->has_header("Content-Range"));
  4065. EXPECT_EQ(267U, res->body.size());
  4066. // Check that both range contents are present
  4067. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4068. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4069. // Check that Content-Range headers are present for both ranges
  4070. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4071. std::string::npos);
  4072. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4073. std::string::npos);
  4074. }
  4075. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4076. Ranges ranges;
  4077. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4078. ranges.emplace_back(0, -1);
  4079. }
  4080. auto res =
  4081. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4084. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(0U, res->body.size());
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(5U, res->body.size());
  4094. // Check that overlapping ranges are coalesced into a single range
  4095. EXPECT_EQ("bcdef", res->body);
  4096. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4097. // Should be single range, not multipart
  4098. EXPECT_TRUE(res->has_header("Content-Range"));
  4099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. }
  4101. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4102. auto res =
  4103. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4106. EXPECT_EQ(268U, res->body.size());
  4107. // Check that both range contents are present
  4108. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4109. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4110. // Check that Content-Range headers are present for both ranges
  4111. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4112. std::string::npos);
  4113. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4114. std::string::npos);
  4115. }
  4116. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4117. auto res =
  4118. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ(269U, res->body.size());
  4122. // Check that both duplicate range contents are present
  4123. size_t first_abc = res->body.find("abc\r\n");
  4124. EXPECT_TRUE(first_abc != std::string::npos);
  4125. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4126. EXPECT_TRUE(second_abc != std::string::npos);
  4127. // Check that Content-Range headers are present for both ranges
  4128. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4129. EXPECT_TRUE(first_range != std::string::npos);
  4130. size_t second_range =
  4131. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4132. EXPECT_TRUE(second_range != std::string::npos);
  4133. }
  4134. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4135. auto res = cli_.Get("/streamed-with-range?error",
  4136. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(0U, res->body.size());
  4142. }
  4143. TEST_F(ServerTest, GetStreamedEndless) {
  4144. uint64_t offset = 0;
  4145. auto res = cli_.Get("/streamed-cancel",
  4146. [&](const char * /*data*/, uint64_t data_length) {
  4147. if (offset < 100) {
  4148. offset += data_length;
  4149. return true;
  4150. }
  4151. return false;
  4152. });
  4153. ASSERT_TRUE(!res);
  4154. EXPECT_EQ(Error::Canceled, res.error());
  4155. }
  4156. TEST_F(ServerTest, ClientStop) {
  4157. std::atomic_size_t count{4};
  4158. std::vector<std::thread> threads;
  4159. for (auto i = count.load(); i != 0; --i) {
  4160. threads.emplace_back([&]() {
  4161. auto res = cli_.Get("/streamed-cancel",
  4162. [&](const char *, uint64_t) { return true; });
  4163. --count;
  4164. ASSERT_TRUE(!res);
  4165. EXPECT_TRUE(res.error() == Error::Canceled ||
  4166. res.error() == Error::Read || res.error() == Error::Write);
  4167. });
  4168. }
  4169. std::this_thread::sleep_for(std::chrono::seconds(2));
  4170. while (count != 0) {
  4171. cli_.stop();
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4173. }
  4174. for (auto &t : threads) {
  4175. t.join();
  4176. }
  4177. }
  4178. TEST_F(ServerTest, GetWithRange1) {
  4179. auto res = cli_.Get("/with-range", {
  4180. make_range_header({{3, 5}}),
  4181. {"Accept-Encoding", ""},
  4182. });
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4185. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(true, res->has_header("Content-Range"));
  4187. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4188. EXPECT_EQ(std::string("def"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetWithRange2) {
  4191. auto res = cli_.Get("/with-range", {
  4192. make_range_header({{1, -1}}),
  4193. {"Accept-Encoding", ""},
  4194. });
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4197. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4198. EXPECT_EQ(true, res->has_header("Content-Range"));
  4199. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4200. EXPECT_EQ(std::string("bcdefg"), res->body);
  4201. }
  4202. TEST_F(ServerTest, GetWithRange3) {
  4203. auto res = cli_.Get("/with-range", {
  4204. make_range_header({{0, 0}}),
  4205. {"Accept-Encoding", ""},
  4206. });
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("a"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetWithRange4) {
  4215. auto res = cli_.Get("/with-range", {
  4216. make_range_header({{-1, 2}}),
  4217. {"Accept-Encoding", ""},
  4218. });
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(true, res->has_header("Content-Range"));
  4223. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4224. EXPECT_EQ(std::string("fg"), res->body);
  4225. }
  4226. TEST_F(ServerTest, GetWithRange5) {
  4227. auto res = cli_.Get("/with-range", {
  4228. make_range_header({{0, 5}}),
  4229. {"Accept-Encoding", ""},
  4230. });
  4231. ASSERT_TRUE(res);
  4232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4233. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4236. EXPECT_EQ(std::string("abcdef"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4239. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4242. }
  4243. TEST_F(ServerTest, GetWithRangeMultipart) {
  4244. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4247. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4248. EXPECT_EQ(false, res->has_header("Content-Range"));
  4249. EXPECT_EQ(267U, res->body.size());
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4252. auto res =
  4253. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4256. }
  4257. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4258. auto res = cli_.Get("/with-range-customized-response",
  4259. {{make_range_header({{1, 2}})}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4262. EXPECT_EQ(true, res->has_header("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(JSON_DATA, res->body);
  4265. }
  4266. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4267. auto res = cli_.Get("/with-range-customized-response",
  4268. {{make_range_header({{1, 2}, {4, 5}})}});
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4271. EXPECT_EQ(true, res->has_header("Content-Length"));
  4272. EXPECT_EQ(false, res->has_header("Content-Range"));
  4273. EXPECT_EQ(JSON_DATA, res->body);
  4274. }
  4275. TEST_F(ServerTest, Issue1772) {
  4276. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4279. }
  4280. TEST_F(ServerTest, Issue609) {
  4281. auto res = cli_.Delete("/issue609");
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ(std::string("ok"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetStreamedChunked) {
  4287. auto res = cli_.Get("/streamed-chunked");
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. EXPECT_EQ(std::string("123456789"), res->body);
  4291. }
  4292. TEST_F(ServerTest, GetStreamedChunked2) {
  4293. auto res = cli_.Get("/streamed-chunked2");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ(std::string("123456789"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4299. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ(std::string("123456789"), res->body);
  4303. EXPECT_TRUE(res->has_header("Trailer"));
  4304. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4305. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4306. // Trailers are now stored separately from headers (security fix)
  4307. EXPECT_EQ(2U, res->trailers.size());
  4308. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4309. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4310. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4311. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4312. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4313. // Verify trailers are NOT in headers (security verification)
  4314. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4315. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4316. }
  4317. TEST_F(ServerTest, LargeChunkedPost) {
  4318. Request req;
  4319. req.method = "POST";
  4320. req.path = "/large-chunked";
  4321. std::string host_and_port;
  4322. host_and_port += HOST;
  4323. host_and_port += ":";
  4324. host_and_port += std::to_string(PORT);
  4325. req.headers.emplace("Host", host_and_port.c_str());
  4326. req.headers.emplace("Accept", "*/*");
  4327. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4328. req.headers.emplace("Content-Type", "text/plain");
  4329. req.headers.emplace("Content-Length", "0");
  4330. req.headers.emplace("Transfer-Encoding", "chunked");
  4331. std::string long_string(30 * 1024u, 'a');
  4332. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4333. // Attempt to make a large enough post to exceed OS buffers, to test that
  4334. // the server handles short reads if the full chunk data isn't available.
  4335. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4336. auto res = std::make_shared<Response>();
  4337. auto error = Error::Success;
  4338. auto ret = cli_.send(req, *res, error);
  4339. ASSERT_TRUE(ret);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. }
  4342. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4343. auto res = cli_.Get("/remote_addr");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4347. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4348. }
  4349. TEST_F(ServerTest, GetMethodLocalAddr) {
  4350. auto res = cli_.Get("/local_addr");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4354. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4355. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4356. }
  4357. TEST_F(ServerTest, HTTPResponseSplitting) {
  4358. auto res = cli_.Get("/http_response_splitting");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. }
  4362. TEST_F(ServerTest, SlowRequest) {
  4363. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4364. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4366. }
  4367. #if 0
  4368. TEST_F(ServerTest, SlowPost) {
  4369. char buffer[64 * 1024];
  4370. memset(buffer, 0x42, sizeof(buffer));
  4371. auto res = cli_.Post(
  4372. "/slowpost", 64 * 1024 * 1024,
  4373. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4374. auto ret = sink.write(buffer, sizeof(buffer));
  4375. EXPECT_TRUE(ret);
  4376. return true;
  4377. },
  4378. "text/plain");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. TEST_F(ServerTest, SlowPostFail) {
  4383. char buffer[64 * 1024];
  4384. memset(buffer, 0x42, sizeof(buffer));
  4385. cli_.set_write_timeout(std::chrono::seconds(0));
  4386. auto res = cli_.Post(
  4387. "/slowpost", 64 * 1024 * 1024,
  4388. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4389. sink.write(buffer, sizeof(buffer));
  4390. return true;
  4391. },
  4392. "text/plain");
  4393. ASSERT_TRUE(!res);
  4394. EXPECT_EQ(Error::Write, res.error());
  4395. }
  4396. #endif
  4397. TEST_F(ServerTest, Put) {
  4398. auto res = cli_.Put("/put", "PUT", "text/plain");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("PUT", res->body);
  4402. }
  4403. TEST_F(ServerTest, PutWithContentProvider) {
  4404. auto res = cli_.Put(
  4405. "/put", 3,
  4406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4407. sink.os << "PUT";
  4408. return true;
  4409. },
  4410. "text/plain");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("PUT", res->body);
  4414. }
  4415. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4416. auto res = cli_.Post(
  4417. "/post", 42,
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4419. return false;
  4420. },
  4421. "text/plain");
  4422. ASSERT_TRUE(!res);
  4423. EXPECT_EQ(Error::Canceled, res.error());
  4424. }
  4425. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4426. auto res = cli_.Put(
  4427. "/put",
  4428. [](size_t /*offset*/, DataSink &sink) {
  4429. sink.os << "PUT";
  4430. sink.done();
  4431. return true;
  4432. },
  4433. "text/plain");
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ("PUT", res->body);
  4437. }
  4438. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4439. auto res = cli_.Post(
  4440. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4441. "text/plain");
  4442. ASSERT_TRUE(!res);
  4443. EXPECT_EQ(Error::Canceled, res.error());
  4444. }
  4445. TEST_F(ServerTest, PostLoopBack) {
  4446. std::string body;
  4447. auto res = cli_.Post(
  4448. "/post-loopback", 9,
  4449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4450. EXPECT_EQ(9u, length);
  4451. sink.write("123", 3);
  4452. sink.write("456", 3);
  4453. sink.write("789", 3);
  4454. return true;
  4455. },
  4456. "text/plain",
  4457. [&body](const char *data, size_t data_length) {
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::OK_200, res->status);
  4463. EXPECT_EQ("123456789", body);
  4464. }
  4465. TEST_F(ServerTest, PutLoopBack) {
  4466. std::string body;
  4467. auto res = cli_.Put(
  4468. "/put-loopback", 9,
  4469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4470. EXPECT_EQ(9u, length);
  4471. sink.write("123", 3);
  4472. sink.write("456", 3);
  4473. sink.write("789", 3);
  4474. return true;
  4475. },
  4476. "text/plain",
  4477. [&body](const char *data, size_t data_length) {
  4478. body.append(data, data_length);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("123456789", body);
  4484. }
  4485. TEST_F(ServerTest, PatchLoopBack) {
  4486. std::string body;
  4487. auto res = cli_.Patch(
  4488. "/patch-loopback", 9,
  4489. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4490. EXPECT_EQ(9u, length);
  4491. sink.write("123", 3);
  4492. sink.write("456", 3);
  4493. sink.write("789", 3);
  4494. return true;
  4495. },
  4496. "text/plain",
  4497. [&body](const char *data, size_t data_length) {
  4498. body.append(data, data_length);
  4499. return true;
  4500. });
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ("123456789", body);
  4504. }
  4505. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4506. std::string body;
  4507. auto res = cli_.Post(
  4508. "/post-loopback",
  4509. [](size_t /*offset*/, DataSink &sink) {
  4510. sink.write("123", 3);
  4511. sink.write("456", 3);
  4512. sink.write("789", 3);
  4513. sink.done();
  4514. return true;
  4515. },
  4516. "text/plain",
  4517. [&body](const char *data, size_t data_length) {
  4518. body.append(data, data_length);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("123456789", body);
  4524. }
  4525. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4526. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4527. cli_.set_compress(true);
  4528. auto res = cli_.Put(
  4529. "/put", 3,
  4530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4531. sink.os << "PUT";
  4532. return true;
  4533. },
  4534. "text/plain");
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("PUT", res->body);
  4538. }
  4539. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4540. cli_.set_compress(true);
  4541. auto res = cli_.Post(
  4542. "/post", 42,
  4543. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4544. return false;
  4545. },
  4546. "text/plain");
  4547. ASSERT_TRUE(!res);
  4548. EXPECT_EQ(Error::Canceled, res.error());
  4549. }
  4550. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4551. cli_.set_compress(true);
  4552. auto res = cli_.Put(
  4553. "/put",
  4554. [](size_t /*offset*/, DataSink &sink) {
  4555. sink.os << "PUT";
  4556. sink.done();
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4568. "text/plain");
  4569. ASSERT_TRUE(!res);
  4570. EXPECT_EQ(Error::Canceled, res.error());
  4571. }
  4572. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ(LARGE_DATA, res->body);
  4578. }
  4579. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4581. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4582. Client cli(s.c_str());
  4583. cli.enable_server_certificate_verification(false);
  4584. #else
  4585. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4586. Client cli(s.c_str());
  4587. #endif
  4588. cli.set_compress(true);
  4589. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ(LARGE_DATA, res->body);
  4593. // The compressed size should be less than a 10th of the original. May vary
  4594. // depending on the zlib library.
  4595. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4596. static_cast<uint64_t>(10 * 1024 * 1024));
  4597. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4598. }
  4599. TEST_F(ServerTest, PutContentWithDeflate) {
  4600. cli_.set_compress(false);
  4601. Headers headers;
  4602. headers.emplace("Content-Encoding", "deflate");
  4603. // PUT in deflate format:
  4604. auto res = cli_.Put("/put", headers,
  4605. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("PUT", res->body);
  4609. }
  4610. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4611. Headers headers;
  4612. headers.emplace("Accept-Encoding", "gzip, deflate");
  4613. auto res = cli_.Get("/streamed-chunked", headers);
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ(std::string("123456789"), res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked2", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4627. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. }
  4631. TEST(GzipDecompressor, ChunkedDecompression) {
  4632. std::string data;
  4633. for (size_t i = 0; i < 32 * 1024; ++i) {
  4634. data.push_back(static_cast<char>('a' + i % 26));
  4635. }
  4636. std::string compressed_data;
  4637. {
  4638. httplib::detail::gzip_compressor compressor;
  4639. bool result = compressor.compress(
  4640. data.data(), data.size(),
  4641. /*last=*/true,
  4642. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4643. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4644. compressed_data_size);
  4645. return true;
  4646. });
  4647. ASSERT_TRUE(result);
  4648. }
  4649. std::string decompressed_data;
  4650. {
  4651. httplib::detail::gzip_decompressor decompressor;
  4652. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4653. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4654. size_t chunk_size = 130;
  4655. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4656. chunk_begin += chunk_size) {
  4657. size_t current_chunk_size =
  4658. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4659. bool result = decompressor.decompress(
  4660. compressed_data.data() + chunk_begin, current_chunk_size,
  4661. [&](const char *decompressed_data_chunk,
  4662. size_t decompressed_data_chunk_size) {
  4663. decompressed_data.insert(decompressed_data.size(),
  4664. decompressed_data_chunk,
  4665. decompressed_data_chunk_size);
  4666. return true;
  4667. });
  4668. ASSERT_TRUE(result);
  4669. }
  4670. }
  4671. ASSERT_EQ(data, decompressed_data);
  4672. }
  4673. TEST(GzipDecompressor, DeflateDecompression) {
  4674. std::string original_text = "Raw deflate without gzip";
  4675. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4676. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4677. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4678. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4679. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4680. std::string decompressed_data;
  4681. {
  4682. httplib::detail::gzip_decompressor decompressor;
  4683. bool result = decompressor.decompress(
  4684. compressed_data.data(), compressed_data.size(),
  4685. [&](const char *decompressed_data_chunk,
  4686. size_t decompressed_data_chunk_size) {
  4687. decompressed_data.insert(decompressed_data.size(),
  4688. decompressed_data_chunk,
  4689. decompressed_data_chunk_size);
  4690. return true;
  4691. });
  4692. ASSERT_TRUE(result);
  4693. }
  4694. ASSERT_EQ(original_text, decompressed_data);
  4695. }
  4696. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4697. std::string original_text = "Raw deflate without gzip";
  4698. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4699. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4700. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4701. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4702. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4703. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4704. std::string decompressed_data;
  4705. {
  4706. httplib::detail::gzip_decompressor decompressor;
  4707. bool result = decompressor.decompress(
  4708. compressed_data.data(), compressed_data.size(),
  4709. [&](const char *decompressed_data_chunk,
  4710. size_t decompressed_data_chunk_size) {
  4711. decompressed_data.insert(decompressed_data.size(),
  4712. decompressed_data_chunk,
  4713. decompressed_data_chunk_size);
  4714. return true;
  4715. });
  4716. ASSERT_TRUE(result);
  4717. }
  4718. ASSERT_EQ(original_text, decompressed_data);
  4719. }
  4720. #ifdef _WIN32
  4721. TEST(GzipDecompressor, LargeRandomData) {
  4722. // prepare large random data that is difficult to be compressed and is
  4723. // expected to have large size even when compressed
  4724. std::random_device seed_gen;
  4725. std::mt19937 random(seed_gen());
  4726. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4727. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4728. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4729. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4730. // compress data over 4GiB
  4731. std::string compressed_data;
  4732. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4733. httplib::detail::gzip_compressor compressor;
  4734. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4735. data.size() * sizeof(std::uint32_t), true,
  4736. [&](const char *data, size_t size) {
  4737. compressed_data.insert(
  4738. compressed_data.size(), data, size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. // FIXME: compressed data size is expected to be greater than 4GiB,
  4743. // but there is no guarantee
  4744. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4745. // decompress data over 4GiB
  4746. std::string decompressed_data;
  4747. decompressed_data.reserve(data_size);
  4748. httplib::detail::gzip_decompressor decompressor;
  4749. result = decompressor.decompress(
  4750. compressed_data.data(), compressed_data.size(),
  4751. [&](const char *data, size_t size) {
  4752. decompressed_data.insert(decompressed_data.size(), data, size);
  4753. return true;
  4754. });
  4755. ASSERT_TRUE(result);
  4756. // compare
  4757. ASSERT_EQ(data_size, decompressed_data.size());
  4758. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4759. 0);
  4760. }
  4761. #endif
  4762. #endif
  4763. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4764. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4765. Headers headers;
  4766. headers.emplace("Accept-Encoding", "br");
  4767. auto res = cli_.Get("/streamed-chunked", headers);
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ(std::string("123456789"), res->body);
  4771. }
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked2", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Patch) {
  4782. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PATCH", res->body);
  4786. }
  4787. TEST_F(ServerTest, Delete) {
  4788. auto res = cli_.Delete("/delete");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("DELETE", res->body);
  4792. }
  4793. TEST_F(ServerTest, DeleteContentReceiver) {
  4794. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("content", res->body);
  4798. }
  4799. TEST_F(ServerTest, Options) {
  4800. auto res = cli_.Options("*");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4804. EXPECT_TRUE(res->body.empty());
  4805. }
  4806. TEST_F(ServerTest, URL) {
  4807. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, ArrayParam) {
  4812. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, NoMultipleHeaders) {
  4817. Headers headers = {{"Content-Length", "5"}};
  4818. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4819. "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. }
  4823. TEST_F(ServerTest, PostContentReceiver) {
  4824. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4830. UploadFormDataItems items = {
  4831. {"text1", "text default", "", ""},
  4832. {"text2", "aωb", "", ""},
  4833. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4834. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4835. {"file3", "", "", "application/octet-stream"},
  4836. };
  4837. auto res = cli_.Post("/content_receiver", items);
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4842. UploadFormDataItems items = {
  4843. {"text1", "text default", "", ""},
  4844. {"text2", "aωb", "", ""},
  4845. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4846. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4847. {"file3", "", "", "application/octet-stream"},
  4848. };
  4849. auto boundary = std::string("+++++");
  4850. std::string body;
  4851. for (const auto &item : items) {
  4852. body += "--" + boundary + "\r\n";
  4853. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4854. if (!item.filename.empty()) {
  4855. body += "; filename=\"" + item.filename + "\"";
  4856. }
  4857. body += "\r\n";
  4858. if (!item.content_type.empty()) {
  4859. body += "Content-Type: " + item.content_type + "\r\n";
  4860. }
  4861. body += "\r\n";
  4862. body += item.content + "\r\n";
  4863. }
  4864. body += "--" + boundary + "--\r\n";
  4865. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4866. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, PostContentReceiverGzip) {
  4871. cli_.set_compress(true);
  4872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4873. ASSERT_TRUE(res);
  4874. ASSERT_EQ(StatusCode::OK_200, res->status);
  4875. ASSERT_EQ("content", res->body);
  4876. }
  4877. TEST_F(ServerTest, PutContentReceiver) {
  4878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4879. ASSERT_TRUE(res);
  4880. ASSERT_EQ(StatusCode::OK_200, res->status);
  4881. ASSERT_EQ("content", res->body);
  4882. }
  4883. TEST_F(ServerTest, PatchContentReceiver) {
  4884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4885. ASSERT_TRUE(res);
  4886. ASSERT_EQ(StatusCode::OK_200, res->status);
  4887. ASSERT_EQ("content", res->body);
  4888. }
  4889. template <typename ClientType>
  4890. void TestWithHeadersAndContentReceiver(
  4891. ClientType &cli,
  4892. std::function<Result(ClientType &, const std::string &, const Headers &,
  4893. const std::string &, const std::string &,
  4894. ContentReceiver, DownloadProgress)>
  4895. request_func) {
  4896. Headers headers;
  4897. headers.emplace("X-Custom-Header", "test-value");
  4898. std::string received_body;
  4899. auto res = request_func(
  4900. cli, "/content_receiver", headers, "content", "application/json",
  4901. [&](const char *data, size_t data_length) {
  4902. received_body.append(data, data_length);
  4903. return true;
  4904. },
  4905. nullptr);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("content", received_body);
  4909. }
  4910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4912. using ClientT = SSLClient;
  4913. #else
  4914. using ClientT = Client;
  4915. #endif
  4916. TestWithHeadersAndContentReceiver<ClientT>(
  4917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4918. const std::string &body, const std::string &content_type,
  4919. ContentReceiver receiver, DownloadProgress progress) {
  4920. return cli.Post(path, headers, body, content_type, receiver, progress);
  4921. });
  4922. }
  4923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4925. using ClientT = SSLClient;
  4926. #else
  4927. using ClientT = Client;
  4928. #endif
  4929. TestWithHeadersAndContentReceiver<ClientT>(
  4930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4931. const std::string &body, const std::string &content_type,
  4932. ContentReceiver receiver, DownloadProgress progress) {
  4933. return cli.Put(path, headers, body, content_type, receiver, progress);
  4934. });
  4935. }
  4936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4937. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4938. using ClientT = SSLClient;
  4939. #else
  4940. using ClientT = Client;
  4941. #endif
  4942. TestWithHeadersAndContentReceiver<ClientT>(
  4943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4944. const std::string &body, const std::string &content_type,
  4945. ContentReceiver receiver, DownloadProgress progress) {
  4946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4947. });
  4948. }
  4949. template <typename ClientType>
  4950. void TestWithHeadersAndContentReceiverWithProgress(
  4951. ClientType &cli,
  4952. std::function<Result(ClientType &, const std::string &, const Headers &,
  4953. const std::string &, const std::string &,
  4954. ContentReceiver, DownloadProgress)>
  4955. request_func) {
  4956. Headers headers;
  4957. headers.emplace("X-Test-Header", "progress-test");
  4958. std::string received_body;
  4959. auto progress_called = false;
  4960. auto res = request_func(
  4961. cli, "/content_receiver", headers, "content", "text/plain",
  4962. [&](const char *data, size_t data_length) {
  4963. received_body.append(data, data_length);
  4964. return true;
  4965. },
  4966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4967. progress_called = true;
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ("content", received_body);
  4973. EXPECT_TRUE(progress_called);
  4974. }
  4975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4977. using ClientT = SSLClient;
  4978. #else
  4979. using ClientT = Client;
  4980. #endif
  4981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4983. const std::string &body, const std::string &content_type,
  4984. ContentReceiver receiver, DownloadProgress progress) {
  4985. return cli.Post(path, headers, body, content_type, receiver, progress);
  4986. });
  4987. }
  4988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4990. using ClientT = SSLClient;
  4991. #else
  4992. using ClientT = Client;
  4993. #endif
  4994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4996. const std::string &body, const std::string &content_type,
  4997. ContentReceiver receiver, DownloadProgress progress) {
  4998. return cli.Put(path, headers, body, content_type, receiver, progress);
  4999. });
  5000. }
  5001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5003. using ClientT = SSLClient;
  5004. #else
  5005. using ClientT = Client;
  5006. #endif
  5007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5009. const std::string &body, const std::string &content_type,
  5010. ContentReceiver receiver, DownloadProgress progress) {
  5011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5012. });
  5013. }
  5014. template <typename ClientType>
  5015. void TestWithHeadersAndContentReceiverError(
  5016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5017. const Headers &, const std::string &,
  5018. const std::string &, ContentReceiver)>
  5019. request_func) {
  5020. Headers headers;
  5021. headers.emplace("X-Error-Test", "true");
  5022. std::string received_body;
  5023. auto receiver_failed = false;
  5024. auto res =
  5025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5026. [&](const char *data, size_t data_length) {
  5027. received_body.append(data, data_length);
  5028. receiver_failed = true;
  5029. return false;
  5030. });
  5031. ASSERT_FALSE(res);
  5032. EXPECT_TRUE(receiver_failed);
  5033. }
  5034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5036. using ClientT = SSLClient;
  5037. #else
  5038. using ClientT = Client;
  5039. #endif
  5040. TestWithHeadersAndContentReceiverError<ClientT>(
  5041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5042. const std::string &body, const std::string &content_type,
  5043. ContentReceiver receiver) {
  5044. return cli.Post(path, headers, body, content_type, receiver);
  5045. });
  5046. }
  5047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverError<ClientT>(
  5054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5055. const std::string &body, const std::string &content_type,
  5056. ContentReceiver receiver) {
  5057. return cli.Put(path, headers, body, content_type, receiver);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverError<ClientT>(
  5067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5068. const std::string &body, const std::string &content_type,
  5069. ContentReceiver receiver) {
  5070. return cli.Patch(path, headers, body, content_type, receiver);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PostQueryStringAndBody) {
  5074. auto res =
  5075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5076. ASSERT_TRUE(res);
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, HTTP2Magic) {
  5080. Request req;
  5081. req.method = "PRI";
  5082. req.path = "*";
  5083. req.body = "SM";
  5084. auto res = std::make_shared<Response>();
  5085. auto error = Error::Success;
  5086. auto ret = cli_.send(req, *res, error);
  5087. ASSERT_TRUE(ret);
  5088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5089. }
  5090. TEST_F(ServerTest, KeepAlive) {
  5091. auto res = cli_.Get("/hi");
  5092. ASSERT_TRUE(res);
  5093. EXPECT_EQ(StatusCode::OK_200, res->status);
  5094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5095. EXPECT_EQ("Hello World!", res->body);
  5096. res = cli_.Get("/hi");
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("Hello World!", res->body);
  5101. res = cli_.Get("/hi");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5105. EXPECT_EQ("Hello World!", res->body);
  5106. res = cli_.Get("/not-exist");
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5109. res = cli_.Post("/empty", "", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("empty", res->body);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. res = cli_.Post(
  5116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5117. "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. cli_.set_keep_alive(false);
  5123. res = cli_.Get("/last-request");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("close", res->get_header_value("Connection"));
  5127. }
  5128. TEST_F(ServerTest, TooManyRedirect) {
  5129. cli_.set_follow_location(true);
  5130. auto res = cli_.Get("/redirect/0");
  5131. ASSERT_TRUE(!res);
  5132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5133. }
  5134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5135. Request req;
  5136. req.method = "FOOBAR";
  5137. req.path = "/hi";
  5138. cli_.set_keep_alive(true);
  5139. auto res = cli_.send(req);
  5140. ASSERT_TRUE(res);
  5141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5142. EXPECT_EQ("close", res->get_header_value("Connection"));
  5143. EXPECT_FALSE(cli_.is_socket_open());
  5144. }
  5145. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5146. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5147. TEST_F(ServerTest, Gzip) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "gzip, deflate");
  5150. auto res = cli_.Get("/compress", headers);
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5156. "7890123456789012345678901234567890",
  5157. res->body);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. }
  5160. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5161. Headers headers;
  5162. headers.emplace("Accept-Encoding", "");
  5163. auto res = cli_.Get("/compress", headers);
  5164. ASSERT_TRUE(res);
  5165. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. res->body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. TEST_F(ServerTest, GzipWithContentReceiver) {
  5174. Headers headers;
  5175. headers.emplace("Accept-Encoding", "gzip, deflate");
  5176. std::string body;
  5177. auto res = cli_.Get("/compress", headers,
  5178. [&](const char *data, uint64_t data_length) {
  5179. EXPECT_EQ(100U, data_length);
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5186. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5188. "7890123456789012345678901234567890",
  5189. body);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. }
  5192. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5193. Headers headers;
  5194. headers.emplace("Accept-Encoding", "gzip, deflate");
  5195. cli_.set_decompress(false);
  5196. auto res = cli_.Get("/compress", headers);
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5200. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5201. EXPECT_EQ(33U, res->body.size());
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. std::string body;
  5208. auto res = cli_.Get("/compress", headers,
  5209. [&](const char *data, uint64_t data_length) {
  5210. EXPECT_EQ(100U, data_length);
  5211. body.append(data, data_length);
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5217. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5218. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5219. "7890123456789012345678901234567890",
  5220. body);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. }
  5223. TEST_F(ServerTest, NoGzip) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "gzip, deflate");
  5226. auto res = cli_.Get("/nocompress", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5229. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. res->body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. std::string body;
  5240. auto res = cli_.Get("/nocompress", headers,
  5241. [&](const char *data, uint64_t data_length) {
  5242. EXPECT_EQ(100U, data_length);
  5243. body.append(data, data_length);
  5244. return true;
  5245. });
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5248. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5250. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5251. "7890123456789012345678901234567890",
  5252. body);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. }
  5255. TEST_F(ServerTest, MultipartFormDataGzip) {
  5256. UploadFormDataItems items = {
  5257. {"key1", "test", "", ""},
  5258. {"key2", "--abcdefg123", "", ""},
  5259. };
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/compress-multipart", items);
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. }
  5265. #endif
  5266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5267. TEST_F(ServerTest, Brotli) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "br");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. #endif
  5281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5282. TEST_F(ServerTest, Zstd) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "zstd");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "");
  5298. auto res = cli_.Get("/compress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "zstd");
  5311. std::string body;
  5312. auto res = cli_.Get("/compress", headers,
  5313. [&](const char *data, uint64_t data_length) {
  5314. EXPECT_EQ(100U, data_length);
  5315. body.append(data, data_length);
  5316. return true;
  5317. });
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5323. "7890123456789012345678901234567890",
  5324. body);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "zstd");
  5330. cli_.set_decompress(false);
  5331. auto res = cli_.Get("/compress", headers);
  5332. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5333. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5334. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5335. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ(26U, res->body.size());
  5342. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5343. 0);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "");
  5348. std::string body;
  5349. auto res = cli_.Get("/compress", headers,
  5350. [&](const char *data, uint64_t data_length) {
  5351. EXPECT_EQ(100U, data_length);
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. ASSERT_TRUE(res);
  5356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoZstd) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "zstd");
  5367. auto res = cli_.Get("/nocompress", headers);
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5370. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5373. "7890123456789012345678901234567890",
  5374. res->body);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. }
  5377. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5378. Headers headers;
  5379. headers.emplace("Accept-Encoding", "zstd");
  5380. std::string body;
  5381. auto res = cli_.Get("/nocompress", headers,
  5382. [&](const char *data, uint64_t data_length) {
  5383. EXPECT_EQ(100U, data_length);
  5384. body.append(data, data_length);
  5385. return true;
  5386. });
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5390. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5391. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5392. "7890123456789012345678901234567890",
  5393. body);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. }
  5396. // TODO: How to enable zstd ??
  5397. TEST_F(ServerTest, MultipartFormDataZstd) {
  5398. UploadFormDataItems items = {
  5399. {"key1", "test", "", ""},
  5400. {"key2", "--abcdefg123", "", ""},
  5401. };
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "zstd");
  5404. cli_.set_compress(true);
  5405. auto res = cli_.Post("/compress-multipart", headers, items);
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Put(
  5414. "/put", headers, 3,
  5415. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5416. sink.os << "PUT";
  5417. return true;
  5418. },
  5419. "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. // Pre-compression logging tests
  5425. TEST_F(ServerTest, PreCompressionLogging) {
  5426. // Test data for compression (matches the actual /compress endpoint content)
  5427. const std::string test_content =
  5428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5429. "3456789012345678901234567890";
  5430. // Variables to capture logging data
  5431. std::string pre_compression_body;
  5432. std::string pre_compression_content_type;
  5433. std::string pre_compression_content_encoding;
  5434. std::string post_compression_body;
  5435. std::string post_compression_content_type;
  5436. std::string post_compression_content_encoding;
  5437. // Set up pre-compression logger
  5438. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5439. const Response &res) {
  5440. pre_compression_body = res.body;
  5441. pre_compression_content_type = res.get_header_value("Content-Type");
  5442. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5443. });
  5444. // Set up post-compression logger
  5445. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5446. post_compression_body = res.body;
  5447. post_compression_content_type = res.get_header_value("Content-Type");
  5448. post_compression_content_encoding =
  5449. res.get_header_value("Content-Encoding");
  5450. });
  5451. // Test with gzip compression
  5452. Headers headers;
  5453. headers.emplace("Accept-Encoding", "gzip");
  5454. auto res = cli_.Get("/compress", headers);
  5455. // Verify response was compressed
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5459. // Verify pre-compression logger captured uncompressed content
  5460. EXPECT_EQ(test_content, pre_compression_body);
  5461. EXPECT_EQ("text/plain", pre_compression_content_type);
  5462. EXPECT_TRUE(pre_compression_content_encoding
  5463. .empty()); // No encoding header before compression
  5464. // Verify post-compression logger captured compressed content
  5465. EXPECT_NE(test_content,
  5466. post_compression_body); // Should be different after compression
  5467. EXPECT_EQ("text/plain", post_compression_content_type);
  5468. EXPECT_EQ("gzip", post_compression_content_encoding);
  5469. // Verify compressed content is smaller
  5470. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5471. }
  5472. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5473. const std::string test_content =
  5474. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5475. "3456789012345678901234567890";
  5476. std::string pre_compression_body;
  5477. std::string post_compression_body;
  5478. svr_.set_pre_compression_logger(
  5479. [&](const Request & /*req*/, const Response &res) {
  5480. pre_compression_body = res.body;
  5481. });
  5482. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5483. post_compression_body = res.body;
  5484. });
  5485. Headers headers;
  5486. headers.emplace("Accept-Encoding", "br");
  5487. auto res = cli_.Get("/compress", headers);
  5488. ASSERT_TRUE(res);
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5491. // Verify pre-compression content is uncompressed
  5492. EXPECT_EQ(test_content, pre_compression_body);
  5493. // Verify post-compression content is compressed
  5494. EXPECT_NE(test_content, post_compression_body);
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. // Request without compression (use /nocompress endpoint)
  5511. Headers headers;
  5512. auto res = cli_.Get("/nocompress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5516. // Pre-compression logger should not be called when no compression is applied
  5517. EXPECT_TRUE(
  5518. pre_compression_body.empty()); // Pre-compression logger not called
  5519. EXPECT_EQ(
  5520. test_content,
  5521. post_compression_body); // Post-compression logger captures final content
  5522. }
  5523. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5524. const std::string test_content =
  5525. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5526. "3456789012345678901234567890";
  5527. std::string pre_compression_body;
  5528. bool pre_logger_called = false;
  5529. // Set only pre-compression logger
  5530. svr_.set_pre_compression_logger(
  5531. [&](const Request & /*req*/, const Response &res) {
  5532. pre_compression_body = res.body;
  5533. pre_logger_called = true;
  5534. });
  5535. Headers headers;
  5536. headers.emplace("Accept-Encoding", "gzip");
  5537. auto res = cli_.Get("/compress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5541. // Verify pre-compression logger was called
  5542. EXPECT_TRUE(pre_logger_called);
  5543. EXPECT_EQ(test_content, pre_compression_body);
  5544. }
  5545. TEST(ZstdDecompressor, ChunkedDecompression) {
  5546. std::string data;
  5547. for (size_t i = 0; i < 32 * 1024; ++i) {
  5548. data.push_back(static_cast<char>('a' + i % 26));
  5549. }
  5550. std::string compressed_data;
  5551. {
  5552. httplib::detail::zstd_compressor compressor;
  5553. bool result = compressor.compress(
  5554. data.data(), data.size(),
  5555. /*last=*/true,
  5556. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5557. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5558. compressed_data_size);
  5559. return true;
  5560. });
  5561. ASSERT_TRUE(result);
  5562. }
  5563. std::string decompressed_data;
  5564. {
  5565. httplib::detail::zstd_decompressor decompressor;
  5566. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5567. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5568. size_t chunk_size = 130;
  5569. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5570. chunk_begin += chunk_size) {
  5571. size_t current_chunk_size =
  5572. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5573. bool result = decompressor.decompress(
  5574. compressed_data.data() + chunk_begin, current_chunk_size,
  5575. [&](const char *decompressed_data_chunk,
  5576. size_t decompressed_data_chunk_size) {
  5577. decompressed_data.insert(decompressed_data.size(),
  5578. decompressed_data_chunk,
  5579. decompressed_data_chunk_size);
  5580. return true;
  5581. });
  5582. ASSERT_TRUE(result);
  5583. }
  5584. }
  5585. ASSERT_EQ(data, decompressed_data);
  5586. }
  5587. TEST(ZstdDecompressor, Decompress) {
  5588. std::string original_text = "Compressed with ZSTD";
  5589. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5590. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5591. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5592. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5593. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5594. std::string decompressed_data;
  5595. {
  5596. httplib::detail::zstd_decompressor decompressor;
  5597. bool result = decompressor.decompress(
  5598. compressed_data.data(), compressed_data.size(),
  5599. [&](const char *decompressed_data_chunk,
  5600. size_t decompressed_data_chunk_size) {
  5601. decompressed_data.insert(decompressed_data.size(),
  5602. decompressed_data_chunk,
  5603. decompressed_data_chunk_size);
  5604. return true;
  5605. });
  5606. ASSERT_TRUE(result);
  5607. }
  5608. ASSERT_EQ(original_text, decompressed_data);
  5609. }
  5610. #endif
  5611. // Sends a raw request to a server listening at HOST:PORT.
  5612. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5613. std::string *resp = nullptr) {
  5614. auto error = Error::Success;
  5615. auto client_sock = detail::create_client_socket(
  5616. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5617. /*connection_timeout_sec=*/5, 0,
  5618. /*read_timeout_sec=*/5, 0,
  5619. /*write_timeout_sec=*/5, 0, std::string(), error);
  5620. if (client_sock == INVALID_SOCKET) { return false; }
  5621. auto ret = detail::process_client_socket(
  5622. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5623. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5624. if (req.size() !=
  5625. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5626. return false;
  5627. }
  5628. char buf[512];
  5629. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5630. while (line_reader.getline()) {
  5631. if (resp) { *resp += line_reader.ptr(); }
  5632. }
  5633. return true;
  5634. });
  5635. detail::close_socket(client_sock);
  5636. return ret;
  5637. }
  5638. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5639. Server svr;
  5640. std::string header_value;
  5641. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5642. header_value = req.get_header_value("foo");
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. thread t = thread([&] { svr.listen(HOST, PORT); });
  5646. auto se = detail::scope_exit([&] {
  5647. svr.stop();
  5648. t.join();
  5649. ASSERT_FALSE(svr.is_running());
  5650. });
  5651. svr.wait_until_ready();
  5652. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5653. // like characters are not treated the same - use vertical tab and escape.
  5654. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5655. "foo: \t \v bar \x1B\t \r\n"
  5656. "Connection: close\r\n"
  5657. "\r\n";
  5658. std::string res;
  5659. ASSERT_TRUE(send_request(5, req, &res));
  5660. EXPECT_EQ(header_value, "");
  5661. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5662. }
  5663. // Sends a raw request and verifies that there isn't a crash or exception.
  5664. static void test_raw_request(const std::string &req,
  5665. std::string *out = nullptr) {
  5666. Server svr;
  5667. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5668. res.set_content("ok", "text/plain");
  5669. });
  5670. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5671. res.set_content("ok", "text/plain");
  5672. });
  5673. svr.Get("/header_field_value_check",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_content("ok", "text/plain");
  5676. });
  5677. // Server read timeout must be longer than the client read timeout for the
  5678. // bug to reproduce, probably to force the server to process a request
  5679. // without a trailing blank line.
  5680. const time_t client_read_timeout_sec = 1;
  5681. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5682. bool listen_thread_ok = false;
  5683. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5684. auto se = detail::scope_exit([&] {
  5685. svr.stop();
  5686. t.join();
  5687. ASSERT_FALSE(svr.is_running());
  5688. EXPECT_TRUE(listen_thread_ok);
  5689. });
  5690. svr.wait_until_ready();
  5691. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5692. }
  5693. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5694. // A certain header line causes an exception if the header property is parsed
  5695. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5696. test_raw_request(
  5697. "GET /hi HTTP/1.1\r\n"
  5698. " : "
  5699. " "
  5700. " ");
  5701. }
  5702. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5703. // A certain header line causes an exception if the header property *name* is
  5704. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5705. // greedy matcher and requires backtracking when there are a lot of ":"
  5706. // characters.
  5707. // This occurs with libc++ but not libstdc++.
  5708. test_raw_request(
  5709. "GET /hi HTTP/1.1\r\n"
  5710. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5711. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5712. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5713. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5714. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5715. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5716. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5717. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5718. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5719. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5720. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5722. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5723. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5724. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5725. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5726. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5727. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5728. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5729. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5730. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5731. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5732. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5733. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5734. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5735. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5736. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5737. "&&&%%%");
  5738. }
  5739. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5740. // Make sure this doesn't crash the server.
  5741. // In a previous version of the header line regex, the "\r" rendered the line
  5742. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5743. // a new position where the leading white space ended and the field value
  5744. // began.
  5745. // The crash occurs with libc++ but not libstdc++.
  5746. test_raw_request("GET /hi HTTP/1.1\r\n"
  5747. "a:" +
  5748. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5749. "\r\n"
  5750. "\r\n");
  5751. }
  5752. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5753. std::string out;
  5754. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5755. "Content-Type: text/plain\r\n"
  5756. "Transfer-Encoding: chunked\r\n"
  5757. "\r\n"
  5758. "nothex\r\n",
  5759. &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5763. std::string out;
  5764. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5765. "Content-Type: text/plain\r\n"
  5766. "Transfer-Encoding: chunked\r\n"
  5767. "\r\n"
  5768. "3\r\n"
  5769. "xyz\r\n"
  5770. "NaN\r\n",
  5771. &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5775. std::string out;
  5776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5777. "Content-Type: text/plain\r\n"
  5778. "Transfer-Encoding: chunked\r\n"
  5779. "\r\n"
  5780. // Length is too large for 64 bits.
  5781. "1ffffffffffffffff\r\n"
  5782. "xyz\r\n",
  5783. &out);
  5784. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5785. }
  5786. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5787. test_raw_request("GET /hi HTTP/1.1\r\n"
  5788. "Content-Type: text/plain\r\n\r");
  5789. }
  5790. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5791. std::string out;
  5792. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5793. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5794. }
  5795. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5796. Server svr;
  5797. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5798. EXPECT_TRUE(!req.remote_addr.empty());
  5799. });
  5800. thread t = thread([&] { svr.listen(HOST, PORT); });
  5801. auto se = detail::scope_exit([&] {
  5802. svr.stop();
  5803. t.join();
  5804. ASSERT_FALSE(svr.is_running());
  5805. });
  5806. svr.wait_until_ready();
  5807. // Send an invalid request line to trigger Bad Request
  5808. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5809. std::string out;
  5810. ASSERT_TRUE(send_request(5, bad_req, &out));
  5811. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5812. }
  5813. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5814. std::string out;
  5815. std::string request(
  5816. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5817. test_raw_request(request, &out);
  5818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5819. }
  5820. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5821. std::string out;
  5822. std::string request(
  5823. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5824. test_raw_request(request, &out);
  5825. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5826. }
  5827. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5828. std::string out;
  5829. std::string request(
  5830. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5831. test_raw_request(request, &out);
  5832. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5833. }
  5834. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5835. std::string out;
  5836. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5837. "Test: \r\n\r\n",
  5838. &out);
  5839. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5840. }
  5841. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5842. Server svr;
  5843. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5844. res.set_header("Cache-Control", "no-cache");
  5845. res.set_chunked_content_provider(
  5846. "text/event-stream", [](size_t offset, DataSink &sink) {
  5847. std::string s = "data:";
  5848. s += std::to_string(offset);
  5849. s += "\n\n";
  5850. auto ret = sink.write(s.data(), s.size());
  5851. EXPECT_TRUE(ret);
  5852. std::this_thread::sleep_for(std::chrono::seconds(1));
  5853. return true;
  5854. });
  5855. });
  5856. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5857. svr.wait_until_ready();
  5858. Client client(HOST, PORT);
  5859. const Headers headers = {{"Accept", "text/event-stream"}};
  5860. auto get_thread = std::thread([&client, &headers]() {
  5861. auto res = client.Get(
  5862. "/events", headers,
  5863. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5864. });
  5865. auto se = detail::scope_exit([&] {
  5866. svr.stop();
  5867. get_thread.join();
  5868. listen_thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. // Give GET time to get a few messages.
  5872. std::this_thread::sleep_for(std::chrono::seconds(2));
  5873. }
  5874. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5875. httplib::Server svr;
  5876. svr.Post("/hi",
  5877. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5878. res.status = StatusCode::OK_200;
  5879. });
  5880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5881. svr.wait_until_ready();
  5882. Client cli(HOST, PORT);
  5883. auto res = cli.Post("/hi", "data", "text/plain");
  5884. ASSERT_TRUE(res);
  5885. EXPECT_EQ(StatusCode::OK_200, res->status);
  5886. svr.stop();
  5887. thread.join();
  5888. ASSERT_FALSE(svr.is_running());
  5889. res = cli.Post("/hi", "data", "text/plain");
  5890. ASSERT_FALSE(res);
  5891. }
  5892. TEST(ServerStopTest, ListenFailure) {
  5893. Server svr;
  5894. auto t = thread([&]() {
  5895. auto ret = svr.listen("????", PORT);
  5896. EXPECT_FALSE(ret);
  5897. });
  5898. svr.wait_until_ready();
  5899. svr.stop();
  5900. t.join();
  5901. }
  5902. TEST(ServerStopTest, Decommision) {
  5903. Server svr;
  5904. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5905. for (int i = 0; i < 4; i++) {
  5906. auto is_even = !(i % 2);
  5907. std::thread t{[&] {
  5908. try {
  5909. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5910. if (is_even) {
  5911. throw std::runtime_error("Some thing that happens to go wrong.");
  5912. }
  5913. svr.listen(HOST, PORT);
  5914. } catch (...) { svr.decommission(); }
  5915. }};
  5916. svr.wait_until_ready();
  5917. // Server is up
  5918. {
  5919. Client cli(HOST, PORT);
  5920. auto res = cli.Get("/hi");
  5921. if (is_even) {
  5922. EXPECT_FALSE(res);
  5923. } else {
  5924. EXPECT_TRUE(res);
  5925. EXPECT_EQ("hi...", res->body);
  5926. }
  5927. }
  5928. svr.stop();
  5929. t.join();
  5930. // Server is down...
  5931. {
  5932. Client cli(HOST, PORT);
  5933. auto res = cli.Get("/hi");
  5934. EXPECT_FALSE(res);
  5935. }
  5936. }
  5937. }
  5938. // Helper function for string body upload progress tests
  5939. template <typename SetupHandler, typename ClientCall>
  5940. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5941. ClientCall &&client_call,
  5942. const string &body) {
  5943. Server svr;
  5944. setup_handler(svr);
  5945. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5946. auto se = detail::scope_exit([&] {
  5947. svr.stop();
  5948. t.join();
  5949. });
  5950. svr.wait_until_ready();
  5951. Client cli(HOST, PORT);
  5952. vector<uint64_t> progress_values;
  5953. bool progress_called = false;
  5954. auto res =
  5955. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5956. progress_values.push_back(current);
  5957. progress_called = true;
  5958. return true;
  5959. });
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ(200, res->status);
  5962. EXPECT_TRUE(progress_called);
  5963. }
  5964. TEST(UploadProgressTest, PostStringBodyBasic) {
  5965. TestStringBodyUploadProgress(
  5966. [](Server &svr) {
  5967. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5968. res.set_content("received", "text/plain");
  5969. });
  5970. },
  5971. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5972. return cli.Post("/test", body, "text/plain", progress_callback);
  5973. },
  5974. "test data for upload progress");
  5975. }
  5976. TEST(UploadProgressTest, PutStringBodyBasic) {
  5977. TestStringBodyUploadProgress(
  5978. [](Server &svr) {
  5979. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5980. res.set_content("put received", "text/plain");
  5981. });
  5982. },
  5983. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5984. return cli.Put("/test", body, "text/plain", progress_callback);
  5985. },
  5986. "put test data for upload progress");
  5987. }
  5988. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5989. TestStringBodyUploadProgress(
  5990. [](Server &svr) {
  5991. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5992. res.set_content("patch received", "text/plain");
  5993. });
  5994. },
  5995. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5996. return cli.Patch("/test", body, "text/plain", progress_callback);
  5997. },
  5998. "patch test data for upload progress");
  5999. }
  6000. // Helper function for content provider upload progress tests
  6001. template <typename SetupHandler, typename ClientCall>
  6002. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6003. ClientCall &&client_call) {
  6004. Server svr;
  6005. setup_handler(svr);
  6006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. vector<uint64_t> progress_values;
  6014. auto res =
  6015. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6016. progress_values.push_back(current);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(200, res->status);
  6021. EXPECT_FALSE(progress_values.empty());
  6022. }
  6023. TEST(UploadProgressTest, PostContentProviderProgress) {
  6024. TestContentProviderUploadProgress(
  6025. [](Server &svr) {
  6026. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6027. res.set_content("provider received", "text/plain");
  6028. });
  6029. },
  6030. [](Client &cli, UploadProgress progress_callback) {
  6031. return cli.Post(
  6032. "/test", 10,
  6033. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6034. sink.os << "test data";
  6035. return true;
  6036. },
  6037. "text/plain", progress_callback);
  6038. });
  6039. }
  6040. // Helper function for multipart upload progress tests
  6041. template <typename SetupHandler, typename ClientCall>
  6042. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6043. ClientCall &&client_call,
  6044. const string &endpoint) {
  6045. Server svr;
  6046. setup_handler(svr);
  6047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. t.join();
  6051. });
  6052. svr.wait_until_ready();
  6053. Client cli(HOST, PORT);
  6054. vector<uint64_t> progress_values;
  6055. UploadFormDataItems items = {
  6056. {"field1", "value1", "", ""},
  6057. {"field2", "longer value for progress tracking test", "", ""},
  6058. {"file1", "file content data for upload progress", "test.txt",
  6059. "text/plain"}};
  6060. auto res = client_call(cli, endpoint, items,
  6061. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6062. progress_values.push_back(current);
  6063. return true;
  6064. });
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(200, res->status);
  6067. EXPECT_FALSE(progress_values.empty());
  6068. }
  6069. TEST(UploadProgressTest, PostMultipartProgress) {
  6070. TestMultipartUploadProgress(
  6071. [](Server &svr) {
  6072. svr.Post("/multipart", [](const Request &req, Response &res) {
  6073. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6074. res.set_content("multipart received", "text/plain");
  6075. });
  6076. },
  6077. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6078. UploadProgress progress_callback) {
  6079. return cli.Post(endpoint, items, progress_callback);
  6080. },
  6081. "/multipart");
  6082. }
  6083. // Helper function for basic download progress tests
  6084. template <typename SetupHandler, typename ClientCall>
  6085. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6086. ClientCall &&client_call, const string &endpoint,
  6087. size_t expected_content_size) {
  6088. Server svr;
  6089. setup_handler(svr);
  6090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6091. auto se = detail::scope_exit([&] {
  6092. svr.stop();
  6093. t.join();
  6094. });
  6095. svr.wait_until_ready();
  6096. Client cli(HOST, PORT);
  6097. vector<uint64_t> progress_values;
  6098. auto res = client_call(cli, endpoint,
  6099. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6100. progress_values.push_back(current);
  6101. return true;
  6102. });
  6103. ASSERT_TRUE(res);
  6104. EXPECT_EQ(200, res->status);
  6105. EXPECT_FALSE(progress_values.empty());
  6106. EXPECT_EQ(expected_content_size, res->body.size());
  6107. }
  6108. TEST(DownloadProgressTest, GetBasic) {
  6109. TestBasicDownloadProgress(
  6110. [](Server &svr) {
  6111. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6112. string content(1000, 'D');
  6113. res.set_content(content, "text/plain");
  6114. });
  6115. },
  6116. [](Client &cli, const string &endpoint,
  6117. DownloadProgress progress_callback) {
  6118. return cli.Get(endpoint, progress_callback);
  6119. },
  6120. "/download", 1000u);
  6121. }
  6122. // Helper function for content receiver download progress tests
  6123. template <typename SetupHandler, typename ClientCall>
  6124. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6125. ClientCall &&client_call,
  6126. const string &endpoint,
  6127. size_t expected_content_size) {
  6128. Server svr;
  6129. setup_handler(svr);
  6130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6131. auto se = detail::scope_exit([&] {
  6132. svr.stop();
  6133. t.join();
  6134. });
  6135. svr.wait_until_ready();
  6136. Client cli(HOST, PORT);
  6137. vector<uint64_t> progress_values;
  6138. string received_body;
  6139. auto res = client_call(
  6140. cli, endpoint,
  6141. [&](const char *data, size_t data_length) -> bool {
  6142. received_body.append(data, data_length);
  6143. return true;
  6144. },
  6145. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(res);
  6150. EXPECT_EQ(200, res->status);
  6151. EXPECT_FALSE(progress_values.empty());
  6152. EXPECT_EQ(expected_content_size, received_body.size());
  6153. EXPECT_TRUE(res->body.empty());
  6154. }
  6155. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6156. TestContentReceiverDownloadProgress(
  6157. [](Server &svr) {
  6158. svr.Get("/download-receiver",
  6159. [](const Request & /*req*/, Response &res) {
  6160. string content(2000, 'R');
  6161. res.set_content(content, "text/plain");
  6162. });
  6163. },
  6164. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6165. DownloadProgress progress_callback) {
  6166. return cli.Get(endpoint, content_receiver, progress_callback);
  6167. },
  6168. "/download-receiver", 2000u);
  6169. }
  6170. TEST(StreamingTest, NoContentLengthStreaming) {
  6171. Server svr;
  6172. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6173. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6174. if (offset < 6) {
  6175. sink.os << (offset < 3 ? "a" : "b");
  6176. } else {
  6177. sink.done();
  6178. }
  6179. return true;
  6180. });
  6181. });
  6182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6183. auto listen_se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. listen_thread.join();
  6186. ASSERT_FALSE(svr.is_running());
  6187. });
  6188. svr.wait_until_ready();
  6189. Client client(HOST, PORT);
  6190. auto get_thread = std::thread([&client]() {
  6191. std::string s;
  6192. auto res =
  6193. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6194. s += std::string(data, len);
  6195. return true;
  6196. });
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("aaabbb", s);
  6200. });
  6201. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6202. // Give GET time to get a few messages.
  6203. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6204. }
  6205. TEST(MountTest, Unmount) {
  6206. Server svr;
  6207. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6208. auto se = detail::scope_exit([&] {
  6209. svr.stop();
  6210. listen_thread.join();
  6211. ASSERT_FALSE(svr.is_running());
  6212. });
  6213. svr.wait_until_ready();
  6214. Client cli("localhost", PORT);
  6215. svr.set_mount_point("/mount2", "./www2");
  6216. auto res = cli.Get("/");
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6219. res = cli.Get("/mount2/dir/test.html");
  6220. ASSERT_TRUE(res);
  6221. EXPECT_EQ(StatusCode::OK_200, res->status);
  6222. svr.set_mount_point("/", "./www");
  6223. res = cli.Get("/dir/");
  6224. ASSERT_TRUE(res);
  6225. EXPECT_EQ(StatusCode::OK_200, res->status);
  6226. svr.remove_mount_point("/");
  6227. res = cli.Get("/dir/");
  6228. ASSERT_TRUE(res);
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. svr.remove_mount_point("/mount2");
  6231. res = cli.Get("/mount2/dir/test.html");
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6234. }
  6235. TEST(MountTest, Redicect) {
  6236. Server svr;
  6237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. listen_thread.join();
  6241. ASSERT_FALSE(svr.is_running());
  6242. });
  6243. svr.set_mount_point("/", "./www");
  6244. svr.wait_until_ready();
  6245. Client cli("localhost", PORT);
  6246. auto res = cli.Get("/dir/");
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. res = cli.Get("/dir");
  6250. ASSERT_TRUE(res);
  6251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6252. res = cli.Get("/file");
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. res = cli.Get("/file/");
  6256. ASSERT_TRUE(res);
  6257. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6258. cli.set_follow_location(true);
  6259. res = cli.Get("/dir");
  6260. ASSERT_TRUE(res);
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. }
  6263. TEST(MountTest, MultibytesPathName) {
  6264. Server svr;
  6265. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6266. auto se = detail::scope_exit([&] {
  6267. svr.stop();
  6268. listen_thread.join();
  6269. ASSERT_FALSE(svr.is_running());
  6270. });
  6271. svr.set_mount_point("/", "./www");
  6272. svr.wait_until_ready();
  6273. Client cli("localhost", PORT);
  6274. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6278. }
  6279. TEST(KeepAliveTest, ReadTimeout) {
  6280. Server svr;
  6281. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6282. std::this_thread::sleep_for(std::chrono::seconds(2));
  6283. res.set_content("a", "text/plain");
  6284. });
  6285. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6286. res.set_content("b", "text/plain");
  6287. });
  6288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6289. auto se = detail::scope_exit([&] {
  6290. svr.stop();
  6291. listen_thread.join();
  6292. ASSERT_FALSE(svr.is_running());
  6293. });
  6294. svr.wait_until_ready();
  6295. Client cli("localhost", PORT);
  6296. cli.set_keep_alive(true);
  6297. cli.set_read_timeout(std::chrono::seconds(1));
  6298. auto resa = cli.Get("/a");
  6299. ASSERT_FALSE(resa);
  6300. EXPECT_EQ(Error::Read, resa.error());
  6301. auto resb = cli.Get("/b");
  6302. ASSERT_TRUE(resb);
  6303. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6304. EXPECT_EQ("b", resb->body);
  6305. }
  6306. TEST(KeepAliveTest, MaxCount) {
  6307. size_t keep_alive_max_count = 3;
  6308. Server svr;
  6309. svr.set_keep_alive_max_count(keep_alive_max_count);
  6310. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6311. res.set_content("Hello World!", "text/plain");
  6312. });
  6313. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6314. auto se = detail::scope_exit([&] {
  6315. svr.stop();
  6316. listen_thread.join();
  6317. ASSERT_FALSE(svr.is_running());
  6318. });
  6319. svr.wait_until_ready();
  6320. Client cli(HOST, PORT);
  6321. cli.set_keep_alive(true);
  6322. for (size_t i = 0; i < 5; i++) {
  6323. auto result = cli.Get("/hi");
  6324. ASSERT_TRUE(result);
  6325. EXPECT_EQ(StatusCode::OK_200, result->status);
  6326. if (i == keep_alive_max_count - 1) {
  6327. EXPECT_EQ("close", result->get_header_value("Connection"));
  6328. } else {
  6329. EXPECT_FALSE(result->has_header("Connection"));
  6330. }
  6331. }
  6332. }
  6333. TEST(KeepAliveTest, Issue1041) {
  6334. Server svr;
  6335. svr.set_keep_alive_timeout(3);
  6336. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6337. res.set_content("Hello World!", "text/plain");
  6338. });
  6339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6340. auto se = detail::scope_exit([&] {
  6341. svr.stop();
  6342. listen_thread.join();
  6343. ASSERT_FALSE(svr.is_running());
  6344. });
  6345. svr.wait_until_ready();
  6346. Client cli(HOST, PORT);
  6347. cli.set_keep_alive(true);
  6348. auto result = cli.Get("/hi");
  6349. ASSERT_TRUE(result);
  6350. EXPECT_EQ(StatusCode::OK_200, result->status);
  6351. std::this_thread::sleep_for(std::chrono::seconds(5));
  6352. result = cli.Get("/hi");
  6353. ASSERT_TRUE(result);
  6354. EXPECT_EQ(StatusCode::OK_200, result->status);
  6355. }
  6356. TEST(KeepAliveTest, Issue1959) {
  6357. Server svr;
  6358. svr.set_keep_alive_timeout(5);
  6359. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6360. res.set_content("a", "text/plain");
  6361. });
  6362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6363. auto se = detail::scope_exit([&] {
  6364. if (!svr.is_running()) return;
  6365. svr.stop();
  6366. listen_thread.join();
  6367. ASSERT_FALSE(svr.is_running());
  6368. });
  6369. svr.wait_until_ready();
  6370. Client cli("localhost", PORT);
  6371. cli.set_keep_alive(true);
  6372. using namespace std::chrono;
  6373. auto start = steady_clock::now();
  6374. cli.Get("/a");
  6375. svr.stop();
  6376. listen_thread.join();
  6377. auto end = steady_clock::now();
  6378. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6379. EXPECT_LT(elapsed, 5000);
  6380. }
  6381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6382. TEST(KeepAliveTest, SSLClientReconnection) {
  6383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6384. ASSERT_TRUE(svr.is_valid());
  6385. svr.set_keep_alive_timeout(1);
  6386. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6387. res.set_content("Hello World!", "text/plain");
  6388. });
  6389. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6390. auto se = detail::scope_exit([&] {
  6391. svr.stop();
  6392. listen_thread.join();
  6393. ASSERT_FALSE(svr.is_running());
  6394. });
  6395. svr.wait_until_ready();
  6396. SSLClient cli(HOST, PORT);
  6397. cli.enable_server_certificate_verification(false);
  6398. cli.set_keep_alive(true);
  6399. auto result = cli.Get("/hi");
  6400. ASSERT_TRUE(result);
  6401. EXPECT_EQ(StatusCode::OK_200, result->status);
  6402. result = cli.Get("/hi");
  6403. ASSERT_TRUE(result);
  6404. EXPECT_EQ(StatusCode::OK_200, result->status);
  6405. std::this_thread::sleep_for(std::chrono::seconds(2));
  6406. // Recoonect
  6407. result = cli.Get("/hi");
  6408. ASSERT_TRUE(result);
  6409. EXPECT_EQ(StatusCode::OK_200, result->status);
  6410. result = cli.Get("/hi");
  6411. ASSERT_TRUE(result);
  6412. EXPECT_EQ(StatusCode::OK_200, result->status);
  6413. }
  6414. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6416. ASSERT_TRUE(svr.is_valid());
  6417. svr.set_keep_alive_timeout(1);
  6418. std::string content = "reconnect";
  6419. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6420. res.set_content("Hello World!", "text/plain");
  6421. });
  6422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6423. auto se = detail::scope_exit([&] {
  6424. svr.stop();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. svr.wait_until_ready();
  6429. SSLClient cli(HOST, PORT);
  6430. cli.enable_server_certificate_verification(false);
  6431. cli.set_keep_alive(true);
  6432. auto result = cli.Post(
  6433. "/hi", content.size(),
  6434. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6435. sink.write(content.c_str(), content.size());
  6436. return true;
  6437. },
  6438. "text/plain");
  6439. ASSERT_TRUE(result);
  6440. EXPECT_EQ(200, result->status);
  6441. std::this_thread::sleep_for(std::chrono::seconds(2));
  6442. // Recoonect
  6443. result = cli.Post(
  6444. "/hi", content.size(),
  6445. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6446. sink.write(content.c_str(), content.size());
  6447. return true;
  6448. },
  6449. "text/plain");
  6450. ASSERT_TRUE(result);
  6451. EXPECT_EQ(200, result->status);
  6452. result = cli.Post(
  6453. "/hi", content.size(),
  6454. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6455. sink.write(content.c_str(), content.size());
  6456. return true;
  6457. },
  6458. "text/plain");
  6459. ASSERT_TRUE(result);
  6460. EXPECT_EQ(200, result->status);
  6461. }
  6462. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6463. {
  6464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6465. ASSERT_TRUE(svr.is_valid());
  6466. svr.Get("/sni", [&](const Request &req, Response &res) {
  6467. std::string expected;
  6468. if (req.ssl) {
  6469. if (const char *sni =
  6470. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6471. expected = sni;
  6472. }
  6473. }
  6474. EXPECT_EQ(expected, req.get_param_value("expected"));
  6475. res.set_content("ok", "text/plain");
  6476. });
  6477. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6478. auto se = detail::scope_exit([&] {
  6479. svr.stop();
  6480. listen_thread.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. svr.wait_until_ready();
  6484. {
  6485. SSLClient cli("localhost", PORT);
  6486. cli.enable_server_certificate_verification(false);
  6487. auto res = cli.Get("/sni?expected=localhost");
  6488. ASSERT_TRUE(res);
  6489. }
  6490. {
  6491. SSLClient cli("::1", PORT);
  6492. cli.enable_server_certificate_verification(false);
  6493. auto res = cli.Get("/sni?expected=");
  6494. // NOTE: This may fail if the server is listening on IPv4 only
  6495. // (e.g., when localhost resolves to 127.0.0.1 only)
  6496. if (res) {
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. } else {
  6499. EXPECT_EQ(Error::Connection, res.error());
  6500. }
  6501. }
  6502. }
  6503. }
  6504. #endif
  6505. TEST(ClientProblemDetectionTest, ContentProvider) {
  6506. Server svr;
  6507. size_t content_length = 1024 * 1024;
  6508. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6509. res.set_content_provider(
  6510. content_length, "text/plain",
  6511. [&](size_t offset, size_t length, DataSink &sink) {
  6512. auto out_len = std::min(length, static_cast<size_t>(1024));
  6513. std::string out(out_len, '@');
  6514. sink.write(out.data(), out_len);
  6515. return offset < 4096;
  6516. },
  6517. [](bool success) { ASSERT_FALSE(success); });
  6518. });
  6519. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6520. res.set_content_provider(
  6521. 0, "text/plain",
  6522. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6523. EXPECT_TRUE(false);
  6524. return true;
  6525. },
  6526. [](bool success) { ASSERT_FALSE(success); });
  6527. });
  6528. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. listen_thread.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", PORT);
  6536. {
  6537. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6538. size_t /*data_length*/) { return false; });
  6539. ASSERT_FALSE(res);
  6540. }
  6541. {
  6542. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6543. size_t /*data_length*/) { return false; });
  6544. ASSERT_TRUE(res);
  6545. }
  6546. }
  6547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6548. Server svr;
  6549. svr.set_error_handler([](Request const &, Response &res) -> void {
  6550. res.set_chunked_content_provider(
  6551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6552. sink.os << "hello";
  6553. sink.os << "world";
  6554. sink.done();
  6555. return true;
  6556. });
  6557. });
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.wait_until_ready();
  6565. Client cli("localhost", PORT);
  6566. auto res = cli.Get("/");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6569. EXPECT_EQ("helloworld", res->body);
  6570. }
  6571. TEST(LongPollingTest, ClientCloseDetection) {
  6572. Server svr;
  6573. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6574. res.set_chunked_content_provider(
  6575. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6576. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6577. sink.os << "hello";
  6578. auto count = 10;
  6579. while (count > 0 && sink.is_writable()) {
  6580. this_thread::sleep_for(chrono::milliseconds(10));
  6581. count--;
  6582. }
  6583. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6584. return true;
  6585. });
  6586. });
  6587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6588. auto se = detail::scope_exit([&] {
  6589. svr.stop();
  6590. listen_thread.join();
  6591. ASSERT_FALSE(svr.is_running());
  6592. });
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6596. EXPECT_EQ("hello", string(data, data_length));
  6597. return false; // close the socket immediately.
  6598. });
  6599. ASSERT_FALSE(res);
  6600. }
  6601. TEST(GetWithParametersTest, GetWithParameters) {
  6602. Server svr;
  6603. svr.Get("/", [&](const Request &req, Response &) {
  6604. EXPECT_EQ("world", req.get_param_value("hello"));
  6605. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6606. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6607. });
  6608. svr.Get("/params", [&](const Request &req, Response &) {
  6609. EXPECT_EQ("world", req.get_param_value("hello"));
  6610. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6611. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6612. });
  6613. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6614. EXPECT_EQ("resource-id", req.matches[1]);
  6615. EXPECT_EQ("foo", req.get_param_value("param1"));
  6616. EXPECT_EQ("bar", req.get_param_value("param2"));
  6617. });
  6618. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6619. EXPECT_EQ("user-id", req.path_params.at("id"));
  6620. EXPECT_EQ("foo", req.get_param_value("param1"));
  6621. EXPECT_EQ("bar", req.get_param_value("param2"));
  6622. });
  6623. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6624. auto se = detail::scope_exit([&] {
  6625. svr.stop();
  6626. listen_thread.join();
  6627. ASSERT_FALSE(svr.is_running());
  6628. });
  6629. svr.wait_until_ready();
  6630. {
  6631. Client cli(HOST, PORT);
  6632. Params params;
  6633. params.emplace("hello", "world");
  6634. params.emplace("hello2", "world2");
  6635. params.emplace("hello3", "world3");
  6636. auto res = cli.Get("/", params, Headers{});
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. {
  6641. Client cli(HOST, PORT);
  6642. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6643. ASSERT_TRUE(res);
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. }
  6646. {
  6647. Client cli(HOST, PORT);
  6648. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6649. ASSERT_TRUE(res);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. {
  6653. Client cli(HOST, PORT);
  6654. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. }
  6658. }
  6659. TEST(GetWithParametersTest, GetWithParameters2) {
  6660. Server svr;
  6661. svr.Get("/", [&](const Request &req, Response &res) {
  6662. auto text = req.get_param_value("hello");
  6663. res.set_content(text, "text/plain");
  6664. });
  6665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6666. auto se = detail::scope_exit([&] {
  6667. svr.stop();
  6668. listen_thread.join();
  6669. ASSERT_FALSE(svr.is_running());
  6670. });
  6671. svr.wait_until_ready();
  6672. Client cli("localhost", PORT);
  6673. Params params;
  6674. params.emplace("hello", "world");
  6675. std::string body;
  6676. auto res = cli.Get("/", params, Headers{},
  6677. [&](const char *data, size_t data_length) {
  6678. body.append(data, data_length);
  6679. return true;
  6680. });
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("world", body);
  6684. }
  6685. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6686. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6687. auto host = "httpcan.org";
  6688. auto path = std::string{"/range/32"};
  6689. #else
  6690. auto host = "nghttp2.org";
  6691. auto path = std::string{"/httpbin/range/32"};
  6692. #endif
  6693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6694. SSLClient cli(host);
  6695. #else
  6696. Client cli(host);
  6697. #endif
  6698. cli.set_default_headers({make_range_header({{1, 10}})});
  6699. cli.set_connection_timeout(5);
  6700. {
  6701. auto res = cli.Get(path);
  6702. ASSERT_TRUE(res);
  6703. EXPECT_EQ("bcdefghijk", res->body);
  6704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6705. }
  6706. {
  6707. auto res = cli.Get(path);
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ("bcdefghijk", res->body);
  6710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6711. }
  6712. }
  6713. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6714. Server svr;
  6715. svr.set_default_headers({{"Hello", "World"}});
  6716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6717. res.set_content("ok", "text/plain");
  6718. });
  6719. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6720. auto se = detail::scope_exit([&] {
  6721. svr.stop();
  6722. listen_thread.join();
  6723. ASSERT_FALSE(svr.is_running());
  6724. });
  6725. svr.wait_until_ready();
  6726. Client cli("localhost", PORT);
  6727. auto res = cli.Get("/");
  6728. ASSERT_TRUE(res);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("ok", res->body);
  6731. EXPECT_EQ("World", res->get_header_value("Hello"));
  6732. }
  6733. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6734. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6736. ASSERT_TRUE(svr.is_valid());
  6737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6738. std::this_thread::sleep_for(std::chrono::seconds(2));
  6739. res.set_content("a", "text/plain");
  6740. });
  6741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6742. res.set_content("b", "text/plain");
  6743. });
  6744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. listen_thread.join();
  6748. ASSERT_FALSE(svr.is_running());
  6749. });
  6750. svr.wait_until_ready();
  6751. SSLClient cli("localhost", PORT);
  6752. cli.enable_server_certificate_verification(false);
  6753. cli.set_keep_alive(true);
  6754. cli.set_read_timeout(std::chrono::seconds(1));
  6755. auto resa = cli.Get("/a");
  6756. ASSERT_TRUE(!resa);
  6757. EXPECT_EQ(Error::Read, resa.error());
  6758. auto resb = cli.Get("/b");
  6759. ASSERT_TRUE(resb);
  6760. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6761. EXPECT_EQ("b", resb->body);
  6762. }
  6763. #endif
  6764. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6765. protected:
  6766. ServerTestWithAI_PASSIVE()
  6767. : cli_(HOST, PORT)
  6768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6769. ,
  6770. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6771. #endif
  6772. {
  6773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6774. cli_.enable_server_certificate_verification(false);
  6775. #endif
  6776. }
  6777. virtual void SetUp() {
  6778. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6779. res.set_content("Hello World!", "text/plain");
  6780. });
  6781. t_ = thread(
  6782. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6783. svr_.wait_until_ready();
  6784. }
  6785. virtual void TearDown() {
  6786. svr_.stop();
  6787. t_.join();
  6788. }
  6789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6790. SSLClient cli_;
  6791. SSLServer svr_;
  6792. #else
  6793. Client cli_;
  6794. Server svr_;
  6795. #endif
  6796. thread t_;
  6797. };
  6798. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6799. auto res = cli_.Get("/hi");
  6800. ASSERT_TRUE(res);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6803. EXPECT_EQ("Hello World!", res->body);
  6804. }
  6805. class ServerUpDownTest : public ::testing::Test {
  6806. protected:
  6807. ServerUpDownTest() : cli_(HOST, PORT) {}
  6808. virtual void SetUp() {
  6809. t_ = thread([&]() {
  6810. svr_.bind_to_any_port(HOST);
  6811. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6812. ASSERT_TRUE(svr_.listen_after_bind());
  6813. });
  6814. svr_.wait_until_ready();
  6815. }
  6816. virtual void TearDown() {
  6817. svr_.stop();
  6818. t_.join();
  6819. }
  6820. Client cli_;
  6821. Server svr_;
  6822. thread t_;
  6823. };
  6824. TEST_F(ServerUpDownTest, QuickStartStop) {
  6825. // Should not crash, especially when run with
  6826. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6827. }
  6828. class PayloadMaxLengthTest : public ::testing::Test {
  6829. protected:
  6830. PayloadMaxLengthTest()
  6831. : cli_(HOST, PORT)
  6832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6833. ,
  6834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6835. #endif
  6836. {
  6837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6838. cli_.enable_server_certificate_verification(false);
  6839. #endif
  6840. }
  6841. virtual void SetUp() {
  6842. svr_.set_payload_max_length(8);
  6843. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6844. res.set_content("test", "text/plain");
  6845. });
  6846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6847. svr_.wait_until_ready();
  6848. }
  6849. virtual void TearDown() {
  6850. svr_.stop();
  6851. t_.join();
  6852. }
  6853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6854. SSLClient cli_;
  6855. SSLServer svr_;
  6856. #else
  6857. Client cli_;
  6858. Server svr_;
  6859. #endif
  6860. thread t_;
  6861. };
  6862. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6863. auto res = cli_.Post("/test", "123456789", "text/plain");
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6866. res = cli_.Post("/test", "12345678", "text/plain");
  6867. ASSERT_TRUE(res);
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6871. // Test chunked encoding with payload exceeding the 8-byte limit
  6872. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6873. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6874. ASSERT_TRUE(res);
  6875. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6876. }
  6877. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6878. // Test chunked encoding with payload within the 8-byte limit
  6879. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6880. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6881. ASSERT_TRUE(res);
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6885. // Test using send_request to send chunked data exceeding payload limit
  6886. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6887. "Host: " +
  6888. std::string(HOST) + ":" + std::to_string(PORT) +
  6889. "\r\n"
  6890. "Transfer-Encoding: chunked\r\n"
  6891. "Connection: close\r\n"
  6892. "\r\n"
  6893. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6894. "0123456789\r\n"
  6895. "0\r\n" // End chunk
  6896. "\r\n";
  6897. std::string response;
  6898. bool result = send_request(1, chunked_request, &response);
  6899. if (!result) {
  6900. // If send_request fails, it might be because the server closed the
  6901. // connection due to payload limit enforcement, which is acceptable
  6902. SUCCEED()
  6903. << "Server rejected oversized chunked request (connection closed)";
  6904. } else {
  6905. // If we got a response, check if it's an error response or connection was
  6906. // closed early Short response length indicates connection was closed due to
  6907. // payload limit
  6908. if (response.length() <= 10) {
  6909. SUCCEED() << "Server closed connection for oversized chunked request";
  6910. } else {
  6911. // Check for error status codes
  6912. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6913. response.find("Payload Too Large") != std::string::npos ||
  6914. response.find("400") != std::string::npos);
  6915. }
  6916. }
  6917. }
  6918. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6919. // Test request without Content-Length header exceeding payload limit
  6920. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6921. "Host: " +
  6922. std::string(HOST) + ":" +
  6923. std::to_string(PORT) +
  6924. "\r\n"
  6925. "Connection: close\r\n"
  6926. "\r\n";
  6927. // Add payload exceeding the 8-byte limit
  6928. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6929. request_without_content_length += large_payload;
  6930. std::string response;
  6931. bool result = send_request(1, request_without_content_length, &response);
  6932. if (!result) {
  6933. // If send_request fails, server likely closed connection due to payload
  6934. // limit
  6935. SUCCEED() << "Server rejected oversized request without Content-Length "
  6936. "(connection closed)";
  6937. } else {
  6938. // Check if server responded with error or closed connection early
  6939. if (response.length() <= 10) {
  6940. SUCCEED() << "Server closed connection for oversized request without "
  6941. "Content-Length";
  6942. } else {
  6943. // Check for error status codes
  6944. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6945. response.find("Payload Too Large") != std::string::npos ||
  6946. response.find("400") != std::string::npos);
  6947. }
  6948. }
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6951. // Test request without Content-Length header within payload limit
  6952. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6953. "Host: " +
  6954. std::string(HOST) + ":" +
  6955. std::to_string(PORT) +
  6956. "\r\n"
  6957. "Connection: close\r\n"
  6958. "\r\n";
  6959. // Add payload within the 8-byte limit
  6960. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6961. request_without_content_length += small_payload;
  6962. std::string response;
  6963. bool result = send_request(1, request_without_content_length, &response);
  6964. // For requests without Content-Length, the server may have different behavior
  6965. // The key is that it should not reject due to payload limit for small
  6966. // payloads
  6967. if (result) {
  6968. // Check for any HTTP response (success or error, but not connection closed)
  6969. if (response.length() > 10) {
  6970. SUCCEED()
  6971. << "Server processed request without Content-Length within limit";
  6972. } else {
  6973. // Short response might indicate connection closed, which is acceptable
  6974. SUCCEED() << "Server closed connection for request without "
  6975. "Content-Length (acceptable behavior)";
  6976. }
  6977. } else {
  6978. // Connection failure might be due to protocol requirements
  6979. SUCCEED() << "Connection issue with request without Content-Length "
  6980. "(environment-specific)";
  6981. }
  6982. }
  6983. class LargePayloadMaxLengthTest : public ::testing::Test {
  6984. protected:
  6985. LargePayloadMaxLengthTest()
  6986. : cli_(HOST, PORT)
  6987. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6988. ,
  6989. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6990. #endif
  6991. {
  6992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6993. cli_.enable_server_certificate_verification(false);
  6994. #endif
  6995. }
  6996. virtual void SetUp() {
  6997. // Set 10MB payload limit
  6998. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6999. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7000. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7001. res.set_content("Large payload test", "text/plain");
  7002. });
  7003. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7004. svr_.wait_until_ready();
  7005. }
  7006. virtual void TearDown() {
  7007. svr_.stop();
  7008. t_.join();
  7009. }
  7010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7011. SSLClient cli_;
  7012. SSLServer svr_;
  7013. #else
  7014. Client cli_;
  7015. Server svr_;
  7016. #endif
  7017. thread t_;
  7018. };
  7019. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7020. // Test chunked encoding with payload within 10MB limit
  7021. std::string medium_payload(5 * 1024 * 1024,
  7022. 'A'); // 5MB payload, within 10MB limit
  7023. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. }
  7027. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7028. // Test chunked encoding with payload exceeding 10MB limit
  7029. std::string large_payload(12 * 1024 * 1024,
  7030. 'B'); // 12MB payload, exceeds 10MB limit
  7031. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7032. ASSERT_TRUE(res);
  7033. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7034. }
  7035. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7036. // Test request without Content-Length header within 10MB limit
  7037. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7038. "Host: " +
  7039. std::string(HOST) + ":" +
  7040. std::to_string(PORT) +
  7041. "\r\n"
  7042. "Connection: close\r\n"
  7043. "\r\n";
  7044. // Add 1MB payload (within 10MB limit)
  7045. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7046. request_without_content_length += medium_payload;
  7047. std::string response;
  7048. bool result = send_request(5, request_without_content_length, &response);
  7049. if (result) {
  7050. // Should get a proper HTTP response for payloads within limit
  7051. if (response.length() > 10) {
  7052. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7053. "10MB limit";
  7054. } else {
  7055. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7056. "Content-Length)";
  7057. }
  7058. } else {
  7059. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7060. }
  7061. }
  7062. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7063. // Test request without Content-Length header exceeding 10MB limit
  7064. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7065. "Host: " +
  7066. std::string(HOST) + ":" +
  7067. std::to_string(PORT) +
  7068. "\r\n"
  7069. "Connection: close\r\n"
  7070. "\r\n";
  7071. // Add 12MB payload (exceeds 10MB limit)
  7072. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7073. request_without_content_length += large_payload;
  7074. std::string response;
  7075. bool result = send_request(10, request_without_content_length, &response);
  7076. if (!result) {
  7077. // Server should close connection due to payload limit
  7078. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7079. "(connection closed)";
  7080. } else {
  7081. // Check for error response
  7082. if (response.length() <= 10) {
  7083. SUCCEED()
  7084. << "Server closed connection for 12MB request exceeding 10MB limit";
  7085. } else {
  7086. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7087. response.find("Payload Too Large") != std::string::npos ||
  7088. response.find("400") != std::string::npos);
  7089. }
  7090. }
  7091. }
  7092. TEST(HostAndPortPropertiesTest, NoSSL) {
  7093. httplib::Client cli("www.google.com", 1234);
  7094. ASSERT_EQ("www.google.com", cli.host());
  7095. ASSERT_EQ(1234, cli.port());
  7096. }
  7097. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7098. httplib::Client cli("www.google.com:1234");
  7099. ASSERT_EQ("www.google.com", cli.host());
  7100. ASSERT_EQ(1234, cli.port());
  7101. }
  7102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7103. TEST(HostAndPortPropertiesTest, SSL) {
  7104. httplib::SSLClient cli("www.google.com");
  7105. ASSERT_EQ("www.google.com", cli.host());
  7106. ASSERT_EQ(443, cli.port());
  7107. }
  7108. #endif
  7109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7110. TEST(SSLClientTest, UpdateCAStore) {
  7111. httplib::SSLClient httplib_client("www.google.com");
  7112. auto ca_store_1 = X509_STORE_new();
  7113. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7114. nullptr);
  7115. httplib_client.set_ca_cert_store(ca_store_1);
  7116. auto ca_store_2 = X509_STORE_new();
  7117. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7118. nullptr);
  7119. httplib_client.set_ca_cert_store(ca_store_2);
  7120. }
  7121. TEST(SSLClientTest, ServerNameIndication_Online) {
  7122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7123. auto host = "httpcan.org";
  7124. auto path = std::string{"/get"};
  7125. #else
  7126. auto host = "nghttp2.org";
  7127. auto path = std::string{"/httpbin/get"};
  7128. #endif
  7129. SSLClient cli(host, 443);
  7130. auto res = cli.Get(path);
  7131. ASSERT_TRUE(res);
  7132. ASSERT_EQ(StatusCode::OK_200, res->status);
  7133. }
  7134. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7135. // Use a site that will cause SSL verification failure due to self-signed cert
  7136. SSLClient cli("self-signed.badssl.com", 443);
  7137. cli.enable_server_certificate_verification(true);
  7138. auto res = cli.Get("/");
  7139. ASSERT_TRUE(!res);
  7140. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7141. // For SSL server verification errors, ssl_error should be 0
  7142. EXPECT_EQ(0, res.ssl_error());
  7143. #if defined(_WIN32) && \
  7144. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7145. // On Windows Schannel, verify Windows certificate error is captured
  7146. EXPECT_NE(0UL, res.wincrypt_error());
  7147. // Common errors: CERT_E_UNTRUSTEDROOT, CERT_E_CHAINING
  7148. #else
  7149. // On OpenSSL, verify OpenSSL error is captured for SSLServerVerification
  7150. // This occurs when SSL_get_verify_result() returns a verification failure
  7151. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7152. res.ssl_openssl_error());
  7153. #endif
  7154. }
  7155. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7156. // Use a site where hostname doesn't match the certificate
  7157. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7158. SSLClient cli("wrong.host.badssl.com", 443);
  7159. cli.enable_server_certificate_verification(true);
  7160. cli.enable_server_hostname_verification(true);
  7161. auto res = cli.Get("/");
  7162. ASSERT_TRUE(!res);
  7163. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7164. // For SSL hostname verification errors, ssl_error should be 0
  7165. EXPECT_EQ(0, res.ssl_error());
  7166. #if defined(_WIN32) && \
  7167. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7168. // On Windows Schannel, verify Windows certificate error is captured
  7169. EXPECT_EQ(static_cast<unsigned long>(CERT_E_CN_NO_MATCH),
  7170. res.wincrypt_error());
  7171. #else
  7172. // On OpenSSL, verify OpenSSL error is captured for
  7173. // SSLServerHostnameVerification This occurs when verify_host() fails due to
  7174. // hostname mismatch
  7175. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7176. res.ssl_openssl_error());
  7177. #endif
  7178. }
  7179. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7180. Client cli("https://google.com");
  7181. auto res = cli.Get("/");
  7182. ASSERT_TRUE(res);
  7183. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7184. }
  7185. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7186. SSLClient cli("google.com");
  7187. cli.set_ca_cert_path(CA_CERT_FILE);
  7188. auto res = cli.Get("/");
  7189. ASSERT_TRUE(res);
  7190. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7191. }
  7192. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7193. SSLClient cli("google.com");
  7194. cli.enable_server_certificate_verification(true);
  7195. cli.set_ca_cert_path("hello");
  7196. auto res = cli.Get("/");
  7197. ASSERT_TRUE(!res);
  7198. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7199. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7200. // should be set
  7201. EXPECT_EQ(0, res.ssl_error());
  7202. // Verify OpenSSL error is captured for SSLLoadingCerts
  7203. // This error occurs when SSL_CTX_load_verify_locations() fails
  7204. // > openssl errstr 0x80000002
  7205. // error:80000002:system library::No such file or directory
  7206. // > openssl errstr 0xA000126
  7207. // error:0A000126:SSL routines::unexpected eof while reading
  7208. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7209. res.ssl_openssl_error() == 0xA000126);
  7210. }
  7211. TEST(SSLClientTest, ServerCertificateVerification4) {
  7212. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7213. ASSERT_TRUE(svr.is_valid());
  7214. svr.Get("/test", [&](const Request &, Response &res) {
  7215. res.set_content("test", "text/plain");
  7216. svr.stop();
  7217. ASSERT_TRUE(true);
  7218. });
  7219. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7220. auto se = detail::scope_exit([&] {
  7221. t.join();
  7222. ASSERT_FALSE(svr.is_running());
  7223. });
  7224. svr.wait_until_ready();
  7225. SSLClient cli("127.0.0.1", PORT);
  7226. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7227. cli.enable_server_certificate_verification(true);
  7228. cli.set_connection_timeout(30);
  7229. auto res = cli.Get("/test");
  7230. ASSERT_TRUE(res);
  7231. ASSERT_EQ(StatusCode::OK_200, res->status);
  7232. }
  7233. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7234. std::string cert;
  7235. read_file(CA_CERT_FILE, cert);
  7236. SSLClient cli("google.com");
  7237. cli.load_ca_cert_store(cert.data(), cert.size());
  7238. const auto res = cli.Get("/");
  7239. ASSERT_TRUE(res);
  7240. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7241. }
  7242. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7243. // clang-format off
  7244. static constexpr char cert[] =
  7245. "GlobalSign Root CA\n"
  7246. "==================\n"
  7247. "-----BEGIN CERTIFICATE-----\n"
  7248. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7249. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7250. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7251. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7252. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7253. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7254. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7255. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7256. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7257. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7258. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7259. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7260. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7261. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7262. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7263. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7264. "-----END CERTIFICATE-----\n";
  7265. // clang-format on
  7266. SSLClient cli("google.com");
  7267. cli.load_ca_cert_store(cert, sizeof(cert));
  7268. const auto res = cli.Get("/");
  7269. ASSERT_TRUE(res);
  7270. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7271. }
  7272. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7273. SSLClient cli("www.youtube.com");
  7274. cli.set_ca_cert_path(CA_CERT_FILE);
  7275. cli.enable_server_certificate_verification(true);
  7276. cli.set_follow_location(true);
  7277. auto res = cli.Get("/");
  7278. ASSERT_TRUE(res);
  7279. ASSERT_EQ(StatusCode::OK_200, res->status);
  7280. }
  7281. TEST(SSLClientTest, Issue2004_Online) {
  7282. Client client("https://google.com");
  7283. client.set_follow_location(true);
  7284. auto res = client.Get("/");
  7285. ASSERT_TRUE(res);
  7286. ASSERT_EQ(StatusCode::OK_200, res->status);
  7287. auto body = res->body;
  7288. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7289. }
  7290. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7291. // Create SSLClient with invalid cert/key to make is_valid() return false
  7292. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7293. "nonexistent_key.pem");
  7294. // is_valid() should be false due to cert loading failure
  7295. ASSERT_FALSE(cli.is_valid());
  7296. auto res = cli.Get("/");
  7297. ASSERT_FALSE(res);
  7298. EXPECT_EQ(Error::SSLConnection, res.error());
  7299. }
  7300. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7301. // Test for Issue #2251: SSL error not properly reported when client cert
  7302. // and key paths are swapped or mismatched
  7303. // This simulates the scenario where user accidentally swaps the cert and key
  7304. // files
  7305. // Using client cert file as private key and vice versa (completely wrong)
  7306. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7307. // Should fail validation due to cert/key mismatch
  7308. ASSERT_FALSE(cli.is_valid());
  7309. // Attempt to make a request should fail with proper error
  7310. auto res = cli.Get("/");
  7311. ASSERT_FALSE(res);
  7312. EXPECT_EQ(Error::SSLConnection, res.error());
  7313. // SSL error should be recorded in the Result object (this is the key fix for
  7314. // Issue #2251)
  7315. auto openssl_error = res.ssl_openssl_error();
  7316. EXPECT_NE(0u, openssl_error);
  7317. }
  7318. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7319. // Another variant: using valid file paths but with mismatched cert/key pair
  7320. // This tests the case where files exist but contain incompatible key material
  7321. // Using client cert with wrong key (cert2 key)
  7322. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7323. // Should fail validation
  7324. ASSERT_FALSE(cli.is_valid());
  7325. auto res = cli.Get("/");
  7326. ASSERT_FALSE(res);
  7327. // Must report error properly, not appear as success
  7328. EXPECT_EQ(Error::SSLConnection, res.error());
  7329. // OpenSSL error should be captured in Result
  7330. EXPECT_NE(0u, res.ssl_openssl_error());
  7331. }
  7332. #if 0
  7333. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7334. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7335. ASSERT_TRUE(cli != nullptr);
  7336. cli->set_address_family(AF_INET6);
  7337. cli->set_interface("en0");
  7338. auto res = cli->Get("/get");
  7339. ASSERT_TRUE(res);
  7340. ASSERT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. #endif
  7343. void ClientCertPresent(
  7344. const std::string &client_cert_file,
  7345. const std::string &client_private_key_file,
  7346. const std::string &client_encrypted_private_key_pass = std::string()) {
  7347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7348. CLIENT_CA_CERT_DIR);
  7349. ASSERT_TRUE(svr.is_valid());
  7350. svr.Get("/test", [&](const Request &req, Response &res) {
  7351. res.set_content("test", "text/plain");
  7352. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7353. ASSERT_TRUE(peer_cert != nullptr);
  7354. auto subject_name = X509_get_subject_name(peer_cert);
  7355. ASSERT_TRUE(subject_name != nullptr);
  7356. std::string common_name;
  7357. {
  7358. char name[BUFSIZ];
  7359. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7360. name, sizeof(name));
  7361. common_name.assign(name, static_cast<size_t>(name_len));
  7362. }
  7363. EXPECT_EQ("Common Name", common_name);
  7364. X509_free(peer_cert);
  7365. });
  7366. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7367. auto se = detail::scope_exit([&] {
  7368. svr.stop();
  7369. t.join();
  7370. ASSERT_FALSE(svr.is_running());
  7371. });
  7372. svr.wait_until_ready();
  7373. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7374. client_encrypted_private_key_pass);
  7375. cli.enable_server_certificate_verification(false);
  7376. cli.set_connection_timeout(30);
  7377. auto res = cli.Get("/test");
  7378. ASSERT_TRUE(res);
  7379. ASSERT_EQ(StatusCode::OK_200, res->status);
  7380. }
  7381. TEST(SSLClientServerTest, ClientCertPresent) {
  7382. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7383. }
  7384. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7385. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7386. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7387. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7388. }
  7389. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7390. void MemoryClientCertPresent(
  7391. const std::string &client_cert_file,
  7392. const std::string &client_private_key_file,
  7393. const std::string &client_encrypted_private_key_pass = std::string()) {
  7394. auto f = fopen(SERVER_CERT_FILE, "r+");
  7395. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7396. fclose(f);
  7397. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7398. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7399. fclose(f);
  7400. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7401. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7402. auto client_ca_cert_store = X509_STORE_new();
  7403. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7404. X509_free(client_cert);
  7405. fclose(f);
  7406. f = fopen(client_cert_file.c_str(), "r+");
  7407. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7408. fclose(f);
  7409. f = fopen(client_private_key_file.c_str(), "r+");
  7410. auto client_private_key = PEM_read_PrivateKey(
  7411. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7412. fclose(f);
  7413. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7414. ASSERT_TRUE(svr.is_valid());
  7415. svr.Get("/test", [&](const Request &req, Response &res) {
  7416. res.set_content("test", "text/plain");
  7417. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7418. ASSERT_TRUE(peer_cert != nullptr);
  7419. auto subject_name = X509_get_subject_name(peer_cert);
  7420. ASSERT_TRUE(subject_name != nullptr);
  7421. std::string common_name;
  7422. {
  7423. char name[BUFSIZ];
  7424. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7425. name, sizeof(name));
  7426. common_name.assign(name, static_cast<size_t>(name_len));
  7427. }
  7428. EXPECT_EQ("Common Name", common_name);
  7429. X509_free(peer_cert);
  7430. });
  7431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7432. auto se = detail::scope_exit([&] {
  7433. svr.stop();
  7434. t.join();
  7435. ASSERT_FALSE(svr.is_running());
  7436. });
  7437. svr.wait_until_ready();
  7438. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7439. client_encrypted_private_key_pass);
  7440. cli.enable_server_certificate_verification(false);
  7441. cli.set_connection_timeout(30);
  7442. auto res = cli.Get("/test");
  7443. ASSERT_TRUE(res);
  7444. ASSERT_EQ(StatusCode::OK_200, res->status);
  7445. X509_free(server_cert);
  7446. EVP_PKEY_free(server_private_key);
  7447. X509_free(client_cert);
  7448. EVP_PKEY_free(client_private_key);
  7449. }
  7450. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7451. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7452. }
  7453. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7454. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7455. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7456. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7457. }
  7458. #endif
  7459. TEST(SSLClientServerTest, ClientCertMissing) {
  7460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7461. CLIENT_CA_CERT_DIR);
  7462. ASSERT_TRUE(svr.is_valid());
  7463. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. t.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. SSLClient cli(HOST, PORT);
  7472. cli.set_connection_timeout(30);
  7473. auto res = cli.Get("/test");
  7474. ASSERT_TRUE(!res);
  7475. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7476. // For SSL server verification errors, ssl_error should be 0
  7477. EXPECT_EQ(0, res.ssl_error());
  7478. #if defined(_WIN32) && \
  7479. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7480. // On Windows Schannel, verify Windows certificate error is captured
  7481. EXPECT_NE(0UL, res.wincrypt_error());
  7482. #else
  7483. // Verify OpenSSL error is captured for SSLServerVerification
  7484. // Note: This test may have different error codes depending on the exact
  7485. // verification failure
  7486. EXPECT_NE(0UL, res.ssl_openssl_error());
  7487. #endif
  7488. }
  7489. TEST(SSLClientServerTest, TrustDirOptional) {
  7490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7491. ASSERT_TRUE(svr.is_valid());
  7492. svr.Get("/test", [&](const Request &, Response &res) {
  7493. res.set_content("test", "text/plain");
  7494. });
  7495. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7496. auto se = detail::scope_exit([&] {
  7497. svr.stop();
  7498. t.join();
  7499. ASSERT_FALSE(svr.is_running());
  7500. });
  7501. svr.wait_until_ready();
  7502. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7503. cli.enable_server_certificate_verification(false);
  7504. cli.set_connection_timeout(30);
  7505. auto res = cli.Get("/test");
  7506. ASSERT_TRUE(res);
  7507. ASSERT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7510. class NoListenSSLServer : public SSLServer {
  7511. public:
  7512. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7513. const char *client_ca_cert_file_path,
  7514. const char *client_ca_cert_dir_path = nullptr)
  7515. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7516. client_ca_cert_dir_path),
  7517. stop_(false) {}
  7518. std::atomic_bool stop_;
  7519. private:
  7520. bool process_and_close_socket(socket_t /*sock*/) override {
  7521. // Don't create SSL context
  7522. while (!stop_.load()) {
  7523. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7524. }
  7525. return true;
  7526. }
  7527. };
  7528. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7529. CLIENT_CA_CERT_FILE);
  7530. ASSERT_TRUE(svr.is_valid());
  7531. svr.Get("/test", [&](const Request &, Response &res) {
  7532. res.set_content("test", "text/plain");
  7533. });
  7534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7535. auto se = detail::scope_exit([&] {
  7536. svr.stop_ = true;
  7537. svr.stop();
  7538. t.join();
  7539. ASSERT_FALSE(svr.is_running());
  7540. });
  7541. svr.wait_until_ready();
  7542. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7543. cli.enable_server_certificate_verification(false);
  7544. cli.set_connection_timeout(1);
  7545. auto res = cli.Get("/test");
  7546. ASSERT_TRUE(!res);
  7547. EXPECT_EQ(Error::SSLConnection, res.error());
  7548. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7549. }
  7550. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7551. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7552. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7553. SSL_CTX_set_options(&ssl_ctx,
  7554. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7555. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7556. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7557. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7558. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7559. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7560. "ECDHE-DSS-AES128-SHA256:"
  7561. "ECDHE-RSA-AES256-SHA256:"
  7562. "ECDHE-DSS-AES256-SHA256:";
  7563. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7564. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7565. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7566. SSL_FILETYPE_PEM) != 1) {
  7567. return false;
  7568. }
  7569. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7570. CLIENT_CA_CERT_DIR);
  7571. SSL_CTX_set_verify(
  7572. &ssl_ctx,
  7573. SSL_VERIFY_PEER |
  7574. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7575. nullptr);
  7576. return true;
  7577. };
  7578. SSLServer svr(setup_ssl_ctx_callback);
  7579. ASSERT_TRUE(svr.is_valid());
  7580. svr.Get("/test", [&](const Request &req, Response &res) {
  7581. res.set_content("test", "text/plain");
  7582. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7583. ASSERT_TRUE(peer_cert != nullptr);
  7584. auto subject_name = X509_get_subject_name(peer_cert);
  7585. ASSERT_TRUE(subject_name != nullptr);
  7586. std::string common_name;
  7587. {
  7588. char name[BUFSIZ];
  7589. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7590. name, sizeof(name));
  7591. common_name.assign(name, static_cast<size_t>(name_len));
  7592. }
  7593. EXPECT_EQ("Common Name", common_name);
  7594. X509_free(peer_cert);
  7595. });
  7596. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7597. auto se = detail::scope_exit([&] {
  7598. svr.stop();
  7599. t.join();
  7600. ASSERT_FALSE(svr.is_running());
  7601. });
  7602. svr.wait_until_ready();
  7603. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7604. cli.enable_server_certificate_verification(false);
  7605. cli.set_connection_timeout(30);
  7606. auto res = cli.Get("/test");
  7607. ASSERT_TRUE(res);
  7608. ASSERT_EQ(StatusCode::OK_200, res->status);
  7609. }
  7610. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7612. ASSERT_TRUE(svr.is_valid());
  7613. // Set up a handler to verify client certificate is present
  7614. bool client_cert_verified = false;
  7615. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7616. // Verify that client certificate was provided
  7617. client_cert_verified = true;
  7618. res.set_content("success", "text/plain");
  7619. });
  7620. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7621. auto se = detail::scope_exit([&] {
  7622. svr.stop();
  7623. t.join();
  7624. ASSERT_FALSE(svr.is_running());
  7625. });
  7626. svr.wait_until_ready();
  7627. // Client with certificate
  7628. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7629. cli.enable_server_certificate_verification(false);
  7630. cli.set_connection_timeout(30);
  7631. auto res = cli.Get("/test");
  7632. ASSERT_TRUE(res);
  7633. ASSERT_EQ(StatusCode::OK_200, res->status);
  7634. ASSERT_TRUE(client_cert_verified);
  7635. EXPECT_EQ("success", res->body);
  7636. }
  7637. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7638. // Test that when client CA cert file is provided,
  7639. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7640. // Create a server with client authentication
  7641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7642. ASSERT_TRUE(svr.is_valid());
  7643. // We can't directly access the SSL_CTX from SSLServer to verify,
  7644. // but we can test that the server properly requests client certificates
  7645. // and accepts valid ones from the specified CA
  7646. bool handler_called = false;
  7647. svr.Get("/test", [&](const Request &req, Response &res) {
  7648. handler_called = true;
  7649. // Verify that a client certificate was provided
  7650. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7651. ASSERT_TRUE(peer_cert != nullptr);
  7652. // Get the issuer name
  7653. auto issuer_name = X509_get_issuer_name(peer_cert);
  7654. ASSERT_TRUE(issuer_name != nullptr);
  7655. char issuer_buf[256];
  7656. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7657. // The client certificate should be issued by our test CA
  7658. std::string issuer_str(issuer_buf);
  7659. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7660. X509_free(peer_cert);
  7661. res.set_content("authenticated", "text/plain");
  7662. });
  7663. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7664. auto se = detail::scope_exit([&] {
  7665. svr.stop();
  7666. t.join();
  7667. ASSERT_FALSE(svr.is_running());
  7668. });
  7669. svr.wait_until_ready();
  7670. // Connect with a client certificate issued by the CA
  7671. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7672. cli.enable_server_certificate_verification(false);
  7673. cli.set_connection_timeout(30);
  7674. auto res = cli.Get("/test");
  7675. ASSERT_TRUE(res);
  7676. ASSERT_EQ(StatusCode::OK_200, res->status);
  7677. ASSERT_TRUE(handler_called);
  7678. EXPECT_EQ("authenticated", res->body);
  7679. }
  7680. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7681. // Test 1: Valid CA file - no error should be recorded
  7682. {
  7683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7684. CLIENT_CA_CERT_FILE);
  7685. ASSERT_TRUE(svr.is_valid());
  7686. // With valid setup, last_ssl_error should be 0
  7687. EXPECT_EQ(0, svr.ssl_last_error());
  7688. }
  7689. // Test 2: Invalid CA file content
  7690. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7691. {
  7692. // Create a temporary file with completely invalid content
  7693. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7694. {
  7695. std::ofstream ofs(temp_invalid_ca);
  7696. ofs << "This is not a certificate file at all\n";
  7697. ofs << "Just plain text content\n";
  7698. }
  7699. // Create server with invalid CA file
  7700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7701. // Clean up temporary file
  7702. std::remove(temp_invalid_ca);
  7703. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7704. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7705. // Note: SSL_CTX_load_verify_locations typically fails first,
  7706. // but our error handling code path is still exercised
  7707. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7708. }
  7709. }
  7710. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7711. // Test SSL server using X509_STORE constructor with client CA certificates
  7712. // This test verifies that Phase 2 implementation correctly extracts CA names
  7713. // from an X509_STORE and sets them in the SSL context
  7714. // Load the CA certificate into memory
  7715. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7716. ASSERT_NE(nullptr, bio);
  7717. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7718. BIO_free(bio);
  7719. ASSERT_NE(nullptr, ca_cert);
  7720. // Create an X509_STORE and add the CA certificate
  7721. auto store = X509_STORE_new();
  7722. ASSERT_NE(nullptr, store);
  7723. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7724. // Load server certificate and private key
  7725. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7726. ASSERT_NE(nullptr, cert_bio);
  7727. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7728. BIO_free(cert_bio);
  7729. ASSERT_NE(nullptr, server_cert);
  7730. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7731. ASSERT_NE(nullptr, key_bio);
  7732. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7733. BIO_free(key_bio);
  7734. ASSERT_NE(nullptr, server_key);
  7735. // Create SSLServer with X509_STORE constructor
  7736. // Note: X509_STORE ownership is transferred to SSL_CTX
  7737. SSLServer svr(server_cert, server_key, store);
  7738. ASSERT_TRUE(svr.is_valid());
  7739. // No SSL error should be recorded for valid setup
  7740. EXPECT_EQ(0, svr.ssl_last_error());
  7741. // Set up server endpoints
  7742. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7743. res.set_content("ok", "text/plain");
  7744. });
  7745. // Start server in a thread
  7746. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7747. svr.wait_until_ready();
  7748. // Connect with client certificate (using constructor with paths)
  7749. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7750. cli.enable_server_certificate_verification(false);
  7751. auto res = cli.Get("/test-x509store");
  7752. ASSERT_TRUE(res);
  7753. EXPECT_EQ(200, res->status);
  7754. EXPECT_EQ("ok", res->body);
  7755. // Clean up
  7756. X509_free(server_cert);
  7757. EVP_PKEY_free(server_key);
  7758. X509_free(ca_cert);
  7759. svr.stop();
  7760. server_thread.join();
  7761. }
  7762. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7763. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7764. // prepare large data
  7765. std::random_device seed_gen;
  7766. std::mt19937 random(seed_gen());
  7767. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7768. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7769. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7770. // server
  7771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7772. ASSERT_TRUE(svr.is_valid());
  7773. svr.Post("/binary", [&](const Request &req, Response &res) {
  7774. EXPECT_EQ(large_size_byte, req.body.size());
  7775. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7776. res.set_content(req.body, "application/octet-stream");
  7777. });
  7778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7779. auto se = detail::scope_exit([&] {
  7780. svr.stop();
  7781. listen_thread.join();
  7782. ASSERT_FALSE(svr.is_running());
  7783. });
  7784. svr.wait_until_ready();
  7785. // client POST
  7786. SSLClient cli("localhost", PORT);
  7787. cli.enable_server_certificate_verification(false);
  7788. cli.set_read_timeout(std::chrono::seconds(100));
  7789. cli.set_write_timeout(std::chrono::seconds(100));
  7790. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7791. large_size_byte, "application/octet-stream");
  7792. // compare
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. EXPECT_EQ(large_size_byte, res->body.size());
  7795. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7796. }
  7797. #endif
  7798. #ifdef _WIN32
  7799. TEST(CleanupTest, WSACleanup) {
  7800. int ret = WSACleanup();
  7801. ASSERT_EQ(0, ret);
  7802. }
  7803. #endif
  7804. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7805. TEST(NoSSLSupport, SimpleInterface) {
  7806. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7807. }
  7808. #endif
  7809. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7810. TEST(InvalidScheme, SimpleInterface) {
  7811. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7812. }
  7813. #endif
  7814. TEST(NoScheme, SimpleInterface) {
  7815. Client cli("yahoo.com:80");
  7816. ASSERT_TRUE(cli.is_valid());
  7817. }
  7818. TEST(SendAPI, SimpleInterface_Online) {
  7819. Client cli("http://yahoo.com");
  7820. Request req;
  7821. req.method = "GET";
  7822. req.path = "/";
  7823. auto res = cli.send(req);
  7824. ASSERT_TRUE(res);
  7825. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7826. }
  7827. TEST(SendAPI, WithParamsInRequest) {
  7828. Server svr;
  7829. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7830. EXPECT_TRUE(req.has_param("test"));
  7831. EXPECT_EQ("test_value", req.get_param_value("test"));
  7832. });
  7833. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7834. auto se = detail::scope_exit([&] {
  7835. svr.stop();
  7836. t.join();
  7837. ASSERT_FALSE(svr.is_running());
  7838. });
  7839. svr.wait_until_ready();
  7840. Client cli(HOST, PORT);
  7841. {
  7842. Request req;
  7843. req.method = "GET";
  7844. req.path = "/";
  7845. req.params.emplace("test", "test_value");
  7846. auto res = cli.send(req);
  7847. ASSERT_TRUE(res);
  7848. }
  7849. {
  7850. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7851. ASSERT_TRUE(res);
  7852. }
  7853. }
  7854. TEST(ClientImplMethods, GetSocketTest) {
  7855. httplib::Server svr;
  7856. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7857. res.status = StatusCode::OK_200;
  7858. });
  7859. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7860. auto se = detail::scope_exit([&] {
  7861. svr.stop();
  7862. thread.join();
  7863. ASSERT_FALSE(svr.is_running());
  7864. });
  7865. svr.wait_until_ready();
  7866. {
  7867. httplib::Client cli("http://127.0.0.1:3333");
  7868. cli.set_keep_alive(true);
  7869. // Use the behavior of cpp-httplib of opening the connection
  7870. // only when the first request happens. If that changes,
  7871. // this test would be obsolete.
  7872. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7873. // This also implicitly tests the server. But other tests would fail much
  7874. // earlier than this one to be considered.
  7875. auto res = cli.Get("/");
  7876. ASSERT_TRUE(res);
  7877. EXPECT_EQ(StatusCode::OK_200, res->status);
  7878. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7879. }
  7880. }
  7881. // Disabled due to out-of-memory problem on GitHub Actions
  7882. #ifdef _WIN64
  7883. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7884. // allocate content size larger than 2GB in memory
  7885. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7886. char *content = (char *)malloc(content_size);
  7887. ASSERT_TRUE(content);
  7888. Server svr;
  7889. svr.Get("/foo",
  7890. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7891. res.set_content(content, content_size, "application/octet-stream");
  7892. });
  7893. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7894. auto se = detail::scope_exit([&] {
  7895. svr.stop();
  7896. listen_thread.join();
  7897. if (content) free(content);
  7898. ASSERT_FALSE(svr.is_running());
  7899. });
  7900. svr.wait_until_ready();
  7901. Client cli(HOST, PORT);
  7902. auto res = cli.Get("/foo");
  7903. ASSERT_TRUE(res);
  7904. EXPECT_EQ(StatusCode::OK_200, res->status);
  7905. EXPECT_EQ(content_size, res->body.length());
  7906. }
  7907. #endif
  7908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7909. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7910. Client cli("http://yahoo.com");
  7911. auto res = cli.Get("/");
  7912. ASSERT_TRUE(res);
  7913. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7914. cli.set_follow_location(true);
  7915. res = cli.Get("/");
  7916. ASSERT_TRUE(res);
  7917. EXPECT_EQ(StatusCode::OK_200, res->status);
  7918. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7919. }
  7920. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7921. Client cli("https://yahoo.com");
  7922. auto res = cli.Get("/");
  7923. ASSERT_TRUE(res);
  7924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7925. cli.set_follow_location(true);
  7926. res = cli.Get("/");
  7927. ASSERT_TRUE(res);
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7930. }
  7931. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7932. Client cli("https://yahoo.com");
  7933. auto res = cli.Get("/");
  7934. ASSERT_TRUE(res);
  7935. ASSERT_FALSE(!res);
  7936. ASSERT_TRUE(res);
  7937. ASSERT_FALSE(res == nullptr);
  7938. ASSERT_TRUE(res != nullptr);
  7939. EXPECT_EQ(Error::Success, res.error());
  7940. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7941. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7942. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7943. cli.set_follow_location(true);
  7944. res = cli.Get("/");
  7945. ASSERT_TRUE(res);
  7946. EXPECT_EQ(Error::Success, res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7948. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7951. }
  7952. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7953. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7954. Client cli("https://cdnjs.cloudflare.com");
  7955. auto res =
  7956. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7957. ASSERT_TRUE(res);
  7958. EXPECT_EQ(StatusCode::OK_200, res->status);
  7959. EXPECT_EQ(287630U, res->body.size());
  7960. EXPECT_EQ("application/javascript; charset=utf-8",
  7961. res->get_header_value("Content-Type"));
  7962. }
  7963. #endif
  7964. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7965. #undef REDIR_HOST // Silence compiler warning
  7966. #define REDIR_HOST "https://httpbingo.org"
  7967. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7968. Client cli(REDIR_HOST);
  7969. cli.set_follow_location(true);
  7970. auto res =
  7971. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7972. ASSERT_TRUE(res);
  7973. EXPECT_EQ(StatusCode::OK_200, res->status);
  7974. }
  7975. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7976. Client cli(REDIR_HOST);
  7977. cli.set_follow_location(true);
  7978. Params params;
  7979. params.emplace("url", "http://example.com");
  7980. params.emplace("status_code", "302");
  7981. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7982. ASSERT_TRUE(res);
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. }
  7985. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7986. Client cli(REDIR_HOST);
  7987. cli.set_follow_location(true);
  7988. Params params;
  7989. params.emplace("url", "http://example.com");
  7990. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7991. ASSERT_TRUE(res);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST(HttpToHttpsRedirectTest, CertFile) {
  7995. Server svr;
  7996. ASSERT_TRUE(svr.is_valid());
  7997. svr.Get("/index", [&](const Request &, Response &res) {
  7998. res.set_redirect("https://127.0.0.1:1235/index");
  7999. svr.stop();
  8000. });
  8001. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8002. ASSERT_TRUE(ssl_svr.is_valid());
  8003. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8004. res.set_content("test", "text/plain");
  8005. ssl_svr.stop();
  8006. });
  8007. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8008. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8009. auto se = detail::scope_exit([&] {
  8010. t2.join();
  8011. t.join();
  8012. ASSERT_FALSE(svr.is_running());
  8013. });
  8014. svr.wait_until_ready();
  8015. ssl_svr.wait_until_ready();
  8016. Client cli("127.0.0.1", PORT);
  8017. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8018. cli.enable_server_certificate_verification(true);
  8019. cli.set_follow_location(true);
  8020. cli.set_connection_timeout(30);
  8021. auto res = cli.Get("/index");
  8022. ASSERT_TRUE(res);
  8023. ASSERT_EQ(StatusCode::OK_200, res->status);
  8024. }
  8025. TEST(SSLClientRedirectTest, CertFile) {
  8026. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8027. ASSERT_TRUE(ssl_svr1.is_valid());
  8028. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8029. res.set_redirect("https://127.0.0.1:1235/index");
  8030. ssl_svr1.stop();
  8031. });
  8032. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8033. ASSERT_TRUE(ssl_svr2.is_valid());
  8034. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8035. res.set_content("test", "text/plain");
  8036. ssl_svr2.stop();
  8037. });
  8038. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8039. thread t2 =
  8040. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8041. auto se = detail::scope_exit([&] {
  8042. t2.join();
  8043. t.join();
  8044. ASSERT_FALSE(ssl_svr1.is_running());
  8045. });
  8046. ssl_svr1.wait_until_ready();
  8047. ssl_svr2.wait_until_ready();
  8048. SSLClient cli("127.0.0.1", PORT);
  8049. std::string cert;
  8050. read_file(SERVER_CERT2_FILE, cert);
  8051. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8052. cli.enable_server_certificate_verification(true);
  8053. cli.set_follow_location(true);
  8054. cli.set_connection_timeout(30);
  8055. auto res = cli.Get("/index");
  8056. ASSERT_TRUE(res);
  8057. ASSERT_EQ(StatusCode::OK_200, res->status);
  8058. }
  8059. TEST(MultipartFormDataTest, LargeData) {
  8060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8061. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8062. const ContentReader &content_reader) {
  8063. if (req.is_multipart_form_data()) {
  8064. std::vector<FormData> items;
  8065. content_reader(
  8066. [&](const FormData &file) {
  8067. items.push_back(file);
  8068. return true;
  8069. },
  8070. [&](const char *data, size_t data_length) {
  8071. items.back().content.append(data, data_length);
  8072. return true;
  8073. });
  8074. EXPECT_TRUE(std::string(items[0].name) == "document");
  8075. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8076. EXPECT_TRUE(items[0].filename == "2MB_data");
  8077. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8078. EXPECT_TRUE(items[1].name == "hello");
  8079. EXPECT_TRUE(items[1].content == "world");
  8080. EXPECT_TRUE(items[1].filename == "");
  8081. EXPECT_TRUE(items[1].content_type == "");
  8082. } else {
  8083. std::string body;
  8084. content_reader([&](const char *data, size_t data_length) {
  8085. body.append(data, data_length);
  8086. return true;
  8087. });
  8088. }
  8089. });
  8090. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8091. auto se = detail::scope_exit([&] {
  8092. svr.stop();
  8093. t.join();
  8094. ASSERT_FALSE(svr.is_running());
  8095. });
  8096. svr.wait_until_ready();
  8097. {
  8098. std::string data(1024 * 1024 * 2, '.');
  8099. std::stringstream buffer;
  8100. buffer << data;
  8101. Client cli("https://localhost:8080");
  8102. cli.enable_server_certificate_verification(false);
  8103. UploadFormDataItems items{
  8104. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8105. {"hello", "world", "", ""},
  8106. };
  8107. auto res = cli.Post("/post", items);
  8108. ASSERT_TRUE(res);
  8109. ASSERT_EQ(StatusCode::OK_200, res->status);
  8110. }
  8111. }
  8112. TEST(MultipartFormDataTest, DataProviderItems) {
  8113. std::random_device seed_gen;
  8114. std::mt19937 random(seed_gen());
  8115. std::string rand1;
  8116. rand1.resize(1000);
  8117. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8118. std::string rand2;
  8119. rand2.resize(3000);
  8120. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8122. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8123. const ContentReader &content_reader) {
  8124. ASSERT_FALSE(req.is_multipart_form_data());
  8125. std::string body;
  8126. content_reader([&](const char *data, size_t data_length) {
  8127. body.append(data, data_length);
  8128. return true;
  8129. });
  8130. EXPECT_EQ(body, "");
  8131. });
  8132. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8133. const ContentReader &content_reader) {
  8134. ASSERT_TRUE(req.is_multipart_form_data());
  8135. std::vector<FormData> items;
  8136. content_reader(
  8137. [&](const FormData &file) {
  8138. items.push_back(file);
  8139. return true;
  8140. },
  8141. [&](const char *data, size_t data_length) {
  8142. items.back().content.append(data, data_length);
  8143. return true;
  8144. });
  8145. ASSERT_TRUE(items.size() == 2);
  8146. EXPECT_EQ(std::string(items[0].name), "name1");
  8147. EXPECT_EQ(items[0].content, "Testing123");
  8148. EXPECT_EQ(items[0].filename, "filename1");
  8149. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8150. EXPECT_EQ(items[1].name, "name2");
  8151. EXPECT_EQ(items[1].content, "Testing456");
  8152. EXPECT_EQ(items[1].filename, "");
  8153. EXPECT_EQ(items[1].content_type, "");
  8154. });
  8155. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8156. const ContentReader &content_reader) {
  8157. ASSERT_TRUE(req.is_multipart_form_data());
  8158. std::vector<FormData> items;
  8159. content_reader(
  8160. [&](const FormData &file) {
  8161. items.push_back(file);
  8162. return true;
  8163. },
  8164. [&](const char *data, size_t data_length) {
  8165. items.back().content.append(data, data_length);
  8166. return true;
  8167. });
  8168. ASSERT_TRUE(items.size() == 2);
  8169. EXPECT_EQ(items[0].name, "name3");
  8170. EXPECT_EQ(items[0].content, rand1);
  8171. EXPECT_EQ(items[0].filename, "filename3");
  8172. EXPECT_EQ(items[0].content_type, "");
  8173. EXPECT_EQ(items[1].name, "name4");
  8174. EXPECT_EQ(items[1].content, rand2);
  8175. EXPECT_EQ(items[1].filename, "filename4");
  8176. EXPECT_EQ(items[1].content_type, "");
  8177. });
  8178. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8179. const ContentReader &content_reader) {
  8180. ASSERT_TRUE(req.is_multipart_form_data());
  8181. std::vector<FormData> items;
  8182. content_reader(
  8183. [&](const FormData &file) {
  8184. items.push_back(file);
  8185. return true;
  8186. },
  8187. [&](const char *data, size_t data_length) {
  8188. items.back().content.append(data, data_length);
  8189. return true;
  8190. });
  8191. ASSERT_TRUE(items.size() == 4);
  8192. EXPECT_EQ(std::string(items[0].name), "name1");
  8193. EXPECT_EQ(items[0].content, "Testing123");
  8194. EXPECT_EQ(items[0].filename, "filename1");
  8195. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8196. EXPECT_EQ(items[1].name, "name2");
  8197. EXPECT_EQ(items[1].content, "Testing456");
  8198. EXPECT_EQ(items[1].filename, "");
  8199. EXPECT_EQ(items[1].content_type, "");
  8200. EXPECT_EQ(items[2].name, "name3");
  8201. EXPECT_EQ(items[2].content, rand1);
  8202. EXPECT_EQ(items[2].filename, "filename3");
  8203. EXPECT_EQ(items[2].content_type, "");
  8204. EXPECT_EQ(items[3].name, "name4");
  8205. EXPECT_EQ(items[3].content, rand2);
  8206. EXPECT_EQ(items[3].filename, "filename4");
  8207. EXPECT_EQ(items[3].content_type, "");
  8208. });
  8209. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8210. auto se = detail::scope_exit([&] {
  8211. svr.stop();
  8212. t.join();
  8213. ASSERT_FALSE(svr.is_running());
  8214. });
  8215. svr.wait_until_ready();
  8216. {
  8217. Client cli("https://localhost:8080");
  8218. cli.enable_server_certificate_verification(false);
  8219. UploadFormDataItems items{
  8220. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8221. {"name2", "Testing456", "", ""}, // not a file
  8222. };
  8223. {
  8224. auto res = cli.Post("/post-none", {}, {}, {});
  8225. ASSERT_TRUE(res);
  8226. ASSERT_EQ(StatusCode::OK_200, res->status);
  8227. }
  8228. FormDataProviderItems providers;
  8229. {
  8230. auto res =
  8231. cli.Post("/post-items", {}, items, providers); // empty providers
  8232. ASSERT_TRUE(res);
  8233. ASSERT_EQ(StatusCode::OK_200, res->status);
  8234. }
  8235. providers.push_back({"name3",
  8236. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8237. // test the offset is given correctly at each step
  8238. if (!offset)
  8239. sink.os.write(rand1.data(), 30);
  8240. else if (offset == 30)
  8241. sink.os.write(rand1.data() + 30, 300);
  8242. else if (offset == 330)
  8243. sink.os.write(rand1.data() + 330, 670);
  8244. else if (offset == rand1.size())
  8245. sink.done();
  8246. return true;
  8247. },
  8248. "filename3",
  8249. {}});
  8250. providers.push_back({"name4",
  8251. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8252. // test the offset is given correctly at each step
  8253. if (!offset)
  8254. sink.os.write(rand2.data(), 2000);
  8255. else if (offset == 2000)
  8256. sink.os.write(rand2.data() + 2000, 1);
  8257. else if (offset == 2001)
  8258. sink.os.write(rand2.data() + 2001, 999);
  8259. else if (offset == rand2.size())
  8260. sink.done();
  8261. return true;
  8262. },
  8263. "filename4",
  8264. {}});
  8265. {
  8266. auto res = cli.Post("/post-providers", {}, {}, providers);
  8267. ASSERT_TRUE(res);
  8268. ASSERT_EQ(StatusCode::OK_200, res->status);
  8269. }
  8270. {
  8271. auto res = cli.Post("/post-both", {}, items, providers);
  8272. ASSERT_TRUE(res);
  8273. ASSERT_EQ(StatusCode::OK_200, res->status);
  8274. }
  8275. }
  8276. }
  8277. TEST(MultipartFormDataTest, BadHeader) {
  8278. Server svr;
  8279. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8280. res.set_content("ok", "text/plain");
  8281. });
  8282. thread t = thread([&] { svr.listen(HOST, PORT); });
  8283. auto se = detail::scope_exit([&] {
  8284. svr.stop();
  8285. t.join();
  8286. ASSERT_FALSE(svr.is_running());
  8287. });
  8288. svr.wait_until_ready();
  8289. const std::string body =
  8290. "This is the preamble. It is to be ignored, though it\r\n"
  8291. "is a handy place for composition agents to include an\r\n"
  8292. "explanatory note to non-MIME conformant readers.\r\n"
  8293. "\r\n"
  8294. "\r\n"
  8295. "--simple boundary\r\n"
  8296. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8297. ": BAD...\r\n"
  8298. "\r\n"
  8299. "value1\r\n"
  8300. "--simple boundary\r\n"
  8301. "Content-Disposition: form-data; name=\"field2\"; "
  8302. "filename=\"example.txt\"\r\n"
  8303. "\r\n"
  8304. "value2\r\n"
  8305. "--simple boundary--\r\n"
  8306. "This is the epilogue. It is also to be ignored.\r\n";
  8307. std::string content_type =
  8308. R"(multipart/form-data; boundary="simple boundary")";
  8309. Client cli(HOST, PORT);
  8310. auto res = cli.Post("/post", body, content_type.c_str());
  8311. ASSERT_TRUE(res);
  8312. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8313. }
  8314. TEST(MultipartFormDataTest, WithPreamble) {
  8315. Server svr;
  8316. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8317. res.set_content("ok", "text/plain");
  8318. });
  8319. thread t = thread([&] { svr.listen(HOST, PORT); });
  8320. auto se = detail::scope_exit([&] {
  8321. svr.stop();
  8322. t.join();
  8323. ASSERT_FALSE(svr.is_running());
  8324. });
  8325. svr.wait_until_ready();
  8326. const std::string body =
  8327. "This is the preamble. It is to be ignored, though it\r\n"
  8328. "is a handy place for composition agents to include an\r\n"
  8329. "explanatory note to non-MIME conformant readers.\r\n"
  8330. "\r\n"
  8331. "\r\n"
  8332. "--simple boundary\r\n"
  8333. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8334. "\r\n"
  8335. "value1\r\n"
  8336. "--simple boundary\r\n"
  8337. "Content-Disposition: form-data; name=\"field2\"; "
  8338. "filename=\"example.txt\"\r\n"
  8339. "\r\n"
  8340. "value2\r\n"
  8341. "--simple boundary--\r\n"
  8342. "This is the epilogue. It is also to be ignored.\r\n";
  8343. std::string content_type =
  8344. R"(multipart/form-data; boundary="simple boundary")";
  8345. Client cli(HOST, PORT);
  8346. auto res = cli.Post("/post", body, content_type.c_str());
  8347. ASSERT_TRUE(res);
  8348. EXPECT_EQ(StatusCode::OK_200, res->status);
  8349. }
  8350. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8352. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8353. const ContentReader &content_reader) {
  8354. if (req.is_multipart_form_data()) {
  8355. std::vector<FormData> items;
  8356. content_reader(
  8357. [&](const FormData &file) {
  8358. items.push_back(file);
  8359. return true;
  8360. },
  8361. [&](const char *data, size_t data_length) {
  8362. items.back().content.append(data, data_length);
  8363. return true;
  8364. });
  8365. EXPECT_TRUE(std::string(items[0].name) == "document");
  8366. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8367. EXPECT_TRUE(items[0].filename == "2MB_data");
  8368. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8369. EXPECT_TRUE(items[1].name == "hello");
  8370. EXPECT_TRUE(items[1].content == "world");
  8371. EXPECT_TRUE(items[1].filename == "");
  8372. EXPECT_TRUE(items[1].content_type == "");
  8373. } else {
  8374. std::string body;
  8375. content_reader([&](const char *data, size_t data_length) {
  8376. body.append(data, data_length);
  8377. return true;
  8378. });
  8379. }
  8380. });
  8381. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8382. auto se = detail::scope_exit([&] {
  8383. svr.stop();
  8384. t.join();
  8385. ASSERT_FALSE(svr.is_running());
  8386. });
  8387. svr.wait_until_ready();
  8388. {
  8389. std::string data(1024 * 1024 * 2, '.');
  8390. std::stringstream buffer;
  8391. buffer << data;
  8392. Client cli("https://localhost:8080");
  8393. cli.enable_server_certificate_verification(false);
  8394. UploadFormDataItems items{
  8395. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8396. {"hello", "world", "", ""},
  8397. };
  8398. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8399. ASSERT_TRUE(res);
  8400. ASSERT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. }
  8403. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8404. std::string data(1024 * 1024 * 2, '&');
  8405. std::stringstream buffer;
  8406. buffer << data;
  8407. Client cli("https://localhost:8080");
  8408. UploadFormDataItems items{
  8409. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8410. {"hello", "world", "", ""},
  8411. };
  8412. for (const char &c : " \t\r\n") {
  8413. auto res =
  8414. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8415. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8416. ASSERT_FALSE(res);
  8417. }
  8418. }
  8419. TEST(MultipartFormDataTest, PutFormData) {
  8420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8421. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8422. const ContentReader &content_reader) {
  8423. if (req.is_multipart_form_data()) {
  8424. std::vector<FormData> items;
  8425. content_reader(
  8426. [&](const FormData &file) {
  8427. items.push_back(file);
  8428. return true;
  8429. },
  8430. [&](const char *data, size_t data_length) {
  8431. items.back().content.append(data, data_length);
  8432. return true;
  8433. });
  8434. EXPECT_TRUE(std::string(items[0].name) == "document");
  8435. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8436. EXPECT_TRUE(items[0].filename == "2MB_data");
  8437. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8438. EXPECT_TRUE(items[1].name == "hello");
  8439. EXPECT_TRUE(items[1].content == "world");
  8440. EXPECT_TRUE(items[1].filename == "");
  8441. EXPECT_TRUE(items[1].content_type == "");
  8442. } else {
  8443. std::string body;
  8444. content_reader([&](const char *data, size_t data_length) {
  8445. body.append(data, data_length);
  8446. return true;
  8447. });
  8448. }
  8449. });
  8450. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8451. auto se = detail::scope_exit([&] {
  8452. svr.stop();
  8453. t.join();
  8454. ASSERT_FALSE(svr.is_running());
  8455. });
  8456. svr.wait_until_ready();
  8457. {
  8458. std::string data(1024 * 1024 * 2, '&');
  8459. std::stringstream buffer;
  8460. buffer << data;
  8461. Client cli("https://localhost:8080");
  8462. cli.enable_server_certificate_verification(false);
  8463. UploadFormDataItems items{
  8464. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8465. {"hello", "world", "", ""},
  8466. };
  8467. auto res = cli.Put("/put", items);
  8468. ASSERT_TRUE(res);
  8469. ASSERT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. }
  8472. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8474. svr.Put("/put_customboundary",
  8475. [&](const Request &req, const Response & /*res*/,
  8476. const ContentReader &content_reader) {
  8477. if (req.is_multipart_form_data()) {
  8478. std::vector<FormData> items;
  8479. content_reader(
  8480. [&](const FormData &file) {
  8481. items.push_back(file);
  8482. return true;
  8483. },
  8484. [&](const char *data, size_t data_length) {
  8485. items.back().content.append(data, data_length);
  8486. return true;
  8487. });
  8488. EXPECT_TRUE(std::string(items[0].name) == "document");
  8489. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8490. EXPECT_TRUE(items[0].filename == "2MB_data");
  8491. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8492. EXPECT_TRUE(items[1].name == "hello");
  8493. EXPECT_TRUE(items[1].content == "world");
  8494. EXPECT_TRUE(items[1].filename == "");
  8495. EXPECT_TRUE(items[1].content_type == "");
  8496. } else {
  8497. std::string body;
  8498. content_reader([&](const char *data, size_t data_length) {
  8499. body.append(data, data_length);
  8500. return true;
  8501. });
  8502. }
  8503. });
  8504. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. t.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. });
  8510. svr.wait_until_ready();
  8511. {
  8512. std::string data(1024 * 1024 * 2, '&');
  8513. std::stringstream buffer;
  8514. buffer << data;
  8515. Client cli("https://localhost:8080");
  8516. cli.enable_server_certificate_verification(false);
  8517. UploadFormDataItems items{
  8518. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8519. {"hello", "world", "", ""},
  8520. };
  8521. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8522. ASSERT_TRUE(res);
  8523. ASSERT_EQ(StatusCode::OK_200, res->status);
  8524. }
  8525. }
  8526. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8527. std::string data(1024 * 1024 * 2, '&');
  8528. std::stringstream buffer;
  8529. buffer << data;
  8530. Client cli("https://localhost:8080");
  8531. cli.enable_server_certificate_verification(false);
  8532. UploadFormDataItems items{
  8533. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8534. {"hello", "world", "", ""},
  8535. };
  8536. for (const char &c : " \t\r\n") {
  8537. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8538. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8539. ASSERT_FALSE(res);
  8540. }
  8541. }
  8542. TEST(MultipartFormDataTest, AlternateFilename) {
  8543. auto handled = false;
  8544. Server svr;
  8545. svr.Post("/test", [&](const Request &req, Response &res) {
  8546. ASSERT_EQ(2u, req.form.files.size());
  8547. ASSERT_EQ(1u, req.form.fields.size());
  8548. // Test files
  8549. const auto &file1 = req.form.get_file("file1");
  8550. ASSERT_EQ("file1", file1.name);
  8551. ASSERT_EQ("A.txt", file1.filename);
  8552. ASSERT_EQ("text/plain", file1.content_type);
  8553. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8554. const auto &file2 = req.form.get_file("file2");
  8555. ASSERT_EQ("file2", file2.name);
  8556. ASSERT_EQ("a.html", file2.filename);
  8557. ASSERT_EQ("text/html", file2.content_type);
  8558. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8559. file2.content);
  8560. // Test text field
  8561. const auto &text = req.form.get_field("text");
  8562. ASSERT_EQ("text default", text);
  8563. res.set_content("ok", "text/plain");
  8564. handled = true;
  8565. });
  8566. thread t = thread([&] { svr.listen(HOST, PORT); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. t.join();
  8570. ASSERT_FALSE(svr.is_running());
  8571. ASSERT_TRUE(handled);
  8572. });
  8573. svr.wait_until_ready();
  8574. auto req = "POST /test HTTP/1.1\r\n"
  8575. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8576. "Content-Length: 399\r\n"
  8577. "\r\n"
  8578. "----------\r\n"
  8579. "Content-Disposition: form-data; name=\"text\"\r\n"
  8580. "\r\n"
  8581. "text default\r\n"
  8582. "----------\r\n"
  8583. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8584. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8585. "Content-Type: text/plain\r\n"
  8586. "\r\n"
  8587. "Content of a.txt.\r\n"
  8588. "\r\n"
  8589. "----------\r\n"
  8590. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8591. "\"a.html\"\r\n"
  8592. "Content-Type: text/html\r\n"
  8593. "\r\n"
  8594. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8595. "\r\n"
  8596. "------------\r\n";
  8597. ASSERT_TRUE(send_request(1, req));
  8598. }
  8599. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8600. auto handled = false;
  8601. Server svr;
  8602. svr.Post("/test", [&](const Request &req, Response &) {
  8603. ASSERT_EQ(2u, req.form.fields.size());
  8604. const auto &text1 = req.form.get_field("text1");
  8605. ASSERT_EQ("text1", text1);
  8606. const auto &text2 = req.form.get_field("text2");
  8607. ASSERT_EQ("text2", text2);
  8608. handled = true;
  8609. });
  8610. thread t = thread([&] { svr.listen(HOST, PORT); });
  8611. auto se = detail::scope_exit([&] {
  8612. svr.stop();
  8613. t.join();
  8614. ASSERT_FALSE(svr.is_running());
  8615. ASSERT_TRUE(handled);
  8616. });
  8617. svr.wait_until_ready();
  8618. auto req = "POST /test HTTP/1.1\r\n"
  8619. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8620. "Content-Length: 146\r\n"
  8621. "\r\n----------\r\n"
  8622. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8623. "\r\n"
  8624. "text1"
  8625. "\r\n----------\r\n"
  8626. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8627. "\r\n"
  8628. "text2"
  8629. "\r\n------------";
  8630. std::string response;
  8631. ASSERT_TRUE(send_request(1, req, &response));
  8632. ASSERT_EQ("200", response.substr(9, 3));
  8633. }
  8634. TEST(MultipartFormDataTest, ContentLength) {
  8635. auto handled = false;
  8636. Server svr;
  8637. svr.Post("/test", [&](const Request &req, Response &) {
  8638. ASSERT_EQ(2u, req.form.fields.size());
  8639. const auto &text1 = req.form.get_field("text1");
  8640. ASSERT_EQ("text1", text1);
  8641. const auto &text2 = req.form.get_field("text2");
  8642. ASSERT_EQ("text2", text2);
  8643. handled = true;
  8644. });
  8645. thread t = thread([&] { svr.listen(HOST, PORT); });
  8646. auto se = detail::scope_exit([&] {
  8647. svr.stop();
  8648. t.join();
  8649. ASSERT_FALSE(svr.is_running());
  8650. ASSERT_TRUE(handled);
  8651. });
  8652. svr.wait_until_ready();
  8653. auto req = "POST /test HTTP/1.1\r\n"
  8654. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8655. "Content-Length: 167\r\n"
  8656. "\r\n----------\r\n"
  8657. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8658. "Content-Length: 5\r\n"
  8659. "\r\n"
  8660. "text1"
  8661. "\r\n----------\r\n"
  8662. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8663. "\r\n"
  8664. "text2"
  8665. "\r\n------------\r\n";
  8666. std::string response;
  8667. ASSERT_TRUE(send_request(1, req, &response));
  8668. ASSERT_EQ("200", response.substr(9, 3));
  8669. }
  8670. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8671. auto handled = false;
  8672. Server svr;
  8673. svr.Post("/test", [&](const Request &req, Response &) {
  8674. ASSERT_EQ(2u, req.form.fields.size());
  8675. const auto &text1 = req.form.get_field("text1");
  8676. ASSERT_EQ("text1", text1);
  8677. // TODO: Add header access for text fields if needed
  8678. const auto &text2 = req.form.get_field("text2");
  8679. ASSERT_EQ("text2", text2);
  8680. // TODO: Header access for text fields needs to be implemented
  8681. // auto &headers = it->second.headers;
  8682. // ASSERT_EQ(3U, headers.size());
  8683. // auto custom_header = headers.find("x-whatever");
  8684. // ASSERT_TRUE(custom_header != headers.end());
  8685. // ASSERT_NE("customvalue", custom_header->second);
  8686. // ASSERT_EQ("CustomValue", custom_header->second);
  8687. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8688. handled = true;
  8689. });
  8690. thread t = thread([&] { svr.listen(HOST, PORT); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. t.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. ASSERT_TRUE(handled);
  8696. });
  8697. svr.wait_until_ready();
  8698. auto req = "POST /test HTTP/1.1\r\n"
  8699. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8700. "Content-Length: 232\r\n"
  8701. "\r\n----------\r\n"
  8702. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8703. "Content-Length: 5\r\n"
  8704. "X-Test: 1\r\n"
  8705. "\r\n"
  8706. "text1"
  8707. "\r\n----------\r\n"
  8708. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8709. "Content-Type: text/plain\r\n"
  8710. "X-Whatever: CustomValue\r\n"
  8711. "\r\n"
  8712. "text2"
  8713. "\r\n------------\r\n"
  8714. "That should be disregarded. Not even read";
  8715. std::string response;
  8716. ASSERT_TRUE(send_request(1, req, &response));
  8717. ASSERT_EQ("200", response.substr(9, 3));
  8718. }
  8719. #endif
  8720. TEST(MultipartFormDataTest, LargeHeader) {
  8721. auto handled = false;
  8722. Server svr;
  8723. svr.Post("/test", [&](const Request &req, Response &) {
  8724. ASSERT_EQ(1u, req.form.fields.size());
  8725. const auto &text = req.form.get_field("name1");
  8726. ASSERT_EQ("text1", text);
  8727. handled = true;
  8728. });
  8729. thread t = thread([&] { svr.listen(HOST, PORT); });
  8730. auto se = detail::scope_exit([&] {
  8731. svr.stop();
  8732. t.join();
  8733. ASSERT_FALSE(svr.is_running());
  8734. ASSERT_TRUE(handled);
  8735. });
  8736. svr.wait_until_ready();
  8737. auto boundary = std::string("cpp-httplib-multipart-data");
  8738. std::string content = "--" + boundary +
  8739. "\r\n"
  8740. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8741. "\r\n"
  8742. "text1\r\n"
  8743. "--" +
  8744. boundary + "--\r\n";
  8745. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8746. "Content-Type: multipart/form-data;boundary=" +
  8747. boundary +
  8748. "\r\n"
  8749. "Content-Length: " +
  8750. std::to_string(content.size()) +
  8751. "\r\n"
  8752. "Dummy-Header: ";
  8753. std::string header_suffix = "\r\n"
  8754. "\r\n";
  8755. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8756. size_t header_dummy_size =
  8757. read_buff_size -
  8758. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8759. auto header_dummy = std::string(header_dummy_size, '@');
  8760. auto req = header_prefix + header_dummy + header_suffix + content;
  8761. std::string response;
  8762. ASSERT_TRUE(send_request(1, req, &response));
  8763. ASSERT_EQ("200", response.substr(9, 3));
  8764. }
  8765. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8766. static constexpr unsigned int number_of_tasks{1000000};
  8767. std::atomic_uint count{0};
  8768. std::unique_ptr<TaskQueue> task_queue{
  8769. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8770. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8771. auto queued = task_queue->enqueue(
  8772. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8773. EXPECT_TRUE(queued);
  8774. }
  8775. EXPECT_NO_THROW(task_queue->shutdown());
  8776. EXPECT_EQ(number_of_tasks, count.load());
  8777. }
  8778. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8779. static constexpr unsigned int number_of_tasks{1000000};
  8780. static constexpr unsigned int qlimit{2};
  8781. unsigned int queued_count{0};
  8782. std::atomic_uint count{0};
  8783. std::unique_ptr<TaskQueue> task_queue{
  8784. new ThreadPool{/*num_threads=*/1, qlimit}};
  8785. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8786. if (task_queue->enqueue(
  8787. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8788. queued_count++;
  8789. }
  8790. }
  8791. EXPECT_NO_THROW(task_queue->shutdown());
  8792. EXPECT_EQ(queued_count, count.load());
  8793. EXPECT_TRUE(queued_count <= number_of_tasks);
  8794. EXPECT_TRUE(queued_count >= qlimit);
  8795. }
  8796. TEST(TaskQueueTest, MaxQueuedRequests) {
  8797. static constexpr unsigned int qlimit{3};
  8798. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8799. std::condition_variable sem_cv;
  8800. std::mutex sem_mtx;
  8801. int credits = 0;
  8802. bool queued;
  8803. /* Fill up the queue with tasks that will block until we give them credits to
  8804. * complete. */
  8805. for (unsigned int n = 0; n <= qlimit;) {
  8806. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8807. std::unique_lock<std::mutex> lock(sem_mtx);
  8808. while (credits <= 0) {
  8809. sem_cv.wait(lock);
  8810. }
  8811. /* Consume the credit and signal the test code if they are all gone. */
  8812. if (--credits == 0) { sem_cv.notify_one(); }
  8813. });
  8814. if (n < qlimit) {
  8815. /* The first qlimit enqueues must succeed. */
  8816. EXPECT_TRUE(queued);
  8817. } else {
  8818. /* The last one will succeed only when the worker thread
  8819. * starts and dequeues the first blocking task. Although
  8820. * not necessary for the correctness of this test, we sleep for
  8821. * a short while to avoid busy waiting. */
  8822. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8823. }
  8824. if (queued) { n++; }
  8825. }
  8826. /* Further enqueues must fail since the queue is full. */
  8827. for (auto i = 0; i < 4; i++) {
  8828. queued = task_queue->enqueue([] {});
  8829. EXPECT_FALSE(queued);
  8830. }
  8831. /* Give the credits to allow the previous tasks to complete. */
  8832. {
  8833. std::unique_lock<std::mutex> lock(sem_mtx);
  8834. credits += qlimit + 1;
  8835. }
  8836. sem_cv.notify_all();
  8837. /* Wait for all the credits to be consumed. */
  8838. {
  8839. std::unique_lock<std::mutex> lock(sem_mtx);
  8840. while (credits > 0) {
  8841. sem_cv.wait(lock);
  8842. }
  8843. }
  8844. /* Check that we are able again to enqueue at least qlimit tasks. */
  8845. for (unsigned int i = 0; i < qlimit; i++) {
  8846. queued = task_queue->enqueue([] {});
  8847. EXPECT_TRUE(queued);
  8848. }
  8849. EXPECT_NO_THROW(task_queue->shutdown());
  8850. }
  8851. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8852. Server svr;
  8853. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8854. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8855. });
  8856. svr.Get("/hello", [](const Request &req, Response &res) {
  8857. res.set_content(req.get_param_value("key"), "text/plain");
  8858. });
  8859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. thread.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. {
  8867. Client cli(HOST, PORT);
  8868. cli.set_follow_location(true);
  8869. auto res = cli.Get("/");
  8870. ASSERT_TRUE(res);
  8871. EXPECT_EQ(StatusCode::OK_200, res->status);
  8872. EXPECT_EQ("val&key2=val2", res->body);
  8873. }
  8874. }
  8875. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8876. Server svr;
  8877. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8878. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8879. });
  8880. svr.Get("/hello", [](const Request &req, Response &res) {
  8881. res.set_content(req.get_param_value("key"), "text/plain");
  8882. });
  8883. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8884. auto se = detail::scope_exit([&] {
  8885. svr.stop();
  8886. thread.join();
  8887. ASSERT_FALSE(svr.is_running());
  8888. });
  8889. svr.wait_until_ready();
  8890. {
  8891. Client cli(HOST, PORT);
  8892. cli.set_follow_location(true);
  8893. auto res = cli.Get("/");
  8894. ASSERT_TRUE(res);
  8895. EXPECT_EQ(StatusCode::OK_200, res->status);
  8896. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8897. }
  8898. }
  8899. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8900. TEST(RedirectTest, Issue2185_Online) {
  8901. SSLClient client("github.com");
  8902. client.set_follow_location(true);
  8903. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8904. "Coollab-Windows.zip");
  8905. ASSERT_TRUE(res);
  8906. EXPECT_EQ(StatusCode::OK_200, res->status);
  8907. EXPECT_EQ(9920427U, res->body.size());
  8908. }
  8909. #endif
  8910. TEST(VulnerabilityTest, CRLFInjection) {
  8911. Server svr;
  8912. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8913. res.set_content("Hello 1", "text/plain");
  8914. });
  8915. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8916. res.set_content("Hello 2", "text/plain");
  8917. });
  8918. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8919. res.set_content("Hello 3", "text/plain");
  8920. });
  8921. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8922. res.set_content("Hello 4", "text/plain");
  8923. });
  8924. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8925. for (const auto &x : req.headers) {
  8926. auto key = x.first;
  8927. EXPECT_STRNE("evil", key.c_str());
  8928. }
  8929. });
  8930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8931. auto se = detail::scope_exit([&] {
  8932. svr.stop();
  8933. thread.join();
  8934. ASSERT_FALSE(svr.is_running());
  8935. });
  8936. svr.wait_until_ready();
  8937. {
  8938. Client cli(HOST, PORT);
  8939. cli.Post("/test1", "A=B",
  8940. "application/x-www-form-urlencoded\r\nevil: hello1");
  8941. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8942. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8943. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8944. }
  8945. }
  8946. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  8947. auto server_thread = std::thread([] {
  8948. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8949. default_socket_options(srv);
  8950. sockaddr_in addr{};
  8951. addr.sin_family = AF_INET;
  8952. addr.sin_port = htons(PORT + 1);
  8953. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8954. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8955. ::listen(srv, 1);
  8956. sockaddr_in cli_addr{};
  8957. socklen_t cli_len = sizeof(cli_addr);
  8958. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8959. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  8960. std::string buf_all;
  8961. char buf[2048];
  8962. ssize_t n;
  8963. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  8964. buf_all.append(buf, static_cast<size_t>(n));
  8965. size_t pos;
  8966. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  8967. auto request_block = buf_all.substr(0, pos + 4); // include separator
  8968. auto e = request_block.find("\r\n");
  8969. if (e != std::string::npos) {
  8970. auto request_line = request_block.substr(0, e);
  8971. std::string msg =
  8972. "CRLF injection detected in request line: '" + request_line + "'";
  8973. EXPECT_FALSE(true) << msg;
  8974. }
  8975. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  8976. ::send(cli, resp.c_str(), resp.size(), 0);
  8977. buf_all.erase(0, pos + 4);
  8978. }
  8979. }
  8980. detail::close_socket(cli);
  8981. detail::close_socket(srv);
  8982. });
  8983. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8984. auto cli = Client("127.0.0.1", PORT + 1);
  8985. auto headers = Headers{
  8986. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  8987. {"Connection", "keep-alive"}};
  8988. auto res = cli.Get("/hi", headers);
  8989. EXPECT_FALSE(res);
  8990. EXPECT_EQ(Error::InvalidHeaders, res.error());
  8991. server_thread.join();
  8992. }
  8993. TEST(PathParamsTest, StaticMatch) {
  8994. const auto pattern = "/users/all";
  8995. detail::PathParamsMatcher matcher(pattern);
  8996. Request request;
  8997. request.path = "/users/all";
  8998. ASSERT_TRUE(matcher.match(request));
  8999. std::unordered_map<std::string, std::string> expected_params = {};
  9000. EXPECT_EQ(request.path_params, expected_params);
  9001. }
  9002. TEST(PathParamsTest, StaticMismatch) {
  9003. const auto pattern = "/users/all";
  9004. detail::PathParamsMatcher matcher(pattern);
  9005. Request request;
  9006. request.path = "/users/1";
  9007. ASSERT_FALSE(matcher.match(request));
  9008. }
  9009. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9010. const auto pattern = "/users/:id/subscriptions";
  9011. detail::PathParamsMatcher matcher(pattern);
  9012. Request request;
  9013. request.path = "/users/42/subscriptions";
  9014. ASSERT_TRUE(matcher.match(request));
  9015. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9016. EXPECT_EQ(request.path_params, expected_params);
  9017. }
  9018. TEST(PathParamsTest, SingleParamInTheEnd) {
  9019. const auto pattern = "/users/:id";
  9020. detail::PathParamsMatcher matcher(pattern);
  9021. Request request;
  9022. request.path = "/users/24";
  9023. ASSERT_TRUE(matcher.match(request));
  9024. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9025. EXPECT_EQ(request.path_params, expected_params);
  9026. }
  9027. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9028. const auto pattern = "/users/:id/";
  9029. detail::PathParamsMatcher matcher(pattern);
  9030. Request request;
  9031. request.path = "/users/42/";
  9032. ASSERT_TRUE(matcher.match(request));
  9033. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9034. EXPECT_EQ(request.path_params, expected_params);
  9035. }
  9036. TEST(PathParamsTest, EmptyParam) {
  9037. const auto pattern = "/users/:id/";
  9038. detail::PathParamsMatcher matcher(pattern);
  9039. Request request;
  9040. request.path = "/users//";
  9041. ASSERT_TRUE(matcher.match(request));
  9042. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9043. EXPECT_EQ(request.path_params, expected_params);
  9044. }
  9045. TEST(PathParamsTest, FragmentMismatch) {
  9046. const auto pattern = "/users/:id/";
  9047. detail::PathParamsMatcher matcher(pattern);
  9048. Request request;
  9049. request.path = "/admins/24/";
  9050. ASSERT_FALSE(matcher.match(request));
  9051. }
  9052. TEST(PathParamsTest, ExtraFragments) {
  9053. const auto pattern = "/users/:id";
  9054. detail::PathParamsMatcher matcher(pattern);
  9055. Request request;
  9056. request.path = "/users/42/subscriptions";
  9057. ASSERT_FALSE(matcher.match(request));
  9058. }
  9059. TEST(PathParamsTest, MissingTrailingParam) {
  9060. const auto pattern = "/users/:id";
  9061. detail::PathParamsMatcher matcher(pattern);
  9062. Request request;
  9063. request.path = "/users";
  9064. ASSERT_FALSE(matcher.match(request));
  9065. }
  9066. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9067. const auto pattern = "/users/:id/subscriptions";
  9068. detail::PathParamsMatcher matcher(pattern);
  9069. Request request;
  9070. request.path = "/users/subscriptions";
  9071. ASSERT_FALSE(matcher.match(request));
  9072. }
  9073. TEST(PathParamsTest, MultipleParams) {
  9074. const auto pattern = "/users/:userid/subscriptions/:subid";
  9075. detail::PathParamsMatcher matcher(pattern);
  9076. Request request;
  9077. request.path = "/users/42/subscriptions/2";
  9078. ASSERT_TRUE(matcher.match(request));
  9079. std::unordered_map<std::string, std::string> expected_params = {
  9080. {"userid", "42"}, {"subid", "2"}};
  9081. EXPECT_EQ(request.path_params, expected_params);
  9082. }
  9083. TEST(PathParamsTest, SequenceOfParams) {
  9084. const auto pattern = "/values/:x/:y/:z";
  9085. detail::PathParamsMatcher matcher(pattern);
  9086. Request request;
  9087. request.path = "/values/1/2/3";
  9088. ASSERT_TRUE(matcher.match(request));
  9089. std::unordered_map<std::string, std::string> expected_params = {
  9090. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9091. EXPECT_EQ(request.path_params, expected_params);
  9092. }
  9093. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9094. const auto pattern = "/prefix:suffix";
  9095. detail::PathParamsMatcher matcher(pattern);
  9096. Request request;
  9097. request.path = "/prefix:suffix";
  9098. ASSERT_TRUE(matcher.match(request));
  9099. const std::unordered_map<std::string, std::string> expected_params = {};
  9100. EXPECT_EQ(request.path_params, expected_params);
  9101. }
  9102. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9103. // If ipv6 regex working, regex match codepath is taken.
  9104. // else port will default to 80 in Client impl
  9105. int clientImplMagicPort = 80;
  9106. int port = 4321;
  9107. // above ports must be different to avoid false negative
  9108. EXPECT_NE(clientImplMagicPort, port);
  9109. std::string ipV6TestURL = "http://[ff06::c3]";
  9110. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9111. CLIENT_PRIVATE_KEY_FILE);
  9112. EXPECT_EQ(cli.port(), port);
  9113. }
  9114. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9115. auto file_path = "./www/dir/index.html";
  9116. auto dir_path = "./www/dir";
  9117. detail::FileStat stat_file(file_path);
  9118. EXPECT_TRUE(stat_file.is_file());
  9119. EXPECT_FALSE(stat_file.is_dir());
  9120. detail::FileStat stat_dir(dir_path);
  9121. EXPECT_FALSE(stat_dir.is_file());
  9122. EXPECT_TRUE(stat_dir.is_dir());
  9123. }
  9124. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9125. // IPv4 with default HTTP port (80)
  9126. EXPECT_EQ("example.com",
  9127. detail::make_host_and_port_string("example.com", 80, false));
  9128. // IPv4 with default HTTPS port (443)
  9129. EXPECT_EQ("example.com",
  9130. detail::make_host_and_port_string("example.com", 443, true));
  9131. // IPv4 with non-default HTTP port
  9132. EXPECT_EQ("example.com:8080",
  9133. detail::make_host_and_port_string("example.com", 8080, false));
  9134. // IPv4 with non-default HTTPS port
  9135. EXPECT_EQ("example.com:8443",
  9136. detail::make_host_and_port_string("example.com", 8443, true));
  9137. // IPv6 with default HTTP port (80)
  9138. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9139. // IPv6 with default HTTPS port (443)
  9140. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9141. // IPv6 with non-default HTTP port
  9142. EXPECT_EQ("[::1]:8080",
  9143. detail::make_host_and_port_string("::1", 8080, false));
  9144. // IPv6 with non-default HTTPS port
  9145. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9146. // IPv6 full address with default port
  9147. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9148. detail::make_host_and_port_string(
  9149. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9150. // IPv6 full address with non-default port
  9151. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9152. detail::make_host_and_port_string(
  9153. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9154. // IPv6 localhost with non-default port
  9155. EXPECT_EQ("[::1]:3000",
  9156. detail::make_host_and_port_string("::1", 3000, false));
  9157. // IPv6 with zone ID (link-local address) with default port
  9158. EXPECT_EQ("[fe80::1%eth0]",
  9159. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9160. // IPv6 with zone ID (link-local address) with non-default port
  9161. EXPECT_EQ("[fe80::1%eth0]:8080",
  9162. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9163. // Edge case: Port 443 with is_ssl=false (should add port)
  9164. EXPECT_EQ("example.com:443",
  9165. detail::make_host_and_port_string("example.com", 443, false));
  9166. // Edge case: Port 80 with is_ssl=true (should add port)
  9167. EXPECT_EQ("example.com:80",
  9168. detail::make_host_and_port_string("example.com", 80, true));
  9169. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9170. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9171. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9172. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9173. // Security fix: Already bracketed IPv6 should not get double brackets
  9174. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9175. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9176. EXPECT_EQ("[::1]:8080",
  9177. detail::make_host_and_port_string("[::1]", 8080, false));
  9178. EXPECT_EQ("[2001:db8::1]:8080",
  9179. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9180. EXPECT_EQ("[fe80::1%eth0]",
  9181. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9182. EXPECT_EQ("[fe80::1%eth0]:8080",
  9183. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9184. // Edge case: Empty host (should return as-is)
  9185. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9186. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9187. // This is a known limitation but shouldn't crash
  9188. EXPECT_EQ("[host:name]",
  9189. detail::make_host_and_port_string("host:name", 80, false));
  9190. // Port number edge cases (no validation, but should not crash)
  9191. EXPECT_EQ("example.com:0",
  9192. detail::make_host_and_port_string("example.com", 0, false));
  9193. EXPECT_EQ("example.com:-1",
  9194. detail::make_host_and_port_string("example.com", -1, false));
  9195. EXPECT_EQ("example.com:65535",
  9196. detail::make_host_and_port_string("example.com", 65535, false));
  9197. EXPECT_EQ("example.com:65536",
  9198. detail::make_host_and_port_string("example.com", 65536, false));
  9199. }
  9200. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9201. TEST(SSLClientHostHeaderTest, Issue2301) {
  9202. httplib::SSLClient cli("roblox.com", 443);
  9203. cli.set_follow_location(true);
  9204. auto res = cli.Get("/");
  9205. ASSERT_TRUE(res);
  9206. EXPECT_EQ(StatusCode::OK_200, res->status);
  9207. }
  9208. #endif
  9209. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9210. Server svr;
  9211. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9212. EXPECT_EQ(res.status, 400);
  9213. });
  9214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9215. auto se = detail::scope_exit([&] {
  9216. svr.stop();
  9217. thread.join();
  9218. ASSERT_FALSE(svr.is_running());
  9219. });
  9220. svr.wait_until_ready();
  9221. Client cli(HOST, PORT);
  9222. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9223. }
  9224. TEST(InvalidHeaderCharsTest, is_field_name) {
  9225. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9226. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9227. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9228. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9229. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9230. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9231. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9232. EXPECT_FALSE(detail::fields::is_field_name(""));
  9233. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9234. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9235. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9236. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9237. }
  9238. TEST(InvalidHeaderCharsTest, is_field_value) {
  9239. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9240. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9241. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9242. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9243. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9244. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9245. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9246. EXPECT_TRUE(detail::fields::is_field_value(""));
  9247. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9248. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9249. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9250. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9251. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9252. }
  9253. TEST(InvalidHeaderCharsTest, OnServer) {
  9254. Server svr;
  9255. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9256. std::string header = "Not Set";
  9257. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9258. res.set_header(header, "value");
  9259. res.set_content("Page Content Page Content", "text/plain");
  9260. });
  9261. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9262. std::string header = "Not Set";
  9263. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9264. res.set_header("X-Test", header);
  9265. res.set_content("Page Content Page Content", "text/plain");
  9266. });
  9267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. thread.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. svr.wait_until_ready();
  9274. Client cli(HOST, PORT);
  9275. {
  9276. auto res = cli.Get(
  9277. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9278. ASSERT_TRUE(res);
  9279. EXPECT_EQ("Page Content Page Content", res->body);
  9280. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9281. }
  9282. {
  9283. auto res = cli.Get(
  9284. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9285. ASSERT_TRUE(res);
  9286. EXPECT_EQ("Page Content Page Content", res->body);
  9287. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9288. }
  9289. }
  9290. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9291. auto handled = false;
  9292. Server svr;
  9293. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9294. thread t = thread([&] { svr.listen(HOST, PORT); });
  9295. auto se = detail::scope_exit([&] {
  9296. svr.stop();
  9297. t.join();
  9298. ASSERT_FALSE(svr.is_running());
  9299. ASSERT_FALSE(handled);
  9300. });
  9301. svr.wait_until_ready();
  9302. auto req = "POST /test HTTP/1.1\r\n"
  9303. "Content-Length: x\r\n"
  9304. "\r\n";
  9305. std::string response;
  9306. ASSERT_TRUE(send_request(1, req, &response));
  9307. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9308. response.substr(0, response.find("\r\n")));
  9309. }
  9310. #ifndef _WIN32
  9311. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9312. static constexpr char reject[] = "Unauthorized";
  9313. static constexpr char accept[] = "Upload accepted";
  9314. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9315. Server svr;
  9316. svr.set_expect_100_continue_handler(
  9317. [](const Request & /*req*/, Response &res) {
  9318. res.status = StatusCode::Unauthorized_401;
  9319. res.set_content(reject, "text/plain");
  9320. return res.status;
  9321. });
  9322. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9323. res.set_content(accept, "text/plain");
  9324. });
  9325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9326. auto se = detail::scope_exit([&] {
  9327. svr.stop();
  9328. thread.join();
  9329. ASSERT_FALSE(svr.is_running());
  9330. });
  9331. svr.wait_until_ready();
  9332. {
  9333. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9334. curl_easy_init(), &curl_easy_cleanup};
  9335. ASSERT_NE(curl, nullptr);
  9336. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9337. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9338. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9339. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9340. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9341. &curl_slist_free_all};
  9342. ASSERT_NE(list, nullptr);
  9343. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9344. struct read_data {
  9345. size_t read_size;
  9346. size_t total_size;
  9347. } data = {0, total_size};
  9348. using read_callback_t =
  9349. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9350. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9351. void *userdata) -> size_t {
  9352. read_data *data = (read_data *)userdata;
  9353. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9354. std::fill_n(ptr, size * nmemb, 'A');
  9355. data->read_size += size * nmemb;
  9356. return size * nmemb;
  9357. };
  9358. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9359. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9360. std::vector<char> buffer;
  9361. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9362. using write_callback_t =
  9363. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9364. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9365. void *userdata) -> size_t {
  9366. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9367. buffer->reserve(buffer->size() + size * nmemb + 1);
  9368. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9369. return size * nmemb;
  9370. };
  9371. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9372. {
  9373. const auto res = curl_easy_perform(curl.get());
  9374. ASSERT_EQ(res, CURLE_OK);
  9375. }
  9376. {
  9377. auto response_code = long{};
  9378. const auto res =
  9379. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9380. ASSERT_EQ(res, CURLE_OK);
  9381. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9382. }
  9383. {
  9384. auto dl = curl_off_t{};
  9385. const auto res =
  9386. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9387. ASSERT_EQ(res, CURLE_OK);
  9388. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9389. }
  9390. {
  9391. buffer.push_back('\0');
  9392. ASSERT_STRCASEEQ(buffer.data(), reject);
  9393. }
  9394. }
  9395. }
  9396. #endif
  9397. template <typename S, typename C>
  9398. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9399. svr.Get("/stream", [&](const Request &, Response &res) {
  9400. auto data = new std::string("01234567890123456789");
  9401. res.set_content_provider(
  9402. data->size(), "text/plain",
  9403. [&, data](size_t offset, size_t length, DataSink &sink) {
  9404. const size_t DATA_CHUNK_SIZE = 4;
  9405. const auto &d = *data;
  9406. std::this_thread::sleep_for(std::chrono::seconds(1));
  9407. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9408. return true;
  9409. },
  9410. [data](bool success) {
  9411. EXPECT_FALSE(success);
  9412. delete data;
  9413. });
  9414. });
  9415. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9416. auto i = new size_t(0);
  9417. res.set_content_provider(
  9418. "text/plain",
  9419. [i](size_t, DataSink &sink) {
  9420. if (*i < 5) {
  9421. std::this_thread::sleep_for(std::chrono::seconds(1));
  9422. sink.write("abcd", 4);
  9423. (*i)++;
  9424. } else {
  9425. sink.done();
  9426. }
  9427. return true;
  9428. },
  9429. [i](bool success) {
  9430. EXPECT_FALSE(success);
  9431. delete i;
  9432. });
  9433. });
  9434. svr.Get("/chunked", [&](const Request &, Response &res) {
  9435. auto i = new size_t(0);
  9436. res.set_chunked_content_provider(
  9437. "text/plain",
  9438. [i](size_t, DataSink &sink) {
  9439. if (*i < 5) {
  9440. std::this_thread::sleep_for(std::chrono::seconds(1));
  9441. sink.os << "abcd";
  9442. (*i)++;
  9443. } else {
  9444. sink.done();
  9445. }
  9446. return true;
  9447. },
  9448. [i](bool success) {
  9449. EXPECT_FALSE(success);
  9450. delete i;
  9451. });
  9452. });
  9453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9454. auto se = detail::scope_exit([&] {
  9455. svr.stop();
  9456. listen_thread.join();
  9457. ASSERT_FALSE(svr.is_running());
  9458. });
  9459. svr.wait_until_ready();
  9460. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9461. {
  9462. auto start = std::chrono::steady_clock::now();
  9463. auto res = cli.Get("/stream");
  9464. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9465. std::chrono::steady_clock::now() - start)
  9466. .count();
  9467. ASSERT_FALSE(res);
  9468. EXPECT_EQ(Error::Read, res.error());
  9469. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9470. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9471. }
  9472. {
  9473. auto start = std::chrono::steady_clock::now();
  9474. auto res = cli.Get("/stream_without_length");
  9475. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9476. std::chrono::steady_clock::now() - start)
  9477. .count();
  9478. ASSERT_FALSE(res);
  9479. EXPECT_EQ(Error::Read, res.error());
  9480. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9481. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9482. }
  9483. {
  9484. auto start = std::chrono::steady_clock::now();
  9485. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9486. EXPECT_EQ("abcd", string(data, data_length));
  9487. return true;
  9488. });
  9489. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9490. std::chrono::steady_clock::now() - start)
  9491. .count();
  9492. ASSERT_FALSE(res);
  9493. EXPECT_EQ(Error::Read, res.error());
  9494. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9495. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9496. }
  9497. }
  9498. TEST(MaxTimeoutTest, ContentStream) {
  9499. time_t timeout = 2000;
  9500. time_t threshold = 200;
  9501. Server svr;
  9502. Client cli("localhost", PORT);
  9503. max_timeout_test(svr, cli, timeout, threshold);
  9504. }
  9505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9506. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9507. time_t timeout = 2000;
  9508. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9510. SSLClient cli("localhost", PORT);
  9511. cli.enable_server_certificate_verification(false);
  9512. max_timeout_test(svr, cli, timeout, threshold);
  9513. }
  9514. #endif
  9515. class EventDispatcher {
  9516. public:
  9517. EventDispatcher() {}
  9518. bool wait_event(DataSink *sink) {
  9519. unique_lock<mutex> lk(m_);
  9520. int id = id_;
  9521. // Wait with timeout to prevent hanging if client disconnects
  9522. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9523. [&] { return cid_ == id; })) {
  9524. return false; // Timeout occurred
  9525. }
  9526. sink->write(message_.data(), message_.size());
  9527. return true;
  9528. }
  9529. void send_event(const string &message) {
  9530. lock_guard<mutex> lk(m_);
  9531. cid_ = id_++;
  9532. message_ = message;
  9533. cv_.notify_all();
  9534. }
  9535. private:
  9536. mutex m_;
  9537. condition_variable cv_;
  9538. atomic_int id_{0};
  9539. atomic_int cid_{-1};
  9540. string message_;
  9541. };
  9542. TEST(ClientInThreadTest, Issue2068) {
  9543. EventDispatcher ed;
  9544. Server svr;
  9545. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9546. res.set_chunked_content_provider("text/event-stream",
  9547. [&](size_t /*offset*/, DataSink &sink) {
  9548. return ed.wait_event(&sink);
  9549. });
  9550. });
  9551. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9552. svr.wait_until_ready();
  9553. thread event_thread([&] {
  9554. int id = 0;
  9555. while (svr.is_running()) {
  9556. this_thread::sleep_for(chrono::milliseconds(500));
  9557. std::stringstream ss;
  9558. ss << "data: " << id << "\n\n";
  9559. ed.send_event(ss.str());
  9560. id++;
  9561. }
  9562. });
  9563. auto se = detail::scope_exit([&] {
  9564. svr.stop();
  9565. listen_thread.join();
  9566. event_thread.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. {
  9570. auto client = detail::make_unique<Client>(HOST, PORT);
  9571. client->set_read_timeout(std::chrono::minutes(10));
  9572. std::atomic<bool> stop{false};
  9573. std::thread t([&] {
  9574. client->Get("/event1",
  9575. [&](const char *, size_t) -> bool { return !stop; });
  9576. });
  9577. std::this_thread::sleep_for(std::chrono::seconds(2));
  9578. stop = true;
  9579. client->stop();
  9580. t.join();
  9581. // Reset client after thread has finished
  9582. client.reset();
  9583. }
  9584. }
  9585. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9586. Server svr;
  9587. svr.Get("/", [](const Request &req, Response &res) {
  9588. EXPECT_EQ(2U, req.trailers.size());
  9589. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9590. // Denied
  9591. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9592. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9593. // Accepted
  9594. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9595. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9596. EXPECT_TRUE(req.has_trailer("X-World"));
  9597. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9598. res.set_content("ok", "text/plain");
  9599. });
  9600. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. svr.stop();
  9603. t.join();
  9604. ASSERT_FALSE(svr.is_running());
  9605. });
  9606. svr.wait_until_ready();
  9607. const std::string req = "GET / HTTP/1.1\r\n"
  9608. "Transfer-Encoding: chunked\r\n"
  9609. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9610. "\r\n"
  9611. "0\r\n"
  9612. "Content-Length: 10\r\n"
  9613. "Host: internal.local\r\n"
  9614. "Content-Type: malicious/content\r\n"
  9615. "Cookie: any\r\n"
  9616. "Set-Cookie: any\r\n"
  9617. "X-Forwarded-For: attacker.com\r\n"
  9618. "X-Real-Ip: 1.1.1.1\r\n"
  9619. "X-Hello: hello\r\n"
  9620. "X-World: world\r\n"
  9621. "\r\n";
  9622. std::string res;
  9623. ASSERT_TRUE(send_request(1, req, &res));
  9624. }
  9625. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9626. Server svr;
  9627. std::string observed_remote_addr;
  9628. std::string observed_xff;
  9629. svr.Get("/ip", [&](const Request &req, Response &res) {
  9630. observed_remote_addr = req.remote_addr;
  9631. observed_xff = req.get_header_value("X-Forwarded-For");
  9632. res.set_content("ok", "text/plain");
  9633. });
  9634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9635. auto se = detail::scope_exit([&] {
  9636. svr.stop();
  9637. t.join();
  9638. ASSERT_FALSE(svr.is_running());
  9639. });
  9640. svr.wait_until_ready();
  9641. Client cli(HOST, PORT);
  9642. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9643. ASSERT_TRUE(res);
  9644. EXPECT_EQ(StatusCode::OK_200, res->status);
  9645. EXPECT_EQ(observed_xff, "203.0.113.66");
  9646. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9647. observed_remote_addr == "127.0.0.1");
  9648. }
  9649. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9650. Server svr;
  9651. svr.set_trusted_proxies({"203.0.113.66"});
  9652. std::string observed_remote_addr;
  9653. std::string observed_xff;
  9654. svr.Get("/ip", [&](const Request &req, Response &res) {
  9655. observed_remote_addr = req.remote_addr;
  9656. observed_xff = req.get_header_value("X-Forwarded-For");
  9657. res.set_content("ok", "text/plain");
  9658. });
  9659. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. Client cli(HOST, PORT);
  9667. auto res = cli.Get("/ip");
  9668. ASSERT_TRUE(res);
  9669. EXPECT_EQ(StatusCode::OK_200, res->status);
  9670. EXPECT_EQ(observed_xff, "");
  9671. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9672. observed_remote_addr == "127.0.0.1");
  9673. }
  9674. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9675. Server svr;
  9676. svr.set_trusted_proxies({"203.0.113.66"});
  9677. std::string observed_remote_addr;
  9678. std::string observed_xff;
  9679. svr.Get("/ip", [&](const Request &req, Response &res) {
  9680. observed_remote_addr = req.remote_addr;
  9681. observed_xff = req.get_header_value("X-Forwarded-For");
  9682. res.set_content("ok", "text/plain");
  9683. });
  9684. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. t.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. });
  9690. svr.wait_until_ready();
  9691. Client cli(HOST, PORT);
  9692. auto res =
  9693. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9694. ASSERT_TRUE(res);
  9695. EXPECT_EQ(StatusCode::OK_200, res->status);
  9696. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9697. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9698. }
  9699. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9700. Server svr;
  9701. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9702. std::string observed_remote_addr;
  9703. std::string observed_xff;
  9704. svr.Get("/ip", [&](const Request &req, Response &res) {
  9705. observed_remote_addr = req.remote_addr;
  9706. observed_xff = req.get_header_value("X-Forwarded-For");
  9707. res.set_content("ok", "text/plain");
  9708. });
  9709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9710. auto se = detail::scope_exit([&] {
  9711. svr.stop();
  9712. t.join();
  9713. ASSERT_FALSE(svr.is_running());
  9714. });
  9715. svr.wait_until_ready();
  9716. Client cli(HOST, PORT);
  9717. auto res = cli.Get(
  9718. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9719. ASSERT_TRUE(res);
  9720. EXPECT_EQ(StatusCode::OK_200, res->status);
  9721. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9722. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9723. }
  9724. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9725. Server svr;
  9726. svr.set_trusted_proxies({"192.0.2.45"});
  9727. std::string observed_remote_addr;
  9728. std::string observed_xff;
  9729. svr.Get("/ip", [&](const Request &req, Response &res) {
  9730. observed_remote_addr = req.remote_addr;
  9731. observed_xff = req.get_header_value("X-Forwarded-For");
  9732. res.set_content("ok", "text/plain");
  9733. });
  9734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. t.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. });
  9740. svr.wait_until_ready();
  9741. Client cli(HOST, PORT);
  9742. auto res =
  9743. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9744. ASSERT_TRUE(res);
  9745. EXPECT_EQ(StatusCode::OK_200, res->status);
  9746. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9747. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9748. }
  9749. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9750. Server svr;
  9751. svr.set_trusted_proxies({"192.0.2.45"});
  9752. std::string observed_remote_addr;
  9753. std::string observed_xff;
  9754. svr.Get("/ip", [&](const Request &req, Response &res) {
  9755. observed_remote_addr = req.remote_addr;
  9756. observed_xff = req.get_header_value("X-Forwarded-For");
  9757. res.set_content("ok", "text/plain");
  9758. });
  9759. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. t.join();
  9763. ASSERT_FALSE(svr.is_running());
  9764. });
  9765. svr.wait_until_ready();
  9766. Client cli(HOST, PORT);
  9767. auto res = cli.Get(
  9768. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9769. ASSERT_TRUE(res);
  9770. EXPECT_EQ(StatusCode::OK_200, res->status);
  9771. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9772. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9773. }
  9774. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9775. Server svr;
  9776. svr.set_trusted_proxies({"192.0.2.45"});
  9777. std::string observed_remote_addr;
  9778. std::string observed_xff;
  9779. svr.Get("/ip", [&](const Request &req, Response &res) {
  9780. observed_remote_addr = req.remote_addr;
  9781. observed_xff = req.get_header_value("X-Forwarded-For");
  9782. res.set_content("ok", "text/plain");
  9783. });
  9784. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9785. auto se = detail::scope_exit([&] {
  9786. svr.stop();
  9787. t.join();
  9788. ASSERT_FALSE(svr.is_running());
  9789. });
  9790. svr.wait_until_ready();
  9791. std::string raw_req =
  9792. "GET /ip HTTP/1.1\r\n"
  9793. "Host: localhost\r\n"
  9794. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9795. "Connection: close\r\n"
  9796. "\r\n";
  9797. std::string out;
  9798. ASSERT_TRUE(send_request(5, raw_req, &out));
  9799. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9800. // Header parser trims surrounding whitespace of the header value
  9801. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9802. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9803. }
  9804. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9805. Server svr;
  9806. svr.Post("/post", [&](const Request &req, Response &res) {
  9807. res.set_content(req.body, "text/plain");
  9808. });
  9809. svr.Put("/put", [&](const Request &req, Response &res) {
  9810. res.set_content(req.body, "text/plain");
  9811. });
  9812. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9813. res.set_content(req.body, "text/plain");
  9814. });
  9815. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9816. res.set_content(req.body, "text/plain");
  9817. });
  9818. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9819. auto se = detail::scope_exit([&] {
  9820. svr.stop();
  9821. t.join();
  9822. ASSERT_FALSE(svr.is_running());
  9823. });
  9824. svr.wait_until_ready();
  9825. std::string resp;
  9826. // POST without Content-Length
  9827. ASSERT_TRUE(send_request(5,
  9828. "POST /post HTTP/1.1\r\n"
  9829. "Host: localhost\r\n"
  9830. "Connection: close\r\n"
  9831. "\r\n",
  9832. &resp));
  9833. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9834. // PUT without Content-Length
  9835. resp.clear();
  9836. ASSERT_TRUE(send_request(5,
  9837. "PUT /put HTTP/1.1\r\n"
  9838. "Host: localhost\r\n"
  9839. "Connection: close\r\n"
  9840. "\r\n",
  9841. &resp));
  9842. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9843. // PATCH without Content-Length
  9844. resp.clear();
  9845. ASSERT_TRUE(send_request(5,
  9846. "PATCH /patch HTTP/1.1\r\n"
  9847. "Host: localhost\r\n"
  9848. "Connection: close\r\n"
  9849. "\r\n",
  9850. &resp));
  9851. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9852. // DELETE without Content-Length
  9853. resp.clear();
  9854. ASSERT_TRUE(send_request(5,
  9855. "DELETE /delete HTTP/1.1\r\n"
  9856. "Host: localhost\r\n"
  9857. "Connection: close\r\n"
  9858. "\r\n",
  9859. &resp));
  9860. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9861. }
  9862. //==============================================================================
  9863. // open_stream() Tests
  9864. //==============================================================================
  9865. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9866. std::string result;
  9867. char buf[8192];
  9868. ssize_t n;
  9869. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9870. result.append(buf, static_cast<size_t>(n));
  9871. }
  9872. return result;
  9873. }
  9874. // Mock stream for unit tests
  9875. class MockStream : public Stream {
  9876. public:
  9877. std::string data;
  9878. size_t pos = 0;
  9879. ssize_t error_after = -1; // -1 = no error
  9880. explicit MockStream(const std::string &d, ssize_t err = -1)
  9881. : data(d), error_after(err) {}
  9882. bool is_readable() const override { return true; }
  9883. bool wait_readable() const override { return true; }
  9884. bool wait_writable() const override { return true; }
  9885. ssize_t read(char *ptr, size_t size) override {
  9886. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9887. if (pos >= data.size()) return 0;
  9888. size_t limit =
  9889. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9890. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9891. std::memcpy(ptr, data.data() + pos, to_read);
  9892. pos += to_read;
  9893. return static_cast<ssize_t>(to_read);
  9894. }
  9895. ssize_t write(const char *, size_t) override { return -1; }
  9896. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9897. ip = "127.0.0.1";
  9898. port = 0;
  9899. }
  9900. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9901. ip = "127.0.0.1";
  9902. port = 0;
  9903. }
  9904. socket_t socket() const override { return INVALID_SOCKET; }
  9905. time_t duration() const override { return 0; }
  9906. };
  9907. TEST(StreamHandleTest, Basic) {
  9908. ClientImpl::StreamHandle handle;
  9909. EXPECT_FALSE(handle.is_valid());
  9910. handle.response = detail::make_unique<Response>();
  9911. handle.error = Error::Connection;
  9912. EXPECT_FALSE(handle.is_valid());
  9913. handle.error = Error::Success;
  9914. EXPECT_TRUE(handle.is_valid());
  9915. }
  9916. TEST(BodyReaderTest, Basic) {
  9917. MockStream stream("Hello, World!");
  9918. detail::BodyReader reader;
  9919. reader.stream = &stream;
  9920. reader.content_length = 13;
  9921. char buf[32];
  9922. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9923. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9924. EXPECT_TRUE(reader.eof);
  9925. }
  9926. TEST(BodyReaderTest, NoStream) {
  9927. detail::BodyReader reader;
  9928. char buf[32];
  9929. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9930. EXPECT_EQ(Error::Connection, reader.last_error);
  9931. }
  9932. TEST(BodyReaderTest, Error) {
  9933. MockStream stream("Hello, World!", 5);
  9934. detail::BodyReader reader;
  9935. reader.stream = &stream;
  9936. reader.content_length = 13;
  9937. char buf[32];
  9938. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9939. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9940. EXPECT_EQ(Error::Read, reader.last_error);
  9941. }
  9942. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9943. // Mock-based StreamHandle tests relying on private internals are removed.
  9944. class OpenStreamTest : public ::testing::Test {
  9945. protected:
  9946. void SetUp() override {
  9947. svr_.Get("/hello", [](const Request &, Response &res) {
  9948. res.set_content("Hello World!", "text/plain");
  9949. });
  9950. svr_.Get("/large", [](const Request &, Response &res) {
  9951. res.set_content(std::string(10000, 'X'), "text/plain");
  9952. });
  9953. svr_.Get("/chunked", [](const Request &, Response &res) {
  9954. res.set_chunked_content_provider("text/plain",
  9955. [](size_t offset, DataSink &sink) {
  9956. if (offset < 15) {
  9957. sink.write("chunk", 5);
  9958. return true;
  9959. }
  9960. sink.done();
  9961. return true;
  9962. });
  9963. });
  9964. svr_.Get("/compressible", [](const Request &, Response &res) {
  9965. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9966. DataSink &sink) {
  9967. if (offset < 100 * 1024) {
  9968. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9969. sink.write(chunk.data(), chunk.size());
  9970. return true;
  9971. }
  9972. sink.done();
  9973. return true;
  9974. });
  9975. });
  9976. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9977. [](const Request & /*req*/, Response &res) {
  9978. auto i = new int(0);
  9979. res.set_header("Trailer", "Content-Length, X-Allowed");
  9980. res.set_chunked_content_provider(
  9981. "text/plain",
  9982. [i](size_t /*offset*/, DataSink &sink) {
  9983. switch (*i) {
  9984. case 0: sink.os << "123"; break;
  9985. case 1: sink.os << "456"; break;
  9986. case 2: sink.os << "789"; break;
  9987. case 3: {
  9988. sink.done_with_trailer(
  9989. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9990. } break;
  9991. }
  9992. (*i)++;
  9993. return true;
  9994. },
  9995. [i](bool success) {
  9996. EXPECT_TRUE(success);
  9997. delete i;
  9998. });
  9999. });
  10000. // Echo headers endpoint for header-related tests
  10001. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10002. std::string body;
  10003. for (const auto &h : req.headers) {
  10004. body.append(h.first);
  10005. body.push_back(':');
  10006. body.append(h.second);
  10007. body.push_back('\n');
  10008. }
  10009. res.set_content(body, "text/plain");
  10010. });
  10011. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10012. std::string body;
  10013. for (const auto &h : req.headers) {
  10014. body.append(h.first);
  10015. body.push_back(':');
  10016. body.append(h.second);
  10017. body.push_back('\n');
  10018. }
  10019. res.set_content(body, "text/plain");
  10020. });
  10021. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10022. svr_.wait_until_ready();
  10023. }
  10024. void TearDown() override {
  10025. svr_.stop();
  10026. if (thread_.joinable()) thread_.join();
  10027. }
  10028. Server svr_;
  10029. std::thread thread_;
  10030. };
  10031. TEST_F(OpenStreamTest, Basic) {
  10032. Client cli("127.0.0.1", 8787);
  10033. auto handle = cli.open_stream("GET", "/hello");
  10034. EXPECT_TRUE(handle.is_valid());
  10035. EXPECT_EQ("Hello World!", read_all(handle));
  10036. }
  10037. TEST_F(OpenStreamTest, SmallBuffer) {
  10038. Client cli("127.0.0.1", 8787);
  10039. auto handle = cli.open_stream("GET", "/hello");
  10040. std::string result;
  10041. char buf[4];
  10042. ssize_t n;
  10043. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10044. result.append(buf, static_cast<size_t>(n));
  10045. EXPECT_EQ("Hello World!", result);
  10046. }
  10047. TEST_F(OpenStreamTest, DefaultHeaders) {
  10048. Client cli("127.0.0.1", 8787);
  10049. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10050. {
  10051. auto handle = cli.open_stream("GET", "/echo-headers");
  10052. ASSERT_TRUE(handle.is_valid());
  10053. auto body = read_all(handle);
  10054. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10055. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10056. std::string::npos);
  10057. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10058. }
  10059. // open_stream POST with body and no explicit content_type should NOT add
  10060. // text/plain Content-Type (behavior differs from non-streaming path), but
  10061. // should include Content-Length
  10062. {
  10063. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10064. ASSERT_TRUE(handle.is_valid());
  10065. auto body = read_all(handle);
  10066. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10067. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10068. }
  10069. // open_stream POST with explicit Content-Type should preserve it
  10070. {
  10071. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10072. {{"Content-Type", "application/custom"}},
  10073. "{}", "application/custom");
  10074. ASSERT_TRUE(handle.is_valid());
  10075. auto body = read_all(handle);
  10076. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10077. }
  10078. // User-specified User-Agent must not be overwritten for stream API
  10079. {
  10080. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10081. {{"User-Agent", "MyAgent/1.2"}});
  10082. ASSERT_TRUE(handle.is_valid());
  10083. auto body = read_all(handle);
  10084. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10085. }
  10086. }
  10087. TEST_F(OpenStreamTest, Large) {
  10088. Client cli("127.0.0.1", 8787);
  10089. auto handle = cli.open_stream("GET", "/large");
  10090. EXPECT_EQ(10000u, read_all(handle).size());
  10091. }
  10092. TEST_F(OpenStreamTest, ConnectionError) {
  10093. Client cli("127.0.0.1", 9999);
  10094. auto handle = cli.open_stream("GET", "/hello");
  10095. EXPECT_FALSE(handle.is_valid());
  10096. }
  10097. TEST_F(OpenStreamTest, Chunked) {
  10098. Client cli("127.0.0.1", 8787);
  10099. auto handle = cli.open_stream("GET", "/chunked");
  10100. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10101. "Transfer-Encoding") == "chunked");
  10102. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10103. }
  10104. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10105. Client cli("127.0.0.1", 8787);
  10106. auto handle =
  10107. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10108. ASSERT_TRUE(handle.is_valid());
  10109. // Consume body to allow trailers to be received/parsed
  10110. auto body = read_all(handle);
  10111. // Explicitly parse trailers (ensure trailers are available for assertion)
  10112. handle.parse_trailers_if_needed();
  10113. EXPECT_EQ(std::string("123456789"), body);
  10114. // The response should include a Trailer header declaring both names
  10115. ASSERT_TRUE(handle.response);
  10116. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10117. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10118. handle.response->get_header_value("Trailer"));
  10119. // Prohibited trailer must not be present
  10120. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10121. // Allowed trailer should be present
  10122. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10123. EXPECT_EQ(std::string("yes"),
  10124. handle.response->get_trailer_value("X-Allowed"));
  10125. // Verify trailers are NOT present as regular headers
  10126. EXPECT_EQ(std::string(""),
  10127. handle.response->get_header_value("Content-Length"));
  10128. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10129. }
  10130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10131. TEST_F(OpenStreamTest, Gzip) {
  10132. Client cli("127.0.0.1", 8787);
  10133. auto handle = cli.open_stream("GET", "/compressible", {},
  10134. {{"Accept-Encoding", "gzip"}});
  10135. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10136. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10137. }
  10138. #endif
  10139. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10140. TEST_F(OpenStreamTest, Brotli) {
  10141. Client cli("127.0.0.1", 8787);
  10142. auto handle =
  10143. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10144. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10145. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10146. }
  10147. #endif
  10148. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10149. TEST_F(OpenStreamTest, Zstd) {
  10150. Client cli("127.0.0.1", 8787);
  10151. auto handle = cli.open_stream("GET", "/compressible", {},
  10152. {{"Accept-Encoding", "zstd"}});
  10153. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10154. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10155. }
  10156. #endif
  10157. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10158. class SSLOpenStreamTest : public ::testing::Test {
  10159. protected:
  10160. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10161. void SetUp() override {
  10162. svr_.Get("/hello", [](const Request &, Response &res) {
  10163. res.set_content("Hello SSL World!", "text/plain");
  10164. });
  10165. svr_.Get("/chunked", [](const Request &, Response &res) {
  10166. res.set_chunked_content_provider("text/plain",
  10167. [](size_t offset, DataSink &sink) {
  10168. if (offset < 15) {
  10169. sink.write("chunk", 5);
  10170. return true;
  10171. }
  10172. sink.done();
  10173. return true;
  10174. });
  10175. });
  10176. svr_.Post("/echo", [](const Request &req, Response &res) {
  10177. res.set_content(req.body, req.get_header_value("Content-Type"));
  10178. });
  10179. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10180. std::string body = req.body;
  10181. res.set_chunked_content_provider(
  10182. "text/plain", [body](size_t offset, DataSink &sink) {
  10183. if (offset < body.size()) {
  10184. sink.write(body.data() + offset, body.size() - offset);
  10185. }
  10186. sink.done();
  10187. return true;
  10188. });
  10189. });
  10190. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10191. svr_.wait_until_ready();
  10192. }
  10193. void TearDown() override {
  10194. svr_.stop();
  10195. if (thread_.joinable()) thread_.join();
  10196. }
  10197. SSLServer svr_;
  10198. std::thread thread_;
  10199. };
  10200. TEST_F(SSLOpenStreamTest, Basic) {
  10201. SSLClient cli("127.0.0.1", 8788);
  10202. cli.enable_server_certificate_verification(false);
  10203. auto handle = cli.open_stream("GET", "/hello");
  10204. ASSERT_TRUE(handle.is_valid());
  10205. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10206. }
  10207. TEST_F(SSLOpenStreamTest, Chunked) {
  10208. SSLClient cli("127.0.0.1", 8788);
  10209. cli.enable_server_certificate_verification(false);
  10210. auto handle = cli.open_stream("GET", "/chunked");
  10211. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10212. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10213. "Transfer-Encoding") == "chunked");
  10214. auto body = read_all(handle);
  10215. EXPECT_EQ("chunkchunkchunk", body);
  10216. }
  10217. TEST_F(SSLOpenStreamTest, Post) {
  10218. SSLClient cli("127.0.0.1", 8788);
  10219. cli.enable_server_certificate_verification(false);
  10220. auto handle =
  10221. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10222. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10223. EXPECT_EQ(200, handle.response->status);
  10224. auto body = read_all(handle);
  10225. EXPECT_EQ("Hello SSL POST", body);
  10226. }
  10227. TEST_F(SSLOpenStreamTest, PostChunked) {
  10228. SSLClient cli("127.0.0.1", 8788);
  10229. cli.enable_server_certificate_verification(false);
  10230. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10231. "Chunked SSL Data", "text/plain");
  10232. ASSERT_TRUE(handle.is_valid());
  10233. EXPECT_EQ(200, handle.response->status);
  10234. auto body = read_all(handle);
  10235. EXPECT_EQ("Chunked SSL Data", body);
  10236. }
  10237. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10238. //==============================================================================
  10239. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10240. // results for various scenarios.
  10241. //==============================================================================
  10242. TEST(ParityTest, GetVsOpenStream) {
  10243. Server svr;
  10244. const std::string path = "/parity";
  10245. const std::string content = "Parity test content: hello world";
  10246. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10247. res.set_content(content, "text/plain");
  10248. });
  10249. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10250. auto se = detail::scope_exit([&] {
  10251. svr.stop();
  10252. t.join();
  10253. ASSERT_FALSE(svr.is_running());
  10254. });
  10255. svr.wait_until_ready();
  10256. Client cli(HOST, PORT);
  10257. // Non-stream path
  10258. auto r1 = cli.Get(path);
  10259. ASSERT_TRUE(r1);
  10260. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10261. // Stream path
  10262. auto h = cli.open_stream("GET", path);
  10263. ASSERT_TRUE(h.is_valid());
  10264. EXPECT_EQ(r1->body, read_all(h));
  10265. }
  10266. // Helper to compress data with provided compressor type T
  10267. template <typename Compressor>
  10268. static std::string compress_payload_for_parity(const std::string &in) {
  10269. std::string out;
  10270. Compressor compressor;
  10271. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10272. [&](const char *data, size_t n) {
  10273. out.append(data, n);
  10274. return true;
  10275. });
  10276. EXPECT_TRUE(ok);
  10277. return out;
  10278. }
  10279. // Helper function for compression parity tests
  10280. template <typename Compressor>
  10281. static void test_compression_parity(const std::string &original,
  10282. const std::string &path,
  10283. const std::string &encoding) {
  10284. const std::string compressed =
  10285. compress_payload_for_parity<Compressor>(original);
  10286. Server svr;
  10287. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10288. res.set_content(compressed, "application/octet-stream");
  10289. res.set_header("Content-Encoding", encoding);
  10290. });
  10291. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10292. auto se = detail::scope_exit([&] {
  10293. svr.stop();
  10294. t.join();
  10295. ASSERT_FALSE(svr.is_running());
  10296. });
  10297. svr.wait_until_ready();
  10298. Client cli(HOST, PORT);
  10299. // Non-streaming
  10300. {
  10301. auto res = cli.Get(path);
  10302. ASSERT_TRUE(res);
  10303. EXPECT_EQ(StatusCode::OK_200, res->status);
  10304. EXPECT_EQ(original, res->body);
  10305. }
  10306. // Streaming
  10307. {
  10308. auto h = cli.open_stream("GET", path);
  10309. ASSERT_TRUE(h.is_valid());
  10310. EXPECT_EQ(original, read_all(h));
  10311. }
  10312. }
  10313. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10314. TEST(ParityTest, Gzip) {
  10315. test_compression_parity<detail::gzip_compressor>(
  10316. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10317. }
  10318. #endif
  10319. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10320. TEST(ParityTest, Brotli) {
  10321. test_compression_parity<detail::brotli_compressor>(
  10322. "Hello, brotli parity test payload", "/parity-br", "br");
  10323. }
  10324. #endif
  10325. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10326. TEST(ParityTest, Zstd) {
  10327. test_compression_parity<detail::zstd_compressor>(
  10328. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10329. }
  10330. #endif
  10331. //==============================================================================
  10332. // New Stream API Tests
  10333. //==============================================================================
  10334. inline std::string read_body(httplib::stream::Result &result) {
  10335. std::string body;
  10336. while (result.next()) {
  10337. body.append(result.data(), result.size());
  10338. }
  10339. return body;
  10340. }
  10341. TEST(ClientConnectionTest, Basic) {
  10342. httplib::ClientConnection conn;
  10343. EXPECT_FALSE(conn.is_open());
  10344. conn.sock = 1;
  10345. EXPECT_TRUE(conn.is_open());
  10346. httplib::ClientConnection conn2(std::move(conn));
  10347. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10348. conn2.sock = INVALID_SOCKET;
  10349. }
  10350. // Unified test server for all stream::* tests
  10351. class StreamApiTest : public ::testing::Test {
  10352. protected:
  10353. void SetUp() override {
  10354. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10355. res.set_content("Hello World!", "text/plain");
  10356. });
  10357. svr_.Get("/echo-params",
  10358. [](const httplib::Request &req, httplib::Response &res) {
  10359. std::string r;
  10360. for (const auto &p : req.params) {
  10361. if (!r.empty()) r += "&";
  10362. r += p.first + "=" + p.second;
  10363. }
  10364. res.set_content(r, "text/plain");
  10365. });
  10366. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10367. res.set_content(req.body, req.get_header_value("Content-Type"));
  10368. });
  10369. svr_.Post("/echo-headers",
  10370. [](const httplib::Request &req, httplib::Response &res) {
  10371. std::string r;
  10372. for (const auto &h : req.headers)
  10373. r += h.first + ": " + h.second + "\n";
  10374. res.set_content(r, "text/plain");
  10375. });
  10376. svr_.Post("/echo-params",
  10377. [](const httplib::Request &req, httplib::Response &res) {
  10378. std::string r = "params:";
  10379. for (const auto &p : req.params)
  10380. r += p.first + "=" + p.second + ";";
  10381. res.set_content(r + " body:" + req.body, "text/plain");
  10382. });
  10383. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10384. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10385. });
  10386. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10387. res.set_content("PUT:" + req.body, "text/plain");
  10388. });
  10389. svr_.Patch("/echo",
  10390. [](const httplib::Request &req, httplib::Response &res) {
  10391. res.set_content("PATCH:" + req.body, "text/plain");
  10392. });
  10393. svr_.Delete(
  10394. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10395. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10396. "text/plain");
  10397. });
  10398. svr_.Get("/head-test",
  10399. [](const httplib::Request &, httplib::Response &res) {
  10400. res.set_content("body for HEAD", "text/plain");
  10401. });
  10402. svr_.Options("/options",
  10403. [](const httplib::Request &, httplib::Response &res) {
  10404. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10405. });
  10406. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10407. svr_.wait_until_ready();
  10408. }
  10409. void TearDown() override {
  10410. svr_.stop();
  10411. if (thread_.joinable()) thread_.join();
  10412. }
  10413. httplib::Server svr_;
  10414. std::thread thread_;
  10415. };
  10416. // stream::Get tests
  10417. TEST_F(StreamApiTest, GetBasic) {
  10418. httplib::Client cli(HOST, PORT);
  10419. auto result = httplib::stream::Get(cli, "/hello");
  10420. ASSERT_TRUE(result.is_valid());
  10421. EXPECT_EQ(200, result.status());
  10422. EXPECT_EQ("Hello World!", read_body(result));
  10423. }
  10424. TEST_F(StreamApiTest, GetWithParams) {
  10425. httplib::Client cli(HOST, PORT);
  10426. httplib::Params params{{"foo", "bar"}};
  10427. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10428. ASSERT_TRUE(result.is_valid());
  10429. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10430. }
  10431. TEST_F(StreamApiTest, GetConnectionError) {
  10432. httplib::Client cli(HOST, 9999);
  10433. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10434. }
  10435. TEST_F(StreamApiTest, Get404) {
  10436. httplib::Client cli(HOST, PORT);
  10437. auto result = httplib::stream::Get(cli, "/nonexistent");
  10438. EXPECT_TRUE(result.is_valid());
  10439. EXPECT_EQ(404, result.status());
  10440. }
  10441. // stream::Post tests
  10442. TEST_F(StreamApiTest, PostBasic) {
  10443. httplib::Client cli(HOST, PORT);
  10444. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10445. "application/json");
  10446. ASSERT_TRUE(result.is_valid());
  10447. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10448. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10449. }
  10450. TEST_F(StreamApiTest, PostWithHeaders) {
  10451. httplib::Client cli(HOST, PORT);
  10452. httplib::Headers headers{{"X-Custom", "value"}};
  10453. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10454. "text/plain");
  10455. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10456. }
  10457. TEST_F(StreamApiTest, PostWithParams) {
  10458. httplib::Client cli(HOST, PORT);
  10459. httplib::Params params{{"k", "v"}};
  10460. auto result =
  10461. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10462. auto body = read_body(result);
  10463. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10464. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10465. }
  10466. TEST_F(StreamApiTest, PostLarge) {
  10467. httplib::Client cli(HOST, PORT);
  10468. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10469. size_t total = 0;
  10470. while (result.next()) {
  10471. total += result.size();
  10472. }
  10473. EXPECT_EQ(100u * 1024u, total);
  10474. }
  10475. // stream::Put/Patch tests
  10476. TEST_F(StreamApiTest, PutAndPatch) {
  10477. httplib::Client cli(HOST, PORT);
  10478. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10479. EXPECT_EQ("PUT:test", read_body(put));
  10480. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10481. EXPECT_EQ("PATCH:test", read_body(patch));
  10482. }
  10483. // stream::Delete tests
  10484. TEST_F(StreamApiTest, Delete) {
  10485. httplib::Client cli(HOST, PORT);
  10486. auto del1 = httplib::stream::Delete(cli, "/resource");
  10487. EXPECT_EQ("Deleted", read_body(del1));
  10488. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10489. EXPECT_EQ("Deleted:data", read_body(del2));
  10490. }
  10491. // stream::Head/Options tests
  10492. TEST_F(StreamApiTest, HeadAndOptions) {
  10493. httplib::Client cli(HOST, PORT);
  10494. auto head = httplib::stream::Head(cli, "/head-test");
  10495. EXPECT_TRUE(head.is_valid());
  10496. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10497. auto opts = httplib::stream::Options(cli, "/options");
  10498. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10499. }
  10500. // SSL stream::* tests
  10501. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10502. class SSLStreamApiTest : public ::testing::Test {
  10503. protected:
  10504. void SetUp() override {
  10505. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10506. res.set_content("Hello SSL!", "text/plain");
  10507. });
  10508. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10509. res.set_content(req.body, "text/plain");
  10510. });
  10511. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10512. svr_.wait_until_ready();
  10513. }
  10514. void TearDown() override {
  10515. svr_.stop();
  10516. if (thread_.joinable()) thread_.join();
  10517. }
  10518. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10519. std::thread thread_;
  10520. };
  10521. TEST_F(SSLStreamApiTest, GetAndPost) {
  10522. httplib::SSLClient cli("127.0.0.1", 8803);
  10523. cli.enable_server_certificate_verification(false);
  10524. auto get = httplib::stream::Get(cli, "/hello");
  10525. EXPECT_EQ("Hello SSL!", read_body(get));
  10526. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10527. EXPECT_EQ("test", read_body(post));
  10528. }
  10529. #endif
  10530. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10531. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10532. // BodyReader
  10533. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10534. // Test that read timeout during streaming is detected
  10535. // Use a large content-length response where server delays mid-stream
  10536. Server svr;
  10537. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10538. // Send a large response with delay in the middle
  10539. res.set_content_provider(
  10540. 1000, // content_length
  10541. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10542. if (offset < 100) {
  10543. // Send first 100 bytes immediately
  10544. std::string data(100, 'A');
  10545. sink.write(data.c_str(), data.size());
  10546. return true;
  10547. }
  10548. // Then delay longer than client timeout
  10549. std::this_thread::sleep_for(std::chrono::seconds(3));
  10550. std::string data(900, 'B');
  10551. sink.write(data.c_str(), data.size());
  10552. return true;
  10553. });
  10554. });
  10555. auto port = 8091;
  10556. std::thread t([&]() { svr.listen("localhost", port); });
  10557. svr.wait_until_ready();
  10558. Client cli("localhost", port);
  10559. cli.set_read_timeout(1, 0); // 1 second timeout
  10560. auto handle = cli.open_stream("GET", "/slow-stream");
  10561. ASSERT_TRUE(handle.is_valid());
  10562. char buf[256];
  10563. ssize_t total = 0;
  10564. ssize_t n;
  10565. bool got_error = false;
  10566. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10567. total += n;
  10568. }
  10569. if (n < 0) {
  10570. got_error = true;
  10571. // Should be timeout or read error
  10572. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10573. handle.get_read_error() == Error::Read)
  10574. << "Actual error: " << to_string(handle.get_read_error());
  10575. }
  10576. // Either we got an error, or we got less data than expected
  10577. EXPECT_TRUE(got_error || total < 1000)
  10578. << "Expected timeout but got all " << total << " bytes";
  10579. svr.stop();
  10580. t.join();
  10581. }
  10582. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10583. // Test connection closed detection via BodyReader
  10584. Server svr;
  10585. std::atomic<bool> close_now{false};
  10586. svr.Get("/will-close", [&](const Request &, Response &res) {
  10587. res.set_content_provider(
  10588. 10000, // Large content_length that we won't fully send
  10589. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10590. if (offset < 100) {
  10591. std::string data(100, 'X');
  10592. sink.write(data.c_str(), data.size());
  10593. return true;
  10594. }
  10595. // Wait for signal then abort
  10596. while (!close_now) {
  10597. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10598. }
  10599. return false; // Abort - server will close connection
  10600. });
  10601. });
  10602. auto port = 8092;
  10603. std::thread t([&]() { svr.listen("localhost", port); });
  10604. svr.wait_until_ready();
  10605. Client cli("localhost", port);
  10606. auto handle = cli.open_stream("GET", "/will-close");
  10607. ASSERT_TRUE(handle.is_valid());
  10608. char buf[256];
  10609. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10610. EXPECT_GT(n, 0) << "First read should succeed";
  10611. // Signal server to close
  10612. close_now = true;
  10613. // Keep reading until error or EOF
  10614. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10615. // Keep reading
  10616. }
  10617. // Should get an error since content_length wasn't satisfied
  10618. if (n < 0) {
  10619. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10620. handle.get_read_error() == Error::Read)
  10621. << "Actual error: " << to_string(handle.get_read_error());
  10622. }
  10623. svr.stop();
  10624. t.join();
  10625. }
  10626. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10627. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10628. // Test that read timeout during SSL streaming is detected
  10629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10630. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10631. res.set_content_provider(
  10632. 1000, "text/plain",
  10633. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10634. if (offset < 100) {
  10635. std::string data(100, 'A');
  10636. sink.write(data.c_str(), data.size());
  10637. return true;
  10638. }
  10639. std::this_thread::sleep_for(std::chrono::seconds(3));
  10640. std::string data(900, 'B');
  10641. sink.write(data.c_str(), data.size());
  10642. return true;
  10643. });
  10644. });
  10645. auto port = 8093;
  10646. std::thread t([&]() { svr.listen("localhost", port); });
  10647. svr.wait_until_ready();
  10648. SSLClient cli("localhost", port);
  10649. cli.enable_server_certificate_verification(false);
  10650. cli.set_read_timeout(1, 0); // 1 second timeout
  10651. auto handle = cli.open_stream("GET", "/slow-stream");
  10652. ASSERT_TRUE(handle.is_valid());
  10653. char buf[256];
  10654. ssize_t total = 0;
  10655. ssize_t n;
  10656. bool got_error = false;
  10657. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10658. total += n;
  10659. }
  10660. if (n < 0) {
  10661. got_error = true;
  10662. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10663. handle.get_read_error() == Error::Read)
  10664. << "Actual error: " << to_string(handle.get_read_error());
  10665. }
  10666. EXPECT_TRUE(got_error || total < 1000)
  10667. << "Expected timeout but got all " << total << " bytes";
  10668. svr.stop();
  10669. t.join();
  10670. }
  10671. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10672. // Test SSL connection closed detection
  10673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10674. std::atomic<bool> close_now{false};
  10675. svr.Get("/will-close", [&](const Request &, Response &res) {
  10676. res.set_content_provider(
  10677. 10000, "text/plain",
  10678. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10679. if (offset < 100) {
  10680. std::string data(100, 'X');
  10681. sink.write(data.c_str(), data.size());
  10682. return true;
  10683. }
  10684. while (!close_now) {
  10685. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10686. }
  10687. return false;
  10688. });
  10689. });
  10690. auto port = 8094;
  10691. std::thread t([&]() { svr.listen("localhost", port); });
  10692. svr.wait_until_ready();
  10693. SSLClient cli("localhost", port);
  10694. cli.enable_server_certificate_verification(false);
  10695. auto handle = cli.open_stream("GET", "/will-close");
  10696. ASSERT_TRUE(handle.is_valid());
  10697. char buf[256];
  10698. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10699. EXPECT_GT(n, 0);
  10700. // Signal server to close
  10701. close_now = true;
  10702. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10703. // Keep reading
  10704. }
  10705. if (n < 0) {
  10706. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10707. handle.get_read_error() == Error::Read)
  10708. << "Actual error: " << to_string(handle.get_read_error());
  10709. }
  10710. svr.stop();
  10711. t.join();
  10712. }
  10713. #endif
  10714. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10715. using namespace httplib;
  10716. // Create a test file
  10717. const char *fname = "etag_testfile.txt";
  10718. const char *content = "etag-content";
  10719. {
  10720. std::ofstream ofs(fname);
  10721. ofs << content;
  10722. ASSERT_TRUE(ofs.good());
  10723. }
  10724. Server svr;
  10725. svr.set_mount_point("/static", ".");
  10726. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10727. svr.wait_until_ready();
  10728. Client cli(HOST, PORT);
  10729. // First request: should get 200 with ETag header
  10730. auto res1 = cli.Get("/static/etag_testfile.txt");
  10731. ASSERT_TRUE(res1);
  10732. ASSERT_EQ(200, res1->status);
  10733. ASSERT_TRUE(res1->has_header("ETag"));
  10734. std::string etag = res1->get_header_value("ETag");
  10735. EXPECT_FALSE(etag.empty());
  10736. // Verify ETag format: W/"hex-hex"
  10737. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10738. EXPECT_EQ('W', etag[0]);
  10739. EXPECT_EQ('/', etag[1]);
  10740. EXPECT_EQ('"', etag[2]);
  10741. EXPECT_EQ('"', etag.back());
  10742. // Exact match: expect 304 Not Modified
  10743. Headers h2 = {{"If-None-Match", etag}};
  10744. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10745. ASSERT_TRUE(res2);
  10746. EXPECT_EQ(304, res2->status);
  10747. // Wildcard match: expect 304 Not Modified
  10748. Headers h3 = {{"If-None-Match", "*"}};
  10749. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10750. ASSERT_TRUE(res3);
  10751. EXPECT_EQ(304, res3->status);
  10752. // Non-matching ETag: expect 200
  10753. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10754. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10755. ASSERT_TRUE(res4);
  10756. EXPECT_EQ(200, res4->status);
  10757. // Multiple ETags with one matching: expect 304
  10758. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10759. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10760. ASSERT_TRUE(res5);
  10761. EXPECT_EQ(304, res5->status);
  10762. svr.stop();
  10763. t.join();
  10764. std::remove(fname);
  10765. }
  10766. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10767. using namespace httplib;
  10768. Server svr;
  10769. svr.set_mount_point("/static", ".");
  10770. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10771. svr.wait_until_ready();
  10772. Client cli(HOST, PORT);
  10773. // Send If-None-Match: * to a non-existent file
  10774. Headers h = {{"If-None-Match", "*"}};
  10775. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10776. ASSERT_TRUE(res);
  10777. EXPECT_EQ(404, res->status);
  10778. svr.stop();
  10779. t.join();
  10780. }
  10781. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10782. using namespace httplib;
  10783. // Create a test file
  10784. const char *fname = "ims_testfile.txt";
  10785. const char *content = "if-modified-since-test";
  10786. {
  10787. std::ofstream ofs(fname);
  10788. ofs << content;
  10789. ASSERT_TRUE(ofs.good());
  10790. }
  10791. Server svr;
  10792. svr.set_mount_point("/static", ".");
  10793. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10794. svr.wait_until_ready();
  10795. Client cli(HOST, PORT);
  10796. // First request: should get 200 with Last-Modified header
  10797. auto res1 = cli.Get("/static/ims_testfile.txt");
  10798. ASSERT_TRUE(res1);
  10799. ASSERT_EQ(200, res1->status);
  10800. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10801. std::string last_modified = res1->get_header_value("Last-Modified");
  10802. EXPECT_FALSE(last_modified.empty());
  10803. // If-Modified-Since with same time: expect 304
  10804. Headers h2 = {{"If-Modified-Since", last_modified}};
  10805. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10806. ASSERT_TRUE(res2);
  10807. EXPECT_EQ(304, res2->status);
  10808. // If-Modified-Since with future time: expect 304
  10809. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10810. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10811. ASSERT_TRUE(res3);
  10812. EXPECT_EQ(304, res3->status);
  10813. // If-Modified-Since with past time: expect 200
  10814. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10815. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10816. ASSERT_TRUE(res4);
  10817. EXPECT_EQ(200, res4->status);
  10818. // If-None-Match takes precedence over If-Modified-Since
  10819. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10820. ASSERT_TRUE(res1->has_header("ETag"));
  10821. std::string etag = res1->get_header_value("ETag");
  10822. Headers h5 = {{"If-None-Match", etag},
  10823. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10824. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10825. ASSERT_TRUE(res5);
  10826. EXPECT_EQ(304, res5->status);
  10827. svr.stop();
  10828. t.join();
  10829. std::remove(fname);
  10830. }
  10831. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10832. using namespace httplib;
  10833. Server svr;
  10834. // Endpoint that returns compressible content
  10835. svr.Get("/compressible", [](const Request &, Response &res) {
  10836. // Return a large enough body to trigger compression
  10837. std::string body(1000, 'a');
  10838. res.set_content(body, "text/plain");
  10839. });
  10840. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10841. svr.wait_until_ready();
  10842. Client cli(HOST, PORT);
  10843. // Request with gzip support: should get Vary header when compressed
  10844. cli.set_compress(true);
  10845. auto res1 = cli.Get("/compressible");
  10846. ASSERT_TRUE(res1);
  10847. EXPECT_EQ(200, res1->status);
  10848. // If Content-Encoding is set, Vary should also be set
  10849. if (res1->has_header("Content-Encoding")) {
  10850. EXPECT_TRUE(res1->has_header("Vary"));
  10851. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10852. }
  10853. // Request without Accept-Encoding header: should not have compression
  10854. Headers h_no_compress;
  10855. auto res2 = cli.Get("/compressible", h_no_compress);
  10856. ASSERT_TRUE(res2);
  10857. EXPECT_EQ(200, res2->status);
  10858. // Verify Vary header is present when compression is applied
  10859. // (the exact behavior depends on server configuration)
  10860. svr.stop();
  10861. t.join();
  10862. }
  10863. TEST(ETagTest, IfRangeWithETag) {
  10864. using namespace httplib;
  10865. // Create a test file with known content
  10866. const char *fname = "if_range_testfile.txt";
  10867. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10868. {
  10869. std::ofstream ofs(fname);
  10870. ofs << content;
  10871. ASSERT_TRUE(ofs.good());
  10872. }
  10873. Server svr;
  10874. svr.set_mount_point("/static", ".");
  10875. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10876. svr.wait_until_ready();
  10877. Client cli(HOST, PORT);
  10878. // First request: get ETag
  10879. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10880. ASSERT_TRUE(res1);
  10881. ASSERT_EQ(200, res1->status);
  10882. ASSERT_TRUE(res1->has_header("ETag"));
  10883. std::string etag = res1->get_header_value("ETag");
  10884. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10885. // Since our server generates weak ETags (W/"..."), If-Range with our
  10886. // ETag should NOT result in partial content - it should return full content.
  10887. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10888. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10889. ASSERT_TRUE(res2);
  10890. // Weak ETag in If-Range -> full content (200), not partial (206)
  10891. EXPECT_EQ(200, res2->status);
  10892. EXPECT_EQ(content, res2->body);
  10893. EXPECT_FALSE(res2->has_header("Content-Range"));
  10894. // Range request with non-matching If-Range (ETag): should get 200 (full
  10895. // content)
  10896. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10897. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10898. ASSERT_TRUE(res3);
  10899. EXPECT_EQ(200, res3->status);
  10900. EXPECT_EQ(content, res3->body);
  10901. EXPECT_FALSE(res3->has_header("Content-Range"));
  10902. // Range request with strong ETag (hypothetical - our server doesn't generate
  10903. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10904. // should return full content)
  10905. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10906. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10907. ASSERT_TRUE(res4);
  10908. EXPECT_EQ(200, res4->status);
  10909. EXPECT_EQ(content, res4->body);
  10910. EXPECT_FALSE(res4->has_header("Content-Range"));
  10911. svr.stop();
  10912. t.join();
  10913. std::remove(fname);
  10914. }
  10915. TEST(ETagTest, IfRangeWithDate) {
  10916. using namespace httplib;
  10917. // Create a test file
  10918. const char *fname = "if_range_date_testfile.txt";
  10919. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10920. {
  10921. std::ofstream ofs(fname);
  10922. ofs << content;
  10923. ASSERT_TRUE(ofs.good());
  10924. }
  10925. Server svr;
  10926. svr.set_mount_point("/static", ".");
  10927. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, PORT);
  10930. // First request: get Last-Modified
  10931. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10932. ASSERT_TRUE(res1);
  10933. ASSERT_EQ(200, res1->status);
  10934. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10935. std::string last_modified = res1->get_header_value("Last-Modified");
  10936. // Range request with matching If-Range (date): should get 206
  10937. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10938. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10939. ASSERT_TRUE(res2);
  10940. EXPECT_EQ(206, res2->status);
  10941. EXPECT_EQ("FGHIJ", res2->body);
  10942. // Range request with old If-Range date: should get 200 (full content)
  10943. Headers h3 = {{"Range", "bytes=5-9"},
  10944. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10945. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10946. ASSERT_TRUE(res3);
  10947. EXPECT_EQ(200, res3->status);
  10948. EXPECT_EQ(content, res3->body);
  10949. // Range request with future If-Range date: should get 206
  10950. Headers h4 = {{"Range", "bytes=0-4"},
  10951. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10952. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10953. ASSERT_TRUE(res4);
  10954. EXPECT_EQ(206, res4->status);
  10955. EXPECT_EQ("ABCDE", res4->body);
  10956. svr.stop();
  10957. t.join();
  10958. std::remove(fname);
  10959. }
  10960. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10961. using namespace httplib;
  10962. const char *fname = "etag_malformed.txt";
  10963. const char *content = "malformed-etag";
  10964. {
  10965. std::ofstream ofs(fname);
  10966. ofs << content;
  10967. ASSERT_TRUE(ofs.good());
  10968. }
  10969. Server svr;
  10970. svr.set_mount_point("/static", ".");
  10971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10972. svr.wait_until_ready();
  10973. Client cli(HOST, PORT);
  10974. // baseline: should get 200 and an ETag
  10975. auto res1 = cli.Get("/static/etag_malformed.txt");
  10976. ASSERT_TRUE(res1);
  10977. ASSERT_EQ(200, res1->status);
  10978. ASSERT_TRUE(res1->has_header("ETag"));
  10979. // Malformed ETag value (missing quotes) should be treated as non-matching
  10980. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10981. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10982. ASSERT_TRUE(res_bad);
  10983. EXPECT_EQ(200, res_bad->status);
  10984. // Whitespace-only header value should be considered invalid / non-matching
  10985. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  10986. "Host: localhost\r\n"
  10987. "If-None-Match: \r\n"
  10988. "Connection: close\r\n"
  10989. "\r\n";
  10990. std::string out;
  10991. ASSERT_TRUE(send_request(5, raw_req, &out));
  10992. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10993. svr.stop();
  10994. t.join();
  10995. std::remove(fname);
  10996. }
  10997. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10998. using namespace httplib;
  10999. const char *fname = "ims_invalid_format.txt";
  11000. const char *content = "ims-bad-format";
  11001. {
  11002. std::ofstream ofs(fname);
  11003. ofs << content;
  11004. ASSERT_TRUE(ofs.good());
  11005. }
  11006. Server svr;
  11007. svr.set_mount_point("/static", ".");
  11008. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11009. svr.wait_until_ready();
  11010. Client cli(HOST, PORT);
  11011. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11012. ASSERT_TRUE(res1);
  11013. ASSERT_EQ(200, res1->status);
  11014. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11015. // If-Modified-Since with invalid format should not result in 304
  11016. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11017. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11018. ASSERT_TRUE(res_bad);
  11019. EXPECT_EQ(200, res_bad->status);
  11020. // If-Range with invalid date format should be treated as mismatch -> full
  11021. // content (200)
  11022. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11023. {"If-Range", "invalid-date"}};
  11024. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11025. ASSERT_TRUE(res_ifrange);
  11026. EXPECT_EQ(200, res_ifrange->status);
  11027. svr.stop();
  11028. t.join();
  11029. std::remove(fname);
  11030. }
  11031. TEST(ETagTest, IfRangeWithMalformedETag) {
  11032. using namespace httplib;
  11033. const char *fname = "ifrange_malformed.txt";
  11034. const std::string content = "0123456789";
  11035. {
  11036. std::ofstream ofs(fname);
  11037. ofs << content;
  11038. ASSERT_TRUE(ofs.good());
  11039. }
  11040. Server svr;
  11041. svr.set_mount_point("/static", ".");
  11042. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11043. svr.wait_until_ready();
  11044. Client cli(HOST, PORT);
  11045. // First request: get ETag
  11046. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11047. ASSERT_TRUE(res1);
  11048. ASSERT_EQ(200, res1->status);
  11049. ASSERT_TRUE(res1->has_header("ETag"));
  11050. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11051. // full content (200)
  11052. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11053. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11054. ASSERT_TRUE(res2);
  11055. EXPECT_EQ(200, res2->status);
  11056. EXPECT_EQ(content, res2->body);
  11057. svr.stop();
  11058. t.join();
  11059. std::remove(fname);
  11060. }
  11061. TEST(ETagTest, ExtremeLargeDateValues) {
  11062. using namespace httplib;
  11063. const char *fname = "ims_extreme_date.txt";
  11064. const char *content = "ims-extreme-date";
  11065. {
  11066. std::ofstream ofs(fname);
  11067. ofs << content;
  11068. ASSERT_TRUE(ofs.good());
  11069. }
  11070. Server svr;
  11071. svr.set_mount_point("/static", ".");
  11072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11073. svr.wait_until_ready();
  11074. Client cli(HOST, PORT);
  11075. auto res1 = cli.Get(std::string("/static/") + fname);
  11076. ASSERT_TRUE(res1);
  11077. ASSERT_EQ(200, res1->status);
  11078. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11079. // Extremely large year that may overflow date parsing routines.
  11080. Headers h_large_date = {
  11081. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11082. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11083. ASSERT_TRUE(res_bad);
  11084. // Expect server to treat this as invalid/mismatch and return full content
  11085. EXPECT_EQ(200, res_bad->status);
  11086. // If-Range with extremely large date should be treated as mismatch -> full
  11087. // content (200)
  11088. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11089. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11090. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11091. ASSERT_TRUE(res_ifrange);
  11092. EXPECT_EQ(200, res_ifrange->status);
  11093. svr.stop();
  11094. t.join();
  11095. std::remove(fname);
  11096. }
  11097. TEST(ETagTest, NegativeFileModificationTime) {
  11098. using namespace httplib;
  11099. const char *fname = "ims_negative_mtime.txt";
  11100. const std::string content = "negative-mtime";
  11101. {
  11102. std::ofstream ofs(fname);
  11103. ofs << content;
  11104. ASSERT_TRUE(ofs.good());
  11105. }
  11106. // Try to set file mtime to a negative value. This may fail on some
  11107. // platforms/filesystems; if it fails, the test will still verify server
  11108. // behaves safely by performing a regular conditional request.
  11109. #if defined(__APPLE__) || defined(__linux__)
  11110. bool set_negative = false;
  11111. do {
  11112. struct timeval times[2];
  11113. // access time: now
  11114. times[0].tv_sec = time(nullptr);
  11115. times[0].tv_usec = 0;
  11116. // modification time: negative (e.g., -1)
  11117. times[1].tv_sec = -1;
  11118. times[1].tv_usec = 0;
  11119. if (utimes(fname, times) == 0) { set_negative = true; }
  11120. } while (0);
  11121. #else
  11122. bool set_negative = false;
  11123. #endif
  11124. Server svr;
  11125. svr.set_mount_point("/static", ".");
  11126. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11127. svr.wait_until_ready();
  11128. Client cli(HOST, PORT);
  11129. auto res1 = cli.Get(std::string("/static/") + fname);
  11130. ASSERT_TRUE(res1);
  11131. ASSERT_EQ(200, res1->status);
  11132. bool has_last_modified = res1->has_header("Last-Modified");
  11133. std::string last_modified;
  11134. if (has_last_modified) {
  11135. last_modified = res1->get_header_value("Last-Modified");
  11136. }
  11137. if (set_negative) {
  11138. // If we successfully set a negative mtime, ensure server returns a
  11139. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11140. // with an old date and ensure server handles it without crash.
  11141. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11142. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11143. ASSERT_TRUE(res2);
  11144. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11145. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11146. } else {
  11147. // Could not set negative mtime on this platform; fall back to verifying
  11148. // that normal invalid/malformed dates are treated safely (non-304).
  11149. Headers h_bad_date = {
  11150. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11151. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11152. ASSERT_TRUE(res_bad);
  11153. EXPECT_EQ(200, res_bad->status);
  11154. }
  11155. svr.stop();
  11156. t.join();
  11157. std::remove(fname);
  11158. }
  11159. //==============================================================================
  11160. // SSE Parsing Tests
  11161. //==============================================================================
  11162. class SSEParsingTest : public ::testing::Test {
  11163. protected:
  11164. // Test helper that mimics SSE parsing behavior
  11165. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11166. int &retry_ms) {
  11167. // Blank line signals end of event
  11168. if (line.empty() || line == "\r") { return true; }
  11169. // Lines starting with ':' are comments (ignored)
  11170. if (!line.empty() && line[0] == ':') { return false; }
  11171. // Find the colon separator
  11172. auto colon_pos = line.find(':');
  11173. if (colon_pos == std::string::npos) {
  11174. // Line with no colon is treated as field name with empty value
  11175. return false;
  11176. }
  11177. std::string field = line.substr(0, colon_pos);
  11178. std::string value;
  11179. // Value starts after colon, skip optional single space
  11180. if (colon_pos + 1 < line.size()) {
  11181. size_t value_start = colon_pos + 1;
  11182. if (line[value_start] == ' ') { value_start++; }
  11183. value = line.substr(value_start);
  11184. // Remove trailing \r if present
  11185. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11186. }
  11187. // Handle known fields
  11188. if (field == "event") {
  11189. msg.event = value;
  11190. } else if (field == "data") {
  11191. // Multiple data lines are concatenated with newlines
  11192. if (!msg.data.empty()) { msg.data += "\n"; }
  11193. msg.data += value;
  11194. } else if (field == "id") {
  11195. // Empty id is valid (clears the last event ID)
  11196. msg.id = value;
  11197. } else if (field == "retry") {
  11198. // Parse retry interval in milliseconds
  11199. try {
  11200. retry_ms = std::stoi(value);
  11201. } catch (...) {
  11202. // Invalid retry value, ignore
  11203. }
  11204. }
  11205. // Unknown fields are ignored per SSE spec
  11206. return false;
  11207. }
  11208. };
  11209. // Test: Single-line data
  11210. TEST_F(SSEParsingTest, SingleLineData) {
  11211. sse::SSEMessage msg;
  11212. int retry_ms = 3000;
  11213. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11214. EXPECT_EQ(msg.data, "hello");
  11215. EXPECT_EQ(msg.event, "message");
  11216. // Blank line ends event
  11217. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11218. }
  11219. // Test: Multi-line data
  11220. TEST_F(SSEParsingTest, MultiLineData) {
  11221. sse::SSEMessage msg;
  11222. int retry_ms = 3000;
  11223. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11224. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11225. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11226. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11227. }
  11228. // Test: Custom event types
  11229. TEST_F(SSEParsingTest, CustomEventType) {
  11230. sse::SSEMessage msg;
  11231. int retry_ms = 3000;
  11232. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11233. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11234. EXPECT_EQ(msg.event, "update");
  11235. EXPECT_EQ(msg.data, "payload");
  11236. }
  11237. // Test: Event ID handling
  11238. TEST_F(SSEParsingTest, EventIdHandling) {
  11239. sse::SSEMessage msg;
  11240. int retry_ms = 3000;
  11241. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11242. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11243. EXPECT_EQ(msg.id, "12345");
  11244. }
  11245. // Test: Empty event ID (clears last event ID)
  11246. TEST_F(SSEParsingTest, EmptyEventId) {
  11247. sse::SSEMessage msg;
  11248. msg.id = "previous";
  11249. int retry_ms = 3000;
  11250. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11251. EXPECT_EQ(msg.id, "");
  11252. }
  11253. // Test: Retry field parsing
  11254. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11255. sse::SSEMessage msg;
  11256. int retry_ms = 3000;
  11257. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11258. EXPECT_EQ(retry_ms, 5000);
  11259. }
  11260. // Test: Invalid retry value
  11261. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11262. sse::SSEMessage msg;
  11263. int retry_ms = 3000;
  11264. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11265. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11266. }
  11267. // Test: Comments (lines starting with :)
  11268. TEST_F(SSEParsingTest, CommentsIgnored) {
  11269. sse::SSEMessage msg;
  11270. int retry_ms = 3000;
  11271. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11272. EXPECT_EQ(msg.data, "");
  11273. EXPECT_EQ(msg.event, "message");
  11274. }
  11275. // Test: Colon in value
  11276. TEST_F(SSEParsingTest, ColonInValue) {
  11277. sse::SSEMessage msg;
  11278. int retry_ms = 3000;
  11279. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11280. EXPECT_EQ(msg.data, "hello:world:test");
  11281. }
  11282. // Test: Line with no colon (field name only)
  11283. TEST_F(SSEParsingTest, FieldNameOnly) {
  11284. sse::SSEMessage msg;
  11285. int retry_ms = 3000;
  11286. // According to SSE spec, this is treated as field name with empty value
  11287. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11288. // Since we don't recognize "data" without colon, data should be empty
  11289. EXPECT_EQ(msg.data, "");
  11290. }
  11291. // Test: Trailing \r handling
  11292. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11293. sse::SSEMessage msg;
  11294. int retry_ms = 3000;
  11295. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11296. EXPECT_EQ(msg.data, "hello");
  11297. }
  11298. // Test: Unknown fields ignored
  11299. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11300. sse::SSEMessage msg;
  11301. int retry_ms = 3000;
  11302. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11303. EXPECT_EQ(msg.data, "");
  11304. EXPECT_EQ(msg.event, "message");
  11305. }
  11306. // Test: Space after colon is optional
  11307. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11308. sse::SSEMessage msg1, msg2;
  11309. int retry_ms = 3000;
  11310. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11311. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11312. EXPECT_EQ(msg1.data, "hello");
  11313. EXPECT_EQ(msg2.data, "hello");
  11314. }
  11315. // Test: SSEMessage clear
  11316. TEST_F(SSEParsingTest, MessageClear) {
  11317. sse::SSEMessage msg;
  11318. msg.event = "custom";
  11319. msg.data = "some data";
  11320. msg.id = "123";
  11321. msg.clear();
  11322. EXPECT_EQ(msg.event, "message");
  11323. EXPECT_EQ(msg.data, "");
  11324. EXPECT_EQ(msg.id, "");
  11325. }
  11326. // Test: Complete event parsing
  11327. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11328. sse::SSEMessage msg;
  11329. int retry_ms = 3000;
  11330. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11331. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11332. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11333. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11334. // Blank line ends event
  11335. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11336. EXPECT_EQ(msg.event, "notification");
  11337. EXPECT_EQ(msg.id, "evt-42");
  11338. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11339. EXPECT_EQ(retry_ms, 1000);
  11340. }
  11341. //==============================================================================
  11342. // Integration Tests with Server
  11343. //==============================================================================
  11344. class SSEIntegrationTest : public ::testing::Test {
  11345. protected:
  11346. void SetUp() override {
  11347. stop_server_.store(false);
  11348. events_.clear();
  11349. server_ = httplib::detail::make_unique<Server>();
  11350. setup_server();
  11351. start_server();
  11352. }
  11353. void TearDown() override {
  11354. stop_server_.store(true);
  11355. event_cv_.notify_all();
  11356. server_->stop();
  11357. if (server_thread_.joinable()) { server_thread_.join(); }
  11358. }
  11359. void setup_server() {
  11360. // Simple SSE endpoint
  11361. server_->Get("/events", [this](const Request &req, Response &res) {
  11362. auto last_id = req.get_header_value("Last-Event-ID");
  11363. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11364. res.set_chunked_content_provider(
  11365. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11366. std::unique_lock<std::mutex> lock(event_mutex_);
  11367. if (event_cv_.wait_for(
  11368. lock, std::chrono::milliseconds(200), [this] {
  11369. return !events_.empty() || stop_server_.load();
  11370. })) {
  11371. if (stop_server_.load()) { return false; }
  11372. if (!events_.empty()) {
  11373. std::string event = events_.front();
  11374. events_.erase(events_.begin());
  11375. sink.write(event.data(), event.size());
  11376. return true;
  11377. }
  11378. }
  11379. return !stop_server_.load();
  11380. });
  11381. });
  11382. // Endpoint that returns error
  11383. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11384. res.status = 500;
  11385. res.set_content("Internal Server Error", "text/plain");
  11386. });
  11387. // Endpoint for custom event types
  11388. server_->Get("/custom-events", [](const Request &, Response &res) {
  11389. res.set_chunked_content_provider(
  11390. "text/event-stream", [](size_t offset, DataSink &sink) {
  11391. if (offset == 0) {
  11392. std::string event = "event: update\ndata: updated\n\n"
  11393. "event: delete\ndata: deleted\n\n";
  11394. sink.write(event.data(), event.size());
  11395. }
  11396. return false; // End stream after sending
  11397. });
  11398. });
  11399. }
  11400. void start_server() {
  11401. port_ = server_->bind_to_any_port(HOST);
  11402. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11403. // Wait for server to start
  11404. while (!server_->is_running()) {
  11405. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11406. }
  11407. }
  11408. int get_port() const { return port_; }
  11409. void send_event(const std::string &event) {
  11410. std::lock_guard<std::mutex> lock(event_mutex_);
  11411. events_.push_back(event);
  11412. event_cv_.notify_all();
  11413. }
  11414. std::unique_ptr<Server> server_;
  11415. std::thread server_thread_;
  11416. std::mutex event_mutex_;
  11417. std::condition_variable event_cv_;
  11418. std::vector<std::string> events_;
  11419. std::atomic<bool> stop_server_{false};
  11420. std::string last_received_event_id_;
  11421. int port_ = 0;
  11422. };
  11423. // Test: Successful connection and on_open callback
  11424. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11425. // Add a simple endpoint that sends one event and closes
  11426. server_->Get("/simple-event", [](const Request &, Response &res) {
  11427. res.set_chunked_content_provider(
  11428. "text/event-stream", [](size_t offset, DataSink &sink) {
  11429. if (offset == 0) {
  11430. std::string event = "data: hello\n\n";
  11431. sink.write(event.data(), event.size());
  11432. }
  11433. return false; // Close stream after sending
  11434. });
  11435. });
  11436. Client client("localhost", get_port());
  11437. sse::SSEClient sse(client, "/simple-event");
  11438. std::atomic<bool> open_called{false};
  11439. std::atomic<bool> message_received{false};
  11440. sse.on_open([&open_called]() { open_called.store(true); });
  11441. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11442. if (msg.data == "hello") { message_received.store(true); }
  11443. });
  11444. sse.set_reconnect_interval(100);
  11445. sse.set_max_reconnect_attempts(1);
  11446. // Start async
  11447. sse.start_async();
  11448. // Wait for message to be processed
  11449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11450. sse.stop();
  11451. EXPECT_TRUE(open_called.load());
  11452. EXPECT_TRUE(message_received.load());
  11453. }
  11454. // Test: on_message callback
  11455. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11456. // Endpoint that sends multiple events then closes
  11457. server_->Get("/multi-event", [](const Request &, Response &res) {
  11458. res.set_chunked_content_provider(
  11459. "text/event-stream", [](size_t offset, DataSink &sink) {
  11460. if (offset == 0) {
  11461. std::string events = "data: message1\n\ndata: message2\n\n";
  11462. sink.write(events.data(), events.size());
  11463. }
  11464. return false;
  11465. });
  11466. });
  11467. Client client("localhost", get_port());
  11468. sse::SSEClient sse(client, "/multi-event");
  11469. std::vector<std::string> received_messages;
  11470. std::mutex messages_mutex;
  11471. sse.on_message([&](const sse::SSEMessage &msg) {
  11472. std::lock_guard<std::mutex> lock(messages_mutex);
  11473. received_messages.push_back(msg.data);
  11474. });
  11475. sse.set_reconnect_interval(100);
  11476. sse.set_max_reconnect_attempts(1);
  11477. sse.start_async();
  11478. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11479. sse.stop();
  11480. std::lock_guard<std::mutex> lock(messages_mutex);
  11481. EXPECT_GE(received_messages.size(), 2u);
  11482. if (received_messages.size() >= 2) {
  11483. EXPECT_EQ(received_messages[0], "message1");
  11484. EXPECT_EQ(received_messages[1], "message2");
  11485. }
  11486. }
  11487. // Test: on_event for specific types
  11488. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11489. Client client("localhost", get_port());
  11490. sse::SSEClient sse(client, "/custom-events");
  11491. std::atomic<bool> update_received{false};
  11492. std::atomic<bool> delete_received{false};
  11493. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11494. if (msg.data == "updated") { update_received.store(true); }
  11495. });
  11496. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11497. if (msg.data == "deleted") { delete_received.store(true); }
  11498. });
  11499. sse.set_max_reconnect_attempts(1);
  11500. sse.start_async();
  11501. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11502. sse.stop();
  11503. EXPECT_TRUE(update_received.load());
  11504. EXPECT_TRUE(delete_received.load());
  11505. }
  11506. // Test: on_error callback on connection failure
  11507. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11508. // Connect to a non-existent port
  11509. Client client("localhost", 59999);
  11510. sse::SSEClient sse(client, "/events");
  11511. std::atomic<bool> error_called{false};
  11512. Error received_error = Error::Success;
  11513. sse.on_error([&](Error err) {
  11514. error_called.store(true);
  11515. received_error = err;
  11516. });
  11517. sse.set_reconnect_interval(50);
  11518. sse.set_max_reconnect_attempts(1);
  11519. sse.start_async();
  11520. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11521. sse.stop();
  11522. EXPECT_TRUE(error_called.load());
  11523. EXPECT_NE(received_error, Error::Success);
  11524. }
  11525. // Test: Last-Event-ID header sent on reconnect
  11526. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11527. // Endpoint that sends event with ID
  11528. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11529. res.set_chunked_content_provider(
  11530. "text/event-stream", [](size_t offset, DataSink &sink) {
  11531. if (offset == 0) {
  11532. std::string event = "id: evt-123\ndata: test\n\n";
  11533. sink.write(event.data(), event.size());
  11534. }
  11535. return false;
  11536. });
  11537. });
  11538. Client client("localhost", get_port());
  11539. sse::SSEClient sse(client, "/event-with-id");
  11540. std::atomic<bool> id_received{false};
  11541. sse.on_message([&](const sse::SSEMessage &msg) {
  11542. if (!msg.id.empty()) { id_received.store(true); }
  11543. });
  11544. sse.set_reconnect_interval(100);
  11545. sse.set_max_reconnect_attempts(1);
  11546. sse.start_async();
  11547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11548. sse.stop();
  11549. EXPECT_TRUE(id_received.load());
  11550. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11551. }
  11552. // Test: Manual stop
  11553. TEST_F(SSEIntegrationTest, ManualStop) {
  11554. // Endpoint that sends one event and stays open briefly
  11555. std::atomic<bool> handler_running{true};
  11556. server_->Get("/stay-open", [&handler_running](const Request &,
  11557. Response &res) {
  11558. res.set_chunked_content_provider(
  11559. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11560. if (offset == 0) {
  11561. std::string event = "data: connected\n\n";
  11562. sink.write(event.data(), event.size());
  11563. }
  11564. // Keep connection open while handler_running is true
  11565. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11566. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11567. }
  11568. return false;
  11569. });
  11570. });
  11571. Client client("localhost", get_port());
  11572. sse::SSEClient sse(client, "/stay-open");
  11573. std::atomic<bool> connected{false};
  11574. sse.on_open([&connected]() { connected.store(true); });
  11575. sse.set_reconnect_interval(100);
  11576. sse.set_max_reconnect_attempts(1);
  11577. sse.start_async();
  11578. // Wait for connection to establish
  11579. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11580. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11581. }
  11582. EXPECT_TRUE(connected.load());
  11583. EXPECT_TRUE(sse.is_connected());
  11584. // Signal handler to stop
  11585. handler_running.store(false);
  11586. // Stop SSE client
  11587. sse.stop();
  11588. EXPECT_FALSE(sse.is_connected());
  11589. }
  11590. // Test: SSEClient with custom headers
  11591. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11592. // Setup a server endpoint that checks for custom header
  11593. std::atomic<bool> header_received{false};
  11594. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11595. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11596. header_received.store(true);
  11597. }
  11598. res.set_chunked_content_provider("text/event-stream",
  11599. [](size_t, DataSink &) { return false; });
  11600. });
  11601. Client client("localhost", get_port());
  11602. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11603. sse::SSEClient sse(client, "/header-check", headers);
  11604. sse.set_max_reconnect_attempts(1);
  11605. sse.start_async();
  11606. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11607. sse.stop();
  11608. EXPECT_TRUE(header_received.load());
  11609. }
  11610. // Test: Reconnect interval configuration
  11611. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11612. Client client("localhost", get_port());
  11613. sse::SSEClient sse(client, "/events");
  11614. auto &result = sse.set_reconnect_interval(500);
  11615. // Builder pattern should return reference to self
  11616. EXPECT_EQ(&result, &sse);
  11617. }
  11618. // Test: Max reconnect attempts
  11619. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11620. // Connect to non-existent port to force reconnects
  11621. Client client("localhost", 59998);
  11622. sse::SSEClient sse(client, "/events");
  11623. std::atomic<int> error_count{0};
  11624. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11625. sse.set_reconnect_interval(50);
  11626. sse.set_max_reconnect_attempts(2);
  11627. auto start = std::chrono::steady_clock::now();
  11628. sse.start(); // Blocking call
  11629. auto end = std::chrono::steady_clock::now();
  11630. // Should have stopped after 2 failed attempts
  11631. EXPECT_GE(error_count.load(), 2);
  11632. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11633. auto duration =
  11634. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11635. #ifdef _WIN32
  11636. // Windows is much slower for socket connection failures
  11637. EXPECT_LT(duration.count(), 7000);
  11638. #else
  11639. EXPECT_LT(duration.count(), 1000);
  11640. #endif
  11641. }
  11642. // Test: Multi-line data in integration
  11643. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11644. // Endpoint with multi-line data
  11645. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11646. res.set_chunked_content_provider(
  11647. "text/event-stream", [](size_t offset, DataSink &sink) {
  11648. if (offset == 0) {
  11649. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11650. sink.write(event.data(), event.size());
  11651. }
  11652. return false;
  11653. });
  11654. });
  11655. Client client("localhost", get_port());
  11656. sse::SSEClient sse(client, "/multiline-data");
  11657. std::string received_data;
  11658. std::mutex data_mutex;
  11659. sse.on_message([&](const sse::SSEMessage &msg) {
  11660. std::lock_guard<std::mutex> lock(data_mutex);
  11661. received_data = msg.data;
  11662. });
  11663. sse.set_reconnect_interval(100);
  11664. sse.set_max_reconnect_attempts(1);
  11665. sse.start_async();
  11666. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11667. sse.stop();
  11668. std::lock_guard<std::mutex> lock(data_mutex);
  11669. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11670. }
  11671. // Test: Auto-reconnect after server disconnection
  11672. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11673. std::atomic<int> connection_count{0};
  11674. std::atomic<int> message_count{0};
  11675. // Endpoint that sends one event and closes, forcing reconnect
  11676. server_->Get("/reconnect-test",
  11677. [&connection_count](const Request &, Response &res) {
  11678. connection_count.fetch_add(1);
  11679. res.set_chunked_content_provider(
  11680. "text/event-stream", [](size_t offset, DataSink &sink) {
  11681. if (offset == 0) {
  11682. std::string event = "data: hello\n\n";
  11683. sink.write(event.data(), event.size());
  11684. }
  11685. return false; // Close connection after sending
  11686. });
  11687. });
  11688. Client client("localhost", get_port());
  11689. sse::SSEClient sse(client, "/reconnect-test");
  11690. sse.on_message([&message_count](const sse::SSEMessage &) {
  11691. message_count.fetch_add(1);
  11692. });
  11693. sse.set_reconnect_interval(100);
  11694. sse.set_max_reconnect_attempts(3);
  11695. sse.start_async();
  11696. // Wait long enough for multiple reconnects
  11697. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11698. sse.stop();
  11699. // Should have connected multiple times (initial + reconnects)
  11700. EXPECT_GE(connection_count.load(), 2);
  11701. // Should have received messages from multiple connections
  11702. EXPECT_GE(message_count.load(), 2);
  11703. }
  11704. // Test: Last-Event-ID sent on reconnect
  11705. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11706. std::atomic<int> connection_count{0};
  11707. std::vector<std::string> received_last_event_ids;
  11708. std::mutex id_mutex;
  11709. // Endpoint that checks Last-Event-ID header and sends event with ID
  11710. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11711. int conn = connection_count.fetch_add(1);
  11712. // Capture the Last-Event-ID header from each connection
  11713. {
  11714. std::lock_guard<std::mutex> lock(id_mutex);
  11715. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11716. }
  11717. res.set_chunked_content_provider(
  11718. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11719. if (offset == 0) {
  11720. std::string event =
  11721. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11722. sink.write(event.data(), event.size());
  11723. }
  11724. return false;
  11725. });
  11726. });
  11727. Client client("localhost", get_port());
  11728. sse::SSEClient sse(client, "/reconnect-with-id");
  11729. sse.set_reconnect_interval(100);
  11730. sse.set_max_reconnect_attempts(3);
  11731. sse.start_async();
  11732. // Wait for at least 2 connections
  11733. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11734. sse.stop();
  11735. // Verify behavior
  11736. std::lock_guard<std::mutex> lock(id_mutex);
  11737. EXPECT_GE(received_last_event_ids.size(), 2u);
  11738. // First connection should have no Last-Event-ID
  11739. if (!received_last_event_ids.empty()) {
  11740. EXPECT_EQ(received_last_event_ids[0], "");
  11741. }
  11742. // Second connection should have Last-Event-ID from first connection
  11743. if (received_last_event_ids.size() >= 2) {
  11744. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11745. }
  11746. }
  11747. TEST(Issue2318Test, EmptyHostString) {
  11748. {
  11749. httplib::Client cli_empty("", PORT);
  11750. auto res = cli_empty.Get("/");
  11751. ASSERT_FALSE(res);
  11752. EXPECT_EQ(httplib::Error::Connection, res.error());
  11753. }
  11754. {
  11755. httplib::Client cli(" ", PORT);
  11756. auto res = cli.Get("/");
  11757. ASSERT_FALSE(res);
  11758. EXPECT_EQ(httplib::Error::Connection, res.error());
  11759. }
  11760. }
  11761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11762. #ifdef _WIN32
  11763. // Windows Certificate Verification Tests
  11764. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11765. // Test 1: Default behavior (Windows verification enabled)
  11766. SSLClient cli("www.google.com", 443);
  11767. cli.enable_server_certificate_verification(true);
  11768. auto res = cli.Get("/");
  11769. // Should succeed or fail gracefully (may fail due to network)
  11770. // The important thing is that Windows verification was enabled
  11771. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11772. }
  11773. TEST(SSLClientTest, WindowsCertificateVerification_DisableWindows) {
  11774. // Test 2: Disable Windows verification (OpenSSL only)
  11775. SSLClient cli("www.google.com", 443);
  11776. cli.enable_server_certificate_verification(true);
  11777. cli.enable_windows_certificate_verification(false);
  11778. auto res = cli.Get("/");
  11779. // Should work with OpenSSL verification only
  11780. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11781. }
  11782. TEST(SSLClientTest, WindowsCertificateVerification_CustomTimeout) {
  11783. // Test 3: Custom timeout
  11784. SSLClient cli("www.google.com", 443);
  11785. cli.enable_server_certificate_verification(true);
  11786. cli.set_windows_certificate_verification_timeout(2);
  11787. auto res = cli.Get("/");
  11788. // Should complete within reasonable time
  11789. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11790. }
  11791. TEST(SSLClientTest, WindowsCertificateVerification_InvalidCertificate) {
  11792. // Test 4: Invalid certificate (should fail)
  11793. SSLClient cli("self-signed.badssl.com", 443);
  11794. cli.enable_server_certificate_verification(true);
  11795. auto res = cli.Get("/");
  11796. // Should fail due to invalid certificate
  11797. EXPECT_FALSE(res);
  11798. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11799. }
  11800. TEST(SSLClientTest, WindowsCertificateVerification_CachingBehavior) {
  11801. // Test 5: Multiple connections (test caching)
  11802. SSLClient cli("www.google.com", 443);
  11803. cli.enable_server_certificate_verification(true);
  11804. // First connection
  11805. auto res1 = cli.Get("/");
  11806. auto start2 = std::chrono::high_resolution_clock::now();
  11807. // Second connection (should use cache)
  11808. auto res2 = cli.Get("/");
  11809. auto end2 = std::chrono::high_resolution_clock::now();
  11810. auto duration2 =
  11811. std::chrono::duration_cast<std::chrono::milliseconds>(end2 - start2);
  11812. // Second connection should be fast (cache hit)
  11813. if (res2) {
  11814. EXPECT_NE(StatusCode::InternalServerError_500, res2->status);
  11815. // Cache should make second connection faster (very loose bound)
  11816. EXPECT_LT(duration2.count(), 5000); // Within 5 seconds
  11817. }
  11818. }
  11819. #endif
  11820. #endif