1
0

test.cc 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307
  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. auto port = 1234;
  74. Server svr;
  75. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  76. res.set_content("Benchmark Response", "text/plain");
  77. });
  78. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  79. auto se = detail::scope_exit([&] {
  80. svr.stop();
  81. listen_thread.join();
  82. ASSERT_FALSE(svr.is_running());
  83. });
  84. svr.wait_until_ready();
  85. Client cli(host, port);
  86. // Warm-up request to establish connection and resolve DNS
  87. auto warmup_res = cli.Get("/benchmark");
  88. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  89. // Run multiple trials and collect timings
  90. const int num_trials = 20;
  91. std::vector<int64_t> timings;
  92. timings.reserve(num_trials);
  93. for (int i = 0; i < num_trials; i++) {
  94. auto start = std::chrono::high_resolution_clock::now();
  95. auto res = cli.Get("/benchmark");
  96. auto end = std::chrono::high_resolution_clock::now();
  97. auto elapsed =
  98. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  99. .count();
  100. // Assertions after timing measurement to avoid overhead
  101. ASSERT_TRUE(res);
  102. EXPECT_EQ(StatusCode::OK_200, res->status);
  103. timings.push_back(elapsed);
  104. }
  105. // Calculate 25th percentile (lower quartile)
  106. std::sort(timings.begin(), timings.end());
  107. auto p25 = timings[num_trials / 4];
  108. // Format timings for output
  109. std::ostringstream timings_str;
  110. timings_str << "[";
  111. for (size_t i = 0; i < timings.size(); i++) {
  112. if (i > 0) timings_str << ", ";
  113. timings_str << timings[i];
  114. }
  115. timings_str << "]";
  116. // Localhost HTTP GET should be fast even in CI environments
  117. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  118. << "ms (Issue #1777). Timings: " << timings_str.str();
  119. }
  120. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  121. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. const std::string pathname_{"./httplib-server.sock"};
  136. const std::string pattern_{"/hi"};
  137. const std::string content_{"Hello World!"};
  138. };
  139. TEST_F(UnixSocketTest, pathname) {
  140. httplib::Server svr;
  141. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  142. res.set_content(content_, "text/plain");
  143. });
  144. std::thread t{[&] {
  145. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  146. }};
  147. auto se = detail::scope_exit([&] {
  148. svr.stop();
  149. t.join();
  150. ASSERT_FALSE(svr.is_running());
  151. });
  152. svr.wait_until_ready();
  153. ASSERT_TRUE(svr.is_running());
  154. client_GET(pathname_);
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.wait_writable());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(PORT + 1);
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  263. ASSERT_EQ(0, listen(s, 1));
  264. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  268. std::thread cli{[&] {
  269. const int s = socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_LE(0, s);
  271. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. cli.join();
  275. svr.join();
  276. ASSERT_NE(disconnected_svr_sock, -1);
  277. const auto asSocketStream = [&](socket_t fd,
  278. std::function<bool(Stream &)> func) {
  279. return detail::process_client_socket(
  280. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  281. };
  282. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  283. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  284. EXPECT_FALSE(ss.wait_writable());
  285. return true;
  286. });
  287. ASSERT_EQ(0, close(disconnected_svr_sock));
  288. }
  289. #endif // #ifndef _WIN32
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. u8"descrip=Gastos áéíóúñÑ 6");
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  319. string unescapedCharacters = "-_.!~*'()";
  320. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  321. }
  322. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  323. string reservedCharacters = ";,/?:@&=+$";
  324. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  325. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  326. }
  327. TEST(ClientQueryOrder, PreserveOrder) {
  328. // This test reproduces Issue #2259: client may reorder query parameters
  329. // when sending a GET request. The expected behavior is that the client
  330. // preserves the original query string order when the caller supplied it
  331. // as part of the path.
  332. Server svr;
  333. svr.Get("/", [&](const Request &req, Response &res) {
  334. // Echo back the raw target so the test can assert ordering
  335. res.set_content(req.target, "text/plain");
  336. });
  337. std::thread t{[&] { svr.listen(HOST, PORT); }};
  338. auto se = detail::scope_exit([&] {
  339. svr.stop();
  340. t.join();
  341. ASSERT_FALSE(svr.is_running());
  342. });
  343. svr.wait_until_ready();
  344. Client cli(HOST, PORT);
  345. ASSERT_TRUE(cli.is_valid());
  346. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  347. auto res = cli.Get(original);
  348. ASSERT_TRUE(res);
  349. // Expect the echoed target to exactly match the original path (order
  350. // preserved)
  351. EXPECT_EQ(res->body, original);
  352. }
  353. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  354. string chineseCharacters = u8"中国語";
  355. string russianCharacters = u8"дом";
  356. string brazilianCharacters = u8"óculos";
  357. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  358. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  359. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  360. "%D0%B4%D0%BE%D0%BC");
  361. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  362. }
  363. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  364. string unescapedCharacters = "-_.!~*'()";
  365. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  366. }
  367. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  368. string reservedCharacters = ";,/?:@&=+$";
  369. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  370. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  371. }
  372. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  373. string chineseCharacters = u8"中国語";
  374. string russianCharacters = u8"дом";
  375. string brazilianCharacters = u8"óculos";
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  383. // Issue #2082 use case: encoding path component with ampersand
  384. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  385. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  386. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  387. }
  388. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$#";
  394. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  395. }
  396. TEST(EncodeUriTest, TestUTF8Characters) {
  397. string chineseCharacters = u8"中国語";
  398. string russianCharacters = u8"дом";
  399. string brazilianCharacters = u8"óculos";
  400. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  401. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  402. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  403. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  404. }
  405. TEST(EncodeUriTest, TestCompleteUri) {
  406. string uri =
  407. "https://example.com/path/to/resource?query=value&param=test#fragment";
  408. EXPECT_EQ(
  409. httplib::encode_uri(uri),
  410. "https://example.com/path/to/resource?query=value&param=test#fragment");
  411. }
  412. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  413. string uri =
  414. "https://example.com/path with spaces/file name.html?q=hello world";
  415. EXPECT_EQ(httplib::encode_uri(uri),
  416. "https://example.com/path%20with%20spaces/"
  417. "file%20name.html?q=hello%20world");
  418. }
  419. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  420. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  421. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  422. }
  423. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  424. string unescapedCharacters = "-_.!~*'()";
  425. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  426. }
  427. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  428. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  429. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  430. string encodedBrazilian = "%C3%B3culos";
  431. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  433. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  434. }
  435. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  436. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  437. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  438. "Piri Tommy Villiers - on & on");
  439. }
  440. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  441. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  442. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  443. }
  444. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  445. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  446. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  447. }
  448. TEST(DecodeUriTest, TestUTF8Characters) {
  449. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  450. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  451. string encodedBrazilian = "%C3%B3culos";
  452. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  453. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  454. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  455. }
  456. TEST(DecodeUriTest, TestCompleteUri) {
  457. string encodedUri = "https://example.com/path%20with%20spaces/"
  458. "file%20name.html?q=hello%20world";
  459. EXPECT_EQ(
  460. httplib::decode_uri(encodedUri),
  461. "https://example.com/path with spaces/file name.html?q=hello world");
  462. }
  463. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  464. string original =
  465. "https://example.com/path with spaces/file name.html?q=hello world";
  466. string encoded = httplib::encode_uri(original);
  467. string decoded = httplib::decode_uri(encoded);
  468. EXPECT_EQ(decoded, original);
  469. }
  470. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  471. string original = "Piri Tommy Villiers - on & on";
  472. string encoded = httplib::encode_uri_component(original);
  473. string decoded = httplib::decode_uri_component(encoded);
  474. EXPECT_EQ(decoded, original);
  475. }
  476. TEST(TrimTests, TrimStringTests) {
  477. EXPECT_EQ("abc", detail::trim_copy("abc"));
  478. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  479. EXPECT_TRUE(detail::trim_copy("").empty());
  480. }
  481. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  482. // Simple case without quality values
  483. std::vector<std::string> result1;
  484. EXPECT_TRUE(detail::parse_accept_header(
  485. "text/html,application/json,text/plain", result1));
  486. EXPECT_EQ(result1.size(), 3U);
  487. EXPECT_EQ(result1[0], "text/html");
  488. EXPECT_EQ(result1[1], "application/json");
  489. EXPECT_EQ(result1[2], "text/plain");
  490. // With quality values
  491. std::vector<std::string> result2;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  494. EXPECT_EQ(result2.size(), 3U);
  495. EXPECT_EQ(result2[0], "application/json"); // highest q value
  496. EXPECT_EQ(result2[1], "text/html");
  497. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  498. }
  499. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  500. // Mixed with and without quality values
  501. std::vector<std::string> result;
  502. EXPECT_TRUE(detail::parse_accept_header(
  503. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  504. EXPECT_EQ(result.size(), 3U);
  505. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  506. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  507. EXPECT_EQ(result[2], "application/json"); // q=0.5
  508. }
  509. TEST(ParseAcceptHeaderTest, EdgeCases) {
  510. // Empty header
  511. std::vector<std::string> empty_result;
  512. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  513. EXPECT_TRUE(empty_result.empty());
  514. // Single type
  515. std::vector<std::string> single_result;
  516. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  517. EXPECT_EQ(single_result.size(), 1U);
  518. EXPECT_EQ(single_result[0], "application/json");
  519. // Wildcard types
  520. std::vector<std::string> wildcard_result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  523. EXPECT_EQ(wildcard_result.size(), 3U);
  524. EXPECT_EQ(wildcard_result[0], "application/json");
  525. EXPECT_EQ(wildcard_result[1], "text/*");
  526. EXPECT_EQ(wildcard_result[2], "*/*");
  527. }
  528. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  529. // Common browser Accept header
  530. std::vector<std::string> browser_result;
  531. EXPECT_TRUE(
  532. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  533. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  534. browser_result));
  535. EXPECT_EQ(browser_result.size(), 6U);
  536. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  540. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  541. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  542. // API client header
  543. std::vector<std::string> api_result;
  544. EXPECT_TRUE(detail::parse_accept_header(
  545. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  546. api_result));
  547. EXPECT_EQ(api_result.size(), 3U);
  548. EXPECT_EQ(api_result[0], "application/json");
  549. EXPECT_EQ(api_result[1], "application/xml");
  550. EXPECT_EQ(api_result[2], "text/plain");
  551. }
  552. TEST(ParseAcceptHeaderTest, SpecialCases) {
  553. // Quality value with 3 decimal places
  554. std::vector<std::string> decimal_result;
  555. EXPECT_TRUE(detail::parse_accept_header(
  556. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  557. EXPECT_EQ(decimal_result.size(), 2U);
  558. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  559. EXPECT_EQ(decimal_result[1], "text/html");
  560. // Zero quality (should still be included but with lowest priority)
  561. std::vector<std::string> zero_q_result;
  562. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  563. zero_q_result));
  564. EXPECT_EQ(zero_q_result.size(), 2U);
  565. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  566. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  567. // No spaces around commas
  568. std::vector<std::string> no_space_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  571. no_space_result));
  572. EXPECT_EQ(no_space_result.size(), 3U);
  573. EXPECT_EQ(no_space_result[0], "text/html");
  574. EXPECT_EQ(no_space_result[1], "application/json");
  575. EXPECT_EQ(no_space_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, InvalidCases) {
  578. std::vector<std::string> result;
  579. // Invalid quality value (> 1.0)
  580. EXPECT_FALSE(
  581. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  582. // Invalid quality value (< 0.0)
  583. EXPECT_FALSE(
  584. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  585. // Invalid quality value (not a number)
  586. EXPECT_FALSE(detail::parse_accept_header(
  587. "text/html;q=invalid,application/json", result));
  588. // Empty quality value
  589. EXPECT_FALSE(
  590. detail::parse_accept_header("text/html;q=,application/json", result));
  591. // Invalid media type format (no slash and not wildcard)
  592. EXPECT_FALSE(
  593. detail::parse_accept_header("invalidtype,application/json", result));
  594. // Empty media type
  595. result.clear();
  596. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  597. // Only commas
  598. result.clear();
  599. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  600. // Valid cases should still work
  601. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  602. EXPECT_EQ(result.size(), 1U);
  603. EXPECT_EQ(result[0], "*/*");
  604. EXPECT_TRUE(detail::parse_accept_header("*", result));
  605. EXPECT_EQ(result.size(), 1U);
  606. EXPECT_EQ(result[0], "*");
  607. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  608. EXPECT_EQ(result.size(), 1U);
  609. EXPECT_EQ(result[0], "text/*");
  610. }
  611. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  612. Server svr;
  613. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  614. EXPECT_EQ(req.accept_content_types.size(), 3U);
  615. EXPECT_EQ(req.accept_content_types[0], "application/json");
  616. EXPECT_EQ(req.accept_content_types[1], "text/html");
  617. EXPECT_EQ(req.accept_content_types[2], "*/*");
  618. res.set_content("ok", "text/plain");
  619. });
  620. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  621. EXPECT_TRUE(false);
  622. res.set_content("bad request", "text/plain");
  623. });
  624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  625. auto se = detail::scope_exit([&] {
  626. svr.stop();
  627. listen_thread.join();
  628. ASSERT_FALSE(svr.is_running());
  629. });
  630. svr.wait_until_ready();
  631. Client cli("localhost", PORT);
  632. {
  633. auto res =
  634. cli.Get("/accept_ok",
  635. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  636. ASSERT_TRUE(res);
  637. EXPECT_EQ(StatusCode::OK_200, res->status);
  638. }
  639. {
  640. auto res = cli.Get("/accept_bad_request",
  641. {{"Accept", "text/html;q=abc,application/json"}});
  642. ASSERT_TRUE(res);
  643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  644. }
  645. }
  646. TEST(DivideTest, DivideStringTests) {
  647. auto divide = [](const std::string &str, char d) {
  648. std::string lhs;
  649. std::string rhs;
  650. detail::divide(str, d,
  651. [&](const char *lhs_data, std::size_t lhs_size,
  652. const char *rhs_data, std::size_t rhs_size) {
  653. lhs.assign(lhs_data, lhs_size);
  654. rhs.assign(rhs_data, rhs_size);
  655. });
  656. return std::make_pair(std::move(lhs), std::move(rhs));
  657. };
  658. {
  659. const auto res = divide("", '=');
  660. EXPECT_EQ(res.first, "");
  661. EXPECT_EQ(res.second, "");
  662. }
  663. {
  664. const auto res = divide("=", '=');
  665. EXPECT_EQ(res.first, "");
  666. EXPECT_EQ(res.second, "");
  667. }
  668. {
  669. const auto res = divide(" ", '=');
  670. EXPECT_EQ(res.first, " ");
  671. EXPECT_EQ(res.second, "");
  672. }
  673. {
  674. const auto res = divide("a", '=');
  675. EXPECT_EQ(res.first, "a");
  676. EXPECT_EQ(res.second, "");
  677. }
  678. {
  679. const auto res = divide("a=", '=');
  680. EXPECT_EQ(res.first, "a");
  681. EXPECT_EQ(res.second, "");
  682. }
  683. {
  684. const auto res = divide("=b", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "b");
  687. }
  688. {
  689. const auto res = divide("a=b", '=');
  690. EXPECT_EQ(res.first, "a");
  691. EXPECT_EQ(res.second, "b");
  692. }
  693. {
  694. const auto res = divide("a=b=", '=');
  695. EXPECT_EQ(res.first, "a");
  696. EXPECT_EQ(res.second, "b=");
  697. }
  698. {
  699. const auto res = divide("a=b=c", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "b=c");
  702. }
  703. }
  704. TEST(SplitTest, ParseQueryString) {
  705. string s = "key1=val1&key2=val2&key3=val3";
  706. Params dic;
  707. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  708. [&](const char *b, const char *e) {
  709. string key, val;
  710. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  711. if (key.empty()) {
  712. key.assign(b2, e2);
  713. } else {
  714. val.assign(b2, e2);
  715. }
  716. });
  717. dic.emplace(key, val);
  718. });
  719. EXPECT_EQ("val1", dic.find("key1")->second);
  720. EXPECT_EQ("val2", dic.find("key2")->second);
  721. EXPECT_EQ("val3", dic.find("key3")->second);
  722. }
  723. TEST(SplitTest, ParseInvalidQueryTests) {
  724. {
  725. string s = " ";
  726. Params dict;
  727. detail::parse_query_text(s, dict);
  728. EXPECT_TRUE(dict.empty());
  729. }
  730. {
  731. string s = " = =";
  732. Params dict;
  733. detail::parse_query_text(s, dict);
  734. EXPECT_TRUE(dict.empty());
  735. }
  736. }
  737. TEST(ParseQueryTest, ParseQueryString) {
  738. {
  739. std::string s = "key1=val1&key2=val2&key3=val3";
  740. Params dic;
  741. detail::parse_query_text(s, dic);
  742. EXPECT_EQ("val1", dic.find("key1")->second);
  743. EXPECT_EQ("val2", dic.find("key2")->second);
  744. EXPECT_EQ("val3", dic.find("key3")->second);
  745. }
  746. {
  747. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("", dic.find("key1")->second);
  751. EXPECT_EQ("val1", dic.find("key2")->second);
  752. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  753. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  754. }
  755. }
  756. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  757. Params dic;
  758. EXPECT_EQ(detail::params_to_query_str(dic), "");
  759. dic.emplace("key1", "val1");
  760. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  761. dic.emplace("key2", "val2");
  762. dic.emplace("key3", "val3");
  763. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  764. }
  765. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  766. string content_type = "multipart/form-data; boundary=something";
  767. string boundary;
  768. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  769. EXPECT_TRUE(ret);
  770. EXPECT_EQ(boundary, "something");
  771. }
  772. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  773. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  780. string content_type =
  781. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  794. }
  795. TEST(GetHeaderValueTest, DefaultValue) {
  796. Headers headers = {{"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  798. EXPECT_STREQ("text/plain", val);
  799. }
  800. TEST(GetHeaderValueTest, DefaultValueInt) {
  801. Headers headers = {{"Dummy", "Dummy"}};
  802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  803. EXPECT_EQ(100ull, val);
  804. }
  805. TEST(GetHeaderValueTest, RegularValue) {
  806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  808. EXPECT_STREQ("text/html", val);
  809. }
  810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  813. EXPECT_STREQ("text/html", val);
  814. }
  815. TEST(GetHeaderValueTest, SetContent) {
  816. Response res;
  817. res.set_content("html", "text/html");
  818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  819. res.set_content("text", "text/plain");
  820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  822. }
  823. TEST(GetHeaderValueTest, RegularValueInt) {
  824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  826. EXPECT_EQ(100ull, val);
  827. }
  828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  829. Headers headers = {{"Content-Length", "x"}};
  830. auto is_invalid_value = false;
  831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  832. is_invalid_value);
  833. EXPECT_EQ(0ull, val);
  834. EXPECT_TRUE(is_invalid_value);
  835. }
  836. TEST(GetHeaderValueTest, Range) {
  837. {
  838. Headers headers = {make_range_header({{1, -1}})};
  839. auto val = detail::get_header_value(headers, "Range", 0, 0);
  840. EXPECT_STREQ("bytes=1-", val);
  841. }
  842. {
  843. Headers headers = {make_range_header({{-1, 1}})};
  844. auto val = detail::get_header_value(headers, "Range", 0, 0);
  845. EXPECT_STREQ("bytes=-1", val);
  846. }
  847. {
  848. Headers headers = {make_range_header({{1, 10}})};
  849. auto val = detail::get_header_value(headers, "Range", 0, 0);
  850. EXPECT_STREQ("bytes=1-10", val);
  851. }
  852. {
  853. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  854. auto val = detail::get_header_value(headers, "Range", 0, 0);
  855. EXPECT_STREQ("bytes=1-10, 100-", val);
  856. }
  857. {
  858. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  859. auto val = detail::get_header_value(headers, "Range", 0, 0);
  860. EXPECT_STREQ("bytes=1-10, 100-200", val);
  861. }
  862. {
  863. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=0-0, -1", val);
  866. }
  867. }
  868. TEST(ParseHeaderValueTest, Range) {
  869. {
  870. Ranges ranges;
  871. auto ret = detail::parse_range_header("bytes=1-", ranges);
  872. EXPECT_TRUE(ret);
  873. EXPECT_EQ(1u, ranges.size());
  874. EXPECT_EQ(1u, ranges[0].first);
  875. EXPECT_EQ(-1, ranges[0].second);
  876. }
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=-1", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(-1, ranges[0].first);
  883. EXPECT_EQ(1u, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(1u, ranges[0].first);
  891. EXPECT_EQ(10u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  896. EXPECT_FALSE(ret);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(2u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. EXPECT_EQ(100u, ranges[1].first);
  906. EXPECT_EQ(-1, ranges[1].second);
  907. }
  908. {
  909. Ranges ranges;
  910. auto ret =
  911. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  912. EXPECT_TRUE(ret);
  913. EXPECT_EQ(3u, ranges.size());
  914. EXPECT_EQ(1u, ranges[0].first);
  915. EXPECT_EQ(10u, ranges[0].second);
  916. EXPECT_EQ(100u, ranges[1].first);
  917. EXPECT_EQ(200u, ranges[1].second);
  918. EXPECT_EQ(300u, ranges[2].first);
  919. EXPECT_EQ(400u, ranges[2].second);
  920. }
  921. {
  922. Ranges ranges;
  923. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", 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_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  936. EXPECT_TRUE(ranges.empty());
  937. }
  938. }
  939. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding", "gzip");
  942. Response res;
  943. res.set_header("Content-Type", "text/plain");
  944. auto ret = detail::encoding_type(req, res);
  945. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  947. #else
  948. EXPECT_TRUE(ret == detail::EncodingType::None);
  949. #endif
  950. }
  951. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  952. Request req;
  953. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  954. Response res;
  955. res.set_header("Content-Type", "text/plain");
  956. auto ret = detail::encoding_type(req, res);
  957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  963. #else
  964. EXPECT_TRUE(ret == detail::EncodingType::None);
  965. #endif
  966. }
  967. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  968. Request req;
  969. req.set_header("Accept-Encoding",
  970. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  971. Response res;
  972. res.set_header("Content-Type", "text/plain");
  973. auto ret = detail::encoding_type(req, res);
  974. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  976. #elif CPPHTTPLIB_ZLIB_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  980. #else
  981. EXPECT_TRUE(ret == detail::EncodingType::None);
  982. #endif
  983. }
  984. TEST(BufferStreamTest, read) {
  985. detail::BufferStream strm1;
  986. Stream &strm = strm1;
  987. EXPECT_EQ(5, strm.write("hello"));
  988. char buf[512];
  989. EXPECT_EQ(2, strm.read(buf, 2));
  990. EXPECT_EQ('h', buf[0]);
  991. EXPECT_EQ('e', buf[1]);
  992. EXPECT_EQ(2, strm.read(buf, 2));
  993. EXPECT_EQ('l', buf[0]);
  994. EXPECT_EQ('l', buf[1]);
  995. EXPECT_EQ(1, strm.read(buf, 1));
  996. EXPECT_EQ('o', buf[0]);
  997. EXPECT_EQ(0, strm.read(buf, 1));
  998. }
  999. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1000. auto host = "www.httpwatch.com";
  1001. auto ip = hosted_at(host);
  1002. EXPECT_EQ("23.96.13.243", ip);
  1003. std::vector<std::string> addrs;
  1004. hosted_at(host, addrs);
  1005. EXPECT_EQ(1u, addrs.size());
  1006. }
  1007. #if 0 // It depends on each test environment...
  1008. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1009. auto host = "www.youtube.com";
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(20u, addrs.size());
  1013. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1014. EXPECT_TRUE(it != addrs.end());
  1015. }
  1016. #endif
  1017. class ChunkedEncodingTest : public ::testing::Test {
  1018. protected:
  1019. ChunkedEncodingTest()
  1020. : cli_(HOST, PORT)
  1021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1022. ,
  1023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1024. #endif
  1025. {
  1026. cli_.set_connection_timeout(2);
  1027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1028. cli_.enable_server_certificate_verification(false);
  1029. #endif
  1030. }
  1031. virtual void SetUp() {
  1032. read_file("./image.jpg", image_data_);
  1033. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1034. res.set_content("Hello World!", "text/plain");
  1035. });
  1036. svr_.Get(
  1037. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1038. res.set_chunked_content_provider(
  1039. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1040. size_t remaining = image_data_.size() - offset;
  1041. if (remaining == 0) {
  1042. sink.done();
  1043. } else {
  1044. constexpr size_t CHUNK_SIZE = 1024;
  1045. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1046. sink.write(&image_data_[offset], send_size);
  1047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1048. }
  1049. return true;
  1050. });
  1051. });
  1052. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1053. svr_.wait_until_ready();
  1054. }
  1055. virtual void TearDown() {
  1056. svr_.stop();
  1057. if (!request_threads_.empty()) {
  1058. std::this_thread::sleep_for(std::chrono::seconds(1));
  1059. for (auto &t : request_threads_) {
  1060. t.join();
  1061. }
  1062. }
  1063. t_.join();
  1064. }
  1065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1066. SSLClient cli_;
  1067. SSLServer svr_;
  1068. #else
  1069. Client cli_;
  1070. Server svr_;
  1071. #endif
  1072. thread t_;
  1073. std::vector<thread> request_threads_;
  1074. std::string image_data_;
  1075. };
  1076. TEST_F(ChunkedEncodingTest, NormalGet) {
  1077. auto res = cli_.Get("/chunked");
  1078. ASSERT_TRUE(res);
  1079. std::string out;
  1080. read_file("./image.jpg", out);
  1081. EXPECT_EQ(StatusCode::OK_200, res->status);
  1082. EXPECT_EQ(out, res->body);
  1083. }
  1084. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1085. std::string body;
  1086. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1087. body.append(data, data_length);
  1088. return true;
  1089. });
  1090. ASSERT_TRUE(res);
  1091. std::string out;
  1092. read_file("./image.jpg", out);
  1093. EXPECT_EQ(StatusCode::OK_200, res->status);
  1094. EXPECT_EQ(out, body);
  1095. }
  1096. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1097. std::string body;
  1098. auto res = cli_.Get(
  1099. "/chunked",
  1100. [&](const Response &response) {
  1101. EXPECT_EQ(StatusCode::OK_200, response.status);
  1102. return true;
  1103. },
  1104. [&](const char *data, size_t data_length) {
  1105. body.append(data, data_length);
  1106. return true;
  1107. });
  1108. ASSERT_TRUE(res);
  1109. std::string out;
  1110. read_file("./image.jpg", out);
  1111. EXPECT_EQ(StatusCode::OK_200, res->status);
  1112. EXPECT_EQ(out, body);
  1113. }
  1114. TEST(RangeTest, FromHTTPBin_Online) {
  1115. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1116. auto host = "httpcan.org";
  1117. auto path = std::string{"/range/32"};
  1118. #else
  1119. auto host = "nghttp2.org";
  1120. auto path = std::string{"/httpbin/range/32"};
  1121. #endif
  1122. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1123. auto port = 443;
  1124. SSLClient cli(host, port);
  1125. #else
  1126. auto port = 80;
  1127. Client cli(host, port);
  1128. #endif
  1129. cli.set_connection_timeout(5);
  1130. {
  1131. auto res = cli.Get(path);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{1, -1}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, 10}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijk", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{0, 31}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, -1}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, 32}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1169. }
  1170. }
  1171. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1172. auto host = "unresolvableaddress.local";
  1173. auto path = std::string{"/"};
  1174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1175. auto port = 443;
  1176. SSLClient cli(host, port);
  1177. #else
  1178. auto port = 80;
  1179. Client cli(host, port);
  1180. #endif
  1181. cli.set_connection_timeout(1);
  1182. {
  1183. auto res = cli.Get(path);
  1184. ASSERT_FALSE(res);
  1185. }
  1186. std::this_thread::sleep_for(std::chrono::seconds(8));
  1187. }
  1188. TEST(ConnectionErrorTest, InvalidHost) {
  1189. auto host = "-abcde.com";
  1190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1191. auto port = 443;
  1192. SSLClient cli(host, port);
  1193. #else
  1194. auto port = 80;
  1195. Client cli(host, port);
  1196. #endif
  1197. cli.set_connection_timeout(std::chrono::seconds(2));
  1198. auto res = cli.Get("/");
  1199. ASSERT_TRUE(!res);
  1200. EXPECT_EQ(Error::Connection, res.error());
  1201. }
  1202. TEST(ConnectionErrorTest, InvalidHost2) {
  1203. auto host = "httpcan.org/";
  1204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1205. SSLClient cli(host);
  1206. #else
  1207. Client cli(host);
  1208. #endif
  1209. cli.set_connection_timeout(std::chrono::seconds(2));
  1210. auto res = cli.Get("/");
  1211. ASSERT_TRUE(!res);
  1212. EXPECT_EQ(Error::Connection, res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1215. auto host = "httpcan.org/";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. SSLClient cli(host);
  1218. #else
  1219. Client cli(host);
  1220. #endif
  1221. cli.set_connection_timeout(std::chrono::seconds(2));
  1222. auto res = cli.Get("/");
  1223. ASSERT_TRUE(!res);
  1224. stringstream s;
  1225. s << "error code: " << res.error();
  1226. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1227. }
  1228. TEST(ConnectionErrorTest, InvalidPort) {
  1229. auto host = "localhost";
  1230. auto port = 44380;
  1231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1232. SSLClient cli(host, port);
  1233. #else
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(2));
  1237. auto res = cli.Get("/");
  1238. ASSERT_TRUE(!res);
  1239. EXPECT_TRUE(Error::Connection == res.error() ||
  1240. Error::ConnectionTimeout == res.error());
  1241. }
  1242. TEST(ConnectionErrorTest, Timeout_Online) {
  1243. auto host = "google.com";
  1244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1245. auto port = 44380;
  1246. SSLClient cli(host, port);
  1247. #else
  1248. auto port = 8080;
  1249. Client cli(host, port);
  1250. #endif
  1251. cli.set_connection_timeout(std::chrono::seconds(2));
  1252. // only probe one address type so that the error reason
  1253. // correlates to the timed-out IPv4, not the unsupported
  1254. // IPv6 connection attempt
  1255. cli.set_address_family(AF_INET);
  1256. auto res = cli.Get("/");
  1257. ASSERT_TRUE(!res);
  1258. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1259. }
  1260. TEST(CancelTest, NoCancel_Online) {
  1261. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1262. auto host = "httpcan.org";
  1263. auto path = std::string{"/range/32"};
  1264. #else
  1265. auto host = "nghttp2.org";
  1266. auto path = std::string{"/httpbin/range/32"};
  1267. #endif
  1268. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1269. auto port = 443;
  1270. SSLClient cli(host, port);
  1271. #else
  1272. auto port = 80;
  1273. Client cli(host, port);
  1274. #endif
  1275. cli.set_connection_timeout(std::chrono::seconds(5));
  1276. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1277. ASSERT_TRUE(res);
  1278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1279. EXPECT_EQ(StatusCode::OK_200, res->status);
  1280. }
  1281. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1282. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1283. auto host = "httpcan.org";
  1284. auto path = std::string{"/range/32"};
  1285. #else
  1286. auto host = "nghttp2.org";
  1287. auto path = std::string{"/httpbin/range/32"};
  1288. #endif
  1289. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1290. auto port = 443;
  1291. SSLClient cli(host, port);
  1292. #else
  1293. auto port = 80;
  1294. Client cli(host, port);
  1295. #endif
  1296. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. ASSERT_TRUE(!res);
  1299. EXPECT_EQ(Error::Canceled, res.error());
  1300. }
  1301. TEST(CancelTest, WithCancelLargePayload_Online) {
  1302. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1303. auto host = "httpcan.org";
  1304. auto path = std::string{"/range/65536"};
  1305. #else
  1306. auto host = "nghttp2.org";
  1307. auto path = std::string{"/httpbin/range/65536"};
  1308. #endif
  1309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1310. auto port = 443;
  1311. SSLClient cli(host, port);
  1312. #else
  1313. auto port = 80;
  1314. Client cli(host, port);
  1315. #endif
  1316. cli.set_connection_timeout(std::chrono::seconds(5));
  1317. uint32_t count = 0;
  1318. auto res =
  1319. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, NoCancelPost) {
  1324. Server svr;
  1325. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1326. res.set_content("Hello World!", "text/plain");
  1327. });
  1328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. thread.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. Client cli(HOST, PORT);
  1336. cli.set_connection_timeout(std::chrono::seconds(5));
  1337. auto res =
  1338. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1339. "application/json", [](uint64_t, uint64_t) { return true; });
  1340. ASSERT_TRUE(res);
  1341. EXPECT_EQ("Hello World!", res->body);
  1342. EXPECT_EQ(StatusCode::OK_200, res->status);
  1343. }
  1344. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1345. Server svr;
  1346. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1347. res.set_content("Hello World!", "text/plain");
  1348. });
  1349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1350. auto se = detail::scope_exit([&] {
  1351. svr.stop();
  1352. thread.join();
  1353. ASSERT_FALSE(svr.is_running());
  1354. });
  1355. svr.wait_until_ready();
  1356. Client cli(HOST, PORT);
  1357. cli.set_connection_timeout(std::chrono::seconds(5));
  1358. auto res =
  1359. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1360. "application/json", [](uint64_t, uint64_t) { return false; });
  1361. ASSERT_TRUE(!res);
  1362. EXPECT_EQ(Error::Canceled, res.error());
  1363. }
  1364. TEST(CancelTest, WithCancelLargePayloadPost) {
  1365. Server svr;
  1366. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1367. res.set_content(LARGE_DATA, "text/plain");
  1368. });
  1369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1370. auto se = detail::scope_exit([&] {
  1371. svr.stop();
  1372. thread.join();
  1373. ASSERT_FALSE(svr.is_running());
  1374. });
  1375. svr.wait_until_ready();
  1376. Client cli(HOST, PORT);
  1377. cli.set_connection_timeout(std::chrono::seconds(5));
  1378. auto res =
  1379. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1380. "application/json", [](uint64_t, uint64_t) { return false; });
  1381. ASSERT_TRUE(!res);
  1382. EXPECT_EQ(Error::Canceled, res.error());
  1383. }
  1384. TEST(CancelTest, NoCancelPut) {
  1385. Server svr;
  1386. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1387. res.set_content("Hello World!", "text/plain");
  1388. });
  1389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. thread.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, PORT);
  1397. cli.set_connection_timeout(std::chrono::seconds(5));
  1398. auto res =
  1399. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1400. "application/json", [](uint64_t, uint64_t) { return true; });
  1401. ASSERT_TRUE(res);
  1402. EXPECT_EQ("Hello World!", res->body);
  1403. EXPECT_EQ(StatusCode::OK_200, res->status);
  1404. }
  1405. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1406. Server svr;
  1407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1408. res.set_content("Hello World!", "text/plain");
  1409. });
  1410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1411. auto se = detail::scope_exit([&] {
  1412. svr.stop();
  1413. thread.join();
  1414. ASSERT_FALSE(svr.is_running());
  1415. });
  1416. svr.wait_until_ready();
  1417. Client cli(HOST, PORT);
  1418. cli.set_connection_timeout(std::chrono::seconds(5));
  1419. auto res =
  1420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1421. "application/json", [](uint64_t, uint64_t) { return false; });
  1422. ASSERT_TRUE(!res);
  1423. EXPECT_EQ(Error::Canceled, res.error());
  1424. }
  1425. TEST(CancelTest, WithCancelLargePayloadPut) {
  1426. Server svr;
  1427. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1428. res.set_content(LARGE_DATA, "text/plain");
  1429. });
  1430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. thread.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, PORT);
  1438. cli.set_connection_timeout(std::chrono::seconds(5));
  1439. auto res =
  1440. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1441. "application/json", [](uint64_t, uint64_t) { return false; });
  1442. ASSERT_TRUE(!res);
  1443. EXPECT_EQ(Error::Canceled, res.error());
  1444. }
  1445. TEST(CancelTest, NoCancelPatch) {
  1446. Server svr;
  1447. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1448. res.set_content("Hello World!", "text/plain");
  1449. });
  1450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1451. auto se = detail::scope_exit([&] {
  1452. svr.stop();
  1453. thread.join();
  1454. ASSERT_FALSE(svr.is_running());
  1455. });
  1456. svr.wait_until_ready();
  1457. Client cli(HOST, PORT);
  1458. cli.set_connection_timeout(std::chrono::seconds(5));
  1459. auto res =
  1460. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1461. "application/json", [](uint64_t, uint64_t) { return true; });
  1462. ASSERT_TRUE(res);
  1463. EXPECT_EQ("Hello World!", res->body);
  1464. EXPECT_EQ(StatusCode::OK_200, res->status);
  1465. }
  1466. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1467. Server svr;
  1468. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1469. res.set_content("Hello World!", "text/plain");
  1470. });
  1471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1472. auto se = detail::scope_exit([&] {
  1473. svr.stop();
  1474. thread.join();
  1475. ASSERT_FALSE(svr.is_running());
  1476. });
  1477. svr.wait_until_ready();
  1478. Client cli(HOST, PORT);
  1479. cli.set_connection_timeout(std::chrono::seconds(5));
  1480. auto res =
  1481. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1482. "application/json", [](uint64_t, uint64_t) { return false; });
  1483. ASSERT_TRUE(!res);
  1484. EXPECT_EQ(Error::Canceled, res.error());
  1485. }
  1486. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1487. Server svr;
  1488. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1489. res.set_content(LARGE_DATA, "text/plain");
  1490. });
  1491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. thread.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, PORT);
  1499. cli.set_connection_timeout(std::chrono::seconds(5));
  1500. auto res =
  1501. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1502. "application/json", [](uint64_t, uint64_t) { return false; });
  1503. ASSERT_TRUE(!res);
  1504. EXPECT_EQ(Error::Canceled, res.error());
  1505. }
  1506. TEST(CancelTest, NoCancelDelete) {
  1507. Server svr;
  1508. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1509. res.set_content("Hello World!", "text/plain");
  1510. });
  1511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1512. auto se = detail::scope_exit([&] {
  1513. svr.stop();
  1514. thread.join();
  1515. ASSERT_FALSE(svr.is_running());
  1516. });
  1517. svr.wait_until_ready();
  1518. Client cli(HOST, PORT);
  1519. cli.set_connection_timeout(std::chrono::seconds(5));
  1520. auto res =
  1521. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1522. "application/json", [](uint64_t, uint64_t) { return true; });
  1523. ASSERT_TRUE(res);
  1524. EXPECT_EQ("Hello World!", res->body);
  1525. EXPECT_EQ(StatusCode::OK_200, res->status);
  1526. }
  1527. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1528. Server svr;
  1529. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1530. res.set_content("Hello World!", "text/plain");
  1531. });
  1532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1533. auto se = detail::scope_exit([&] {
  1534. svr.stop();
  1535. thread.join();
  1536. ASSERT_FALSE(svr.is_running());
  1537. });
  1538. svr.wait_until_ready();
  1539. Client cli(HOST, PORT);
  1540. cli.set_connection_timeout(std::chrono::seconds(5));
  1541. auto res =
  1542. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1543. "application/json", [](uint64_t, uint64_t) { return false; });
  1544. ASSERT_TRUE(!res);
  1545. EXPECT_EQ(Error::Canceled, res.error());
  1546. }
  1547. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1548. Server svr;
  1549. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1550. res.set_content(LARGE_DATA, "text/plain");
  1551. });
  1552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. Client cli(HOST, PORT);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. static std::string remove_whitespace(const std::string &input) {
  1568. std::string output;
  1569. output.reserve(input.size());
  1570. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1571. [](unsigned char c) { return !std::isspace(c); });
  1572. return output;
  1573. }
  1574. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1575. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1576. auto host = "httpcan.org";
  1577. auto path = std::string{"/basic-auth/hello/world"};
  1578. #else
  1579. auto host = "nghttp2.org";
  1580. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1581. #endif
  1582. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1583. auto port = 443;
  1584. SSLClient cli(host, port);
  1585. #else
  1586. auto port = 80;
  1587. Client cli(host, port);
  1588. #endif
  1589. {
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. {
  1595. auto res =
  1596. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1599. remove_whitespace(res->body));
  1600. EXPECT_EQ(StatusCode::OK_200, res->status);
  1601. }
  1602. {
  1603. cli.set_basic_auth("hello", "world");
  1604. auto res = cli.Get(path);
  1605. ASSERT_TRUE(res);
  1606. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1607. remove_whitespace(res->body));
  1608. EXPECT_EQ(StatusCode::OK_200, res->status);
  1609. }
  1610. {
  1611. cli.set_basic_auth("hello", "bad");
  1612. auto res = cli.Get(path);
  1613. ASSERT_TRUE(res);
  1614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1615. }
  1616. {
  1617. cli.set_basic_auth("bad", "world");
  1618. auto res = cli.Get(path);
  1619. ASSERT_TRUE(res);
  1620. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1621. }
  1622. }
  1623. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1624. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1625. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1626. auto host = "httpcan.org";
  1627. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1628. auto paths = std::vector<std::string>{
  1629. "/digest-auth/auth/hello/world/MD5",
  1630. "/digest-auth/auth/hello/world/SHA-256",
  1631. "/digest-auth/auth/hello/world/SHA-512",
  1632. };
  1633. #else
  1634. auto host = "nghttp2.org";
  1635. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1636. auto paths = std::vector<std::string>{
  1637. "/httpbin/digest-auth/auth/hello/world/MD5",
  1638. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1639. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1640. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1641. };
  1642. #endif
  1643. auto port = 443;
  1644. SSLClient cli(host, port);
  1645. {
  1646. auto res = cli.Get(unauth_path);
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1649. }
  1650. {
  1651. cli.set_digest_auth("hello", "world");
  1652. for (const auto &path : paths) {
  1653. auto res = cli.Get(path.c_str());
  1654. ASSERT_TRUE(res);
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. std::string algo(path.substr(path.rfind('/') + 1));
  1657. EXPECT_EQ(
  1658. remove_whitespace("{\"algorithm\":\"" + algo +
  1659. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1660. remove_whitespace(res->body));
  1661. #else
  1662. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1663. remove_whitespace(res->body));
  1664. #endif
  1665. EXPECT_EQ(StatusCode::OK_200, res->status);
  1666. }
  1667. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1668. cli.set_digest_auth("hello", "bad");
  1669. for (const auto &path : paths) {
  1670. auto res = cli.Get(path.c_str());
  1671. ASSERT_TRUE(res);
  1672. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1673. }
  1674. #endif
  1675. }
  1676. }
  1677. #ifndef CPPHTTPLIB_DEFAULT_HTTPBIN
  1678. TEST(DigestAuthTest, FromHTTPWatch_Online_HTTPCan) {
  1679. auto host = "httpcan.org";
  1680. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1681. auto paths = std::vector<std::string>{
  1682. "/digest-auth/auth/hello/world/MD5",
  1683. "/digest-auth/auth/hello/world/SHA-256",
  1684. "/digest-auth/auth/hello/world/SHA-512",
  1685. };
  1686. auto port = 443;
  1687. SSLClient cli(host, port);
  1688. {
  1689. auto res = cli.Get(unauth_path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_digest_auth("hello", "world");
  1695. for (const auto &path : paths) {
  1696. auto res = cli.Get(path.c_str());
  1697. ASSERT_TRUE(res);
  1698. std::string algo(path.substr(path.rfind('/') + 1));
  1699. EXPECT_EQ(
  1700. remove_whitespace("{\"algorithm\":\"" + algo +
  1701. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1702. remove_whitespace(res->body));
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. }
  1705. cli.set_digest_auth("hello", "bad");
  1706. for (const auto &path : paths) {
  1707. auto res = cli.Get(path.c_str());
  1708. ASSERT_TRUE(res);
  1709. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1710. }
  1711. cli.set_digest_auth("bad", "world");
  1712. for (const auto &path : paths) {
  1713. auto res = cli.Get(path.c_str());
  1714. ASSERT_TRUE(res);
  1715. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1716. }
  1717. }
  1718. }
  1719. #endif
  1720. #endif
  1721. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1722. auto host = "google.com";
  1723. auto another_host = "example.com";
  1724. auto wrong_ip = "0.0.0.0";
  1725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1726. SSLClient cli(host);
  1727. #else
  1728. Client cli(host);
  1729. #endif
  1730. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1731. auto res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1734. }
  1735. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1736. auto host = "google.com";
  1737. auto wrong_ip = "0.0.0.0";
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_hostname_addr_map({{host, wrong_ip}});
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(!res);
  1746. EXPECT_EQ(Error::Connection, res.error());
  1747. }
  1748. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1757. ASSERT_TRUE(res);
  1758. EXPECT_EQ(StatusCode::OK_200, res->status);
  1759. }
  1760. TEST(RedirectTest, Redirect_Online) {
  1761. auto host = "nghttp2.org";
  1762. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1763. SSLClient cli(host);
  1764. #else
  1765. Client cli(host);
  1766. #endif
  1767. cli.set_follow_location(true);
  1768. auto res = cli.Get("/httpbin/redirect/3");
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ(StatusCode::OK_200, res->status);
  1771. }
  1772. TEST(RelativeRedirectTest, Redirect_Online) {
  1773. auto host = "nghttp2.org";
  1774. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1775. SSLClient cli(host);
  1776. #else
  1777. Client cli(host);
  1778. #endif
  1779. cli.set_follow_location(true);
  1780. auto res = cli.Get("/httpbin/relative-redirect/3");
  1781. ASSERT_TRUE(res);
  1782. EXPECT_EQ(StatusCode::OK_200, res->status);
  1783. }
  1784. TEST(TooManyRedirectTest, Redirect_Online) {
  1785. auto host = "nghttp2.org";
  1786. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1787. SSLClient cli(host);
  1788. #else
  1789. Client cli(host);
  1790. #endif
  1791. cli.set_follow_location(true);
  1792. auto res = cli.Get("/httpbin/redirect/21");
  1793. ASSERT_TRUE(!res);
  1794. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1795. }
  1796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1797. TEST(YahooRedirectTest, Redirect_Online) {
  1798. Client cli("yahoo.com");
  1799. auto res = cli.Get("/");
  1800. ASSERT_TRUE(res);
  1801. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1802. cli.set_follow_location(true);
  1803. res = cli.Get("/");
  1804. ASSERT_TRUE(res);
  1805. EXPECT_EQ(StatusCode::OK_200, res->status);
  1806. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1807. }
  1808. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1809. #define REDIR_HOST "httpbingo.org"
  1810. #define REDIR_PATH "/redirect-to"
  1811. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1812. SSLClient cli(REDIR_HOST);
  1813. cli.set_follow_location(true);
  1814. auto res =
  1815. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. }
  1819. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. Params params;
  1823. params.emplace("url", "http://example.com");
  1824. params.emplace("status_code", "302");
  1825. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1826. ASSERT_TRUE(res);
  1827. EXPECT_EQ(StatusCode::OK_200, res->status);
  1828. }
  1829. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1830. SSLClient cli(REDIR_HOST);
  1831. cli.set_follow_location(true);
  1832. Params params;
  1833. params.emplace("url", "http://example.com");
  1834. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1835. ASSERT_TRUE(res);
  1836. EXPECT_EQ(StatusCode::OK_200, res->status);
  1837. }
  1838. TEST(UrlWithSpace, Redirect_Online) {
  1839. SSLClient cli("edge.forgecdn.net");
  1840. cli.set_follow_location(true);
  1841. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(StatusCode::OK_200, res->status);
  1844. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1845. }
  1846. #endif
  1847. #if !defined(_WIN32) && !defined(_WIN64)
  1848. TEST(ReceiveSignals, Signal) {
  1849. auto setupSignalHandlers = []() {
  1850. struct sigaction act;
  1851. sigemptyset(&act.sa_mask);
  1852. act.sa_flags = SA_SIGINFO;
  1853. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1854. switch (sig) {
  1855. case SIGINT:
  1856. default: break;
  1857. }
  1858. };
  1859. ::sigaction(SIGINT, &act, nullptr);
  1860. };
  1861. Server svr;
  1862. int port = 0;
  1863. auto thread = std::thread([&]() {
  1864. setupSignalHandlers();
  1865. port = svr.bind_to_any_port("localhost");
  1866. svr.listen_after_bind();
  1867. });
  1868. auto se = detail::scope_exit([&] {
  1869. svr.stop();
  1870. thread.join();
  1871. ASSERT_FALSE(svr.is_running());
  1872. });
  1873. svr.wait_until_ready();
  1874. ASSERT_TRUE(svr.is_running());
  1875. pthread_kill(thread.native_handle(), SIGINT);
  1876. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1877. ASSERT_TRUE(svr.is_running());
  1878. }
  1879. #endif
  1880. TEST(RedirectToDifferentPort, Redirect) {
  1881. Server svr1;
  1882. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("Hello World!", "text/plain");
  1884. });
  1885. int svr1_port = 0;
  1886. auto thread1 = std::thread([&]() {
  1887. svr1_port = svr1.bind_to_any_port("localhost");
  1888. svr1.listen_after_bind();
  1889. });
  1890. Server svr2;
  1891. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1892. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1893. });
  1894. int svr2_port = 0;
  1895. auto thread2 = std::thread([&]() {
  1896. svr2_port = svr2.bind_to_any_port("localhost");
  1897. svr2.listen_after_bind();
  1898. });
  1899. auto se = detail::scope_exit([&] {
  1900. svr2.stop();
  1901. thread2.join();
  1902. svr1.stop();
  1903. thread1.join();
  1904. ASSERT_FALSE(svr2.is_running());
  1905. ASSERT_FALSE(svr1.is_running());
  1906. });
  1907. svr1.wait_until_ready();
  1908. svr2.wait_until_ready();
  1909. Client cli("localhost", svr2_port);
  1910. cli.set_follow_location(true);
  1911. auto res = cli.Get("/2");
  1912. ASSERT_TRUE(res);
  1913. EXPECT_EQ(StatusCode::OK_200, res->status);
  1914. EXPECT_EQ("Hello World!", res->body);
  1915. }
  1916. TEST(RedirectFromPageWithContent, Redirect) {
  1917. Server svr;
  1918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("___", "text/plain");
  1920. res.set_redirect("/2");
  1921. });
  1922. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1923. res.set_content("Hello World!", "text/plain");
  1924. });
  1925. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. th.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. svr.wait_until_ready();
  1932. {
  1933. Client cli("localhost", PORT);
  1934. cli.set_follow_location(true);
  1935. std::string body;
  1936. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1937. body.append(data, data_length);
  1938. return true;
  1939. });
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::OK_200, res->status);
  1942. EXPECT_EQ("Hello World!", body);
  1943. }
  1944. {
  1945. Client cli("localhost", PORT);
  1946. std::string body;
  1947. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1948. body.append(data, data_length);
  1949. return true;
  1950. });
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::Found_302, res->status);
  1953. EXPECT_EQ("___", body);
  1954. }
  1955. }
  1956. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1957. Server svr;
  1958. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1959. res.set_content("___", "text/plain");
  1960. // res.set_redirect("/2");
  1961. res.set_redirect("http://[::1]:1234/2");
  1962. });
  1963. svr.Get("/2", [&](const Request &req, Response &res) {
  1964. auto host_header = req.headers.find("Host");
  1965. ASSERT_TRUE(host_header != req.headers.end());
  1966. EXPECT_EQ("[::1]:1234", host_header->second);
  1967. res.set_content("Hello World!", "text/plain");
  1968. });
  1969. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1970. auto se = detail::scope_exit([&] {
  1971. svr.stop();
  1972. th.join();
  1973. ASSERT_FALSE(svr.is_running());
  1974. });
  1975. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1976. // actually starts anything, so the condition !svr.is_running() will
  1977. // always remain true, and the loop never stops.
  1978. // This basically counts how many milliseconds have passed since the
  1979. // call to svr.listen(), and if after 5 seconds nothing started yet
  1980. // aborts the test.
  1981. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1982. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1983. ASSERT_LT(milliseconds, 5000U);
  1984. }
  1985. {
  1986. Client cli("http://[::1]:1234");
  1987. cli.set_follow_location(true);
  1988. std::string body;
  1989. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1990. body.append(data, data_length);
  1991. return true;
  1992. });
  1993. ASSERT_TRUE(res);
  1994. EXPECT_EQ(StatusCode::OK_200, res->status);
  1995. EXPECT_EQ("Hello World!", body);
  1996. }
  1997. {
  1998. Client cli("http://[::1]:1234");
  1999. std::string body;
  2000. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2001. body.append(data, data_length);
  2002. return true;
  2003. });
  2004. ASSERT_TRUE(res);
  2005. EXPECT_EQ(StatusCode::Found_302, res->status);
  2006. EXPECT_EQ("___", body);
  2007. }
  2008. }
  2009. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2010. Server svr;
  2011. svr.Get("/foo", [](const Request &req, Response &res) {
  2012. auto a = req.params.find("a");
  2013. if (a != req.params.end()) {
  2014. res.set_content((*a).second, "text/plain");
  2015. res.status = StatusCode::OK_200;
  2016. } else {
  2017. res.status = StatusCode::BadRequest_400;
  2018. }
  2019. });
  2020. auto thread = std::thread([&]() { svr.listen(HOST, 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(HOST, PORT);
  2029. cli.set_path_encode(false);
  2030. auto res = cli.Get("/foo?a=explicitly+encoded");
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::OK_200, res->status);
  2033. // This expects it back with a space, as the `+` won't have been
  2034. // url-encoded, and server-side the params get decoded turning `+`
  2035. // into spaces.
  2036. EXPECT_EQ("explicitly encoded", res->body);
  2037. }
  2038. }
  2039. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2040. Server svr;
  2041. svr.Get("/", [](const Request &req, Response &) {
  2042. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. Client cli(HOST, PORT);
  2053. cli.set_path_encode(false);
  2054. auto res = cli.Get("/?something=%0A");
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::OK_200, res->status);
  2057. }
  2058. }
  2059. TEST(BindServerTest, DISABLED_BindDualStack) {
  2060. Server svr;
  2061. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2062. res.set_content("Hello World!", "text/plain");
  2063. });
  2064. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2065. auto se = detail::scope_exit([&] {
  2066. svr.stop();
  2067. thread.join();
  2068. ASSERT_FALSE(svr.is_running());
  2069. });
  2070. svr.wait_until_ready();
  2071. {
  2072. Client cli("127.0.0.1", PORT);
  2073. auto res = cli.Get("/1");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. EXPECT_EQ("Hello World!", res->body);
  2077. }
  2078. {
  2079. Client cli("::1", PORT);
  2080. auto res = cli.Get("/1");
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. EXPECT_EQ("Hello World!", res->body);
  2084. }
  2085. }
  2086. TEST(BindServerTest, BindAndListenSeparately) {
  2087. Server svr;
  2088. int port = svr.bind_to_any_port("0.0.0.0");
  2089. ASSERT_TRUE(svr.is_valid());
  2090. ASSERT_TRUE(port > 0);
  2091. svr.stop();
  2092. }
  2093. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2094. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2096. CLIENT_CA_CERT_DIR);
  2097. int port = svr.bind_to_any_port("0.0.0.0");
  2098. ASSERT_TRUE(svr.is_valid());
  2099. ASSERT_TRUE(port > 0);
  2100. svr.stop();
  2101. }
  2102. #endif
  2103. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2104. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2105. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2106. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2107. int port = svr.bind_to_any_port("0.0.0.0");
  2108. ASSERT_TRUE(svr.is_valid());
  2109. ASSERT_TRUE(port > 0);
  2110. svr.stop();
  2111. }
  2112. #endif
  2113. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2114. X509 *readCertificate(const std::string &strFileName) {
  2115. std::ifstream inStream(strFileName);
  2116. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2117. std::istreambuf_iterator<char>());
  2118. if (strCertPEM.empty()) return (nullptr);
  2119. BIO *pbCert = BIO_new(BIO_s_mem());
  2120. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2121. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2122. BIO_free(pbCert);
  2123. return (pCert);
  2124. }
  2125. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2126. std::ifstream inStream(strFileName);
  2127. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2128. std::istreambuf_iterator<char>());
  2129. if (strPrivateKeyPEM.empty()) return (nullptr);
  2130. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2131. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2132. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2133. BIO_free(pbPrivKey);
  2134. return (pPrivateKey);
  2135. }
  2136. TEST(BindServerTest, UpdateCerts) {
  2137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2138. int port = svr.bind_to_any_port("0.0.0.0");
  2139. ASSERT_TRUE(svr.is_valid());
  2140. ASSERT_TRUE(port > 0);
  2141. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2142. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2143. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2144. ASSERT_TRUE(cert != nullptr);
  2145. ASSERT_TRUE(ca_cert != nullptr);
  2146. ASSERT_TRUE(key != nullptr);
  2147. X509_STORE *cert_store = X509_STORE_new();
  2148. X509_STORE_add_cert(cert_store, ca_cert);
  2149. svr.update_certs(cert, key, cert_store);
  2150. ASSERT_TRUE(svr.is_valid());
  2151. svr.stop();
  2152. X509_free(cert);
  2153. X509_free(ca_cert);
  2154. EVP_PKEY_free(key);
  2155. }
  2156. #endif
  2157. TEST(ErrorHandlerTest, ContentLength) {
  2158. Server svr;
  2159. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2160. res.status = StatusCode::OK_200;
  2161. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2162. "text/html"); // <= Content-Length still 13
  2163. });
  2164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2165. res.set_content("Hello World!\n", "text/plain");
  2166. res.status = 524;
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. {
  2176. Client cli(HOST, PORT);
  2177. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(StatusCode::OK_200, res->status);
  2180. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2181. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2182. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2183. }
  2184. }
  2185. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2186. TEST(ExceptionTest, WithoutExceptionHandler) {
  2187. Server svr;
  2188. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception...");
  2190. });
  2191. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2192. throw std::runtime_error("exception\r\n...");
  2193. });
  2194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. listen_thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli("localhost", PORT);
  2202. {
  2203. auto res = cli.Get("/exception");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2206. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2207. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2208. }
  2209. {
  2210. auto res = cli.Get("/unknown");
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2213. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2214. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2215. }
  2216. }
  2217. TEST(ExceptionTest, WithExceptionHandler) {
  2218. Server svr;
  2219. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2220. std::exception_ptr ep) {
  2221. EXPECT_FALSE(ep == nullptr);
  2222. try {
  2223. std::rethrow_exception(ep);
  2224. } catch (std::exception &e) {
  2225. EXPECT_EQ("abc", std::string(e.what()));
  2226. } catch (...) {}
  2227. res.status = StatusCode::InternalServerError_500;
  2228. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2229. "text/html"); // <= Content-Length still 13 at this point
  2230. });
  2231. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2232. res.set_content("Hello World!\n", "text/plain");
  2233. throw std::runtime_error("abc");
  2234. });
  2235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2236. auto se = detail::scope_exit([&] {
  2237. svr.stop();
  2238. thread.join();
  2239. ASSERT_FALSE(svr.is_running());
  2240. });
  2241. svr.wait_until_ready();
  2242. for (size_t i = 0; i < 10; i++) {
  2243. Client cli(HOST, PORT);
  2244. for (size_t j = 0; j < 100; j++) {
  2245. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2246. ASSERT_TRUE(res);
  2247. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2248. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2249. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2251. }
  2252. cli.set_keep_alive(true);
  2253. for (size_t j = 0; j < 100; j++) {
  2254. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2255. ASSERT_TRUE(res);
  2256. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2257. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2258. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2259. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2260. }
  2261. }
  2262. }
  2263. TEST(ExceptionTest, AndErrorHandler) {
  2264. Server svr;
  2265. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2266. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2267. });
  2268. svr.set_exception_handler(
  2269. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2270. EXPECT_FALSE(ep == nullptr);
  2271. try {
  2272. std::rethrow_exception(ep);
  2273. } catch (std::exception &e) {
  2274. res.set_content(e.what(), "text/html");
  2275. } catch (...) {}
  2276. res.status = StatusCode::InternalServerError_500;
  2277. });
  2278. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2279. throw std::runtime_error("EXCEPTION");
  2280. });
  2281. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2282. res.set_content("ERROR", "text/html");
  2283. res.status = StatusCode::InternalServerError_500;
  2284. });
  2285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2286. auto se = detail::scope_exit([&] {
  2287. svr.stop();
  2288. thread.join();
  2289. ASSERT_FALSE(svr.is_running());
  2290. });
  2291. svr.wait_until_ready();
  2292. Client cli(HOST, PORT);
  2293. {
  2294. auto res = cli.Get("/exception");
  2295. ASSERT_TRUE(res);
  2296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2297. EXPECT_EQ("EXCEPTION", res->body);
  2298. }
  2299. {
  2300. auto res = cli.Get("/error");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2303. EXPECT_EQ("ERROR", res->body);
  2304. }
  2305. {
  2306. auto res = cli.Get("/invalid");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2309. EXPECT_EQ("NOT_FOUND", res->body);
  2310. }
  2311. }
  2312. #endif
  2313. TEST(NoContentTest, ContentLength) {
  2314. Server svr;
  2315. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2316. res.status = StatusCode::NoContent_204;
  2317. });
  2318. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2319. auto se = detail::scope_exit([&] {
  2320. svr.stop();
  2321. thread.join();
  2322. ASSERT_FALSE(svr.is_running());
  2323. });
  2324. svr.wait_until_ready();
  2325. {
  2326. Client cli(HOST, PORT);
  2327. auto res = cli.Get("/hi");
  2328. ASSERT_TRUE(res);
  2329. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2330. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2331. }
  2332. }
  2333. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2336. ASSERT_TRUE(svr.is_valid());
  2337. #else
  2338. Server svr;
  2339. #endif
  2340. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2341. if (req.path == "/routing_handler") {
  2342. res.set_header("PRE_ROUTING", "on");
  2343. res.set_content("Routing Handler", "text/plain");
  2344. return httplib::Server::HandlerResponse::Handled;
  2345. }
  2346. return httplib::Server::HandlerResponse::Unhandled;
  2347. });
  2348. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2349. res.set_content("Error", "text/html");
  2350. });
  2351. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2352. if (req.path == "/routing_handler") {
  2353. res.set_header("POST_ROUTING", "on");
  2354. }
  2355. });
  2356. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2357. res.set_content("Hello World!\n", "text/plain");
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. {
  2367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2368. SSLClient cli(HOST, PORT);
  2369. cli.enable_server_certificate_verification(false);
  2370. #else
  2371. Client cli(HOST, PORT);
  2372. #endif
  2373. auto res = cli.Get("/routing_handler");
  2374. ASSERT_TRUE(res);
  2375. EXPECT_EQ(StatusCode::OK_200, res->status);
  2376. EXPECT_EQ("Routing Handler", res->body);
  2377. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2378. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2379. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2380. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2381. }
  2382. {
  2383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2384. SSLClient cli(HOST, PORT);
  2385. cli.enable_server_certificate_verification(false);
  2386. #else
  2387. Client cli(HOST, PORT);
  2388. #endif
  2389. auto res = cli.Get("/hi");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. EXPECT_EQ("Hello World!\n", res->body);
  2393. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2394. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2395. }
  2396. {
  2397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2398. SSLClient cli(HOST, PORT);
  2399. cli.enable_server_certificate_verification(false);
  2400. #else
  2401. Client cli(HOST, PORT);
  2402. #endif
  2403. auto res = cli.Get("/aaa");
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2406. EXPECT_EQ("Error", res->body);
  2407. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2408. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2409. }
  2410. }
  2411. TEST(RequestHandlerTest, PreRequestHandler) {
  2412. auto route_path = "/user/:user";
  2413. Server svr;
  2414. svr.Get("/hi", [](const Request &, Response &res) {
  2415. res.set_content("hi", "text/plain");
  2416. });
  2417. svr.Get(route_path, [](const Request &req, Response &res) {
  2418. res.set_content(req.path_params.at("user"), "text/plain");
  2419. });
  2420. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2421. if (req.matched_route == route_path) {
  2422. auto user = req.path_params.at("user");
  2423. if (user != "john") {
  2424. res.status = StatusCode::Forbidden_403;
  2425. res.set_content("error", "text/html");
  2426. return Server::HandlerResponse::Handled;
  2427. }
  2428. }
  2429. return Server::HandlerResponse::Unhandled;
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. {
  2440. auto res = cli.Get("/hi");
  2441. ASSERT_TRUE(res);
  2442. EXPECT_EQ(StatusCode::OK_200, res->status);
  2443. EXPECT_EQ("hi", res->body);
  2444. }
  2445. {
  2446. auto res = cli.Get("/user/john");
  2447. ASSERT_TRUE(res);
  2448. EXPECT_EQ(StatusCode::OK_200, res->status);
  2449. EXPECT_EQ("john", res->body);
  2450. }
  2451. {
  2452. auto res = cli.Get("/user/invalid-user");
  2453. ASSERT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2455. EXPECT_EQ("error", res->body);
  2456. }
  2457. }
  2458. TEST(InvalidFormatTest, StatusCode) {
  2459. Server svr;
  2460. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2461. res.set_content("Hello World!\n", "text/plain");
  2462. res.status = 9999; // Status should be a three-digit code...
  2463. });
  2464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2465. auto se = detail::scope_exit([&] {
  2466. svr.stop();
  2467. thread.join();
  2468. ASSERT_FALSE(svr.is_running());
  2469. });
  2470. svr.wait_until_ready();
  2471. {
  2472. Client cli(HOST, PORT);
  2473. auto res = cli.Get("/hi");
  2474. ASSERT_FALSE(res);
  2475. }
  2476. }
  2477. TEST(URLFragmentTest, WithFragment) {
  2478. Server svr;
  2479. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2480. EXPECT_TRUE(req.target == "/hi");
  2481. });
  2482. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2483. auto se = detail::scope_exit([&] {
  2484. svr.stop();
  2485. thread.join();
  2486. ASSERT_FALSE(svr.is_running());
  2487. });
  2488. svr.wait_until_ready();
  2489. {
  2490. Client cli(HOST, PORT);
  2491. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2492. EXPECT_TRUE(res);
  2493. EXPECT_EQ(StatusCode::OK_200, res->status);
  2494. res = cli.Get("/hi%23key1=val1=key2=val2");
  2495. EXPECT_TRUE(res);
  2496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2497. }
  2498. }
  2499. TEST(HeaderWriter, SetHeaderWriter) {
  2500. Server svr;
  2501. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2502. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2503. return detail::write_headers(strm, hdrs);
  2504. });
  2505. svr.Get("/hi", [](const Request &req, Response &res) {
  2506. auto it = req.headers.find("CustomClientHeader");
  2507. EXPECT_TRUE(it != req.headers.end());
  2508. EXPECT_EQ(it->second, "CustomClientValue");
  2509. res.set_content("Hello World!\n", "text/plain");
  2510. });
  2511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2512. auto se = detail::scope_exit([&] {
  2513. svr.stop();
  2514. thread.join();
  2515. ASSERT_FALSE(svr.is_running());
  2516. });
  2517. svr.wait_until_ready();
  2518. {
  2519. Client cli(HOST, PORT);
  2520. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2521. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2522. return detail::write_headers(strm, hdrs);
  2523. });
  2524. auto res = cli.Get("/hi");
  2525. EXPECT_TRUE(res);
  2526. EXPECT_EQ(StatusCode::OK_200, res->status);
  2527. auto it = res->headers.find("CustomServerHeader");
  2528. EXPECT_TRUE(it != res->headers.end());
  2529. EXPECT_EQ(it->second, "CustomServerValue");
  2530. }
  2531. }
  2532. class ServerTest : public ::testing::Test {
  2533. protected:
  2534. ServerTest()
  2535. : cli_(HOST, PORT)
  2536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2537. ,
  2538. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2539. #endif
  2540. {
  2541. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2542. cli_.enable_server_certificate_verification(false);
  2543. #endif
  2544. }
  2545. virtual void SetUp() {
  2546. svr_.set_mount_point("/", "./www");
  2547. svr_.set_mount_point("/mount", "./www2");
  2548. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2549. svr_.Get("/hi",
  2550. [&](const Request & /*req*/, Response &res) {
  2551. res.set_content("Hello World!", "text/plain");
  2552. })
  2553. .Get("/file_content",
  2554. [&](const Request & /*req*/, Response &res) {
  2555. res.set_file_content("./www/dir/test.html");
  2556. })
  2557. .Get("/file_content_with_content_type",
  2558. [&](const Request & /*req*/, Response &res) {
  2559. res.set_file_content("./www/file", "text/plain");
  2560. })
  2561. .Get("/invalid_file_content",
  2562. [&](const Request & /*req*/, Response &res) {
  2563. res.set_file_content("./www/dir/invalid_file_path");
  2564. })
  2565. .Get("/http_response_splitting",
  2566. [&](const Request & /*req*/, Response &res) {
  2567. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2568. EXPECT_EQ(0U, res.headers.size());
  2569. EXPECT_FALSE(res.has_header("a"));
  2570. res.set_header("a", "1\nSet-Cookie: a=1");
  2571. EXPECT_EQ(0U, res.headers.size());
  2572. EXPECT_FALSE(res.has_header("a"));
  2573. res.set_header("a", "1\rSet-Cookie: a=1");
  2574. EXPECT_EQ(0U, res.headers.size());
  2575. EXPECT_FALSE(res.has_header("a"));
  2576. res.set_header("a\r\nb", "0");
  2577. EXPECT_EQ(0U, res.headers.size());
  2578. EXPECT_FALSE(res.has_header("a"));
  2579. res.set_header("a\rb", "0");
  2580. EXPECT_EQ(0U, res.headers.size());
  2581. EXPECT_FALSE(res.has_header("a"));
  2582. res.set_header("a\nb", "0");
  2583. EXPECT_EQ(0U, res.headers.size());
  2584. EXPECT_FALSE(res.has_header("a"));
  2585. res.set_redirect("1\r\nSet-Cookie: a=1");
  2586. EXPECT_EQ(0U, res.headers.size());
  2587. EXPECT_FALSE(res.has_header("Location"));
  2588. })
  2589. .Get("/slow",
  2590. [&](const Request & /*req*/, Response &res) {
  2591. std::this_thread::sleep_for(std::chrono::seconds(2));
  2592. res.set_content("slow", "text/plain");
  2593. })
  2594. #if 0
  2595. .Post("/slowpost",
  2596. [&](const Request & /*req*/, Response &res) {
  2597. std::this_thread::sleep_for(std::chrono::seconds(2));
  2598. res.set_content("slow", "text/plain");
  2599. })
  2600. #endif
  2601. .Get("/remote_addr",
  2602. [&](const Request &req, Response &res) {
  2603. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2604. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2605. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2606. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2607. res.set_content(req.remote_addr, "text/plain");
  2608. })
  2609. .Get("/local_addr",
  2610. [&](const Request &req, Response &res) {
  2611. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2612. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2613. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2614. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2615. auto local_addr = req.local_addr;
  2616. auto local_port = std::to_string(req.local_port);
  2617. res.set_content(local_addr.append(":").append(local_port),
  2618. "text/plain");
  2619. })
  2620. .Get("/endwith%",
  2621. [&](const Request & /*req*/, Response &res) {
  2622. res.set_content("Hello World!", "text/plain");
  2623. })
  2624. .Get("/a\\+\\+b",
  2625. [&](const Request &req, Response &res) {
  2626. ASSERT_TRUE(req.has_param("a +b"));
  2627. auto val = req.get_param_value("a +b");
  2628. res.set_content(val, "text/plain");
  2629. })
  2630. .Get("/", [&](const Request & /*req*/,
  2631. Response &res) { res.set_redirect("/hi"); })
  2632. .Post("/1",
  2633. [](const Request & /*req*/, Response &res) {
  2634. res.set_redirect("/2", StatusCode::SeeOther_303);
  2635. })
  2636. .Get("/2",
  2637. [](const Request & /*req*/, Response &res) {
  2638. res.set_content("redirected.", "text/plain");
  2639. res.status = StatusCode::OK_200;
  2640. })
  2641. .Post("/person",
  2642. [&](const Request &req, Response &res) {
  2643. if (req.has_param("name") && req.has_param("note")) {
  2644. persons_[req.get_param_value("name")] =
  2645. req.get_param_value("note");
  2646. } else {
  2647. res.status = StatusCode::BadRequest_400;
  2648. }
  2649. })
  2650. .Put("/person",
  2651. [&](const Request &req, Response &res) {
  2652. if (req.has_param("name") && req.has_param("note")) {
  2653. persons_[req.get_param_value("name")] =
  2654. req.get_param_value("note");
  2655. } else {
  2656. res.status = StatusCode::BadRequest_400;
  2657. }
  2658. })
  2659. .Get("/person/(.*)",
  2660. [&](const Request &req, Response &res) {
  2661. string name = req.matches[1];
  2662. if (persons_.find(name) != persons_.end()) {
  2663. auto note = persons_[name];
  2664. res.set_content(note, "text/plain");
  2665. } else {
  2666. res.status = StatusCode::NotFound_404;
  2667. }
  2668. })
  2669. .Delete("/person",
  2670. [&](const Request &req, Response &res) {
  2671. if (req.has_param("name")) {
  2672. string name = req.get_param_value("name");
  2673. if (persons_.find(name) != persons_.end()) {
  2674. persons_.erase(name);
  2675. res.set_content("DELETED", "text/plain");
  2676. } else {
  2677. res.status = StatusCode::NotFound_404;
  2678. }
  2679. } else {
  2680. res.status = StatusCode::BadRequest_400;
  2681. }
  2682. })
  2683. .Post("/x-www-form-urlencoded-json",
  2684. [&](const Request &req, Response &res) {
  2685. auto json = req.get_param_value("json");
  2686. ASSERT_EQ(JSON_DATA, json);
  2687. res.set_content(json, "appliation/json");
  2688. res.status = StatusCode::OK_200;
  2689. })
  2690. .Get("/streamed-chunked",
  2691. [&](const Request & /*req*/, Response &res) {
  2692. res.set_chunked_content_provider(
  2693. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2694. sink.os << "123";
  2695. sink.os << "456";
  2696. sink.os << "789";
  2697. sink.done();
  2698. return true;
  2699. });
  2700. })
  2701. .Get("/streamed-chunked-with-prohibited-trailer",
  2702. [&](const Request & /*req*/, Response &res) {
  2703. auto i = new int(0);
  2704. // Declare both a prohibited trailer (Content-Length) and an
  2705. // allowed one
  2706. res.set_header("Trailer", "Content-Length, X-Allowed");
  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. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  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-chunked2",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. auto i = new int(0);
  2730. res.set_chunked_content_provider(
  2731. "text/plain",
  2732. [i](size_t /*offset*/, DataSink &sink) {
  2733. switch (*i) {
  2734. case 0: sink.os << "123"; break;
  2735. case 1: sink.os << "456"; break;
  2736. case 2: sink.os << "789"; break;
  2737. case 3: sink.done(); break;
  2738. }
  2739. (*i)++;
  2740. return true;
  2741. },
  2742. [i](bool success) {
  2743. EXPECT_TRUE(success);
  2744. delete i;
  2745. });
  2746. })
  2747. .Get("/streamed-chunked-with-trailer",
  2748. [&](const Request & /*req*/, Response &res) {
  2749. auto i = new int(0);
  2750. res.set_header("Trailer", "Dummy1, Dummy2");
  2751. res.set_chunked_content_provider(
  2752. "text/plain",
  2753. [i](size_t /*offset*/, DataSink &sink) {
  2754. switch (*i) {
  2755. case 0: sink.os << "123"; break;
  2756. case 1: sink.os << "456"; break;
  2757. case 2: sink.os << "789"; break;
  2758. case 3: {
  2759. sink.done_with_trailer(
  2760. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2761. } break;
  2762. }
  2763. (*i)++;
  2764. return true;
  2765. },
  2766. [i](bool success) {
  2767. EXPECT_TRUE(success);
  2768. delete i;
  2769. });
  2770. })
  2771. .Get("/streamed",
  2772. [&](const Request & /*req*/, Response &res) {
  2773. res.set_content_provider(
  2774. 6, "text/plain",
  2775. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2776. sink.os << (offset < 3 ? "a" : "b");
  2777. return true;
  2778. });
  2779. })
  2780. .Get("/streamed-with-range",
  2781. [&](const Request &req, Response &res) {
  2782. auto data = new std::string("abcdefg");
  2783. res.set_content_provider(
  2784. data->size(), "text/plain",
  2785. [data](size_t offset, size_t length, DataSink &sink) {
  2786. size_t DATA_CHUNK_SIZE = 4;
  2787. const auto &d = *data;
  2788. auto out_len =
  2789. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2790. auto ret =
  2791. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2792. EXPECT_TRUE(ret);
  2793. return true;
  2794. },
  2795. [data, &req](bool success) {
  2796. EXPECT_EQ(success, !req.has_param("error"));
  2797. delete data;
  2798. });
  2799. })
  2800. .Get("/streamed-cancel",
  2801. [&](const Request & /*req*/, Response &res) {
  2802. res.set_content_provider(
  2803. size_t(-1), "text/plain",
  2804. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2805. sink.os << "data_chunk";
  2806. return true;
  2807. });
  2808. })
  2809. .Get("/regex-with-delimiter",
  2810. [&](const Request &req, Response & /*res*/) {
  2811. ASSERT_TRUE(req.has_param("key"));
  2812. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2813. })
  2814. .Get("/with-range",
  2815. [&](const Request & /*req*/, Response &res) {
  2816. res.set_content("abcdefg", "text/plain");
  2817. })
  2818. .Get("/test-start-time",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_NE(req.start_time_,
  2821. std::chrono::steady_clock::time_point::min());
  2822. })
  2823. .Get("/with-range-customized-response",
  2824. [&](const Request & /*req*/, Response &res) {
  2825. res.status = StatusCode::BadRequest_400;
  2826. res.set_content(JSON_DATA, "application/json");
  2827. })
  2828. .Post("/chunked",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(req.body, "dechunked post body");
  2831. })
  2832. .Post("/large-chunked",
  2833. [&](const Request &req, Response & /*res*/) {
  2834. std::string expected(6 * 30 * 1024u, 'a');
  2835. EXPECT_EQ(req.body, expected);
  2836. })
  2837. .Post("/multipart",
  2838. [&](const Request &req, Response & /*res*/) {
  2839. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2840. req.form.get_field_count("text2") +
  2841. req.form.get_field_count("file3") +
  2842. req.form.get_field_count("file4"));
  2843. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2844. req.form.get_file_count("file2"));
  2845. ASSERT_TRUE(!req.form.has_file("???"));
  2846. ASSERT_TRUE(!req.form.has_field("???"));
  2847. ASSERT_TRUE(req.body.empty());
  2848. {
  2849. const auto &text = req.form.get_field("text1");
  2850. EXPECT_EQ("text default", text);
  2851. }
  2852. {
  2853. const auto &text = req.form.get_field("text2");
  2854. EXPECT_EQ("aωb", text);
  2855. }
  2856. {
  2857. const auto &file = req.form.get_file("file1");
  2858. EXPECT_EQ("hello.txt", file.filename);
  2859. EXPECT_EQ("text/plain", file.content_type);
  2860. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2861. }
  2862. {
  2863. const auto &file = req.form.get_file("file2");
  2864. EXPECT_EQ("world.json", file.filename);
  2865. EXPECT_EQ("application/json", file.content_type);
  2866. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2867. }
  2868. {
  2869. const auto &text = req.form.get_field("file3");
  2870. EXPECT_EQ(0u, text.size());
  2871. }
  2872. {
  2873. const auto &text = req.form.get_field("file4");
  2874. EXPECT_EQ(0u, text.size());
  2875. }
  2876. })
  2877. .Post("/multipart/multi_file_values",
  2878. [&](const Request &req, Response & /*res*/) {
  2879. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2880. req.form.get_field_count("multi_text1"));
  2881. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2882. ASSERT_TRUE(!req.form.has_file("???"));
  2883. ASSERT_TRUE(!req.form.has_field("???"));
  2884. ASSERT_TRUE(req.body.empty());
  2885. {
  2886. const auto &text = req.form.get_field("text");
  2887. EXPECT_EQ("default text", text);
  2888. }
  2889. {
  2890. const auto &text1_values = req.form.get_fields("multi_text1");
  2891. EXPECT_EQ(2u, text1_values.size());
  2892. EXPECT_EQ("aaaaa", text1_values[0]);
  2893. EXPECT_EQ("bbbbb", text1_values[1]);
  2894. }
  2895. {
  2896. const auto &file1_values = req.form.get_files("multi_file1");
  2897. EXPECT_EQ(2u, file1_values.size());
  2898. auto file1 = file1_values[0];
  2899. EXPECT_EQ(file1.filename, "hello.txt");
  2900. EXPECT_EQ(file1.content_type, "text/plain");
  2901. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2902. auto file2 = file1_values[1];
  2903. EXPECT_EQ(file2.filename, "world.json");
  2904. EXPECT_EQ(file2.content_type, "application/json");
  2905. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2906. }
  2907. })
  2908. .Post("/empty",
  2909. [&](const Request &req, Response &res) {
  2910. EXPECT_EQ(req.body, "");
  2911. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2912. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2913. res.set_content("empty", "text/plain");
  2914. })
  2915. .Post("/empty-no-content-type",
  2916. [&](const Request &req, Response &res) {
  2917. EXPECT_EQ(req.body, "");
  2918. EXPECT_FALSE(req.has_header("Content-Type"));
  2919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2920. res.set_content("empty-no-content-type", "text/plain");
  2921. })
  2922. .Post("/path-only",
  2923. [&](const Request &req, Response &res) {
  2924. EXPECT_EQ(req.body, "");
  2925. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2926. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2927. res.set_content("path-only", "text/plain");
  2928. })
  2929. .Post("/path-headers-only",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "");
  2932. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2934. EXPECT_EQ("world", req.get_header_value("hello"));
  2935. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2936. res.set_content("path-headers-only", "text/plain");
  2937. })
  2938. .Post("/post-large",
  2939. [&](const Request &req, Response &res) {
  2940. EXPECT_EQ(req.body, LARGE_DATA);
  2941. res.set_content(req.body, "text/plain");
  2942. })
  2943. .Post("/post-loopback",
  2944. [&](const Request &, Response &res,
  2945. ContentReader const &content_reader) {
  2946. std::string body;
  2947. content_reader([&](const char *data, size_t data_length) {
  2948. body.append(data, data_length);
  2949. return true;
  2950. });
  2951. res.set_content(body, "text/plain");
  2952. })
  2953. .Put("/put-loopback",
  2954. [&](const Request &, Response &res,
  2955. ContentReader const &content_reader) {
  2956. std::string body;
  2957. content_reader([&](const char *data, size_t data_length) {
  2958. body.append(data, data_length);
  2959. return true;
  2960. });
  2961. res.set_content(body, "text/plain");
  2962. })
  2963. .Patch("/patch-loopback",
  2964. [&](const Request &, Response &res,
  2965. ContentReader const &content_reader) {
  2966. std::string body;
  2967. content_reader([&](const char *data, size_t data_length) {
  2968. body.append(data, data_length);
  2969. return true;
  2970. });
  2971. res.set_content(body, "text/plain");
  2972. })
  2973. .Put("/empty-no-content-type",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(req.body, "");
  2976. EXPECT_FALSE(req.has_header("Content-Type"));
  2977. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2978. res.set_content("empty-no-content-type", "text/plain");
  2979. })
  2980. .Put("/put",
  2981. [&](const Request &req, Response &res) {
  2982. EXPECT_EQ(req.body, "PUT");
  2983. res.set_content(req.body, "text/plain");
  2984. })
  2985. .Put("/put-large",
  2986. [&](const Request &req, Response &res) {
  2987. EXPECT_EQ(req.body, LARGE_DATA);
  2988. res.set_content(req.body, "text/plain");
  2989. })
  2990. .Patch("/patch",
  2991. [&](const Request &req, Response &res) {
  2992. EXPECT_EQ(req.body, "PATCH");
  2993. res.set_content(req.body, "text/plain");
  2994. })
  2995. .Delete("/delete",
  2996. [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("DELETE", "text/plain");
  2998. })
  2999. .Delete("/delete-body",
  3000. [&](const Request &req, Response &res) {
  3001. EXPECT_EQ(req.body, "content");
  3002. res.set_content(req.body, "text/plain");
  3003. })
  3004. .Options(R"(\*)",
  3005. [&](const Request & /*req*/, Response &res) {
  3006. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3007. })
  3008. .Get("/request-target",
  3009. [&](const Request &req, Response & /*res*/) {
  3010. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3011. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3012. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3013. })
  3014. .Get("/long-query-value",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3017. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3018. })
  3019. .Get("/too-long-query-value",
  3020. [&](const Request &req, Response & /*res*/) {
  3021. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3022. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3023. })
  3024. .Get("/array-param",
  3025. [&](const Request &req, Response & /*res*/) {
  3026. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3027. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3028. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3029. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3030. })
  3031. .Post("/validate-no-multiple-headers",
  3032. [&](const Request &req, Response & /*res*/) {
  3033. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3034. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3035. })
  3036. .Post("/content_receiver",
  3037. [&](const Request &req, Response &res,
  3038. const ContentReader &content_reader) {
  3039. if (req.is_multipart_form_data()) {
  3040. std::vector<FormData> items;
  3041. content_reader(
  3042. [&](const FormData &file) {
  3043. items.push_back(file);
  3044. return true;
  3045. },
  3046. [&](const char *data, size_t data_length) {
  3047. items.back().content.append(data, data_length);
  3048. return true;
  3049. });
  3050. EXPECT_EQ(5u, items.size());
  3051. {
  3052. const auto &file = get_file_value(items, "text1");
  3053. EXPECT_TRUE(file.filename.empty());
  3054. EXPECT_EQ("text default", file.content);
  3055. }
  3056. {
  3057. const auto &file = get_file_value(items, "text2");
  3058. EXPECT_TRUE(file.filename.empty());
  3059. EXPECT_EQ("aωb", file.content);
  3060. }
  3061. {
  3062. const auto &file = get_file_value(items, "file1");
  3063. EXPECT_EQ("hello.txt", file.filename);
  3064. EXPECT_EQ("text/plain", file.content_type);
  3065. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3066. }
  3067. {
  3068. const auto &file = get_file_value(items, "file2");
  3069. EXPECT_EQ("world.json", file.filename);
  3070. EXPECT_EQ("application/json", file.content_type);
  3071. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3072. }
  3073. {
  3074. const auto &file = get_file_value(items, "file3");
  3075. EXPECT_TRUE(file.filename.empty());
  3076. EXPECT_EQ("application/octet-stream", file.content_type);
  3077. EXPECT_EQ(0u, file.content.size());
  3078. }
  3079. } else {
  3080. std::string body;
  3081. content_reader([&](const char *data, size_t data_length) {
  3082. EXPECT_EQ(7U, data_length);
  3083. body.append(data, data_length);
  3084. return true;
  3085. });
  3086. EXPECT_EQ(body, "content");
  3087. res.set_content(body, "text/plain");
  3088. }
  3089. })
  3090. .Put("/content_receiver",
  3091. [&](const Request & /*req*/, Response &res,
  3092. const ContentReader &content_reader) {
  3093. std::string body;
  3094. content_reader([&](const char *data, size_t data_length) {
  3095. body.append(data, data_length);
  3096. return true;
  3097. });
  3098. EXPECT_EQ(body, "content");
  3099. res.set_content(body, "text/plain");
  3100. })
  3101. .Patch("/content_receiver",
  3102. [&](const Request & /*req*/, Response &res,
  3103. const ContentReader &content_reader) {
  3104. std::string body;
  3105. content_reader([&](const char *data, size_t data_length) {
  3106. body.append(data, data_length);
  3107. return true;
  3108. });
  3109. EXPECT_EQ(body, "content");
  3110. res.set_content(body, "text/plain");
  3111. })
  3112. .Post("/query-string-and-body",
  3113. [&](const Request &req, Response & /*res*/) {
  3114. ASSERT_TRUE(req.has_param("key"));
  3115. EXPECT_EQ(req.get_param_value("key"), "value");
  3116. EXPECT_EQ(req.body, "content");
  3117. })
  3118. .Get("/last-request",
  3119. [&](const Request &req, Response & /*res*/) {
  3120. EXPECT_EQ("close", req.get_header_value("Connection"));
  3121. })
  3122. .Get(R"(/redirect/(\d+))",
  3123. [&](const Request &req, Response &res) {
  3124. auto num = std::stoi(req.matches[1]) + 1;
  3125. std::string url = "/redirect/" + std::to_string(num);
  3126. res.set_redirect(url);
  3127. })
  3128. .Post("/binary",
  3129. [&](const Request &req, Response &res) {
  3130. EXPECT_EQ(4U, req.body.size());
  3131. EXPECT_EQ("application/octet-stream",
  3132. req.get_header_value("Content-Type"));
  3133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3134. res.set_content(req.body, "application/octet-stream");
  3135. })
  3136. .Put("/binary",
  3137. [&](const Request &req, Response &res) {
  3138. EXPECT_EQ(4U, req.body.size());
  3139. EXPECT_EQ("application/octet-stream",
  3140. req.get_header_value("Content-Type"));
  3141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3142. res.set_content(req.body, "application/octet-stream");
  3143. })
  3144. .Patch("/binary",
  3145. [&](const Request &req, Response &res) {
  3146. EXPECT_EQ(4U, req.body.size());
  3147. EXPECT_EQ("application/octet-stream",
  3148. req.get_header_value("Content-Type"));
  3149. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3150. res.set_content(req.body, "application/octet-stream");
  3151. })
  3152. .Delete("/binary",
  3153. [&](const Request &req, Response &res) {
  3154. EXPECT_EQ(4U, req.body.size());
  3155. EXPECT_EQ("application/octet-stream",
  3156. req.get_header_value("Content-Type"));
  3157. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3158. res.set_content(req.body, "application/octet-stream");
  3159. })
  3160. .Get("/issue1772",
  3161. [&](const Request & /*req*/, Response &res) {
  3162. res.status = 401;
  3163. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3164. })
  3165. .Delete("/issue609",
  3166. [](const httplib::Request &, httplib::Response &res,
  3167. const httplib::ContentReader &) {
  3168. res.set_content("ok", "text/plain");
  3169. })
  3170. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3171. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3172. .Get("/compress",
  3173. [&](const Request & /*req*/, Response &res) {
  3174. res.set_content(
  3175. "12345678901234567890123456789012345678901234567890123456789"
  3176. "01234567890123456789012345678901234567890",
  3177. "text/plain");
  3178. })
  3179. .Get("/nocompress",
  3180. [&](const Request & /*req*/, Response &res) {
  3181. res.set_content(
  3182. "12345678901234567890123456789012345678901234567890123456789"
  3183. "01234567890123456789012345678901234567890",
  3184. "application/octet-stream");
  3185. })
  3186. .Post("/compress-multipart",
  3187. [&](const Request &req, Response & /*res*/) {
  3188. EXPECT_EQ(2u, req.form.fields.size());
  3189. ASSERT_TRUE(!req.form.has_field("???"));
  3190. {
  3191. const auto &text = req.form.get_field("key1");
  3192. EXPECT_EQ("test", text);
  3193. }
  3194. {
  3195. const auto &text = req.form.get_field("key2");
  3196. EXPECT_EQ("--abcdefg123", text);
  3197. }
  3198. })
  3199. #endif
  3200. ;
  3201. persons_["john"] = "programmer";
  3202. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3203. svr_.wait_until_ready();
  3204. }
  3205. virtual void TearDown() {
  3206. svr_.stop();
  3207. if (!request_threads_.empty()) {
  3208. std::this_thread::sleep_for(std::chrono::seconds(1));
  3209. for (auto &t : request_threads_) {
  3210. t.join();
  3211. }
  3212. }
  3213. t_.join();
  3214. }
  3215. map<string, string> persons_;
  3216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3217. SSLClient cli_;
  3218. SSLServer svr_;
  3219. #else
  3220. Client cli_;
  3221. Server svr_;
  3222. #endif
  3223. thread t_;
  3224. std::vector<thread> request_threads_;
  3225. };
  3226. TEST_F(ServerTest, GetMethod200) {
  3227. auto res = cli_.Get("/hi");
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ("HTTP/1.1", res->version);
  3230. EXPECT_EQ(StatusCode::OK_200, res->status);
  3231. EXPECT_EQ("OK", res->reason);
  3232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3233. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3234. EXPECT_EQ("Hello World!", res->body);
  3235. }
  3236. TEST_F(ServerTest, GetEmptyFile) {
  3237. auto res = cli_.Get("/empty_file");
  3238. ASSERT_TRUE(res);
  3239. EXPECT_EQ(StatusCode::OK_200, res->status);
  3240. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3241. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3242. EXPECT_EQ("", res->body);
  3243. }
  3244. TEST_F(ServerTest, GetFileContent) {
  3245. auto res = cli_.Get("/file_content");
  3246. ASSERT_TRUE(res);
  3247. EXPECT_EQ(StatusCode::OK_200, res->status);
  3248. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3249. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3250. EXPECT_EQ("test.html", res->body);
  3251. }
  3252. TEST_F(ServerTest, GetFileContentWithRange) {
  3253. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3254. ASSERT_TRUE(res);
  3255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3256. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3257. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3258. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3259. EXPECT_EQ("est", res->body);
  3260. }
  3261. TEST_F(ServerTest, GetFileContentWithContentType) {
  3262. auto res = cli_.Get("/file_content_with_content_type");
  3263. ASSERT_TRUE(res);
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3266. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3267. EXPECT_EQ("file\n", res->body);
  3268. }
  3269. TEST_F(ServerTest, GetInvalidFileContent) {
  3270. auto res = cli_.Get("/invalid_file_content");
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3273. }
  3274. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3275. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3276. ASSERT_TRUE(res);
  3277. EXPECT_EQ("HTTP/1.1", res->version);
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3280. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3281. EXPECT_EQ("Hello World!", res->body);
  3282. }
  3283. TEST_F(ServerTest, GetMethod302) {
  3284. auto res = cli_.Get("/");
  3285. ASSERT_TRUE(res);
  3286. EXPECT_EQ(StatusCode::Found_302, res->status);
  3287. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3288. }
  3289. TEST_F(ServerTest, GetMethod302Redirect) {
  3290. cli_.set_follow_location(true);
  3291. auto res = cli_.Get("/");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ("Hello World!", res->body);
  3295. EXPECT_EQ("/hi", res->location);
  3296. }
  3297. TEST_F(ServerTest, GetMethod404) {
  3298. auto res = cli_.Get("/invalid");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3301. }
  3302. TEST_F(ServerTest, HeadMethod200) {
  3303. auto res = cli_.Head("/hi");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ(StatusCode::OK_200, res->status);
  3306. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3307. EXPECT_TRUE(res->body.empty());
  3308. }
  3309. TEST_F(ServerTest, HeadMethod200Static) {
  3310. auto res = cli_.Head("/mount/dir/index.html");
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(StatusCode::OK_200, res->status);
  3313. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3314. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3315. EXPECT_TRUE(res->body.empty());
  3316. }
  3317. TEST_F(ServerTest, HeadMethod404) {
  3318. auto res = cli_.Head("/invalid");
  3319. ASSERT_TRUE(res);
  3320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3321. EXPECT_TRUE(res->body.empty());
  3322. }
  3323. TEST_F(ServerTest, GetMethodPersonJohn) {
  3324. auto res = cli_.Get("/person/john");
  3325. ASSERT_TRUE(res);
  3326. EXPECT_EQ(StatusCode::OK_200, res->status);
  3327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3328. EXPECT_EQ("programmer", res->body);
  3329. }
  3330. TEST_F(ServerTest, PostMethod1) {
  3331. auto res = cli_.Get("/person/john1");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3334. res = cli_.Post("/person", "name=john1&note=coder",
  3335. "application/x-www-form-urlencoded");
  3336. ASSERT_TRUE(res);
  3337. ASSERT_EQ(StatusCode::OK_200, res->status);
  3338. res = cli_.Get("/person/john1");
  3339. ASSERT_TRUE(res);
  3340. ASSERT_EQ(StatusCode::OK_200, res->status);
  3341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3342. ASSERT_EQ("coder", res->body);
  3343. }
  3344. TEST_F(ServerTest, PostMethod2) {
  3345. auto res = cli_.Get("/person/john2");
  3346. ASSERT_TRUE(res);
  3347. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3348. Params params;
  3349. params.emplace("name", "john2");
  3350. params.emplace("note", "coder");
  3351. res = cli_.Post("/person", params);
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. res = cli_.Get("/person/john2");
  3355. ASSERT_TRUE(res);
  3356. ASSERT_EQ(StatusCode::OK_200, res->status);
  3357. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3358. ASSERT_EQ("coder", res->body);
  3359. }
  3360. TEST_F(ServerTest, PutMethod3) {
  3361. auto res = cli_.Get("/person/john3");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3364. Params params;
  3365. params.emplace("name", "john3");
  3366. params.emplace("note", "coder");
  3367. res = cli_.Put("/person", params);
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. res = cli_.Get("/person/john3");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::OK_200, res->status);
  3373. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3374. ASSERT_EQ("coder", res->body);
  3375. }
  3376. TEST_F(ServerTest, DeleteMethod1) {
  3377. auto res = cli_.Get("/person/john4");
  3378. ASSERT_TRUE(res);
  3379. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3380. Params params;
  3381. params.emplace("name", "john4");
  3382. params.emplace("note", "coder");
  3383. res = cli_.Post("/person", params);
  3384. ASSERT_TRUE(res);
  3385. ASSERT_EQ(StatusCode::OK_200, res->status);
  3386. res = cli_.Get("/person/john4");
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::OK_200, res->status);
  3389. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3390. ASSERT_EQ("coder", res->body);
  3391. Params delete_params;
  3392. delete_params.emplace("name", "john4");
  3393. res = cli_.Delete("/person", delete_params);
  3394. ASSERT_TRUE(res);
  3395. ASSERT_EQ(StatusCode::OK_200, res->status);
  3396. ASSERT_EQ("DELETED", res->body);
  3397. res = cli_.Get("/person/john4");
  3398. ASSERT_TRUE(res);
  3399. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3400. }
  3401. TEST_F(ServerTest, DeleteMethod2) {
  3402. auto res = cli_.Get("/person/john5");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3405. Params params;
  3406. params.emplace("name", "john5");
  3407. params.emplace("note", "developer");
  3408. res = cli_.Post("/person", params);
  3409. ASSERT_TRUE(res);
  3410. ASSERT_EQ(StatusCode::OK_200, res->status);
  3411. res = cli_.Get("/person/john5");
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3415. ASSERT_EQ("developer", res->body);
  3416. Params delete_params;
  3417. delete_params.emplace("name", "john5");
  3418. Headers headers;
  3419. headers.emplace("Custom-Header", "test-value");
  3420. res = cli_.Delete("/person", headers, delete_params);
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::OK_200, res->status);
  3423. ASSERT_EQ("DELETED", res->body);
  3424. res = cli_.Get("/person/john5");
  3425. ASSERT_TRUE(res);
  3426. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3427. }
  3428. TEST_F(ServerTest, DeleteMethod3) {
  3429. auto res = cli_.Get("/person/john6");
  3430. ASSERT_TRUE(res);
  3431. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3432. Params params;
  3433. params.emplace("name", "john6");
  3434. params.emplace("note", "tester");
  3435. res = cli_.Post("/person", params);
  3436. ASSERT_TRUE(res);
  3437. ASSERT_EQ(StatusCode::OK_200, res->status);
  3438. res = cli_.Get("/person/john6");
  3439. ASSERT_TRUE(res);
  3440. ASSERT_EQ(StatusCode::OK_200, res->status);
  3441. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3442. ASSERT_EQ("tester", res->body);
  3443. Params delete_params;
  3444. delete_params.emplace("name", "john6");
  3445. Headers headers;
  3446. headers.emplace("Custom-Header", "test-value");
  3447. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3448. ASSERT_TRUE(res);
  3449. ASSERT_EQ(StatusCode::OK_200, res->status);
  3450. ASSERT_EQ("DELETED", res->body);
  3451. res = cli_.Get("/person/john6");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3454. }
  3455. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3456. Params params;
  3457. params.emplace("json", JSON_DATA);
  3458. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3459. ASSERT_TRUE(res);
  3460. ASSERT_EQ(StatusCode::OK_200, res->status);
  3461. ASSERT_EQ(JSON_DATA, res->body);
  3462. }
  3463. TEST_F(ServerTest, PostEmptyContent) {
  3464. auto res = cli_.Post("/empty", "", "text/plain");
  3465. ASSERT_TRUE(res);
  3466. ASSERT_EQ(StatusCode::OK_200, res->status);
  3467. ASSERT_EQ("empty", res->body);
  3468. }
  3469. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3470. auto res = cli_.Post("/empty-no-content-type");
  3471. ASSERT_TRUE(res);
  3472. ASSERT_EQ(StatusCode::OK_200, res->status);
  3473. ASSERT_EQ("empty-no-content-type", res->body);
  3474. }
  3475. TEST_F(ServerTest, PostPathOnly) {
  3476. auto res = cli_.Post("/path-only");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::OK_200, res->status);
  3479. ASSERT_EQ("path-only", res->body);
  3480. }
  3481. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3482. auto res = cli_.Post("/path-headers-only",
  3483. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3484. ASSERT_TRUE(res);
  3485. ASSERT_EQ(StatusCode::OK_200, res->status);
  3486. ASSERT_EQ("path-headers-only", res->body);
  3487. }
  3488. TEST_F(ServerTest, PostLarge) {
  3489. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3490. ASSERT_TRUE(res);
  3491. ASSERT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ(LARGE_DATA, res->body);
  3493. }
  3494. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3495. auto res = cli_.Put("/empty-no-content-type");
  3496. ASSERT_TRUE(res);
  3497. ASSERT_EQ(StatusCode::OK_200, res->status);
  3498. ASSERT_EQ("empty-no-content-type", res->body);
  3499. }
  3500. TEST_F(ServerTest, GetMethodDir) {
  3501. auto res = cli_.Get("/dir/");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3505. auto body = R"(<html>
  3506. <head>
  3507. </head>
  3508. <body>
  3509. <a href="/dir/test.html">Test</a>
  3510. <a href="/hi">hi</a>
  3511. </body>
  3512. </html>
  3513. )";
  3514. EXPECT_EQ(body, res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDirTest) {
  3517. auto res = cli_.Get("/dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("test.html", res->body);
  3522. }
  3523. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3524. auto res = cli_.Get("/dir/../dir/test.html");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::OK_200, res->status);
  3527. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3528. EXPECT_EQ("test.html", res->body);
  3529. }
  3530. TEST_F(ServerTest, GetMethodInvalidPath) {
  3531. auto res = cli_.Get("/dir/../test.html");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3534. }
  3535. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3536. auto res = cli_.Get("/../www/dir/test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3541. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3544. }
  3545. TEST_F(ServerTest, GetMethodDirMountTest) {
  3546. auto res = cli_.Get("/mount/dir/test.html");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::OK_200, res->status);
  3549. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3550. EXPECT_EQ("test.html", res->body);
  3551. }
  3552. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3553. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3554. ASSERT_TRUE(res);
  3555. EXPECT_EQ(StatusCode::OK_200, res->status);
  3556. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3557. EXPECT_EQ("test.html", res->body);
  3558. }
  3559. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3560. auto res = cli_.Get("/mount/dir/../test.html");
  3561. ASSERT_TRUE(res);
  3562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3563. }
  3564. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3565. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3568. }
  3569. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3570. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3575. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3576. ASSERT_TRUE(res);
  3577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3578. }
  3579. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3580. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3583. }
  3584. TEST_F(ServerTest, PostMethod303) {
  3585. auto res = cli_.Post("/1", "body", "text/plain");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3588. EXPECT_EQ("/2", res->get_header_value("Location"));
  3589. }
  3590. TEST_F(ServerTest, PostMethod303Redirect) {
  3591. cli_.set_follow_location(true);
  3592. auto res = cli_.Post("/1", "body", "text/plain");
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. EXPECT_EQ("redirected.", res->body);
  3596. EXPECT_EQ("/2", res->location);
  3597. }
  3598. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3599. auto res = cli_.Get("/dir/test.abcde");
  3600. ASSERT_TRUE(res);
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3603. EXPECT_EQ("abcde", res->body);
  3604. }
  3605. TEST_F(ServerTest, StaticFileRange) {
  3606. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3607. ASSERT_TRUE(res);
  3608. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3609. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3610. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3611. EXPECT_EQ(true, res->has_header("Content-Range"));
  3612. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3613. EXPECT_EQ(std::string("cd"), res->body);
  3614. }
  3615. TEST_F(ServerTest, StaticFileRanges) {
  3616. auto res =
  3617. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3618. ASSERT_TRUE(res);
  3619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3620. EXPECT_TRUE(
  3621. res->get_header_value("Content-Type")
  3622. .find(
  3623. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3624. 0);
  3625. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3626. }
  3627. TEST_F(ServerTest, StaticFileRangeHead) {
  3628. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3629. ASSERT_TRUE(res);
  3630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3631. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3632. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3633. EXPECT_EQ(true, res->has_header("Content-Range"));
  3634. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3635. }
  3636. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3637. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3641. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3642. EXPECT_EQ(true, res->has_header("Content-Range"));
  3643. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3644. res->get_header_value("Content-Range"));
  3645. EXPECT_EQ("LAST\n", res->body);
  3646. }
  3647. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3648. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3649. ASSERT_TRUE(res);
  3650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3652. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3653. EXPECT_EQ(true, res->has_header("Content-Range"));
  3654. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3655. }
  3656. TEST_F(ServerTest, StaticFileBigFile) {
  3657. auto res = cli_.Get("/dir/1MB.txt");
  3658. ASSERT_TRUE(res);
  3659. EXPECT_EQ(StatusCode::OK_200, res->status);
  3660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3661. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3662. }
  3663. TEST_F(ServerTest, InvalidBaseDirMount) {
  3664. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3665. }
  3666. TEST_F(ServerTest, Binary) {
  3667. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3668. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3669. "application/octet-stream");
  3670. ASSERT_TRUE(res);
  3671. ASSERT_EQ(StatusCode::OK_200, res->status);
  3672. ASSERT_EQ(4U, res->body.size());
  3673. res = cli_.Put("/binary", binary.data(), binary.size(),
  3674. "application/octet-stream");
  3675. ASSERT_TRUE(res);
  3676. ASSERT_EQ(StatusCode::OK_200, res->status);
  3677. ASSERT_EQ(4U, res->body.size());
  3678. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3679. "application/octet-stream");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ(4U, res->body.size());
  3683. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3684. "application/octet-stream");
  3685. ASSERT_TRUE(res);
  3686. ASSERT_EQ(StatusCode::OK_200, res->status);
  3687. ASSERT_EQ(4U, res->body.size());
  3688. }
  3689. TEST_F(ServerTest, BinaryString) {
  3690. auto binary = std::string("\x00\x01\x02\x03", 4);
  3691. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ(4U, res->body.size());
  3695. res = cli_.Put("/binary", binary, "application/octet-stream");
  3696. ASSERT_TRUE(res);
  3697. ASSERT_EQ(StatusCode::OK_200, res->status);
  3698. ASSERT_EQ(4U, res->body.size());
  3699. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3700. ASSERT_TRUE(res);
  3701. ASSERT_EQ(StatusCode::OK_200, res->status);
  3702. ASSERT_EQ(4U, res->body.size());
  3703. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3704. ASSERT_TRUE(res);
  3705. ASSERT_EQ(StatusCode::OK_200, res->status);
  3706. ASSERT_EQ(4U, res->body.size());
  3707. }
  3708. TEST_F(ServerTest, EmptyRequest) {
  3709. auto res = cli_.Get("");
  3710. ASSERT_TRUE(!res);
  3711. EXPECT_EQ(Error::Connection, res.error());
  3712. }
  3713. TEST_F(ServerTest, LongRequest) {
  3714. std::string request;
  3715. for (size_t i = 0; i < 545; i++) {
  3716. request += "/TooLongRequest";
  3717. }
  3718. request += "OK";
  3719. auto res = cli_.Get(request.c_str());
  3720. ASSERT_TRUE(res);
  3721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3722. }
  3723. TEST_F(ServerTest, TooLongRequest) {
  3724. std::string request;
  3725. for (size_t i = 0; i < 546; i++) {
  3726. request += "/TooLongRequest";
  3727. }
  3728. request += "_NG";
  3729. auto start = std::chrono::high_resolution_clock::now();
  3730. cli_.set_keep_alive(true);
  3731. auto res = cli_.Get(request.c_str());
  3732. auto end = std::chrono::high_resolution_clock::now();
  3733. auto elapsed =
  3734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3735. .count();
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3738. EXPECT_LE(elapsed, 100);
  3739. EXPECT_EQ("close", res->get_header_value("Connection"));
  3740. EXPECT_FALSE(cli_.is_socket_open());
  3741. }
  3742. TEST_F(ServerTest, AlmostTooLongRequest) {
  3743. // test for #2046 - URI length check shouldn't include other content on req
  3744. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3745. // leading /, space, HTTP/1.1)
  3746. std::string request =
  3747. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3748. auto res = cli_.Get(request.c_str());
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, LongHeader) {
  3753. Request req;
  3754. req.method = "GET";
  3755. req.path = "/hi";
  3756. std::string host_and_port;
  3757. host_and_port += HOST;
  3758. host_and_port += ":";
  3759. host_and_port += std::to_string(PORT);
  3760. req.headers.emplace("Host", host_and_port.c_str());
  3761. req.headers.emplace("Accept", "*/*");
  3762. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3763. req.headers.emplace(
  3764. "Header-Name",
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@");
  3794. auto res = std::make_shared<Response>();
  3795. auto error = Error::Success;
  3796. auto ret = cli_.send(req, *res, error);
  3797. ASSERT_TRUE(ret);
  3798. EXPECT_EQ(StatusCode::OK_200, res->status);
  3799. }
  3800. TEST_F(ServerTest, LongQueryValue) {
  3801. auto start = std::chrono::high_resolution_clock::now();
  3802. cli_.set_keep_alive(true);
  3803. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3804. auto end = std::chrono::high_resolution_clock::now();
  3805. auto elapsed =
  3806. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3807. .count();
  3808. ASSERT_TRUE(res);
  3809. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3810. EXPECT_LE(elapsed, 100);
  3811. EXPECT_EQ("close", res->get_header_value("Connection"));
  3812. EXPECT_FALSE(cli_.is_socket_open());
  3813. }
  3814. TEST_F(ServerTest, TooLongQueryValue) {
  3815. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3816. ASSERT_FALSE(res);
  3817. EXPECT_EQ(Error::Read, res.error());
  3818. }
  3819. TEST_F(ServerTest, TooLongHeader) {
  3820. Request req;
  3821. req.method = "GET";
  3822. req.path = "/hi";
  3823. std::string host_and_port;
  3824. host_and_port += HOST;
  3825. host_and_port += ":";
  3826. host_and_port += std::to_string(PORT);
  3827. req.headers.emplace("Host", host_and_port.c_str());
  3828. req.headers.emplace("Accept", "*/*");
  3829. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3830. req.headers.emplace(
  3831. "Header-Name",
  3832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@");
  3861. auto res = std::make_shared<Response>();
  3862. auto error = Error::Success;
  3863. auto ret = cli_.send(req, *res, error);
  3864. ASSERT_TRUE(ret);
  3865. EXPECT_EQ(StatusCode::OK_200, res->status);
  3866. }
  3867. TEST_F(ServerTest, HeaderCountAtLimit) {
  3868. // Test with headers just under the 100 limit
  3869. httplib::Headers headers;
  3870. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3871. // This should keep us just under the 100 header limit
  3872. for (int i = 0; i < 95; i++) {
  3873. std::string name = "X-Test-Header-" + std::to_string(i);
  3874. std::string value = "value" + std::to_string(i);
  3875. headers.emplace(name, value);
  3876. }
  3877. // This should work fine as we're under the limit
  3878. auto res = cli_.Get("/hi", headers);
  3879. EXPECT_TRUE(res);
  3880. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3881. }
  3882. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3883. // Test with many headers to exceed the 100 limit
  3884. httplib::Headers headers;
  3885. // Add 150 headers to definitely exceed the 100 limit
  3886. for (int i = 0; i < 150; i++) {
  3887. std::string name = "X-Test-Header-" + std::to_string(i);
  3888. std::string value = "value" + std::to_string(i);
  3889. headers.emplace(name, value);
  3890. }
  3891. // This should fail due to exceeding header count limit
  3892. cli_.set_keep_alive(true);
  3893. auto res = cli_.Get("/hi", headers);
  3894. // The request should either fail or return 400 Bad Request
  3895. if (res) {
  3896. // If we get a response, it should be 400 Bad Request
  3897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3898. } else {
  3899. // Or the request should fail entirely
  3900. EXPECT_FALSE(res);
  3901. }
  3902. EXPECT_EQ("close", res->get_header_value("Connection"));
  3903. EXPECT_FALSE(cli_.is_socket_open());
  3904. }
  3905. TEST_F(ServerTest, PercentEncoding) {
  3906. auto res = cli_.Get("/e%6edwith%");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::OK_200, res->status);
  3909. }
  3910. TEST_F(ServerTest, PercentEncodingUnicode) {
  3911. auto res = cli_.Get("/e%u006edwith%");
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. TEST_F(ServerTest, InvalidPercentEncoding) {
  3916. auto res = cli_.Get("/%endwith%");
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3919. }
  3920. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3921. auto res = cli_.Get("/%uendwith%");
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3924. }
  3925. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3926. auto res = cli_.Get("/hello?aaa=bbb%");
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3929. }
  3930. TEST_F(ServerTest, PlusSignEncoding) {
  3931. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::OK_200, res->status);
  3934. EXPECT_EQ("a +b", res->body);
  3935. }
  3936. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3937. // This test simulates a potential DoS attack using many headers
  3938. // to verify our security fix prevents memory exhaustion
  3939. httplib::Headers attack_headers;
  3940. // Attempt to add many headers like an attacker would (200 headers to far
  3941. // exceed limit)
  3942. for (int i = 0; i < 200; i++) {
  3943. std::string name = "X-Attack-Header-" + std::to_string(i);
  3944. std::string value = "attack_payload_" + std::to_string(i);
  3945. attack_headers.emplace(name, value);
  3946. }
  3947. // Try to POST with excessive headers
  3948. cli_.set_keep_alive(true);
  3949. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3950. // Should either fail or return 400 Bad Request due to security limit
  3951. if (res) {
  3952. // If we get a response, it should be 400 Bad Request
  3953. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3954. } else {
  3955. // Request failed, which is the expected behavior for DoS protection
  3956. EXPECT_FALSE(res);
  3957. }
  3958. EXPECT_EQ("close", res->get_header_value("Connection"));
  3959. EXPECT_FALSE(cli_.is_socket_open());
  3960. }
  3961. TEST_F(ServerTest, MultipartFormData) {
  3962. UploadFormDataItems items = {
  3963. {"text1", "text default", "", ""},
  3964. {"text2", "aωb", "", ""},
  3965. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3966. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3967. {"file3", "", "", "application/octet-stream"},
  3968. {"file4", "", "", " application/json tmp-string "}};
  3969. auto res = cli_.Post("/multipart", items);
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3974. UploadFormDataItems items = {
  3975. {"text", "default text", "", ""},
  3976. {"multi_text1", "aaaaa", "", ""},
  3977. {"multi_text1", "bbbbb", "", ""},
  3978. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3979. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3980. "application/json"},
  3981. };
  3982. auto res = cli_.Post("/multipart/multi_file_values", items);
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. }
  3986. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3987. auto res = cli_.Get("/hi");
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3991. EXPECT_EQ("Hello World!", res->body);
  3992. }
  3993. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3994. Request req;
  3995. req.method = "POST";
  3996. req.path = "/chunked";
  3997. std::string host_and_port;
  3998. host_and_port += HOST;
  3999. host_and_port += ":";
  4000. host_and_port += std::to_string(PORT);
  4001. req.headers.emplace("Host", host_and_port.c_str());
  4002. req.headers.emplace("Accept", "*/*");
  4003. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4004. req.headers.emplace("Content-Type", "text/plain");
  4005. req.headers.emplace("Content-Length", "0");
  4006. req.headers.emplace(
  4007. "Transfer-Encoding",
  4008. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4009. // Client does not chunk, so make a chunked body manually.
  4010. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4011. auto res = std::make_shared<Response>();
  4012. auto error = Error::Success;
  4013. auto ret = cli_.send(req, *res, error);
  4014. ASSERT_TRUE(ret);
  4015. EXPECT_EQ(StatusCode::OK_200, res->status);
  4016. }
  4017. TEST_F(ServerTest, GetStreamed2) {
  4018. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4019. ASSERT_TRUE(res);
  4020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4021. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4022. EXPECT_EQ(true, res->has_header("Content-Range"));
  4023. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4024. EXPECT_EQ(std::string("ab"), res->body);
  4025. }
  4026. TEST_F(ServerTest, GetStreamed) {
  4027. auto res = cli_.Get("/streamed");
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::OK_200, res->status);
  4030. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(std::string("aaabbb"), res->body);
  4032. }
  4033. TEST_F(ServerTest, GetStreamedWithRange1) {
  4034. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4038. EXPECT_EQ(true, res->has_header("Content-Range"));
  4039. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4040. EXPECT_EQ(std::string("def"), res->body);
  4041. }
  4042. TEST_F(ServerTest, GetStreamedWithRange2) {
  4043. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4046. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(true, res->has_header("Content-Range"));
  4048. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4049. EXPECT_EQ(std::string("bcdefg"), res->body);
  4050. }
  4051. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4052. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4055. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(true, res->has_header("Content-Range"));
  4057. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4058. EXPECT_EQ(std::string("efg"), res->body);
  4059. }
  4060. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4061. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4062. ASSERT_TRUE(res);
  4063. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4064. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4065. EXPECT_EQ(false, res->has_header("Content-Range"));
  4066. EXPECT_EQ(0U, res->body.size());
  4067. }
  4068. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4069. auto res = cli_.Get("/streamed-with-range",
  4070. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4071. "92233720368547758079223372036854775807"}});
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4074. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4075. EXPECT_EQ(false, res->has_header("Content-Range"));
  4076. EXPECT_EQ(0U, res->body.size());
  4077. }
  4078. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4079. auto res = cli_.Get(
  4080. "/with-range",
  4081. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4082. {"Accept-Encoding", ""}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4085. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(true, res->has_header("Content-Range"));
  4087. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4088. EXPECT_EQ(std::string("abcdefg"), res->body);
  4089. }
  4090. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4091. auto res = cli_.Get("/with-range", {
  4092. {"Range", "bytes=0-"},
  4093. {"Accept-Encoding", ""},
  4094. });
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4097. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4098. EXPECT_EQ(true, res->has_header("Content-Range"));
  4099. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4100. EXPECT_EQ(std::string("abcdefg"), res->body);
  4101. }
  4102. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4103. auto res =
  4104. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4107. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4108. EXPECT_EQ(false, res->has_header("Content-Range"));
  4109. EXPECT_EQ(267U, res->body.size());
  4110. // Check that both range contents are present
  4111. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4112. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4113. // Check that Content-Range headers are present for both ranges
  4114. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4115. std::string::npos);
  4116. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4117. std::string::npos);
  4118. }
  4119. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4120. Ranges ranges;
  4121. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4122. ranges.emplace_back(0, -1);
  4123. }
  4124. auto res =
  4125. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4126. ASSERT_TRUE(res);
  4127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4129. EXPECT_EQ(false, res->has_header("Content-Range"));
  4130. EXPECT_EQ(0U, res->body.size());
  4131. }
  4132. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4133. auto res =
  4134. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4137. EXPECT_EQ(5U, res->body.size());
  4138. // Check that overlapping ranges are coalesced into a single range
  4139. EXPECT_EQ("bcdef", res->body);
  4140. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4141. // Should be single range, not multipart
  4142. EXPECT_TRUE(res->has_header("Content-Range"));
  4143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4144. }
  4145. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4146. auto res =
  4147. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4148. ASSERT_TRUE(res);
  4149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4150. EXPECT_EQ(268U, res->body.size());
  4151. // Check that both range contents are present
  4152. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4153. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4154. // Check that Content-Range headers are present for both ranges
  4155. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4156. std::string::npos);
  4157. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4158. std::string::npos);
  4159. }
  4160. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4161. auto res =
  4162. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4165. EXPECT_EQ(269U, res->body.size());
  4166. // Check that both duplicate range contents are present
  4167. size_t first_abc = res->body.find("abc\r\n");
  4168. EXPECT_TRUE(first_abc != std::string::npos);
  4169. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4170. EXPECT_TRUE(second_abc != std::string::npos);
  4171. // Check that Content-Range headers are present for both ranges
  4172. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4173. EXPECT_TRUE(first_range != std::string::npos);
  4174. size_t second_range =
  4175. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4176. EXPECT_TRUE(second_range != std::string::npos);
  4177. }
  4178. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4179. auto res = cli_.Get("/streamed-with-range?error",
  4180. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4183. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4184. EXPECT_EQ(false, res->has_header("Content-Range"));
  4185. EXPECT_EQ(0U, res->body.size());
  4186. }
  4187. TEST_F(ServerTest, GetStreamedEndless) {
  4188. uint64_t offset = 0;
  4189. auto res = cli_.Get("/streamed-cancel",
  4190. [&](const char * /*data*/, uint64_t data_length) {
  4191. if (offset < 100) {
  4192. offset += data_length;
  4193. return true;
  4194. }
  4195. return false;
  4196. });
  4197. ASSERT_TRUE(!res);
  4198. EXPECT_EQ(Error::Canceled, res.error());
  4199. }
  4200. TEST_F(ServerTest, ClientStop) {
  4201. std::atomic_size_t count{4};
  4202. std::vector<std::thread> threads;
  4203. for (auto i = count.load(); i != 0; --i) {
  4204. threads.emplace_back([&]() {
  4205. auto res = cli_.Get("/streamed-cancel",
  4206. [&](const char *, uint64_t) { return true; });
  4207. --count;
  4208. ASSERT_TRUE(!res);
  4209. EXPECT_TRUE(res.error() == Error::Canceled ||
  4210. res.error() == Error::Read || res.error() == Error::Write);
  4211. });
  4212. }
  4213. std::this_thread::sleep_for(std::chrono::seconds(2));
  4214. while (count != 0) {
  4215. cli_.stop();
  4216. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4217. }
  4218. for (auto &t : threads) {
  4219. t.join();
  4220. }
  4221. }
  4222. TEST_F(ServerTest, GetWithRange1) {
  4223. auto res = cli_.Get("/with-range", {
  4224. make_range_header({{3, 5}}),
  4225. {"Accept-Encoding", ""},
  4226. });
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4229. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(true, res->has_header("Content-Range"));
  4231. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4232. EXPECT_EQ(std::string("def"), res->body);
  4233. }
  4234. TEST_F(ServerTest, GetWithRange2) {
  4235. auto res = cli_.Get("/with-range", {
  4236. make_range_header({{1, -1}}),
  4237. {"Accept-Encoding", ""},
  4238. });
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("bcdefg"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetWithRange3) {
  4247. auto res = cli_.Get("/with-range", {
  4248. make_range_header({{0, 0}}),
  4249. {"Accept-Encoding", ""},
  4250. });
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4254. EXPECT_EQ(true, res->has_header("Content-Range"));
  4255. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4256. EXPECT_EQ(std::string("a"), res->body);
  4257. }
  4258. TEST_F(ServerTest, GetWithRange4) {
  4259. auto res = cli_.Get("/with-range", {
  4260. make_range_header({{-1, 2}}),
  4261. {"Accept-Encoding", ""},
  4262. });
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4265. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4266. EXPECT_EQ(true, res->has_header("Content-Range"));
  4267. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4268. EXPECT_EQ(std::string("fg"), res->body);
  4269. }
  4270. TEST_F(ServerTest, GetWithRange5) {
  4271. auto res = cli_.Get("/with-range", {
  4272. make_range_header({{0, 5}}),
  4273. {"Accept-Encoding", ""},
  4274. });
  4275. ASSERT_TRUE(res);
  4276. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4277. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4278. EXPECT_EQ(true, res->has_header("Content-Range"));
  4279. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4280. EXPECT_EQ(std::string("abcdef"), res->body);
  4281. }
  4282. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4283. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4284. ASSERT_TRUE(res);
  4285. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4286. }
  4287. TEST_F(ServerTest, GetWithRangeMultipart) {
  4288. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4291. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4292. EXPECT_EQ(false, res->has_header("Content-Range"));
  4293. EXPECT_EQ(267U, res->body.size());
  4294. }
  4295. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4296. auto res =
  4297. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4298. ASSERT_TRUE(res);
  4299. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4300. }
  4301. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4302. auto res = cli_.Get("/with-range-customized-response",
  4303. {{make_range_header({{1, 2}})}});
  4304. ASSERT_TRUE(res);
  4305. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4306. EXPECT_EQ(true, res->has_header("Content-Length"));
  4307. EXPECT_EQ(false, res->has_header("Content-Range"));
  4308. EXPECT_EQ(JSON_DATA, res->body);
  4309. }
  4310. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4311. auto res = cli_.Get("/with-range-customized-response",
  4312. {{make_range_header({{1, 2}, {4, 5}})}});
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4315. EXPECT_EQ(true, res->has_header("Content-Length"));
  4316. EXPECT_EQ(false, res->has_header("Content-Range"));
  4317. EXPECT_EQ(JSON_DATA, res->body);
  4318. }
  4319. TEST_F(ServerTest, Issue1772) {
  4320. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4321. ASSERT_TRUE(res);
  4322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4323. }
  4324. TEST_F(ServerTest, Issue609) {
  4325. auto res = cli_.Delete("/issue609");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ(std::string("ok"), res->body);
  4329. }
  4330. TEST_F(ServerTest, GetStreamedChunked) {
  4331. auto res = cli_.Get("/streamed-chunked");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ(std::string("123456789"), res->body);
  4335. }
  4336. TEST_F(ServerTest, GetStreamedChunked2) {
  4337. auto res = cli_.Get("/streamed-chunked2");
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::OK_200, res->status);
  4340. EXPECT_EQ(std::string("123456789"), res->body);
  4341. }
  4342. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4343. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ(std::string("123456789"), res->body);
  4347. EXPECT_TRUE(res->has_header("Trailer"));
  4348. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4349. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4350. // Trailers are now stored separately from headers (security fix)
  4351. EXPECT_EQ(2U, res->trailers.size());
  4352. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4353. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4354. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4355. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4356. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4357. // Verify trailers are NOT in headers (security verification)
  4358. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4359. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4360. }
  4361. TEST_F(ServerTest, LargeChunkedPost) {
  4362. Request req;
  4363. req.method = "POST";
  4364. req.path = "/large-chunked";
  4365. std::string host_and_port;
  4366. host_and_port += HOST;
  4367. host_and_port += ":";
  4368. host_and_port += std::to_string(PORT);
  4369. req.headers.emplace("Host", host_and_port.c_str());
  4370. req.headers.emplace("Accept", "*/*");
  4371. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4372. req.headers.emplace("Content-Type", "text/plain");
  4373. req.headers.emplace("Content-Length", "0");
  4374. req.headers.emplace("Transfer-Encoding", "chunked");
  4375. std::string long_string(30 * 1024u, 'a');
  4376. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4377. // Attempt to make a large enough post to exceed OS buffers, to test that
  4378. // the server handles short reads if the full chunk data isn't available.
  4379. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4380. auto res = std::make_shared<Response>();
  4381. auto error = Error::Success;
  4382. auto ret = cli_.send(req, *res, error);
  4383. ASSERT_TRUE(ret);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. }
  4386. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4387. auto res = cli_.Get("/remote_addr");
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4391. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4392. }
  4393. TEST_F(ServerTest, GetMethodLocalAddr) {
  4394. auto res = cli_.Get("/local_addr");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4398. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4399. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4400. }
  4401. TEST_F(ServerTest, HTTPResponseSplitting) {
  4402. auto res = cli_.Get("/http_response_splitting");
  4403. ASSERT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. }
  4406. TEST_F(ServerTest, SlowRequest) {
  4407. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4408. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4409. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4410. }
  4411. #if 0
  4412. TEST_F(ServerTest, SlowPost) {
  4413. char buffer[64 * 1024];
  4414. memset(buffer, 0x42, sizeof(buffer));
  4415. auto res = cli_.Post(
  4416. "/slowpost", 64 * 1024 * 1024,
  4417. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4418. auto ret = sink.write(buffer, sizeof(buffer));
  4419. EXPECT_TRUE(ret);
  4420. return true;
  4421. },
  4422. "text/plain");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. }
  4426. TEST_F(ServerTest, SlowPostFail) {
  4427. char buffer[64 * 1024];
  4428. memset(buffer, 0x42, sizeof(buffer));
  4429. cli_.set_write_timeout(std::chrono::seconds(0));
  4430. auto res = cli_.Post(
  4431. "/slowpost", 64 * 1024 * 1024,
  4432. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4433. sink.write(buffer, sizeof(buffer));
  4434. return true;
  4435. },
  4436. "text/plain");
  4437. ASSERT_TRUE(!res);
  4438. EXPECT_EQ(Error::Write, res.error());
  4439. }
  4440. #endif
  4441. TEST_F(ServerTest, Put) {
  4442. auto res = cli_.Put("/put", "PUT", "text/plain");
  4443. ASSERT_TRUE(res);
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. EXPECT_EQ("PUT", res->body);
  4446. }
  4447. TEST_F(ServerTest, PutWithContentProvider) {
  4448. auto res = cli_.Put(
  4449. "/put", 3,
  4450. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4451. sink.os << "PUT";
  4452. return true;
  4453. },
  4454. "text/plain");
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("PUT", res->body);
  4458. }
  4459. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4460. auto res = cli_.Post(
  4461. "/post", 42,
  4462. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4463. return false;
  4464. },
  4465. "text/plain");
  4466. ASSERT_TRUE(!res);
  4467. EXPECT_EQ(Error::Canceled, res.error());
  4468. }
  4469. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4470. auto res = cli_.Put(
  4471. "/put",
  4472. [](size_t /*offset*/, DataSink &sink) {
  4473. sink.os << "PUT";
  4474. sink.done();
  4475. return true;
  4476. },
  4477. "text/plain");
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. EXPECT_EQ("PUT", res->body);
  4481. }
  4482. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4483. auto res = cli_.Post(
  4484. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4485. "text/plain");
  4486. ASSERT_TRUE(!res);
  4487. EXPECT_EQ(Error::Canceled, res.error());
  4488. }
  4489. TEST_F(ServerTest, PostLoopBack) {
  4490. std::string body;
  4491. auto res = cli_.Post(
  4492. "/post-loopback", 9,
  4493. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4494. EXPECT_EQ(9u, length);
  4495. sink.write("123", 3);
  4496. sink.write("456", 3);
  4497. sink.write("789", 3);
  4498. return true;
  4499. },
  4500. "text/plain",
  4501. [&body](const char *data, size_t data_length) {
  4502. body.append(data, data_length);
  4503. return true;
  4504. });
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::OK_200, res->status);
  4507. EXPECT_EQ("123456789", body);
  4508. }
  4509. TEST_F(ServerTest, PutLoopBack) {
  4510. std::string body;
  4511. auto res = cli_.Put(
  4512. "/put-loopback", 9,
  4513. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4514. EXPECT_EQ(9u, length);
  4515. sink.write("123", 3);
  4516. sink.write("456", 3);
  4517. sink.write("789", 3);
  4518. return true;
  4519. },
  4520. "text/plain",
  4521. [&body](const char *data, size_t data_length) {
  4522. body.append(data, data_length);
  4523. return true;
  4524. });
  4525. ASSERT_TRUE(res);
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. EXPECT_EQ("123456789", body);
  4528. }
  4529. TEST_F(ServerTest, PatchLoopBack) {
  4530. std::string body;
  4531. auto res = cli_.Patch(
  4532. "/patch-loopback", 9,
  4533. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4534. EXPECT_EQ(9u, length);
  4535. sink.write("123", 3);
  4536. sink.write("456", 3);
  4537. sink.write("789", 3);
  4538. return true;
  4539. },
  4540. "text/plain",
  4541. [&body](const char *data, size_t data_length) {
  4542. body.append(data, data_length);
  4543. return true;
  4544. });
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("123456789", body);
  4548. }
  4549. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4550. std::string body;
  4551. auto res = cli_.Post(
  4552. "/post-loopback",
  4553. [](size_t /*offset*/, DataSink &sink) {
  4554. sink.write("123", 3);
  4555. sink.write("456", 3);
  4556. sink.write("789", 3);
  4557. sink.done();
  4558. return true;
  4559. },
  4560. "text/plain",
  4561. [&body](const char *data, size_t data_length) {
  4562. body.append(data, data_length);
  4563. return true;
  4564. });
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("123456789", body);
  4568. }
  4569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4570. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4571. cli_.set_compress(true);
  4572. auto res = cli_.Put(
  4573. "/put", 3,
  4574. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4575. sink.os << "PUT";
  4576. return true;
  4577. },
  4578. "text/plain");
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("PUT", res->body);
  4582. }
  4583. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4584. cli_.set_compress(true);
  4585. auto res = cli_.Post(
  4586. "/post", 42,
  4587. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4588. return false;
  4589. },
  4590. "text/plain");
  4591. ASSERT_TRUE(!res);
  4592. EXPECT_EQ(Error::Canceled, res.error());
  4593. }
  4594. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4595. cli_.set_compress(true);
  4596. auto res = cli_.Put(
  4597. "/put",
  4598. [](size_t /*offset*/, DataSink &sink) {
  4599. sink.os << "PUT";
  4600. sink.done();
  4601. return true;
  4602. },
  4603. "text/plain");
  4604. ASSERT_TRUE(res);
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. EXPECT_EQ("PUT", res->body);
  4607. }
  4608. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4609. cli_.set_compress(true);
  4610. auto res = cli_.Post(
  4611. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4612. "text/plain");
  4613. ASSERT_TRUE(!res);
  4614. EXPECT_EQ(Error::Canceled, res.error());
  4615. }
  4616. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4617. cli_.set_compress(true);
  4618. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ(LARGE_DATA, res->body);
  4622. }
  4623. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4624. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4625. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4626. Client cli(s.c_str());
  4627. cli.enable_server_certificate_verification(false);
  4628. #else
  4629. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4630. Client cli(s.c_str());
  4631. #endif
  4632. cli.set_compress(true);
  4633. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::OK_200, res->status);
  4636. EXPECT_EQ(LARGE_DATA, res->body);
  4637. // The compressed size should be less than a 10th of the original. May vary
  4638. // depending on the zlib library.
  4639. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4640. static_cast<uint64_t>(10 * 1024 * 1024));
  4641. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4642. }
  4643. TEST_F(ServerTest, PutContentWithDeflate) {
  4644. cli_.set_compress(false);
  4645. Headers headers;
  4646. headers.emplace("Content-Encoding", "deflate");
  4647. // PUT in deflate format:
  4648. auto res = cli_.Put("/put", headers,
  4649. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("PUT", res->body);
  4653. }
  4654. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4655. Headers headers;
  4656. headers.emplace("Accept-Encoding", "gzip, deflate");
  4657. auto res = cli_.Get("/streamed-chunked", headers);
  4658. ASSERT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. EXPECT_EQ(std::string("123456789"), res->body);
  4661. }
  4662. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4663. Headers headers;
  4664. headers.emplace("Accept-Encoding", "gzip, deflate");
  4665. auto res = cli_.Get("/streamed-chunked2", headers);
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("123456789"), res->body);
  4669. }
  4670. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4671. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. }
  4675. TEST(GzipDecompressor, ChunkedDecompression) {
  4676. std::string data;
  4677. for (size_t i = 0; i < 32 * 1024; ++i) {
  4678. data.push_back(static_cast<char>('a' + i % 26));
  4679. }
  4680. std::string compressed_data;
  4681. {
  4682. httplib::detail::gzip_compressor compressor;
  4683. bool result = compressor.compress(
  4684. data.data(), data.size(),
  4685. /*last=*/true,
  4686. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4687. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4688. compressed_data_size);
  4689. return true;
  4690. });
  4691. ASSERT_TRUE(result);
  4692. }
  4693. std::string decompressed_data;
  4694. {
  4695. httplib::detail::gzip_decompressor decompressor;
  4696. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4697. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4698. size_t chunk_size = 130;
  4699. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4700. chunk_begin += chunk_size) {
  4701. size_t current_chunk_size =
  4702. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4703. bool result = decompressor.decompress(
  4704. compressed_data.data() + chunk_begin, current_chunk_size,
  4705. [&](const char *decompressed_data_chunk,
  4706. size_t decompressed_data_chunk_size) {
  4707. decompressed_data.insert(decompressed_data.size(),
  4708. decompressed_data_chunk,
  4709. decompressed_data_chunk_size);
  4710. return true;
  4711. });
  4712. ASSERT_TRUE(result);
  4713. }
  4714. }
  4715. ASSERT_EQ(data, decompressed_data);
  4716. }
  4717. TEST(GzipDecompressor, DeflateDecompression) {
  4718. std::string original_text = "Raw deflate without gzip";
  4719. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4720. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4721. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4722. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4723. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4724. std::string decompressed_data;
  4725. {
  4726. httplib::detail::gzip_decompressor decompressor;
  4727. bool result = decompressor.decompress(
  4728. compressed_data.data(), compressed_data.size(),
  4729. [&](const char *decompressed_data_chunk,
  4730. size_t decompressed_data_chunk_size) {
  4731. decompressed_data.insert(decompressed_data.size(),
  4732. decompressed_data_chunk,
  4733. decompressed_data_chunk_size);
  4734. return true;
  4735. });
  4736. ASSERT_TRUE(result);
  4737. }
  4738. ASSERT_EQ(original_text, decompressed_data);
  4739. }
  4740. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4741. std::string original_text = "Raw deflate without gzip";
  4742. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4743. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4744. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4745. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4746. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4747. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4748. std::string decompressed_data;
  4749. {
  4750. httplib::detail::gzip_decompressor decompressor;
  4751. bool result = decompressor.decompress(
  4752. compressed_data.data(), compressed_data.size(),
  4753. [&](const char *decompressed_data_chunk,
  4754. size_t decompressed_data_chunk_size) {
  4755. decompressed_data.insert(decompressed_data.size(),
  4756. decompressed_data_chunk,
  4757. decompressed_data_chunk_size);
  4758. return true;
  4759. });
  4760. ASSERT_TRUE(result);
  4761. }
  4762. ASSERT_EQ(original_text, decompressed_data);
  4763. }
  4764. #ifdef _WIN32
  4765. TEST(GzipDecompressor, LargeRandomData) {
  4766. // prepare large random data that is difficult to be compressed and is
  4767. // expected to have large size even when compressed
  4768. std::random_device seed_gen;
  4769. std::mt19937 random(seed_gen());
  4770. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4771. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4772. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4773. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4774. // compress data over 4GiB
  4775. std::string compressed_data;
  4776. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4777. httplib::detail::gzip_compressor compressor;
  4778. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4779. data.size() * sizeof(std::uint32_t), true,
  4780. [&](const char *data, size_t size) {
  4781. compressed_data.insert(
  4782. compressed_data.size(), data, size);
  4783. return true;
  4784. });
  4785. ASSERT_TRUE(result);
  4786. // FIXME: compressed data size is expected to be greater than 4GiB,
  4787. // but there is no guarantee
  4788. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4789. // decompress data over 4GiB
  4790. std::string decompressed_data;
  4791. decompressed_data.reserve(data_size);
  4792. httplib::detail::gzip_decompressor decompressor;
  4793. result = decompressor.decompress(
  4794. compressed_data.data(), compressed_data.size(),
  4795. [&](const char *data, size_t size) {
  4796. decompressed_data.insert(decompressed_data.size(), data, size);
  4797. return true;
  4798. });
  4799. ASSERT_TRUE(result);
  4800. // compare
  4801. ASSERT_EQ(data_size, decompressed_data.size());
  4802. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4803. 0);
  4804. }
  4805. #endif
  4806. #endif
  4807. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4808. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4809. Headers headers;
  4810. headers.emplace("Accept-Encoding", "br");
  4811. auto res = cli_.Get("/streamed-chunked", headers);
  4812. ASSERT_TRUE(res);
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. EXPECT_EQ(std::string("123456789"), res->body);
  4815. }
  4816. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4817. Headers headers;
  4818. headers.emplace("Accept-Encoding", "br");
  4819. auto res = cli_.Get("/streamed-chunked2", headers);
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ(std::string("123456789"), res->body);
  4823. }
  4824. #endif
  4825. TEST_F(ServerTest, Patch) {
  4826. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4827. ASSERT_TRUE(res);
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("PATCH", res->body);
  4830. }
  4831. TEST_F(ServerTest, Delete) {
  4832. auto res = cli_.Delete("/delete");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. EXPECT_EQ("DELETE", res->body);
  4836. }
  4837. TEST_F(ServerTest, DeleteContentReceiver) {
  4838. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::OK_200, res->status);
  4841. EXPECT_EQ("content", res->body);
  4842. }
  4843. TEST_F(ServerTest, Options) {
  4844. auto res = cli_.Options("*");
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4848. EXPECT_TRUE(res->body.empty());
  4849. }
  4850. TEST_F(ServerTest, URL) {
  4851. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. }
  4855. TEST_F(ServerTest, ArrayParam) {
  4856. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. }
  4860. TEST_F(ServerTest, NoMultipleHeaders) {
  4861. Headers headers = {{"Content-Length", "5"}};
  4862. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4863. "text/plain");
  4864. ASSERT_TRUE(res);
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, PostContentReceiver) {
  4868. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4869. ASSERT_TRUE(res);
  4870. ASSERT_EQ(StatusCode::OK_200, res->status);
  4871. ASSERT_EQ("content", res->body);
  4872. }
  4873. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4874. UploadFormDataItems items = {
  4875. {"text1", "text default", "", ""},
  4876. {"text2", "aωb", "", ""},
  4877. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4878. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4879. {"file3", "", "", "application/octet-stream"},
  4880. };
  4881. auto res = cli_.Post("/content_receiver", items);
  4882. ASSERT_TRUE(res);
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. }
  4885. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4886. UploadFormDataItems items = {
  4887. {"text1", "text default", "", ""},
  4888. {"text2", "aωb", "", ""},
  4889. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4890. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4891. {"file3", "", "", "application/octet-stream"},
  4892. };
  4893. auto boundary = std::string("+++++");
  4894. std::string body;
  4895. for (const auto &item : items) {
  4896. body += "--" + boundary + "\r\n";
  4897. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4898. if (!item.filename.empty()) {
  4899. body += "; filename=\"" + item.filename + "\"";
  4900. }
  4901. body += "\r\n";
  4902. if (!item.content_type.empty()) {
  4903. body += "Content-Type: " + item.content_type + "\r\n";
  4904. }
  4905. body += "\r\n";
  4906. body += item.content + "\r\n";
  4907. }
  4908. body += "--" + boundary + "--\r\n";
  4909. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4910. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. }
  4914. TEST_F(ServerTest, PostContentReceiverGzip) {
  4915. cli_.set_compress(true);
  4916. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4917. ASSERT_TRUE(res);
  4918. ASSERT_EQ(StatusCode::OK_200, res->status);
  4919. ASSERT_EQ("content", res->body);
  4920. }
  4921. TEST_F(ServerTest, PutContentReceiver) {
  4922. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. ASSERT_EQ(StatusCode::OK_200, res->status);
  4925. ASSERT_EQ("content", res->body);
  4926. }
  4927. TEST_F(ServerTest, PatchContentReceiver) {
  4928. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4929. ASSERT_TRUE(res);
  4930. ASSERT_EQ(StatusCode::OK_200, res->status);
  4931. ASSERT_EQ("content", res->body);
  4932. }
  4933. template <typename ClientType>
  4934. void TestWithHeadersAndContentReceiver(
  4935. ClientType &cli,
  4936. std::function<Result(ClientType &, const std::string &, const Headers &,
  4937. const std::string &, const std::string &,
  4938. ContentReceiver, DownloadProgress)>
  4939. request_func) {
  4940. Headers headers;
  4941. headers.emplace("X-Custom-Header", "test-value");
  4942. std::string received_body;
  4943. auto res = request_func(
  4944. cli, "/content_receiver", headers, "content", "application/json",
  4945. [&](const char *data, size_t data_length) {
  4946. received_body.append(data, data_length);
  4947. return true;
  4948. },
  4949. nullptr);
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ(StatusCode::OK_200, res->status);
  4952. EXPECT_EQ("content", received_body);
  4953. }
  4954. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4955. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4956. using ClientT = SSLClient;
  4957. #else
  4958. using ClientT = Client;
  4959. #endif
  4960. TestWithHeadersAndContentReceiver<ClientT>(
  4961. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4962. const std::string &body, const std::string &content_type,
  4963. ContentReceiver receiver, DownloadProgress progress) {
  4964. return cli.Post(path, headers, body, content_type, receiver, progress);
  4965. });
  4966. }
  4967. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4968. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4969. using ClientT = SSLClient;
  4970. #else
  4971. using ClientT = Client;
  4972. #endif
  4973. TestWithHeadersAndContentReceiver<ClientT>(
  4974. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4975. const std::string &body, const std::string &content_type,
  4976. ContentReceiver receiver, DownloadProgress progress) {
  4977. return cli.Put(path, headers, body, content_type, receiver, progress);
  4978. });
  4979. }
  4980. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4982. using ClientT = SSLClient;
  4983. #else
  4984. using ClientT = Client;
  4985. #endif
  4986. TestWithHeadersAndContentReceiver<ClientT>(
  4987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4988. const std::string &body, const std::string &content_type,
  4989. ContentReceiver receiver, DownloadProgress progress) {
  4990. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4991. });
  4992. }
  4993. template <typename ClientType>
  4994. void TestWithHeadersAndContentReceiverWithProgress(
  4995. ClientType &cli,
  4996. std::function<Result(ClientType &, const std::string &, const Headers &,
  4997. const std::string &, const std::string &,
  4998. ContentReceiver, DownloadProgress)>
  4999. request_func) {
  5000. Headers headers;
  5001. headers.emplace("X-Test-Header", "progress-test");
  5002. std::string received_body;
  5003. auto progress_called = false;
  5004. auto res = request_func(
  5005. cli, "/content_receiver", headers, "content", "text/plain",
  5006. [&](const char *data, size_t data_length) {
  5007. received_body.append(data, data_length);
  5008. return true;
  5009. },
  5010. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5011. progress_called = true;
  5012. return true;
  5013. });
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::OK_200, res->status);
  5016. EXPECT_EQ("content", received_body);
  5017. EXPECT_TRUE(progress_called);
  5018. }
  5019. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5021. using ClientT = SSLClient;
  5022. #else
  5023. using ClientT = Client;
  5024. #endif
  5025. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5026. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5027. const std::string &body, const std::string &content_type,
  5028. ContentReceiver receiver, DownloadProgress progress) {
  5029. return cli.Post(path, headers, body, content_type, receiver, progress);
  5030. });
  5031. }
  5032. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5034. using ClientT = SSLClient;
  5035. #else
  5036. using ClientT = Client;
  5037. #endif
  5038. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5039. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5040. const std::string &body, const std::string &content_type,
  5041. ContentReceiver receiver, DownloadProgress progress) {
  5042. return cli.Put(path, headers, body, content_type, receiver, progress);
  5043. });
  5044. }
  5045. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5047. using ClientT = SSLClient;
  5048. #else
  5049. using ClientT = Client;
  5050. #endif
  5051. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5052. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5053. const std::string &body, const std::string &content_type,
  5054. ContentReceiver receiver, DownloadProgress progress) {
  5055. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5056. });
  5057. }
  5058. template <typename ClientType>
  5059. void TestWithHeadersAndContentReceiverError(
  5060. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5061. const Headers &, const std::string &,
  5062. const std::string &, ContentReceiver)>
  5063. request_func) {
  5064. Headers headers;
  5065. headers.emplace("X-Error-Test", "true");
  5066. std::string received_body;
  5067. auto receiver_failed = false;
  5068. auto res =
  5069. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5070. [&](const char *data, size_t data_length) {
  5071. received_body.append(data, data_length);
  5072. receiver_failed = true;
  5073. return false;
  5074. });
  5075. ASSERT_FALSE(res);
  5076. EXPECT_TRUE(receiver_failed);
  5077. }
  5078. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5080. using ClientT = SSLClient;
  5081. #else
  5082. using ClientT = Client;
  5083. #endif
  5084. TestWithHeadersAndContentReceiverError<ClientT>(
  5085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5086. const std::string &body, const std::string &content_type,
  5087. ContentReceiver receiver) {
  5088. return cli.Post(path, headers, body, content_type, receiver);
  5089. });
  5090. }
  5091. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5092. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5093. using ClientT = SSLClient;
  5094. #else
  5095. using ClientT = Client;
  5096. #endif
  5097. TestWithHeadersAndContentReceiverError<ClientT>(
  5098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5099. const std::string &body, const std::string &content_type,
  5100. ContentReceiver receiver) {
  5101. return cli.Put(path, headers, body, content_type, receiver);
  5102. });
  5103. }
  5104. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5105. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5106. using ClientT = SSLClient;
  5107. #else
  5108. using ClientT = Client;
  5109. #endif
  5110. TestWithHeadersAndContentReceiverError<ClientT>(
  5111. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5112. const std::string &body, const std::string &content_type,
  5113. ContentReceiver receiver) {
  5114. return cli.Patch(path, headers, body, content_type, receiver);
  5115. });
  5116. }
  5117. TEST_F(ServerTest, PostQueryStringAndBody) {
  5118. auto res =
  5119. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5120. ASSERT_TRUE(res);
  5121. ASSERT_EQ(StatusCode::OK_200, res->status);
  5122. }
  5123. TEST_F(ServerTest, HTTP2Magic) {
  5124. Request req;
  5125. req.method = "PRI";
  5126. req.path = "*";
  5127. req.body = "SM";
  5128. auto res = std::make_shared<Response>();
  5129. auto error = Error::Success;
  5130. auto ret = cli_.send(req, *res, error);
  5131. ASSERT_TRUE(ret);
  5132. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5133. }
  5134. TEST_F(ServerTest, KeepAlive) {
  5135. auto res = cli_.Get("/hi");
  5136. ASSERT_TRUE(res);
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5139. EXPECT_EQ("Hello World!", res->body);
  5140. res = cli_.Get("/hi");
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5144. EXPECT_EQ("Hello World!", res->body);
  5145. res = cli_.Get("/hi");
  5146. ASSERT_TRUE(res);
  5147. EXPECT_EQ(StatusCode::OK_200, res->status);
  5148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5149. EXPECT_EQ("Hello World!", res->body);
  5150. res = cli_.Get("/not-exist");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5153. res = cli_.Post("/empty", "", "text/plain");
  5154. ASSERT_TRUE(res);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("empty", res->body);
  5158. EXPECT_EQ("close", res->get_header_value("Connection"));
  5159. res = cli_.Post(
  5160. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5161. "text/plain");
  5162. ASSERT_TRUE(res);
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5165. EXPECT_EQ("empty", res->body);
  5166. cli_.set_keep_alive(false);
  5167. res = cli_.Get("/last-request");
  5168. ASSERT_TRUE(res);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("close", res->get_header_value("Connection"));
  5171. }
  5172. TEST_F(ServerTest, TooManyRedirect) {
  5173. cli_.set_follow_location(true);
  5174. auto res = cli_.Get("/redirect/0");
  5175. ASSERT_TRUE(!res);
  5176. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5177. }
  5178. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5179. Request req;
  5180. req.method = "FOOBAR";
  5181. req.path = "/hi";
  5182. cli_.set_keep_alive(true);
  5183. auto res = cli_.send(req);
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. EXPECT_FALSE(cli_.is_socket_open());
  5188. }
  5189. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5190. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5191. TEST_F(ServerTest, Gzip) {
  5192. Headers headers;
  5193. headers.emplace("Accept-Encoding", "gzip, deflate");
  5194. auto res = cli_.Get("/compress", headers);
  5195. ASSERT_TRUE(res);
  5196. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5198. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5199. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5200. "7890123456789012345678901234567890",
  5201. res->body);
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. auto res = cli_.Get("/compress", headers);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5211. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5212. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5213. "7890123456789012345678901234567890",
  5214. res->body);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. }
  5217. TEST_F(ServerTest, GzipWithContentReceiver) {
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip, deflate");
  5220. std::string body;
  5221. auto res = cli_.Get("/compress", headers,
  5222. [&](const char *data, uint64_t data_length) {
  5223. EXPECT_EQ(100U, data_length);
  5224. body.append(data, data_length);
  5225. return true;
  5226. });
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. cli_.set_decompress(false);
  5240. auto res = cli_.Get("/compress", headers);
  5241. ASSERT_TRUE(res);
  5242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5244. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5245. EXPECT_EQ(33U, res->body.size());
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. }
  5248. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5249. Headers headers;
  5250. headers.emplace("Accept-Encoding", "");
  5251. std::string body;
  5252. auto res = cli_.Get("/compress", headers,
  5253. [&](const char *data, uint64_t data_length) {
  5254. EXPECT_EQ(100U, data_length);
  5255. body.append(data, data_length);
  5256. return true;
  5257. });
  5258. ASSERT_TRUE(res);
  5259. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5261. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5262. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5263. "7890123456789012345678901234567890",
  5264. body);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, NoGzip) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "gzip, deflate");
  5270. auto res = cli_.Get("/nocompress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5273. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5281. Headers headers;
  5282. headers.emplace("Accept-Encoding", "gzip, deflate");
  5283. std::string body;
  5284. auto res = cli_.Get("/nocompress", headers,
  5285. [&](const char *data, uint64_t data_length) {
  5286. EXPECT_EQ(100U, data_length);
  5287. body.append(data, data_length);
  5288. return true;
  5289. });
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5292. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5293. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5294. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5295. "7890123456789012345678901234567890",
  5296. body);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, MultipartFormDataGzip) {
  5300. UploadFormDataItems items = {
  5301. {"key1", "test", "", ""},
  5302. {"key2", "--abcdefg123", "", ""},
  5303. };
  5304. cli_.set_compress(true);
  5305. auto res = cli_.Post("/compress-multipart", items);
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. }
  5309. #endif
  5310. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5311. TEST_F(ServerTest, Brotli) {
  5312. Headers headers;
  5313. headers.emplace("Accept-Encoding", "br");
  5314. auto res = cli_.Get("/compress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5317. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5318. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5319. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5320. "7890123456789012345678901234567890",
  5321. res->body);
  5322. EXPECT_EQ(StatusCode::OK_200, res->status);
  5323. }
  5324. #endif
  5325. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5326. TEST_F(ServerTest, Zstd) {
  5327. Headers headers;
  5328. headers.emplace("Accept-Encoding", "zstd");
  5329. auto res = cli_.Get("/compress", headers);
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5334. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5335. "7890123456789012345678901234567890",
  5336. res->body);
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. }
  5339. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5340. Headers headers;
  5341. headers.emplace("Accept-Encoding", "");
  5342. auto res = cli_.Get("/compress", headers);
  5343. ASSERT_TRUE(res);
  5344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. res->body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "zstd");
  5355. std::string body;
  5356. auto res = cli_.Get("/compress", headers,
  5357. [&](const char *data, uint64_t data_length) {
  5358. EXPECT_EQ(100U, data_length);
  5359. body.append(data, data_length);
  5360. return true;
  5361. });
  5362. ASSERT_TRUE(res);
  5363. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "zstd");
  5374. cli_.set_decompress(false);
  5375. auto res = cli_.Get("/compress", headers);
  5376. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5377. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5378. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5379. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5380. ASSERT_TRUE(res);
  5381. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. ASSERT_EQ(26U, res->body.size());
  5386. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5387. 0);
  5388. }
  5389. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5390. Headers headers;
  5391. headers.emplace("Accept-Encoding", "");
  5392. std::string body;
  5393. auto res = cli_.Get("/compress", headers,
  5394. [&](const char *data, uint64_t data_length) {
  5395. EXPECT_EQ(100U, data_length);
  5396. body.append(data, data_length);
  5397. return true;
  5398. });
  5399. ASSERT_TRUE(res);
  5400. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5404. "7890123456789012345678901234567890",
  5405. body);
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. }
  5408. TEST_F(ServerTest, NoZstd) {
  5409. Headers headers;
  5410. headers.emplace("Accept-Encoding", "zstd");
  5411. auto res = cli_.Get("/nocompress", headers);
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5414. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. res->body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5422. Headers headers;
  5423. headers.emplace("Accept-Encoding", "zstd");
  5424. std::string body;
  5425. auto res = cli_.Get("/nocompress", headers,
  5426. [&](const char *data, uint64_t data_length) {
  5427. EXPECT_EQ(100U, data_length);
  5428. body.append(data, data_length);
  5429. return true;
  5430. });
  5431. ASSERT_TRUE(res);
  5432. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5433. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5434. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5436. "7890123456789012345678901234567890",
  5437. body);
  5438. EXPECT_EQ(StatusCode::OK_200, res->status);
  5439. }
  5440. // TODO: How to enable zstd ??
  5441. TEST_F(ServerTest, MultipartFormDataZstd) {
  5442. UploadFormDataItems items = {
  5443. {"key1", "test", "", ""},
  5444. {"key2", "--abcdefg123", "", ""},
  5445. };
  5446. Headers headers;
  5447. headers.emplace("Accept-Encoding", "zstd");
  5448. cli_.set_compress(true);
  5449. auto res = cli_.Post("/compress-multipart", headers, items);
  5450. ASSERT_TRUE(res);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5454. Headers headers;
  5455. headers.emplace("Accept-Encoding", "zstd");
  5456. cli_.set_compress(true);
  5457. auto res = cli_.Put(
  5458. "/put", headers, 3,
  5459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5460. sink.os << "PUT";
  5461. return true;
  5462. },
  5463. "text/plain");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("PUT", res->body);
  5467. }
  5468. // Pre-compression logging tests
  5469. TEST_F(ServerTest, PreCompressionLogging) {
  5470. // Test data for compression (matches the actual /compress endpoint content)
  5471. const std::string test_content =
  5472. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5473. "3456789012345678901234567890";
  5474. // Variables to capture logging data
  5475. std::string pre_compression_body;
  5476. std::string pre_compression_content_type;
  5477. std::string pre_compression_content_encoding;
  5478. std::string post_compression_body;
  5479. std::string post_compression_content_type;
  5480. std::string post_compression_content_encoding;
  5481. // Set up pre-compression logger
  5482. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5483. const Response &res) {
  5484. pre_compression_body = res.body;
  5485. pre_compression_content_type = res.get_header_value("Content-Type");
  5486. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5487. });
  5488. // Set up post-compression logger
  5489. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5490. post_compression_body = res.body;
  5491. post_compression_content_type = res.get_header_value("Content-Type");
  5492. post_compression_content_encoding =
  5493. res.get_header_value("Content-Encoding");
  5494. });
  5495. // Test with gzip compression
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "gzip");
  5498. auto res = cli_.Get("/compress", headers);
  5499. // Verify response was compressed
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5503. // Verify pre-compression logger captured uncompressed content
  5504. EXPECT_EQ(test_content, pre_compression_body);
  5505. EXPECT_EQ("text/plain", pre_compression_content_type);
  5506. EXPECT_TRUE(pre_compression_content_encoding
  5507. .empty()); // No encoding header before compression
  5508. // Verify post-compression logger captured compressed content
  5509. EXPECT_NE(test_content,
  5510. post_compression_body); // Should be different after compression
  5511. EXPECT_EQ("text/plain", post_compression_content_type);
  5512. EXPECT_EQ("gzip", post_compression_content_encoding);
  5513. // Verify compressed content is smaller
  5514. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5515. }
  5516. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5517. const std::string test_content =
  5518. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5519. "3456789012345678901234567890";
  5520. std::string pre_compression_body;
  5521. std::string post_compression_body;
  5522. svr_.set_pre_compression_logger(
  5523. [&](const Request & /*req*/, const Response &res) {
  5524. pre_compression_body = res.body;
  5525. });
  5526. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5527. post_compression_body = res.body;
  5528. });
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "br");
  5531. auto res = cli_.Get("/compress", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5535. // Verify pre-compression content is uncompressed
  5536. EXPECT_EQ(test_content, pre_compression_body);
  5537. // Verify post-compression content is compressed
  5538. EXPECT_NE(test_content, post_compression_body);
  5539. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5540. }
  5541. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5542. const std::string test_content =
  5543. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5544. "3456789012345678901234567890";
  5545. std::string pre_compression_body;
  5546. std::string post_compression_body;
  5547. svr_.set_pre_compression_logger(
  5548. [&](const Request & /*req*/, const Response &res) {
  5549. pre_compression_body = res.body;
  5550. });
  5551. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5552. post_compression_body = res.body;
  5553. });
  5554. // Request without compression (use /nocompress endpoint)
  5555. Headers headers;
  5556. auto res = cli_.Get("/nocompress", headers);
  5557. ASSERT_TRUE(res);
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5560. // Pre-compression logger should not be called when no compression is applied
  5561. EXPECT_TRUE(
  5562. pre_compression_body.empty()); // Pre-compression logger not called
  5563. EXPECT_EQ(
  5564. test_content,
  5565. post_compression_body); // Post-compression logger captures final content
  5566. }
  5567. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5568. const std::string test_content =
  5569. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5570. "3456789012345678901234567890";
  5571. std::string pre_compression_body;
  5572. bool pre_logger_called = false;
  5573. // Set only pre-compression logger
  5574. svr_.set_pre_compression_logger(
  5575. [&](const Request & /*req*/, const Response &res) {
  5576. pre_compression_body = res.body;
  5577. pre_logger_called = true;
  5578. });
  5579. Headers headers;
  5580. headers.emplace("Accept-Encoding", "gzip");
  5581. auto res = cli_.Get("/compress", headers);
  5582. ASSERT_TRUE(res);
  5583. EXPECT_EQ(StatusCode::OK_200, res->status);
  5584. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5585. // Verify pre-compression logger was called
  5586. EXPECT_TRUE(pre_logger_called);
  5587. EXPECT_EQ(test_content, pre_compression_body);
  5588. }
  5589. TEST(ZstdDecompressor, ChunkedDecompression) {
  5590. std::string data;
  5591. for (size_t i = 0; i < 32 * 1024; ++i) {
  5592. data.push_back(static_cast<char>('a' + i % 26));
  5593. }
  5594. std::string compressed_data;
  5595. {
  5596. httplib::detail::zstd_compressor compressor;
  5597. bool result = compressor.compress(
  5598. data.data(), data.size(),
  5599. /*last=*/true,
  5600. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5601. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5602. compressed_data_size);
  5603. return true;
  5604. });
  5605. ASSERT_TRUE(result);
  5606. }
  5607. std::string decompressed_data;
  5608. {
  5609. httplib::detail::zstd_decompressor decompressor;
  5610. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5611. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5612. size_t chunk_size = 130;
  5613. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5614. chunk_begin += chunk_size) {
  5615. size_t current_chunk_size =
  5616. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5617. bool result = decompressor.decompress(
  5618. compressed_data.data() + chunk_begin, current_chunk_size,
  5619. [&](const char *decompressed_data_chunk,
  5620. size_t decompressed_data_chunk_size) {
  5621. decompressed_data.insert(decompressed_data.size(),
  5622. decompressed_data_chunk,
  5623. decompressed_data_chunk_size);
  5624. return true;
  5625. });
  5626. ASSERT_TRUE(result);
  5627. }
  5628. }
  5629. ASSERT_EQ(data, decompressed_data);
  5630. }
  5631. TEST(ZstdDecompressor, Decompress) {
  5632. std::string original_text = "Compressed with ZSTD";
  5633. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5634. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5635. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5636. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5637. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5638. std::string decompressed_data;
  5639. {
  5640. httplib::detail::zstd_decompressor decompressor;
  5641. bool result = decompressor.decompress(
  5642. compressed_data.data(), compressed_data.size(),
  5643. [&](const char *decompressed_data_chunk,
  5644. size_t decompressed_data_chunk_size) {
  5645. decompressed_data.insert(decompressed_data.size(),
  5646. decompressed_data_chunk,
  5647. decompressed_data_chunk_size);
  5648. return true;
  5649. });
  5650. ASSERT_TRUE(result);
  5651. }
  5652. ASSERT_EQ(original_text, decompressed_data);
  5653. }
  5654. #endif
  5655. // Sends a raw request to a server listening at HOST:PORT.
  5656. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5657. std::string *resp = nullptr) {
  5658. auto error = Error::Success;
  5659. auto client_sock = detail::create_client_socket(
  5660. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5661. /*connection_timeout_sec=*/5, 0,
  5662. /*read_timeout_sec=*/5, 0,
  5663. /*write_timeout_sec=*/5, 0, std::string(), error);
  5664. if (client_sock == INVALID_SOCKET) { return false; }
  5665. auto ret = detail::process_client_socket(
  5666. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5667. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5668. if (req.size() !=
  5669. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5670. return false;
  5671. }
  5672. char buf[512];
  5673. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5674. while (line_reader.getline()) {
  5675. if (resp) { *resp += line_reader.ptr(); }
  5676. }
  5677. return true;
  5678. });
  5679. detail::close_socket(client_sock);
  5680. return ret;
  5681. }
  5682. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5683. Server svr;
  5684. std::string header_value;
  5685. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5686. header_value = req.get_header_value("foo");
  5687. res.set_content("ok", "text/plain");
  5688. });
  5689. thread t = thread([&] { svr.listen(HOST, PORT); });
  5690. auto se = detail::scope_exit([&] {
  5691. svr.stop();
  5692. t.join();
  5693. ASSERT_FALSE(svr.is_running());
  5694. });
  5695. svr.wait_until_ready();
  5696. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5697. // like characters are not treated the same - use vertical tab and escape.
  5698. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5699. "foo: \t \v bar \x1B\t \r\n"
  5700. "Connection: close\r\n"
  5701. "\r\n";
  5702. std::string res;
  5703. ASSERT_TRUE(send_request(5, req, &res));
  5704. EXPECT_EQ(header_value, "");
  5705. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5706. }
  5707. // Sends a raw request and verifies that there isn't a crash or exception.
  5708. static void test_raw_request(const std::string &req,
  5709. std::string *out = nullptr) {
  5710. Server svr;
  5711. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5712. res.set_content("ok", "text/plain");
  5713. });
  5714. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5715. res.set_content("ok", "text/plain");
  5716. });
  5717. svr.Get("/header_field_value_check",
  5718. [&](const Request & /*req*/, Response &res) {
  5719. res.set_content("ok", "text/plain");
  5720. });
  5721. // Server read timeout must be longer than the client read timeout for the
  5722. // bug to reproduce, probably to force the server to process a request
  5723. // without a trailing blank line.
  5724. const time_t client_read_timeout_sec = 1;
  5725. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5726. bool listen_thread_ok = false;
  5727. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5728. auto se = detail::scope_exit([&] {
  5729. svr.stop();
  5730. t.join();
  5731. ASSERT_FALSE(svr.is_running());
  5732. EXPECT_TRUE(listen_thread_ok);
  5733. });
  5734. svr.wait_until_ready();
  5735. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5736. }
  5737. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5738. // A certain header line causes an exception if the header property is parsed
  5739. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5740. test_raw_request(
  5741. "GET /hi HTTP/1.1\r\n"
  5742. " : "
  5743. " "
  5744. " ");
  5745. }
  5746. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5747. // A certain header line causes an exception if the header property *name* is
  5748. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5749. // greedy matcher and requires backtracking when there are a lot of ":"
  5750. // characters.
  5751. // This occurs with libc++ but not libstdc++.
  5752. test_raw_request(
  5753. "GET /hi HTTP/1.1\r\n"
  5754. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5755. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5756. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5757. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5758. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5759. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5760. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5761. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5762. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5763. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5764. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5765. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5766. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5767. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5768. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5769. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5770. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5771. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5772. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5773. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5774. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5775. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5776. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5777. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5778. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5779. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5780. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5781. "&&&%%%");
  5782. }
  5783. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5784. // Make sure this doesn't crash the server.
  5785. // In a previous version of the header line regex, the "\r" rendered the line
  5786. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5787. // a new position where the leading white space ended and the field value
  5788. // began.
  5789. // The crash occurs with libc++ but not libstdc++.
  5790. test_raw_request("GET /hi HTTP/1.1\r\n"
  5791. "a:" +
  5792. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5793. "\r\n"
  5794. "\r\n");
  5795. }
  5796. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5797. std::string out;
  5798. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5799. "Content-Type: text/plain\r\n"
  5800. "Transfer-Encoding: chunked\r\n"
  5801. "\r\n"
  5802. "nothex\r\n",
  5803. &out);
  5804. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5805. }
  5806. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5807. std::string out;
  5808. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5809. "Content-Type: text/plain\r\n"
  5810. "Transfer-Encoding: chunked\r\n"
  5811. "\r\n"
  5812. "3\r\n"
  5813. "xyz\r\n"
  5814. "NaN\r\n",
  5815. &out);
  5816. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5817. }
  5818. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5819. std::string out;
  5820. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5821. "Content-Type: text/plain\r\n"
  5822. "Transfer-Encoding: chunked\r\n"
  5823. "\r\n"
  5824. // Length is too large for 64 bits.
  5825. "1ffffffffffffffff\r\n"
  5826. "xyz\r\n",
  5827. &out);
  5828. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5829. }
  5830. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5831. test_raw_request("GET /hi HTTP/1.1\r\n"
  5832. "Content-Type: text/plain\r\n\r");
  5833. }
  5834. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5835. std::string out;
  5836. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5837. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5838. }
  5839. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5840. std::string out;
  5841. std::string request(
  5842. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5843. test_raw_request(request, &out);
  5844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5845. }
  5846. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5847. std::string out;
  5848. std::string request(
  5849. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5850. test_raw_request(request, &out);
  5851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5852. }
  5853. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5854. std::string out;
  5855. std::string request(
  5856. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5857. test_raw_request(request, &out);
  5858. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5859. }
  5860. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5861. std::string out;
  5862. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5863. "Test: \r\n\r\n",
  5864. &out);
  5865. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5866. }
  5867. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5868. Server svr;
  5869. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5870. res.set_header("Cache-Control", "no-cache");
  5871. res.set_chunked_content_provider(
  5872. "text/event-stream", [](size_t offset, DataSink &sink) {
  5873. std::string s = "data:";
  5874. s += std::to_string(offset);
  5875. s += "\n\n";
  5876. auto ret = sink.write(s.data(), s.size());
  5877. EXPECT_TRUE(ret);
  5878. std::this_thread::sleep_for(std::chrono::seconds(1));
  5879. return true;
  5880. });
  5881. });
  5882. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5883. svr.wait_until_ready();
  5884. Client client(HOST, PORT);
  5885. const Headers headers = {{"Accept", "text/event-stream"}};
  5886. auto get_thread = std::thread([&client, &headers]() {
  5887. auto res = client.Get(
  5888. "/events", headers,
  5889. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5890. });
  5891. auto se = detail::scope_exit([&] {
  5892. svr.stop();
  5893. get_thread.join();
  5894. listen_thread.join();
  5895. ASSERT_FALSE(svr.is_running());
  5896. });
  5897. // Give GET time to get a few messages.
  5898. std::this_thread::sleep_for(std::chrono::seconds(2));
  5899. }
  5900. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5901. httplib::Server svr;
  5902. svr.Post("/hi",
  5903. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5904. res.status = StatusCode::OK_200;
  5905. });
  5906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5907. svr.wait_until_ready();
  5908. Client cli(HOST, PORT);
  5909. auto res = cli.Post("/hi", "data", "text/plain");
  5910. ASSERT_TRUE(res);
  5911. EXPECT_EQ(StatusCode::OK_200, res->status);
  5912. svr.stop();
  5913. thread.join();
  5914. ASSERT_FALSE(svr.is_running());
  5915. res = cli.Post("/hi", "data", "text/plain");
  5916. ASSERT_FALSE(res);
  5917. }
  5918. TEST(ServerStopTest, ListenFailure) {
  5919. Server svr;
  5920. auto t = thread([&]() {
  5921. auto ret = svr.listen("????", PORT);
  5922. EXPECT_FALSE(ret);
  5923. });
  5924. svr.wait_until_ready();
  5925. svr.stop();
  5926. t.join();
  5927. }
  5928. TEST(ServerStopTest, Decommision) {
  5929. Server svr;
  5930. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5931. for (int i = 0; i < 4; i++) {
  5932. auto is_even = !(i % 2);
  5933. std::thread t{[&] {
  5934. try {
  5935. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5936. if (is_even) {
  5937. throw std::runtime_error("Some thing that happens to go wrong.");
  5938. }
  5939. svr.listen(HOST, PORT);
  5940. } catch (...) { svr.decommission(); }
  5941. }};
  5942. svr.wait_until_ready();
  5943. // Server is up
  5944. {
  5945. Client cli(HOST, PORT);
  5946. auto res = cli.Get("/hi");
  5947. if (is_even) {
  5948. EXPECT_FALSE(res);
  5949. } else {
  5950. EXPECT_TRUE(res);
  5951. EXPECT_EQ("hi...", res->body);
  5952. }
  5953. }
  5954. svr.stop();
  5955. t.join();
  5956. // Server is down...
  5957. {
  5958. Client cli(HOST, PORT);
  5959. auto res = cli.Get("/hi");
  5960. EXPECT_FALSE(res);
  5961. }
  5962. }
  5963. }
  5964. // Helper function for string body upload progress tests
  5965. template <typename SetupHandler, typename ClientCall>
  5966. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5967. ClientCall &&client_call,
  5968. const string &body) {
  5969. Server svr;
  5970. setup_handler(svr);
  5971. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5972. auto se = detail::scope_exit([&] {
  5973. svr.stop();
  5974. t.join();
  5975. });
  5976. svr.wait_until_ready();
  5977. Client cli(HOST, PORT);
  5978. vector<uint64_t> progress_values;
  5979. bool progress_called = false;
  5980. auto res =
  5981. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5982. progress_values.push_back(current);
  5983. progress_called = true;
  5984. return true;
  5985. });
  5986. ASSERT_TRUE(res);
  5987. EXPECT_EQ(200, res->status);
  5988. EXPECT_TRUE(progress_called);
  5989. }
  5990. TEST(UploadProgressTest, PostStringBodyBasic) {
  5991. TestStringBodyUploadProgress(
  5992. [](Server &svr) {
  5993. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5994. res.set_content("received", "text/plain");
  5995. });
  5996. },
  5997. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5998. return cli.Post("/test", body, "text/plain", progress_callback);
  5999. },
  6000. "test data for upload progress");
  6001. }
  6002. TEST(UploadProgressTest, PutStringBodyBasic) {
  6003. TestStringBodyUploadProgress(
  6004. [](Server &svr) {
  6005. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6006. res.set_content("put received", "text/plain");
  6007. });
  6008. },
  6009. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6010. return cli.Put("/test", body, "text/plain", progress_callback);
  6011. },
  6012. "put test data for upload progress");
  6013. }
  6014. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6015. TestStringBodyUploadProgress(
  6016. [](Server &svr) {
  6017. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6018. res.set_content("patch received", "text/plain");
  6019. });
  6020. },
  6021. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6022. return cli.Patch("/test", body, "text/plain", progress_callback);
  6023. },
  6024. "patch test data for upload progress");
  6025. }
  6026. // Helper function for content provider upload progress tests
  6027. template <typename SetupHandler, typename ClientCall>
  6028. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6029. ClientCall &&client_call) {
  6030. Server svr;
  6031. setup_handler(svr);
  6032. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6033. auto se = detail::scope_exit([&] {
  6034. svr.stop();
  6035. t.join();
  6036. });
  6037. svr.wait_until_ready();
  6038. Client cli(HOST, PORT);
  6039. vector<uint64_t> progress_values;
  6040. auto res =
  6041. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6042. progress_values.push_back(current);
  6043. return true;
  6044. });
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(200, res->status);
  6047. EXPECT_FALSE(progress_values.empty());
  6048. }
  6049. TEST(UploadProgressTest, PostContentProviderProgress) {
  6050. TestContentProviderUploadProgress(
  6051. [](Server &svr) {
  6052. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6053. res.set_content("provider received", "text/plain");
  6054. });
  6055. },
  6056. [](Client &cli, UploadProgress progress_callback) {
  6057. return cli.Post(
  6058. "/test", 10,
  6059. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6060. sink.os << "test data";
  6061. return true;
  6062. },
  6063. "text/plain", progress_callback);
  6064. });
  6065. }
  6066. // Helper function for multipart upload progress tests
  6067. template <typename SetupHandler, typename ClientCall>
  6068. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6069. ClientCall &&client_call,
  6070. const string &endpoint) {
  6071. Server svr;
  6072. setup_handler(svr);
  6073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6074. auto se = detail::scope_exit([&] {
  6075. svr.stop();
  6076. t.join();
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli(HOST, PORT);
  6080. vector<uint64_t> progress_values;
  6081. UploadFormDataItems items = {
  6082. {"field1", "value1", "", ""},
  6083. {"field2", "longer value for progress tracking test", "", ""},
  6084. {"file1", "file content data for upload progress", "test.txt",
  6085. "text/plain"}};
  6086. auto res = client_call(cli, endpoint, items,
  6087. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6088. progress_values.push_back(current);
  6089. return true;
  6090. });
  6091. ASSERT_TRUE(res);
  6092. EXPECT_EQ(200, res->status);
  6093. EXPECT_FALSE(progress_values.empty());
  6094. }
  6095. TEST(UploadProgressTest, PostMultipartProgress) {
  6096. TestMultipartUploadProgress(
  6097. [](Server &svr) {
  6098. svr.Post("/multipart", [](const Request &req, Response &res) {
  6099. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6100. res.set_content("multipart received", "text/plain");
  6101. });
  6102. },
  6103. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6104. UploadProgress progress_callback) {
  6105. return cli.Post(endpoint, items, progress_callback);
  6106. },
  6107. "/multipart");
  6108. }
  6109. // Helper function for basic download progress tests
  6110. template <typename SetupHandler, typename ClientCall>
  6111. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6112. ClientCall &&client_call, const string &endpoint,
  6113. size_t expected_content_size) {
  6114. Server svr;
  6115. setup_handler(svr);
  6116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6117. auto se = detail::scope_exit([&] {
  6118. svr.stop();
  6119. t.join();
  6120. });
  6121. svr.wait_until_ready();
  6122. Client cli(HOST, PORT);
  6123. vector<uint64_t> progress_values;
  6124. auto res = client_call(cli, endpoint,
  6125. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6126. progress_values.push_back(current);
  6127. return true;
  6128. });
  6129. ASSERT_TRUE(res);
  6130. EXPECT_EQ(200, res->status);
  6131. EXPECT_FALSE(progress_values.empty());
  6132. EXPECT_EQ(expected_content_size, res->body.size());
  6133. }
  6134. TEST(DownloadProgressTest, GetBasic) {
  6135. TestBasicDownloadProgress(
  6136. [](Server &svr) {
  6137. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6138. string content(1000, 'D');
  6139. res.set_content(content, "text/plain");
  6140. });
  6141. },
  6142. [](Client &cli, const string &endpoint,
  6143. DownloadProgress progress_callback) {
  6144. return cli.Get(endpoint, progress_callback);
  6145. },
  6146. "/download", 1000u);
  6147. }
  6148. // Helper function for content receiver download progress tests
  6149. template <typename SetupHandler, typename ClientCall>
  6150. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6151. ClientCall &&client_call,
  6152. const string &endpoint,
  6153. size_t expected_content_size) {
  6154. Server svr;
  6155. setup_handler(svr);
  6156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6157. auto se = detail::scope_exit([&] {
  6158. svr.stop();
  6159. t.join();
  6160. });
  6161. svr.wait_until_ready();
  6162. Client cli(HOST, PORT);
  6163. vector<uint64_t> progress_values;
  6164. string received_body;
  6165. auto res = client_call(
  6166. cli, endpoint,
  6167. [&](const char *data, size_t data_length) -> bool {
  6168. received_body.append(data, data_length);
  6169. return true;
  6170. },
  6171. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6172. progress_values.push_back(current);
  6173. return true;
  6174. });
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(200, res->status);
  6177. EXPECT_FALSE(progress_values.empty());
  6178. EXPECT_EQ(expected_content_size, received_body.size());
  6179. EXPECT_TRUE(res->body.empty());
  6180. }
  6181. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6182. TestContentReceiverDownloadProgress(
  6183. [](Server &svr) {
  6184. svr.Get("/download-receiver",
  6185. [](const Request & /*req*/, Response &res) {
  6186. string content(2000, 'R');
  6187. res.set_content(content, "text/plain");
  6188. });
  6189. },
  6190. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6191. DownloadProgress progress_callback) {
  6192. return cli.Get(endpoint, content_receiver, progress_callback);
  6193. },
  6194. "/download-receiver", 2000u);
  6195. }
  6196. TEST(StreamingTest, NoContentLengthStreaming) {
  6197. Server svr;
  6198. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6199. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6200. if (offset < 6) {
  6201. sink.os << (offset < 3 ? "a" : "b");
  6202. } else {
  6203. sink.done();
  6204. }
  6205. return true;
  6206. });
  6207. });
  6208. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6209. auto listen_se = detail::scope_exit([&] {
  6210. svr.stop();
  6211. listen_thread.join();
  6212. ASSERT_FALSE(svr.is_running());
  6213. });
  6214. svr.wait_until_ready();
  6215. Client client(HOST, PORT);
  6216. auto get_thread = std::thread([&client]() {
  6217. std::string s;
  6218. auto res =
  6219. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6220. s += std::string(data, len);
  6221. return true;
  6222. });
  6223. ASSERT_TRUE(res);
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. EXPECT_EQ("aaabbb", s);
  6226. });
  6227. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6228. // Give GET time to get a few messages.
  6229. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6230. }
  6231. TEST(MountTest, Unmount) {
  6232. Server svr;
  6233. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6234. auto se = detail::scope_exit([&] {
  6235. svr.stop();
  6236. listen_thread.join();
  6237. ASSERT_FALSE(svr.is_running());
  6238. });
  6239. svr.wait_until_ready();
  6240. Client cli("localhost", PORT);
  6241. svr.set_mount_point("/mount2", "./www2");
  6242. auto res = cli.Get("/");
  6243. ASSERT_TRUE(res);
  6244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6245. res = cli.Get("/mount2/dir/test.html");
  6246. ASSERT_TRUE(res);
  6247. EXPECT_EQ(StatusCode::OK_200, res->status);
  6248. svr.set_mount_point("/", "./www");
  6249. res = cli.Get("/dir/");
  6250. ASSERT_TRUE(res);
  6251. EXPECT_EQ(StatusCode::OK_200, res->status);
  6252. svr.remove_mount_point("/");
  6253. res = cli.Get("/dir/");
  6254. ASSERT_TRUE(res);
  6255. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6256. svr.remove_mount_point("/mount2");
  6257. res = cli.Get("/mount2/dir/test.html");
  6258. ASSERT_TRUE(res);
  6259. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6260. }
  6261. TEST(MountTest, Redicect) {
  6262. Server svr;
  6263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6264. auto se = detail::scope_exit([&] {
  6265. svr.stop();
  6266. listen_thread.join();
  6267. ASSERT_FALSE(svr.is_running());
  6268. });
  6269. svr.set_mount_point("/", "./www");
  6270. svr.wait_until_ready();
  6271. Client cli("localhost", PORT);
  6272. auto res = cli.Get("/dir/");
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. res = cli.Get("/dir");
  6276. ASSERT_TRUE(res);
  6277. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6278. res = cli.Get("/file");
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. res = cli.Get("/file/");
  6282. ASSERT_TRUE(res);
  6283. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6284. cli.set_follow_location(true);
  6285. res = cli.Get("/dir");
  6286. ASSERT_TRUE(res);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. }
  6289. TEST(MountTest, MultibytesPathName) {
  6290. Server svr;
  6291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6292. auto se = detail::scope_exit([&] {
  6293. svr.stop();
  6294. listen_thread.join();
  6295. ASSERT_FALSE(svr.is_running());
  6296. });
  6297. svr.set_mount_point("/", "./www");
  6298. svr.wait_until_ready();
  6299. Client cli("localhost", PORT);
  6300. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6301. ASSERT_TRUE(res);
  6302. EXPECT_EQ(StatusCode::OK_200, res->status);
  6303. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6304. }
  6305. TEST(KeepAliveTest, ReadTimeout) {
  6306. Server svr;
  6307. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6308. std::this_thread::sleep_for(std::chrono::seconds(2));
  6309. res.set_content("a", "text/plain");
  6310. });
  6311. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6312. res.set_content("b", "text/plain");
  6313. });
  6314. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6315. auto se = detail::scope_exit([&] {
  6316. svr.stop();
  6317. listen_thread.join();
  6318. ASSERT_FALSE(svr.is_running());
  6319. });
  6320. svr.wait_until_ready();
  6321. Client cli("localhost", PORT);
  6322. cli.set_keep_alive(true);
  6323. cli.set_read_timeout(std::chrono::seconds(1));
  6324. auto resa = cli.Get("/a");
  6325. ASSERT_FALSE(resa);
  6326. EXPECT_EQ(Error::Read, resa.error());
  6327. auto resb = cli.Get("/b");
  6328. ASSERT_TRUE(resb);
  6329. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6330. EXPECT_EQ("b", resb->body);
  6331. }
  6332. TEST(KeepAliveTest, MaxCount) {
  6333. size_t keep_alive_max_count = 3;
  6334. Server svr;
  6335. svr.set_keep_alive_max_count(keep_alive_max_count);
  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. for (size_t i = 0; i < 5; i++) {
  6349. auto result = cli.Get("/hi");
  6350. ASSERT_TRUE(result);
  6351. EXPECT_EQ(StatusCode::OK_200, result->status);
  6352. if (i == keep_alive_max_count - 1) {
  6353. EXPECT_EQ("close", result->get_header_value("Connection"));
  6354. } else {
  6355. EXPECT_FALSE(result->has_header("Connection"));
  6356. }
  6357. }
  6358. }
  6359. TEST(KeepAliveTest, Issue1041) {
  6360. Server svr;
  6361. svr.set_keep_alive_timeout(3);
  6362. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6363. res.set_content("Hello World!", "text/plain");
  6364. });
  6365. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6366. auto se = detail::scope_exit([&] {
  6367. svr.stop();
  6368. listen_thread.join();
  6369. ASSERT_FALSE(svr.is_running());
  6370. });
  6371. svr.wait_until_ready();
  6372. Client cli(HOST, PORT);
  6373. cli.set_keep_alive(true);
  6374. auto result = cli.Get("/hi");
  6375. ASSERT_TRUE(result);
  6376. EXPECT_EQ(StatusCode::OK_200, result->status);
  6377. std::this_thread::sleep_for(std::chrono::seconds(5));
  6378. result = cli.Get("/hi");
  6379. ASSERT_TRUE(result);
  6380. EXPECT_EQ(StatusCode::OK_200, result->status);
  6381. }
  6382. TEST(KeepAliveTest, Issue1959) {
  6383. Server svr;
  6384. svr.set_keep_alive_timeout(5);
  6385. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6386. res.set_content("a", "text/plain");
  6387. });
  6388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6389. auto se = detail::scope_exit([&] {
  6390. if (!svr.is_running()) return;
  6391. svr.stop();
  6392. listen_thread.join();
  6393. ASSERT_FALSE(svr.is_running());
  6394. });
  6395. svr.wait_until_ready();
  6396. Client cli("localhost", PORT);
  6397. cli.set_keep_alive(true);
  6398. using namespace std::chrono;
  6399. auto start = steady_clock::now();
  6400. cli.Get("/a");
  6401. svr.stop();
  6402. listen_thread.join();
  6403. auto end = steady_clock::now();
  6404. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6405. EXPECT_LT(elapsed, 5000);
  6406. }
  6407. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6408. TEST(KeepAliveTest, SSLClientReconnection) {
  6409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6410. ASSERT_TRUE(svr.is_valid());
  6411. svr.set_keep_alive_timeout(1);
  6412. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6413. res.set_content("Hello World!", "text/plain");
  6414. });
  6415. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6416. auto se = detail::scope_exit([&] {
  6417. svr.stop();
  6418. listen_thread.join();
  6419. ASSERT_FALSE(svr.is_running());
  6420. });
  6421. svr.wait_until_ready();
  6422. SSLClient cli(HOST, PORT);
  6423. cli.enable_server_certificate_verification(false);
  6424. cli.set_keep_alive(true);
  6425. auto result = cli.Get("/hi");
  6426. ASSERT_TRUE(result);
  6427. EXPECT_EQ(StatusCode::OK_200, result->status);
  6428. result = cli.Get("/hi");
  6429. ASSERT_TRUE(result);
  6430. EXPECT_EQ(StatusCode::OK_200, result->status);
  6431. std::this_thread::sleep_for(std::chrono::seconds(2));
  6432. // Recoonect
  6433. result = cli.Get("/hi");
  6434. ASSERT_TRUE(result);
  6435. EXPECT_EQ(StatusCode::OK_200, result->status);
  6436. result = cli.Get("/hi");
  6437. ASSERT_TRUE(result);
  6438. EXPECT_EQ(StatusCode::OK_200, result->status);
  6439. }
  6440. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6442. ASSERT_TRUE(svr.is_valid());
  6443. svr.set_keep_alive_timeout(1);
  6444. std::string content = "reconnect";
  6445. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6446. res.set_content("Hello World!", "text/plain");
  6447. });
  6448. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6449. auto se = detail::scope_exit([&] {
  6450. svr.stop();
  6451. listen_thread.join();
  6452. ASSERT_FALSE(svr.is_running());
  6453. });
  6454. svr.wait_until_ready();
  6455. SSLClient cli(HOST, PORT);
  6456. cli.enable_server_certificate_verification(false);
  6457. cli.set_keep_alive(true);
  6458. auto result = cli.Post(
  6459. "/hi", content.size(),
  6460. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6461. sink.write(content.c_str(), content.size());
  6462. return true;
  6463. },
  6464. "text/plain");
  6465. ASSERT_TRUE(result);
  6466. EXPECT_EQ(200, result->status);
  6467. std::this_thread::sleep_for(std::chrono::seconds(2));
  6468. // Recoonect
  6469. result = cli.Post(
  6470. "/hi", content.size(),
  6471. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6472. sink.write(content.c_str(), content.size());
  6473. return true;
  6474. },
  6475. "text/plain");
  6476. ASSERT_TRUE(result);
  6477. EXPECT_EQ(200, result->status);
  6478. result = cli.Post(
  6479. "/hi", content.size(),
  6480. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6481. sink.write(content.c_str(), content.size());
  6482. return true;
  6483. },
  6484. "text/plain");
  6485. ASSERT_TRUE(result);
  6486. EXPECT_EQ(200, result->status);
  6487. }
  6488. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6489. {
  6490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6491. ASSERT_TRUE(svr.is_valid());
  6492. svr.Get("/sni", [&](const Request &req, Response &res) {
  6493. std::string expected;
  6494. if (req.ssl) {
  6495. if (const char *sni =
  6496. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6497. expected = sni;
  6498. }
  6499. }
  6500. EXPECT_EQ(expected, req.get_param_value("expected"));
  6501. res.set_content("ok", "text/plain");
  6502. });
  6503. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6504. auto se = detail::scope_exit([&] {
  6505. svr.stop();
  6506. listen_thread.join();
  6507. ASSERT_FALSE(svr.is_running());
  6508. });
  6509. svr.wait_until_ready();
  6510. {
  6511. SSLClient cli("localhost", PORT);
  6512. cli.enable_server_certificate_verification(false);
  6513. auto res = cli.Get("/sni?expected=localhost");
  6514. ASSERT_TRUE(res);
  6515. }
  6516. {
  6517. SSLClient cli("::1", PORT);
  6518. cli.enable_server_certificate_verification(false);
  6519. auto res = cli.Get("/sni?expected=");
  6520. // NOTE: This may fail if the server is listening on IPv4 only
  6521. // (e.g., when localhost resolves to 127.0.0.1 only)
  6522. if (res) {
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. } else {
  6525. EXPECT_EQ(Error::Connection, res.error());
  6526. }
  6527. }
  6528. }
  6529. }
  6530. #endif
  6531. TEST(ClientProblemDetectionTest, ContentProvider) {
  6532. Server svr;
  6533. size_t content_length = 1024 * 1024;
  6534. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6535. res.set_content_provider(
  6536. content_length, "text/plain",
  6537. [&](size_t offset, size_t length, DataSink &sink) {
  6538. auto out_len = std::min(length, static_cast<size_t>(1024));
  6539. std::string out(out_len, '@');
  6540. sink.write(out.data(), out_len);
  6541. return offset < 4096;
  6542. },
  6543. [](bool success) { ASSERT_FALSE(success); });
  6544. });
  6545. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6546. res.set_content_provider(
  6547. 0, "text/plain",
  6548. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6549. EXPECT_TRUE(false);
  6550. return true;
  6551. },
  6552. [](bool success) { ASSERT_FALSE(success); });
  6553. });
  6554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6555. auto se = detail::scope_exit([&] {
  6556. svr.stop();
  6557. listen_thread.join();
  6558. ASSERT_FALSE(svr.is_running());
  6559. });
  6560. svr.wait_until_ready();
  6561. Client cli("localhost", PORT);
  6562. {
  6563. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6564. size_t /*data_length*/) { return false; });
  6565. ASSERT_FALSE(res);
  6566. }
  6567. {
  6568. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6569. size_t /*data_length*/) { return false; });
  6570. ASSERT_TRUE(res);
  6571. }
  6572. }
  6573. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6574. Server svr;
  6575. svr.set_error_handler([](Request const &, Response &res) -> void {
  6576. res.set_chunked_content_provider(
  6577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6578. sink.os << "hello";
  6579. sink.os << "world";
  6580. sink.done();
  6581. return true;
  6582. });
  6583. });
  6584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6585. auto se = detail::scope_exit([&] {
  6586. svr.stop();
  6587. listen_thread.join();
  6588. ASSERT_FALSE(svr.is_running());
  6589. });
  6590. svr.wait_until_ready();
  6591. Client cli("localhost", PORT);
  6592. auto res = cli.Get("/");
  6593. ASSERT_TRUE(res);
  6594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6595. EXPECT_EQ("helloworld", res->body);
  6596. }
  6597. TEST(LongPollingTest, ClientCloseDetection) {
  6598. Server svr;
  6599. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6600. res.set_chunked_content_provider(
  6601. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6602. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6603. sink.os << "hello";
  6604. auto count = 10;
  6605. while (count > 0 && sink.is_writable()) {
  6606. this_thread::sleep_for(chrono::milliseconds(10));
  6607. count--;
  6608. }
  6609. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6610. return true;
  6611. });
  6612. });
  6613. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6614. auto se = detail::scope_exit([&] {
  6615. svr.stop();
  6616. listen_thread.join();
  6617. ASSERT_FALSE(svr.is_running());
  6618. });
  6619. svr.wait_until_ready();
  6620. Client cli("localhost", PORT);
  6621. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6622. EXPECT_EQ("hello", string(data, data_length));
  6623. return false; // close the socket immediately.
  6624. });
  6625. ASSERT_FALSE(res);
  6626. }
  6627. TEST(GetWithParametersTest, GetWithParameters) {
  6628. Server svr;
  6629. svr.Get("/", [&](const Request &req, Response &) {
  6630. EXPECT_EQ("world", req.get_param_value("hello"));
  6631. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6632. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6633. });
  6634. svr.Get("/params", [&](const Request &req, Response &) {
  6635. EXPECT_EQ("world", req.get_param_value("hello"));
  6636. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6637. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6638. });
  6639. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6640. EXPECT_EQ("resource-id", req.matches[1]);
  6641. EXPECT_EQ("foo", req.get_param_value("param1"));
  6642. EXPECT_EQ("bar", req.get_param_value("param2"));
  6643. });
  6644. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6645. EXPECT_EQ("user-id", req.path_params.at("id"));
  6646. EXPECT_EQ("foo", req.get_param_value("param1"));
  6647. EXPECT_EQ("bar", req.get_param_value("param2"));
  6648. });
  6649. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6650. auto se = detail::scope_exit([&] {
  6651. svr.stop();
  6652. listen_thread.join();
  6653. ASSERT_FALSE(svr.is_running());
  6654. });
  6655. svr.wait_until_ready();
  6656. {
  6657. Client cli(HOST, PORT);
  6658. Params params;
  6659. params.emplace("hello", "world");
  6660. params.emplace("hello2", "world2");
  6661. params.emplace("hello3", "world3");
  6662. auto res = cli.Get("/", params, Headers{});
  6663. ASSERT_TRUE(res);
  6664. EXPECT_EQ(StatusCode::OK_200, res->status);
  6665. }
  6666. {
  6667. Client cli(HOST, PORT);
  6668. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6669. ASSERT_TRUE(res);
  6670. EXPECT_EQ(StatusCode::OK_200, res->status);
  6671. }
  6672. {
  6673. Client cli(HOST, PORT);
  6674. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6675. ASSERT_TRUE(res);
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. }
  6678. {
  6679. Client cli(HOST, PORT);
  6680. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. }
  6684. }
  6685. TEST(GetWithParametersTest, GetWithParameters2) {
  6686. Server svr;
  6687. svr.Get("/", [&](const Request &req, Response &res) {
  6688. auto text = req.get_param_value("hello");
  6689. res.set_content(text, "text/plain");
  6690. });
  6691. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6692. auto se = detail::scope_exit([&] {
  6693. svr.stop();
  6694. listen_thread.join();
  6695. ASSERT_FALSE(svr.is_running());
  6696. });
  6697. svr.wait_until_ready();
  6698. Client cli("localhost", PORT);
  6699. Params params;
  6700. params.emplace("hello", "world");
  6701. std::string body;
  6702. auto res = cli.Get("/", params, Headers{},
  6703. [&](const char *data, size_t data_length) {
  6704. body.append(data, data_length);
  6705. return true;
  6706. });
  6707. ASSERT_TRUE(res);
  6708. EXPECT_EQ(StatusCode::OK_200, res->status);
  6709. EXPECT_EQ("world", body);
  6710. }
  6711. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6712. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6713. auto host = "httpcan.org";
  6714. auto path = std::string{"/range/32"};
  6715. #else
  6716. auto host = "nghttp2.org";
  6717. auto path = std::string{"/httpbin/range/32"};
  6718. #endif
  6719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6720. SSLClient cli(host);
  6721. #else
  6722. Client cli(host);
  6723. #endif
  6724. cli.set_default_headers({make_range_header({{1, 10}})});
  6725. cli.set_connection_timeout(5);
  6726. {
  6727. auto res = cli.Get(path);
  6728. ASSERT_TRUE(res);
  6729. EXPECT_EQ("bcdefghijk", res->body);
  6730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6731. }
  6732. {
  6733. auto res = cli.Get(path);
  6734. ASSERT_TRUE(res);
  6735. EXPECT_EQ("bcdefghijk", res->body);
  6736. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6737. }
  6738. }
  6739. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6740. Server svr;
  6741. svr.set_default_headers({{"Hello", "World"}});
  6742. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6743. res.set_content("ok", "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. Client cli("localhost", PORT);
  6753. auto res = cli.Get("/");
  6754. ASSERT_TRUE(res);
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. EXPECT_EQ("ok", res->body);
  6757. EXPECT_EQ("World", res->get_header_value("Hello"));
  6758. }
  6759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6760. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6762. ASSERT_TRUE(svr.is_valid());
  6763. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6764. std::this_thread::sleep_for(std::chrono::seconds(2));
  6765. res.set_content("a", "text/plain");
  6766. });
  6767. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6768. res.set_content("b", "text/plain");
  6769. });
  6770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6771. auto se = detail::scope_exit([&] {
  6772. svr.stop();
  6773. listen_thread.join();
  6774. ASSERT_FALSE(svr.is_running());
  6775. });
  6776. svr.wait_until_ready();
  6777. SSLClient cli("localhost", PORT);
  6778. cli.enable_server_certificate_verification(false);
  6779. cli.set_keep_alive(true);
  6780. cli.set_read_timeout(std::chrono::seconds(1));
  6781. auto resa = cli.Get("/a");
  6782. ASSERT_TRUE(!resa);
  6783. EXPECT_EQ(Error::Read, resa.error());
  6784. auto resb = cli.Get("/b");
  6785. ASSERT_TRUE(resb);
  6786. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6787. EXPECT_EQ("b", resb->body);
  6788. }
  6789. #endif
  6790. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6791. protected:
  6792. ServerTestWithAI_PASSIVE()
  6793. : cli_(HOST, PORT)
  6794. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6795. ,
  6796. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6797. #endif
  6798. {
  6799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6800. cli_.enable_server_certificate_verification(false);
  6801. #endif
  6802. }
  6803. virtual void SetUp() {
  6804. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6805. res.set_content("Hello World!", "text/plain");
  6806. });
  6807. t_ = thread(
  6808. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6809. svr_.wait_until_ready();
  6810. }
  6811. virtual void TearDown() {
  6812. svr_.stop();
  6813. t_.join();
  6814. }
  6815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6816. SSLClient cli_;
  6817. SSLServer svr_;
  6818. #else
  6819. Client cli_;
  6820. Server svr_;
  6821. #endif
  6822. thread t_;
  6823. };
  6824. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6825. auto res = cli_.Get("/hi");
  6826. ASSERT_TRUE(res);
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6829. EXPECT_EQ("Hello World!", res->body);
  6830. }
  6831. class ServerUpDownTest : public ::testing::Test {
  6832. protected:
  6833. ServerUpDownTest() : cli_(HOST, PORT) {}
  6834. virtual void SetUp() {
  6835. t_ = thread([&]() {
  6836. svr_.bind_to_any_port(HOST);
  6837. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6838. ASSERT_TRUE(svr_.listen_after_bind());
  6839. });
  6840. svr_.wait_until_ready();
  6841. }
  6842. virtual void TearDown() {
  6843. svr_.stop();
  6844. t_.join();
  6845. }
  6846. Client cli_;
  6847. Server svr_;
  6848. thread t_;
  6849. };
  6850. TEST_F(ServerUpDownTest, QuickStartStop) {
  6851. // Should not crash, especially when run with
  6852. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6853. }
  6854. class PayloadMaxLengthTest : public ::testing::Test {
  6855. protected:
  6856. PayloadMaxLengthTest()
  6857. : cli_(HOST, PORT)
  6858. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6859. ,
  6860. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6861. #endif
  6862. {
  6863. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6864. cli_.enable_server_certificate_verification(false);
  6865. #endif
  6866. }
  6867. virtual void SetUp() {
  6868. svr_.set_payload_max_length(8);
  6869. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6870. res.set_content("test", "text/plain");
  6871. });
  6872. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6873. svr_.wait_until_ready();
  6874. }
  6875. virtual void TearDown() {
  6876. svr_.stop();
  6877. t_.join();
  6878. }
  6879. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6880. SSLClient cli_;
  6881. SSLServer svr_;
  6882. #else
  6883. Client cli_;
  6884. Server svr_;
  6885. #endif
  6886. thread t_;
  6887. };
  6888. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6889. auto res = cli_.Post("/test", "123456789", "text/plain");
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6892. res = cli_.Post("/test", "12345678", "text/plain");
  6893. ASSERT_TRUE(res);
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. }
  6896. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6897. // Test chunked encoding with payload exceeding the 8-byte limit
  6898. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6899. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6900. ASSERT_TRUE(res);
  6901. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6902. }
  6903. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6904. // Test chunked encoding with payload within the 8-byte limit
  6905. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6906. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6907. ASSERT_TRUE(res);
  6908. EXPECT_EQ(StatusCode::OK_200, res->status);
  6909. }
  6910. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6911. // Test using send_request to send chunked data exceeding payload limit
  6912. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6913. "Host: " +
  6914. std::string(HOST) + ":" + std::to_string(PORT) +
  6915. "\r\n"
  6916. "Transfer-Encoding: chunked\r\n"
  6917. "Connection: close\r\n"
  6918. "\r\n"
  6919. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6920. "0123456789\r\n"
  6921. "0\r\n" // End chunk
  6922. "\r\n";
  6923. std::string response;
  6924. bool result = send_request(1, chunked_request, &response);
  6925. if (!result) {
  6926. // If send_request fails, it might be because the server closed the
  6927. // connection due to payload limit enforcement, which is acceptable
  6928. SUCCEED()
  6929. << "Server rejected oversized chunked request (connection closed)";
  6930. } else {
  6931. // If we got a response, check if it's an error response or connection was
  6932. // closed early Short response length indicates connection was closed due to
  6933. // payload limit
  6934. if (response.length() <= 10) {
  6935. SUCCEED() << "Server closed connection for oversized chunked request";
  6936. } else {
  6937. // Check for error status codes
  6938. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6939. response.find("Payload Too Large") != std::string::npos ||
  6940. response.find("400") != std::string::npos);
  6941. }
  6942. }
  6943. }
  6944. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6945. // Test request without Content-Length header exceeding payload limit
  6946. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6947. "Host: " +
  6948. std::string(HOST) + ":" +
  6949. std::to_string(PORT) +
  6950. "\r\n"
  6951. "Connection: close\r\n"
  6952. "\r\n";
  6953. // Add payload exceeding the 8-byte limit
  6954. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6955. request_without_content_length += large_payload;
  6956. std::string response;
  6957. bool result = send_request(1, request_without_content_length, &response);
  6958. if (!result) {
  6959. // If send_request fails, server likely closed connection due to payload
  6960. // limit
  6961. SUCCEED() << "Server rejected oversized request without Content-Length "
  6962. "(connection closed)";
  6963. } else {
  6964. // Check if server responded with error or closed connection early
  6965. if (response.length() <= 10) {
  6966. SUCCEED() << "Server closed connection for oversized request without "
  6967. "Content-Length";
  6968. } else {
  6969. // Check for error status codes
  6970. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6971. response.find("Payload Too Large") != std::string::npos ||
  6972. response.find("400") != std::string::npos);
  6973. }
  6974. }
  6975. }
  6976. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6977. // Test request without Content-Length header within payload limit
  6978. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6979. "Host: " +
  6980. std::string(HOST) + ":" +
  6981. std::to_string(PORT) +
  6982. "\r\n"
  6983. "Connection: close\r\n"
  6984. "\r\n";
  6985. // Add payload within the 8-byte limit
  6986. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6987. request_without_content_length += small_payload;
  6988. std::string response;
  6989. bool result = send_request(1, request_without_content_length, &response);
  6990. // For requests without Content-Length, the server may have different behavior
  6991. // The key is that it should not reject due to payload limit for small
  6992. // payloads
  6993. if (result) {
  6994. // Check for any HTTP response (success or error, but not connection closed)
  6995. if (response.length() > 10) {
  6996. SUCCEED()
  6997. << "Server processed request without Content-Length within limit";
  6998. } else {
  6999. // Short response might indicate connection closed, which is acceptable
  7000. SUCCEED() << "Server closed connection for request without "
  7001. "Content-Length (acceptable behavior)";
  7002. }
  7003. } else {
  7004. // Connection failure might be due to protocol requirements
  7005. SUCCEED() << "Connection issue with request without Content-Length "
  7006. "(environment-specific)";
  7007. }
  7008. }
  7009. class LargePayloadMaxLengthTest : public ::testing::Test {
  7010. protected:
  7011. LargePayloadMaxLengthTest()
  7012. : cli_(HOST, PORT)
  7013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7014. ,
  7015. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7016. #endif
  7017. {
  7018. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7019. cli_.enable_server_certificate_verification(false);
  7020. #endif
  7021. }
  7022. virtual void SetUp() {
  7023. // Set 10MB payload limit
  7024. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7025. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7026. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7027. res.set_content("Large payload test", "text/plain");
  7028. });
  7029. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7030. svr_.wait_until_ready();
  7031. }
  7032. virtual void TearDown() {
  7033. svr_.stop();
  7034. t_.join();
  7035. }
  7036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7037. SSLClient cli_;
  7038. SSLServer svr_;
  7039. #else
  7040. Client cli_;
  7041. Server svr_;
  7042. #endif
  7043. thread t_;
  7044. };
  7045. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7046. // Test chunked encoding with payload within 10MB limit
  7047. std::string medium_payload(5 * 1024 * 1024,
  7048. 'A'); // 5MB payload, within 10MB limit
  7049. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7050. ASSERT_TRUE(res);
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7054. // Test chunked encoding with payload exceeding 10MB limit
  7055. std::string large_payload(12 * 1024 * 1024,
  7056. 'B'); // 12MB payload, exceeds 10MB limit
  7057. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7058. ASSERT_TRUE(res);
  7059. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7060. }
  7061. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7062. // Test request without Content-Length header within 10MB limit
  7063. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7064. "Host: " +
  7065. std::string(HOST) + ":" +
  7066. std::to_string(PORT) +
  7067. "\r\n"
  7068. "Connection: close\r\n"
  7069. "\r\n";
  7070. // Add 1MB payload (within 10MB limit)
  7071. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7072. request_without_content_length += medium_payload;
  7073. std::string response;
  7074. bool result = send_request(5, request_without_content_length, &response);
  7075. if (result) {
  7076. // Should get a proper HTTP response for payloads within limit
  7077. if (response.length() > 10) {
  7078. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7079. "10MB limit";
  7080. } else {
  7081. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7082. "Content-Length)";
  7083. }
  7084. } else {
  7085. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7086. }
  7087. }
  7088. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7089. // Test request without Content-Length header exceeding 10MB limit
  7090. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7091. "Host: " +
  7092. std::string(HOST) + ":" +
  7093. std::to_string(PORT) +
  7094. "\r\n"
  7095. "Connection: close\r\n"
  7096. "\r\n";
  7097. // Add 12MB payload (exceeds 10MB limit)
  7098. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7099. request_without_content_length += large_payload;
  7100. std::string response;
  7101. bool result = send_request(10, request_without_content_length, &response);
  7102. if (!result) {
  7103. // Server should close connection due to payload limit
  7104. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7105. "(connection closed)";
  7106. } else {
  7107. // Check for error response
  7108. if (response.length() <= 10) {
  7109. SUCCEED()
  7110. << "Server closed connection for 12MB request exceeding 10MB limit";
  7111. } else {
  7112. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7113. response.find("Payload Too Large") != std::string::npos ||
  7114. response.find("400") != std::string::npos);
  7115. }
  7116. }
  7117. }
  7118. TEST(HostAndPortPropertiesTest, NoSSL) {
  7119. httplib::Client cli("www.google.com", 1234);
  7120. ASSERT_EQ("www.google.com", cli.host());
  7121. ASSERT_EQ(1234, cli.port());
  7122. }
  7123. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7124. httplib::Client cli("www.google.com:1234");
  7125. ASSERT_EQ("www.google.com", cli.host());
  7126. ASSERT_EQ(1234, cli.port());
  7127. }
  7128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7129. TEST(HostAndPortPropertiesTest, SSL) {
  7130. httplib::SSLClient cli("www.google.com");
  7131. ASSERT_EQ("www.google.com", cli.host());
  7132. ASSERT_EQ(443, cli.port());
  7133. }
  7134. #endif
  7135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7136. TEST(SSLClientTest, UpdateCAStore) {
  7137. httplib::SSLClient httplib_client("www.google.com");
  7138. auto ca_store_1 = X509_STORE_new();
  7139. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7140. nullptr);
  7141. httplib_client.set_ca_cert_store(ca_store_1);
  7142. auto ca_store_2 = X509_STORE_new();
  7143. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7144. nullptr);
  7145. httplib_client.set_ca_cert_store(ca_store_2);
  7146. }
  7147. TEST(SSLClientTest, ServerNameIndication_Online) {
  7148. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7149. auto host = "httpcan.org";
  7150. auto path = std::string{"/get"};
  7151. #else
  7152. auto host = "nghttp2.org";
  7153. auto path = std::string{"/httpbin/get"};
  7154. #endif
  7155. SSLClient cli(host, 443);
  7156. auto res = cli.Get(path);
  7157. ASSERT_TRUE(res);
  7158. ASSERT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7161. // Use a site that will cause SSL verification failure due to self-signed cert
  7162. SSLClient cli("self-signed.badssl.com", 443);
  7163. cli.enable_server_certificate_verification(true);
  7164. auto res = cli.Get("/");
  7165. ASSERT_TRUE(!res);
  7166. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7167. // For SSL server verification errors, ssl_error should be 0, only
  7168. // ssl_openssl_error should be set
  7169. EXPECT_EQ(0, res.ssl_error());
  7170. // Verify OpenSSL error is captured for SSLServerVerification
  7171. // This occurs when SSL_get_verify_result() returns a verification failure
  7172. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7173. res.ssl_openssl_error());
  7174. }
  7175. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7176. // Use a site where hostname doesn't match the certificate
  7177. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7178. SSLClient cli("wrong.host.badssl.com", 443);
  7179. cli.enable_server_certificate_verification(true);
  7180. cli.enable_server_hostname_verification(true);
  7181. auto res = cli.Get("/");
  7182. ASSERT_TRUE(!res);
  7183. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7184. // For SSL hostname verification errors, ssl_error should be 0, only
  7185. // ssl_openssl_error should be set
  7186. EXPECT_EQ(0, res.ssl_error());
  7187. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7188. // This occurs when verify_host() fails due to hostname mismatch
  7189. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7190. res.ssl_openssl_error());
  7191. }
  7192. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7193. Client cli("https://google.com");
  7194. auto res = cli.Get("/");
  7195. ASSERT_TRUE(res);
  7196. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7197. }
  7198. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7199. SSLClient cli("google.com");
  7200. cli.set_ca_cert_path(CA_CERT_FILE);
  7201. auto res = cli.Get("/");
  7202. ASSERT_TRUE(res);
  7203. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7204. }
  7205. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7206. SSLClient cli("google.com");
  7207. cli.enable_server_certificate_verification(true);
  7208. cli.set_ca_cert_path("hello");
  7209. auto res = cli.Get("/");
  7210. ASSERT_TRUE(!res);
  7211. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7212. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7213. // should be set
  7214. EXPECT_EQ(0, res.ssl_error());
  7215. // Verify OpenSSL error is captured for SSLLoadingCerts
  7216. // This error occurs when SSL_CTX_load_verify_locations() fails
  7217. // > openssl errstr 0x80000002
  7218. // error:80000002:system library::No such file or directory
  7219. // > openssl errstr 0xA000126
  7220. // error:0A000126:SSL routines::unexpected eof while reading
  7221. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7222. res.ssl_openssl_error() == 0xA000126);
  7223. }
  7224. TEST(SSLClientTest, ServerCertificateVerification4) {
  7225. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7226. ASSERT_TRUE(svr.is_valid());
  7227. svr.Get("/test", [&](const Request &, Response &res) {
  7228. res.set_content("test", "text/plain");
  7229. svr.stop();
  7230. ASSERT_TRUE(true);
  7231. });
  7232. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7233. auto se = detail::scope_exit([&] {
  7234. t.join();
  7235. ASSERT_FALSE(svr.is_running());
  7236. });
  7237. svr.wait_until_ready();
  7238. SSLClient cli("127.0.0.1", PORT);
  7239. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7240. cli.enable_server_certificate_verification(true);
  7241. cli.set_connection_timeout(30);
  7242. auto res = cli.Get("/test");
  7243. ASSERT_TRUE(res);
  7244. ASSERT_EQ(StatusCode::OK_200, res->status);
  7245. }
  7246. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7247. std::string cert;
  7248. read_file(CA_CERT_FILE, cert);
  7249. SSLClient cli("google.com");
  7250. cli.load_ca_cert_store(cert.data(), cert.size());
  7251. const auto res = cli.Get("/");
  7252. ASSERT_TRUE(res);
  7253. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7254. }
  7255. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7256. // clang-format off
  7257. static constexpr char cert[] =
  7258. "GlobalSign Root CA\n"
  7259. "==================\n"
  7260. "-----BEGIN CERTIFICATE-----\n"
  7261. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7262. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7263. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7264. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7265. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7266. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7267. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7268. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7269. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7270. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7271. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7272. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7273. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7274. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7275. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7276. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7277. "-----END CERTIFICATE-----\n";
  7278. // clang-format on
  7279. SSLClient cli("google.com");
  7280. cli.load_ca_cert_store(cert, sizeof(cert));
  7281. const auto res = cli.Get("/");
  7282. ASSERT_TRUE(res);
  7283. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7284. }
  7285. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7286. SSLClient cli("www.youtube.com");
  7287. cli.set_ca_cert_path(CA_CERT_FILE);
  7288. cli.enable_server_certificate_verification(true);
  7289. cli.set_follow_location(true);
  7290. auto res = cli.Get("/");
  7291. ASSERT_TRUE(res);
  7292. ASSERT_EQ(StatusCode::OK_200, res->status);
  7293. }
  7294. TEST(SSLClientTest, Issue2004_Online) {
  7295. Client client("https://google.com");
  7296. client.set_follow_location(true);
  7297. auto res = client.Get("/");
  7298. ASSERT_TRUE(res);
  7299. ASSERT_EQ(StatusCode::OK_200, res->status);
  7300. auto body = res->body;
  7301. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7302. }
  7303. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7304. // Create SSLClient with invalid cert/key to make is_valid() return false
  7305. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7306. "nonexistent_key.pem");
  7307. // is_valid() should be false due to cert loading failure
  7308. ASSERT_FALSE(cli.is_valid());
  7309. auto res = cli.Get("/");
  7310. ASSERT_FALSE(res);
  7311. EXPECT_EQ(Error::SSLConnection, res.error());
  7312. }
  7313. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7314. // Test for Issue #2251: SSL error not properly reported when client cert
  7315. // and key paths are swapped or mismatched
  7316. // This simulates the scenario where user accidentally swaps the cert and key
  7317. // files
  7318. // Using client cert file as private key and vice versa (completely wrong)
  7319. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7320. // Should fail validation due to cert/key mismatch
  7321. ASSERT_FALSE(cli.is_valid());
  7322. // Attempt to make a request should fail with proper error
  7323. auto res = cli.Get("/");
  7324. ASSERT_FALSE(res);
  7325. EXPECT_EQ(Error::SSLConnection, res.error());
  7326. // SSL error should be recorded in the Result object (this is the key fix for
  7327. // Issue #2251)
  7328. auto openssl_error = res.ssl_openssl_error();
  7329. EXPECT_NE(0u, openssl_error);
  7330. }
  7331. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7332. // Another variant: using valid file paths but with mismatched cert/key pair
  7333. // This tests the case where files exist but contain incompatible key material
  7334. // Using client cert with wrong key (cert2 key)
  7335. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7336. // Should fail validation
  7337. ASSERT_FALSE(cli.is_valid());
  7338. auto res = cli.Get("/");
  7339. ASSERT_FALSE(res);
  7340. // Must report error properly, not appear as success
  7341. EXPECT_EQ(Error::SSLConnection, res.error());
  7342. // OpenSSL error should be captured in Result
  7343. EXPECT_NE(0u, res.ssl_openssl_error());
  7344. }
  7345. #if 0
  7346. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7347. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7348. ASSERT_TRUE(cli != nullptr);
  7349. cli->set_address_family(AF_INET6);
  7350. cli->set_interface("en0");
  7351. auto res = cli->Get("/get");
  7352. ASSERT_TRUE(res);
  7353. ASSERT_EQ(StatusCode::OK_200, res->status);
  7354. }
  7355. #endif
  7356. void ClientCertPresent(
  7357. const std::string &client_cert_file,
  7358. const std::string &client_private_key_file,
  7359. const std::string &client_encrypted_private_key_pass = std::string()) {
  7360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7361. CLIENT_CA_CERT_DIR);
  7362. ASSERT_TRUE(svr.is_valid());
  7363. svr.Get("/test", [&](const Request &req, Response &res) {
  7364. res.set_content("test", "text/plain");
  7365. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7366. ASSERT_TRUE(peer_cert != nullptr);
  7367. auto subject_name = X509_get_subject_name(peer_cert);
  7368. ASSERT_TRUE(subject_name != nullptr);
  7369. std::string common_name;
  7370. {
  7371. char name[BUFSIZ];
  7372. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7373. name, sizeof(name));
  7374. common_name.assign(name, static_cast<size_t>(name_len));
  7375. }
  7376. EXPECT_EQ("Common Name", common_name);
  7377. X509_free(peer_cert);
  7378. });
  7379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7380. auto se = detail::scope_exit([&] {
  7381. svr.stop();
  7382. t.join();
  7383. ASSERT_FALSE(svr.is_running());
  7384. });
  7385. svr.wait_until_ready();
  7386. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7387. client_encrypted_private_key_pass);
  7388. cli.enable_server_certificate_verification(false);
  7389. cli.set_connection_timeout(30);
  7390. auto res = cli.Get("/test");
  7391. ASSERT_TRUE(res);
  7392. ASSERT_EQ(StatusCode::OK_200, res->status);
  7393. }
  7394. TEST(SSLClientServerTest, ClientCertPresent) {
  7395. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7396. }
  7397. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7398. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7399. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7400. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7401. }
  7402. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7403. void MemoryClientCertPresent(
  7404. const std::string &client_cert_file,
  7405. const std::string &client_private_key_file,
  7406. const std::string &client_encrypted_private_key_pass = std::string()) {
  7407. auto f = fopen(SERVER_CERT_FILE, "r+");
  7408. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7409. fclose(f);
  7410. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7411. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7412. fclose(f);
  7413. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7414. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7415. auto client_ca_cert_store = X509_STORE_new();
  7416. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7417. X509_free(client_cert);
  7418. fclose(f);
  7419. f = fopen(client_cert_file.c_str(), "r+");
  7420. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7421. fclose(f);
  7422. f = fopen(client_private_key_file.c_str(), "r+");
  7423. auto client_private_key = PEM_read_PrivateKey(
  7424. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7425. fclose(f);
  7426. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7427. ASSERT_TRUE(svr.is_valid());
  7428. svr.Get("/test", [&](const Request &req, Response &res) {
  7429. res.set_content("test", "text/plain");
  7430. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7431. ASSERT_TRUE(peer_cert != nullptr);
  7432. auto subject_name = X509_get_subject_name(peer_cert);
  7433. ASSERT_TRUE(subject_name != nullptr);
  7434. std::string common_name;
  7435. {
  7436. char name[BUFSIZ];
  7437. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7438. name, sizeof(name));
  7439. common_name.assign(name, static_cast<size_t>(name_len));
  7440. }
  7441. EXPECT_EQ("Common Name", common_name);
  7442. X509_free(peer_cert);
  7443. });
  7444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7445. auto se = detail::scope_exit([&] {
  7446. svr.stop();
  7447. t.join();
  7448. ASSERT_FALSE(svr.is_running());
  7449. });
  7450. svr.wait_until_ready();
  7451. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7452. client_encrypted_private_key_pass);
  7453. cli.enable_server_certificate_verification(false);
  7454. cli.set_connection_timeout(30);
  7455. auto res = cli.Get("/test");
  7456. ASSERT_TRUE(res);
  7457. ASSERT_EQ(StatusCode::OK_200, res->status);
  7458. X509_free(server_cert);
  7459. EVP_PKEY_free(server_private_key);
  7460. X509_free(client_cert);
  7461. EVP_PKEY_free(client_private_key);
  7462. }
  7463. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7464. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7465. }
  7466. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7467. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7468. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7469. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7470. }
  7471. #endif
  7472. TEST(SSLClientServerTest, ClientCertMissing) {
  7473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7474. CLIENT_CA_CERT_DIR);
  7475. ASSERT_TRUE(svr.is_valid());
  7476. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7478. auto se = detail::scope_exit([&] {
  7479. svr.stop();
  7480. t.join();
  7481. ASSERT_FALSE(svr.is_running());
  7482. });
  7483. svr.wait_until_ready();
  7484. SSLClient cli(HOST, PORT);
  7485. cli.set_connection_timeout(30);
  7486. auto res = cli.Get("/test");
  7487. ASSERT_TRUE(!res);
  7488. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7489. // For SSL server verification errors, ssl_error should be 0, only
  7490. // ssl_openssl_error should be set
  7491. EXPECT_EQ(0, res.ssl_error());
  7492. // Verify OpenSSL error is captured for SSLServerVerification
  7493. // Note: This test may have different error codes depending on the exact
  7494. // verification failure
  7495. EXPECT_NE(0UL, res.ssl_openssl_error());
  7496. }
  7497. TEST(SSLClientServerTest, TrustDirOptional) {
  7498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7499. ASSERT_TRUE(svr.is_valid());
  7500. svr.Get("/test", [&](const Request &, Response &res) {
  7501. res.set_content("test", "text/plain");
  7502. });
  7503. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7504. auto se = detail::scope_exit([&] {
  7505. svr.stop();
  7506. t.join();
  7507. ASSERT_FALSE(svr.is_running());
  7508. });
  7509. svr.wait_until_ready();
  7510. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7511. cli.enable_server_certificate_verification(false);
  7512. cli.set_connection_timeout(30);
  7513. auto res = cli.Get("/test");
  7514. ASSERT_TRUE(res);
  7515. ASSERT_EQ(StatusCode::OK_200, res->status);
  7516. }
  7517. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7518. class NoListenSSLServer : public SSLServer {
  7519. public:
  7520. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7521. const char *client_ca_cert_file_path,
  7522. const char *client_ca_cert_dir_path = nullptr)
  7523. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7524. client_ca_cert_dir_path),
  7525. stop_(false) {}
  7526. std::atomic_bool stop_;
  7527. private:
  7528. bool process_and_close_socket(socket_t /*sock*/) override {
  7529. // Don't create SSL context
  7530. while (!stop_.load()) {
  7531. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7532. }
  7533. return true;
  7534. }
  7535. };
  7536. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7537. CLIENT_CA_CERT_FILE);
  7538. ASSERT_TRUE(svr.is_valid());
  7539. svr.Get("/test", [&](const Request &, Response &res) {
  7540. res.set_content("test", "text/plain");
  7541. });
  7542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7543. auto se = detail::scope_exit([&] {
  7544. svr.stop_ = true;
  7545. svr.stop();
  7546. t.join();
  7547. ASSERT_FALSE(svr.is_running());
  7548. });
  7549. svr.wait_until_ready();
  7550. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7551. cli.enable_server_certificate_verification(false);
  7552. cli.set_connection_timeout(1);
  7553. auto res = cli.Get("/test");
  7554. ASSERT_TRUE(!res);
  7555. EXPECT_EQ(Error::SSLConnection, res.error());
  7556. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7557. }
  7558. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7559. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7560. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7561. SSL_CTX_set_options(&ssl_ctx,
  7562. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7563. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7564. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7565. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7566. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7567. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7568. "ECDHE-DSS-AES128-SHA256:"
  7569. "ECDHE-RSA-AES256-SHA256:"
  7570. "ECDHE-DSS-AES256-SHA256:";
  7571. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7572. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7573. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7574. SSL_FILETYPE_PEM) != 1) {
  7575. return false;
  7576. }
  7577. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7578. CLIENT_CA_CERT_DIR);
  7579. SSL_CTX_set_verify(
  7580. &ssl_ctx,
  7581. SSL_VERIFY_PEER |
  7582. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7583. nullptr);
  7584. return true;
  7585. };
  7586. SSLServer svr(setup_ssl_ctx_callback);
  7587. ASSERT_TRUE(svr.is_valid());
  7588. svr.Get("/test", [&](const Request &req, Response &res) {
  7589. res.set_content("test", "text/plain");
  7590. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7591. ASSERT_TRUE(peer_cert != nullptr);
  7592. auto subject_name = X509_get_subject_name(peer_cert);
  7593. ASSERT_TRUE(subject_name != nullptr);
  7594. std::string common_name;
  7595. {
  7596. char name[BUFSIZ];
  7597. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7598. name, sizeof(name));
  7599. common_name.assign(name, static_cast<size_t>(name_len));
  7600. }
  7601. EXPECT_EQ("Common Name", common_name);
  7602. X509_free(peer_cert);
  7603. });
  7604. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7605. auto se = detail::scope_exit([&] {
  7606. svr.stop();
  7607. t.join();
  7608. ASSERT_FALSE(svr.is_running());
  7609. });
  7610. svr.wait_until_ready();
  7611. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7612. cli.enable_server_certificate_verification(false);
  7613. cli.set_connection_timeout(30);
  7614. auto res = cli.Get("/test");
  7615. ASSERT_TRUE(res);
  7616. ASSERT_EQ(StatusCode::OK_200, res->status);
  7617. }
  7618. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7620. ASSERT_TRUE(svr.is_valid());
  7621. // Set up a handler to verify client certificate is present
  7622. bool client_cert_verified = false;
  7623. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7624. // Verify that client certificate was provided
  7625. client_cert_verified = true;
  7626. res.set_content("success", "text/plain");
  7627. });
  7628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7629. auto se = detail::scope_exit([&] {
  7630. svr.stop();
  7631. t.join();
  7632. ASSERT_FALSE(svr.is_running());
  7633. });
  7634. svr.wait_until_ready();
  7635. // Client with certificate
  7636. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7637. cli.enable_server_certificate_verification(false);
  7638. cli.set_connection_timeout(30);
  7639. auto res = cli.Get("/test");
  7640. ASSERT_TRUE(res);
  7641. ASSERT_EQ(StatusCode::OK_200, res->status);
  7642. ASSERT_TRUE(client_cert_verified);
  7643. EXPECT_EQ("success", res->body);
  7644. }
  7645. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7646. // Test that when client CA cert file is provided,
  7647. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7648. // Create a server with client authentication
  7649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7650. ASSERT_TRUE(svr.is_valid());
  7651. // We can't directly access the SSL_CTX from SSLServer to verify,
  7652. // but we can test that the server properly requests client certificates
  7653. // and accepts valid ones from the specified CA
  7654. bool handler_called = false;
  7655. svr.Get("/test", [&](const Request &req, Response &res) {
  7656. handler_called = true;
  7657. // Verify that a client certificate was provided
  7658. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7659. ASSERT_TRUE(peer_cert != nullptr);
  7660. // Get the issuer name
  7661. auto issuer_name = X509_get_issuer_name(peer_cert);
  7662. ASSERT_TRUE(issuer_name != nullptr);
  7663. char issuer_buf[256];
  7664. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7665. // The client certificate should be issued by our test CA
  7666. std::string issuer_str(issuer_buf);
  7667. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7668. X509_free(peer_cert);
  7669. res.set_content("authenticated", "text/plain");
  7670. });
  7671. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7672. auto se = detail::scope_exit([&] {
  7673. svr.stop();
  7674. t.join();
  7675. ASSERT_FALSE(svr.is_running());
  7676. });
  7677. svr.wait_until_ready();
  7678. // Connect with a client certificate issued by the CA
  7679. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7680. cli.enable_server_certificate_verification(false);
  7681. cli.set_connection_timeout(30);
  7682. auto res = cli.Get("/test");
  7683. ASSERT_TRUE(res);
  7684. ASSERT_EQ(StatusCode::OK_200, res->status);
  7685. ASSERT_TRUE(handler_called);
  7686. EXPECT_EQ("authenticated", res->body);
  7687. }
  7688. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7689. // Test 1: Valid CA file - no error should be recorded
  7690. {
  7691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7692. CLIENT_CA_CERT_FILE);
  7693. ASSERT_TRUE(svr.is_valid());
  7694. // With valid setup, last_ssl_error should be 0
  7695. EXPECT_EQ(0, svr.ssl_last_error());
  7696. }
  7697. // Test 2: Invalid CA file content
  7698. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7699. {
  7700. // Create a temporary file with completely invalid content
  7701. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7702. {
  7703. std::ofstream ofs(temp_invalid_ca);
  7704. ofs << "This is not a certificate file at all\n";
  7705. ofs << "Just plain text content\n";
  7706. }
  7707. // Create server with invalid CA file
  7708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7709. // Clean up temporary file
  7710. std::remove(temp_invalid_ca);
  7711. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7712. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7713. // Note: SSL_CTX_load_verify_locations typically fails first,
  7714. // but our error handling code path is still exercised
  7715. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7716. }
  7717. }
  7718. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7719. // Test SSL server using X509_STORE constructor with client CA certificates
  7720. // This test verifies that Phase 2 implementation correctly extracts CA names
  7721. // from an X509_STORE and sets them in the SSL context
  7722. // Load the CA certificate into memory
  7723. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7724. ASSERT_NE(nullptr, bio);
  7725. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7726. BIO_free(bio);
  7727. ASSERT_NE(nullptr, ca_cert);
  7728. // Create an X509_STORE and add the CA certificate
  7729. auto store = X509_STORE_new();
  7730. ASSERT_NE(nullptr, store);
  7731. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7732. // Load server certificate and private key
  7733. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7734. ASSERT_NE(nullptr, cert_bio);
  7735. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7736. BIO_free(cert_bio);
  7737. ASSERT_NE(nullptr, server_cert);
  7738. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7739. ASSERT_NE(nullptr, key_bio);
  7740. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7741. BIO_free(key_bio);
  7742. ASSERT_NE(nullptr, server_key);
  7743. // Create SSLServer with X509_STORE constructor
  7744. // Note: X509_STORE ownership is transferred to SSL_CTX
  7745. SSLServer svr(server_cert, server_key, store);
  7746. ASSERT_TRUE(svr.is_valid());
  7747. // No SSL error should be recorded for valid setup
  7748. EXPECT_EQ(0, svr.ssl_last_error());
  7749. // Set up server endpoints
  7750. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7751. res.set_content("ok", "text/plain");
  7752. });
  7753. // Start server in a thread
  7754. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7755. svr.wait_until_ready();
  7756. // Connect with client certificate (using constructor with paths)
  7757. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7758. cli.enable_server_certificate_verification(false);
  7759. auto res = cli.Get("/test-x509store");
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(200, res->status);
  7762. EXPECT_EQ("ok", res->body);
  7763. // Clean up
  7764. X509_free(server_cert);
  7765. EVP_PKEY_free(server_key);
  7766. X509_free(ca_cert);
  7767. svr.stop();
  7768. server_thread.join();
  7769. }
  7770. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7771. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7772. // prepare large data
  7773. std::random_device seed_gen;
  7774. std::mt19937 random(seed_gen());
  7775. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7776. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7777. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7778. // server
  7779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7780. ASSERT_TRUE(svr.is_valid());
  7781. svr.Post("/binary", [&](const Request &req, Response &res) {
  7782. EXPECT_EQ(large_size_byte, req.body.size());
  7783. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7784. res.set_content(req.body, "application/octet-stream");
  7785. });
  7786. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7787. auto se = detail::scope_exit([&] {
  7788. svr.stop();
  7789. listen_thread.join();
  7790. ASSERT_FALSE(svr.is_running());
  7791. });
  7792. svr.wait_until_ready();
  7793. // client POST
  7794. SSLClient cli("localhost", PORT);
  7795. cli.enable_server_certificate_verification(false);
  7796. cli.set_read_timeout(std::chrono::seconds(100));
  7797. cli.set_write_timeout(std::chrono::seconds(100));
  7798. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7799. large_size_byte, "application/octet-stream");
  7800. // compare
  7801. EXPECT_EQ(StatusCode::OK_200, res->status);
  7802. EXPECT_EQ(large_size_byte, res->body.size());
  7803. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7804. }
  7805. #endif
  7806. #ifdef _WIN32
  7807. TEST(CleanupTest, WSACleanup) {
  7808. int ret = WSACleanup();
  7809. ASSERT_EQ(0, ret);
  7810. }
  7811. #endif
  7812. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7813. TEST(NoSSLSupport, SimpleInterface) {
  7814. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7815. }
  7816. #endif
  7817. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7818. TEST(InvalidScheme, SimpleInterface) {
  7819. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7820. }
  7821. #endif
  7822. TEST(NoScheme, SimpleInterface) {
  7823. Client cli("yahoo.com:80");
  7824. ASSERT_TRUE(cli.is_valid());
  7825. }
  7826. TEST(SendAPI, SimpleInterface_Online) {
  7827. Client cli("http://yahoo.com");
  7828. Request req;
  7829. req.method = "GET";
  7830. req.path = "/";
  7831. auto res = cli.send(req);
  7832. ASSERT_TRUE(res);
  7833. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7834. }
  7835. TEST(SendAPI, WithParamsInRequest) {
  7836. Server svr;
  7837. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7838. EXPECT_TRUE(req.has_param("test"));
  7839. EXPECT_EQ("test_value", req.get_param_value("test"));
  7840. });
  7841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7842. auto se = detail::scope_exit([&] {
  7843. svr.stop();
  7844. t.join();
  7845. ASSERT_FALSE(svr.is_running());
  7846. });
  7847. svr.wait_until_ready();
  7848. Client cli(HOST, PORT);
  7849. {
  7850. Request req;
  7851. req.method = "GET";
  7852. req.path = "/";
  7853. req.params.emplace("test", "test_value");
  7854. auto res = cli.send(req);
  7855. ASSERT_TRUE(res);
  7856. }
  7857. {
  7858. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7859. ASSERT_TRUE(res);
  7860. }
  7861. }
  7862. TEST(ClientImplMethods, GetSocketTest) {
  7863. httplib::Server svr;
  7864. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7865. res.status = StatusCode::OK_200;
  7866. });
  7867. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7868. auto se = detail::scope_exit([&] {
  7869. svr.stop();
  7870. thread.join();
  7871. ASSERT_FALSE(svr.is_running());
  7872. });
  7873. svr.wait_until_ready();
  7874. {
  7875. httplib::Client cli("http://127.0.0.1:3333");
  7876. cli.set_keep_alive(true);
  7877. // Use the behavior of cpp-httplib of opening the connection
  7878. // only when the first request happens. If that changes,
  7879. // this test would be obsolete.
  7880. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7881. // This also implicitly tests the server. But other tests would fail much
  7882. // earlier than this one to be considered.
  7883. auto res = cli.Get("/");
  7884. ASSERT_TRUE(res);
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7887. }
  7888. }
  7889. // Disabled due to out-of-memory problem on GitHub Actions
  7890. #ifdef _WIN64
  7891. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7892. // allocate content size larger than 2GB in memory
  7893. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7894. char *content = (char *)malloc(content_size);
  7895. ASSERT_TRUE(content);
  7896. Server svr;
  7897. svr.Get("/foo",
  7898. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7899. res.set_content(content, content_size, "application/octet-stream");
  7900. });
  7901. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7902. auto se = detail::scope_exit([&] {
  7903. svr.stop();
  7904. listen_thread.join();
  7905. if (content) free(content);
  7906. ASSERT_FALSE(svr.is_running());
  7907. });
  7908. svr.wait_until_ready();
  7909. Client cli(HOST, PORT);
  7910. auto res = cli.Get("/foo");
  7911. ASSERT_TRUE(res);
  7912. EXPECT_EQ(StatusCode::OK_200, res->status);
  7913. EXPECT_EQ(content_size, res->body.length());
  7914. }
  7915. #endif
  7916. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7917. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7918. Client cli("http://yahoo.com");
  7919. auto res = cli.Get("/");
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7922. cli.set_follow_location(true);
  7923. res = cli.Get("/");
  7924. ASSERT_TRUE(res);
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7927. }
  7928. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7929. Client cli("https://yahoo.com");
  7930. auto res = cli.Get("/");
  7931. ASSERT_TRUE(res);
  7932. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7933. cli.set_follow_location(true);
  7934. res = cli.Get("/");
  7935. ASSERT_TRUE(res);
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7938. }
  7939. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7940. Client cli("https://yahoo.com");
  7941. auto res = cli.Get("/");
  7942. ASSERT_TRUE(res);
  7943. ASSERT_FALSE(!res);
  7944. ASSERT_TRUE(res);
  7945. ASSERT_FALSE(res == nullptr);
  7946. ASSERT_TRUE(res != nullptr);
  7947. EXPECT_EQ(Error::Success, res.error());
  7948. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7949. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7950. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7951. cli.set_follow_location(true);
  7952. res = cli.Get("/");
  7953. ASSERT_TRUE(res);
  7954. EXPECT_EQ(Error::Success, res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7956. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7959. }
  7960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7961. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7962. Client cli("https://cdnjs.cloudflare.com");
  7963. auto res =
  7964. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7965. ASSERT_TRUE(res);
  7966. EXPECT_EQ(StatusCode::OK_200, res->status);
  7967. EXPECT_EQ(287630U, res->body.size());
  7968. EXPECT_EQ("application/javascript; charset=utf-8",
  7969. res->get_header_value("Content-Type"));
  7970. }
  7971. #endif
  7972. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7973. #undef REDIR_HOST // Silence compiler warning
  7974. #define REDIR_HOST "https://httpbingo.org"
  7975. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7976. Client cli(REDIR_HOST);
  7977. cli.set_follow_location(true);
  7978. auto res =
  7979. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7980. ASSERT_TRUE(res);
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. }
  7983. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7984. Client cli(REDIR_HOST);
  7985. cli.set_follow_location(true);
  7986. Params params;
  7987. params.emplace("url", "http://example.com");
  7988. params.emplace("status_code", "302");
  7989. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7990. ASSERT_TRUE(res);
  7991. EXPECT_EQ(StatusCode::OK_200, res->status);
  7992. }
  7993. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7994. Client cli(REDIR_HOST);
  7995. cli.set_follow_location(true);
  7996. Params params;
  7997. params.emplace("url", "http://example.com");
  7998. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7999. ASSERT_TRUE(res);
  8000. EXPECT_EQ(StatusCode::OK_200, res->status);
  8001. }
  8002. TEST(HttpToHttpsRedirectTest, CertFile) {
  8003. Server svr;
  8004. ASSERT_TRUE(svr.is_valid());
  8005. svr.Get("/index", [&](const Request &, Response &res) {
  8006. res.set_redirect("https://127.0.0.1:1235/index");
  8007. svr.stop();
  8008. });
  8009. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8010. ASSERT_TRUE(ssl_svr.is_valid());
  8011. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8012. res.set_content("test", "text/plain");
  8013. ssl_svr.stop();
  8014. });
  8015. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8016. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8017. auto se = detail::scope_exit([&] {
  8018. t2.join();
  8019. t.join();
  8020. ASSERT_FALSE(svr.is_running());
  8021. });
  8022. svr.wait_until_ready();
  8023. ssl_svr.wait_until_ready();
  8024. Client cli("127.0.0.1", PORT);
  8025. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8026. cli.enable_server_certificate_verification(true);
  8027. cli.set_follow_location(true);
  8028. cli.set_connection_timeout(30);
  8029. auto res = cli.Get("/index");
  8030. ASSERT_TRUE(res);
  8031. ASSERT_EQ(StatusCode::OK_200, res->status);
  8032. }
  8033. TEST(SSLClientRedirectTest, CertFile) {
  8034. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8035. ASSERT_TRUE(ssl_svr1.is_valid());
  8036. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8037. res.set_redirect("https://127.0.0.1:1235/index");
  8038. ssl_svr1.stop();
  8039. });
  8040. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8041. ASSERT_TRUE(ssl_svr2.is_valid());
  8042. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8043. res.set_content("test", "text/plain");
  8044. ssl_svr2.stop();
  8045. });
  8046. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8047. thread t2 =
  8048. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8049. auto se = detail::scope_exit([&] {
  8050. t2.join();
  8051. t.join();
  8052. ASSERT_FALSE(ssl_svr1.is_running());
  8053. });
  8054. ssl_svr1.wait_until_ready();
  8055. ssl_svr2.wait_until_ready();
  8056. SSLClient cli("127.0.0.1", PORT);
  8057. std::string cert;
  8058. read_file(SERVER_CERT2_FILE, cert);
  8059. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8060. cli.enable_server_certificate_verification(true);
  8061. cli.set_follow_location(true);
  8062. cli.set_connection_timeout(30);
  8063. auto res = cli.Get("/index");
  8064. ASSERT_TRUE(res);
  8065. ASSERT_EQ(StatusCode::OK_200, res->status);
  8066. }
  8067. TEST(MultipartFormDataTest, LargeData) {
  8068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8069. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8070. const ContentReader &content_reader) {
  8071. if (req.is_multipart_form_data()) {
  8072. std::vector<FormData> items;
  8073. content_reader(
  8074. [&](const FormData &file) {
  8075. items.push_back(file);
  8076. return true;
  8077. },
  8078. [&](const char *data, size_t data_length) {
  8079. items.back().content.append(data, data_length);
  8080. return true;
  8081. });
  8082. EXPECT_TRUE(std::string(items[0].name) == "document");
  8083. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8084. EXPECT_TRUE(items[0].filename == "2MB_data");
  8085. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8086. EXPECT_TRUE(items[1].name == "hello");
  8087. EXPECT_TRUE(items[1].content == "world");
  8088. EXPECT_TRUE(items[1].filename == "");
  8089. EXPECT_TRUE(items[1].content_type == "");
  8090. } else {
  8091. std::string body;
  8092. content_reader([&](const char *data, size_t data_length) {
  8093. body.append(data, data_length);
  8094. return true;
  8095. });
  8096. }
  8097. });
  8098. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8099. auto se = detail::scope_exit([&] {
  8100. svr.stop();
  8101. t.join();
  8102. ASSERT_FALSE(svr.is_running());
  8103. });
  8104. svr.wait_until_ready();
  8105. {
  8106. std::string data(1024 * 1024 * 2, '.');
  8107. std::stringstream buffer;
  8108. buffer << data;
  8109. Client cli("https://localhost:8080");
  8110. cli.enable_server_certificate_verification(false);
  8111. UploadFormDataItems items{
  8112. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8113. {"hello", "world", "", ""},
  8114. };
  8115. auto res = cli.Post("/post", items);
  8116. ASSERT_TRUE(res);
  8117. ASSERT_EQ(StatusCode::OK_200, res->status);
  8118. }
  8119. }
  8120. TEST(MultipartFormDataTest, DataProviderItems) {
  8121. std::random_device seed_gen;
  8122. std::mt19937 random(seed_gen());
  8123. std::string rand1;
  8124. rand1.resize(1000);
  8125. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8126. std::string rand2;
  8127. rand2.resize(3000);
  8128. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8130. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8131. const ContentReader &content_reader) {
  8132. ASSERT_FALSE(req.is_multipart_form_data());
  8133. std::string body;
  8134. content_reader([&](const char *data, size_t data_length) {
  8135. body.append(data, data_length);
  8136. return true;
  8137. });
  8138. EXPECT_EQ(body, "");
  8139. });
  8140. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8141. const ContentReader &content_reader) {
  8142. ASSERT_TRUE(req.is_multipart_form_data());
  8143. std::vector<FormData> items;
  8144. content_reader(
  8145. [&](const FormData &file) {
  8146. items.push_back(file);
  8147. return true;
  8148. },
  8149. [&](const char *data, size_t data_length) {
  8150. items.back().content.append(data, data_length);
  8151. return true;
  8152. });
  8153. ASSERT_TRUE(items.size() == 2);
  8154. EXPECT_EQ(std::string(items[0].name), "name1");
  8155. EXPECT_EQ(items[0].content, "Testing123");
  8156. EXPECT_EQ(items[0].filename, "filename1");
  8157. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8158. EXPECT_EQ(items[1].name, "name2");
  8159. EXPECT_EQ(items[1].content, "Testing456");
  8160. EXPECT_EQ(items[1].filename, "");
  8161. EXPECT_EQ(items[1].content_type, "");
  8162. });
  8163. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8164. const ContentReader &content_reader) {
  8165. ASSERT_TRUE(req.is_multipart_form_data());
  8166. std::vector<FormData> items;
  8167. content_reader(
  8168. [&](const FormData &file) {
  8169. items.push_back(file);
  8170. return true;
  8171. },
  8172. [&](const char *data, size_t data_length) {
  8173. items.back().content.append(data, data_length);
  8174. return true;
  8175. });
  8176. ASSERT_TRUE(items.size() == 2);
  8177. EXPECT_EQ(items[0].name, "name3");
  8178. EXPECT_EQ(items[0].content, rand1);
  8179. EXPECT_EQ(items[0].filename, "filename3");
  8180. EXPECT_EQ(items[0].content_type, "");
  8181. EXPECT_EQ(items[1].name, "name4");
  8182. EXPECT_EQ(items[1].content, rand2);
  8183. EXPECT_EQ(items[1].filename, "filename4");
  8184. EXPECT_EQ(items[1].content_type, "");
  8185. });
  8186. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8187. const ContentReader &content_reader) {
  8188. ASSERT_TRUE(req.is_multipart_form_data());
  8189. std::vector<FormData> items;
  8190. content_reader(
  8191. [&](const FormData &file) {
  8192. items.push_back(file);
  8193. return true;
  8194. },
  8195. [&](const char *data, size_t data_length) {
  8196. items.back().content.append(data, data_length);
  8197. return true;
  8198. });
  8199. ASSERT_TRUE(items.size() == 4);
  8200. EXPECT_EQ(std::string(items[0].name), "name1");
  8201. EXPECT_EQ(items[0].content, "Testing123");
  8202. EXPECT_EQ(items[0].filename, "filename1");
  8203. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8204. EXPECT_EQ(items[1].name, "name2");
  8205. EXPECT_EQ(items[1].content, "Testing456");
  8206. EXPECT_EQ(items[1].filename, "");
  8207. EXPECT_EQ(items[1].content_type, "");
  8208. EXPECT_EQ(items[2].name, "name3");
  8209. EXPECT_EQ(items[2].content, rand1);
  8210. EXPECT_EQ(items[2].filename, "filename3");
  8211. EXPECT_EQ(items[2].content_type, "");
  8212. EXPECT_EQ(items[3].name, "name4");
  8213. EXPECT_EQ(items[3].content, rand2);
  8214. EXPECT_EQ(items[3].filename, "filename4");
  8215. EXPECT_EQ(items[3].content_type, "");
  8216. });
  8217. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8218. auto se = detail::scope_exit([&] {
  8219. svr.stop();
  8220. t.join();
  8221. ASSERT_FALSE(svr.is_running());
  8222. });
  8223. svr.wait_until_ready();
  8224. {
  8225. Client cli("https://localhost:8080");
  8226. cli.enable_server_certificate_verification(false);
  8227. UploadFormDataItems items{
  8228. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8229. {"name2", "Testing456", "", ""}, // not a file
  8230. };
  8231. {
  8232. auto res = cli.Post("/post-none", {}, {}, {});
  8233. ASSERT_TRUE(res);
  8234. ASSERT_EQ(StatusCode::OK_200, res->status);
  8235. }
  8236. FormDataProviderItems providers;
  8237. {
  8238. auto res =
  8239. cli.Post("/post-items", {}, items, providers); // empty providers
  8240. ASSERT_TRUE(res);
  8241. ASSERT_EQ(StatusCode::OK_200, res->status);
  8242. }
  8243. providers.push_back({"name3",
  8244. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8245. // test the offset is given correctly at each step
  8246. if (!offset)
  8247. sink.os.write(rand1.data(), 30);
  8248. else if (offset == 30)
  8249. sink.os.write(rand1.data() + 30, 300);
  8250. else if (offset == 330)
  8251. sink.os.write(rand1.data() + 330, 670);
  8252. else if (offset == rand1.size())
  8253. sink.done();
  8254. return true;
  8255. },
  8256. "filename3",
  8257. {}});
  8258. providers.push_back({"name4",
  8259. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8260. // test the offset is given correctly at each step
  8261. if (!offset)
  8262. sink.os.write(rand2.data(), 2000);
  8263. else if (offset == 2000)
  8264. sink.os.write(rand2.data() + 2000, 1);
  8265. else if (offset == 2001)
  8266. sink.os.write(rand2.data() + 2001, 999);
  8267. else if (offset == rand2.size())
  8268. sink.done();
  8269. return true;
  8270. },
  8271. "filename4",
  8272. {}});
  8273. {
  8274. auto res = cli.Post("/post-providers", {}, {}, providers);
  8275. ASSERT_TRUE(res);
  8276. ASSERT_EQ(StatusCode::OK_200, res->status);
  8277. }
  8278. {
  8279. auto res = cli.Post("/post-both", {}, items, providers);
  8280. ASSERT_TRUE(res);
  8281. ASSERT_EQ(StatusCode::OK_200, res->status);
  8282. }
  8283. }
  8284. }
  8285. TEST(MultipartFormDataTest, BadHeader) {
  8286. Server svr;
  8287. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8288. res.set_content("ok", "text/plain");
  8289. });
  8290. thread t = thread([&] { svr.listen(HOST, PORT); });
  8291. auto se = detail::scope_exit([&] {
  8292. svr.stop();
  8293. t.join();
  8294. ASSERT_FALSE(svr.is_running());
  8295. });
  8296. svr.wait_until_ready();
  8297. const std::string body =
  8298. "This is the preamble. It is to be ignored, though it\r\n"
  8299. "is a handy place for composition agents to include an\r\n"
  8300. "explanatory note to non-MIME conformant readers.\r\n"
  8301. "\r\n"
  8302. "\r\n"
  8303. "--simple boundary\r\n"
  8304. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8305. ": BAD...\r\n"
  8306. "\r\n"
  8307. "value1\r\n"
  8308. "--simple boundary\r\n"
  8309. "Content-Disposition: form-data; name=\"field2\"; "
  8310. "filename=\"example.txt\"\r\n"
  8311. "\r\n"
  8312. "value2\r\n"
  8313. "--simple boundary--\r\n"
  8314. "This is the epilogue. It is also to be ignored.\r\n";
  8315. std::string content_type =
  8316. R"(multipart/form-data; boundary="simple boundary")";
  8317. Client cli(HOST, PORT);
  8318. auto res = cli.Post("/post", body, content_type.c_str());
  8319. ASSERT_TRUE(res);
  8320. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8321. }
  8322. TEST(MultipartFormDataTest, WithPreamble) {
  8323. Server svr;
  8324. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8325. res.set_content("ok", "text/plain");
  8326. });
  8327. thread t = thread([&] { svr.listen(HOST, PORT); });
  8328. auto se = detail::scope_exit([&] {
  8329. svr.stop();
  8330. t.join();
  8331. ASSERT_FALSE(svr.is_running());
  8332. });
  8333. svr.wait_until_ready();
  8334. const std::string body =
  8335. "This is the preamble. It is to be ignored, though it\r\n"
  8336. "is a handy place for composition agents to include an\r\n"
  8337. "explanatory note to non-MIME conformant readers.\r\n"
  8338. "\r\n"
  8339. "\r\n"
  8340. "--simple boundary\r\n"
  8341. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8342. "\r\n"
  8343. "value1\r\n"
  8344. "--simple boundary\r\n"
  8345. "Content-Disposition: form-data; name=\"field2\"; "
  8346. "filename=\"example.txt\"\r\n"
  8347. "\r\n"
  8348. "value2\r\n"
  8349. "--simple boundary--\r\n"
  8350. "This is the epilogue. It is also to be ignored.\r\n";
  8351. std::string content_type =
  8352. R"(multipart/form-data; boundary="simple boundary")";
  8353. Client cli(HOST, PORT);
  8354. auto res = cli.Post("/post", body, content_type.c_str());
  8355. ASSERT_TRUE(res);
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. }
  8358. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8360. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8361. const ContentReader &content_reader) {
  8362. if (req.is_multipart_form_data()) {
  8363. std::vector<FormData> items;
  8364. content_reader(
  8365. [&](const FormData &file) {
  8366. items.push_back(file);
  8367. return true;
  8368. },
  8369. [&](const char *data, size_t data_length) {
  8370. items.back().content.append(data, data_length);
  8371. return true;
  8372. });
  8373. EXPECT_TRUE(std::string(items[0].name) == "document");
  8374. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8375. EXPECT_TRUE(items[0].filename == "2MB_data");
  8376. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8377. EXPECT_TRUE(items[1].name == "hello");
  8378. EXPECT_TRUE(items[1].content == "world");
  8379. EXPECT_TRUE(items[1].filename == "");
  8380. EXPECT_TRUE(items[1].content_type == "");
  8381. } else {
  8382. std::string body;
  8383. content_reader([&](const char *data, size_t data_length) {
  8384. body.append(data, data_length);
  8385. return true;
  8386. });
  8387. }
  8388. });
  8389. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8390. auto se = detail::scope_exit([&] {
  8391. svr.stop();
  8392. t.join();
  8393. ASSERT_FALSE(svr.is_running());
  8394. });
  8395. svr.wait_until_ready();
  8396. {
  8397. std::string data(1024 * 1024 * 2, '.');
  8398. std::stringstream buffer;
  8399. buffer << data;
  8400. Client cli("https://localhost:8080");
  8401. cli.enable_server_certificate_verification(false);
  8402. UploadFormDataItems items{
  8403. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8404. {"hello", "world", "", ""},
  8405. };
  8406. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8407. ASSERT_TRUE(res);
  8408. ASSERT_EQ(StatusCode::OK_200, res->status);
  8409. }
  8410. }
  8411. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8412. std::string data(1024 * 1024 * 2, '&');
  8413. std::stringstream buffer;
  8414. buffer << data;
  8415. Client cli("https://localhost:8080");
  8416. UploadFormDataItems items{
  8417. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8418. {"hello", "world", "", ""},
  8419. };
  8420. for (const char &c : " \t\r\n") {
  8421. auto res =
  8422. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8423. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8424. ASSERT_FALSE(res);
  8425. }
  8426. }
  8427. TEST(MultipartFormDataTest, PutFormData) {
  8428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8429. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8430. const ContentReader &content_reader) {
  8431. if (req.is_multipart_form_data()) {
  8432. std::vector<FormData> items;
  8433. content_reader(
  8434. [&](const FormData &file) {
  8435. items.push_back(file);
  8436. return true;
  8437. },
  8438. [&](const char *data, size_t data_length) {
  8439. items.back().content.append(data, data_length);
  8440. return true;
  8441. });
  8442. EXPECT_TRUE(std::string(items[0].name) == "document");
  8443. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8444. EXPECT_TRUE(items[0].filename == "2MB_data");
  8445. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8446. EXPECT_TRUE(items[1].name == "hello");
  8447. EXPECT_TRUE(items[1].content == "world");
  8448. EXPECT_TRUE(items[1].filename == "");
  8449. EXPECT_TRUE(items[1].content_type == "");
  8450. } else {
  8451. std::string body;
  8452. content_reader([&](const char *data, size_t data_length) {
  8453. body.append(data, data_length);
  8454. return true;
  8455. });
  8456. }
  8457. });
  8458. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8459. auto se = detail::scope_exit([&] {
  8460. svr.stop();
  8461. t.join();
  8462. ASSERT_FALSE(svr.is_running());
  8463. });
  8464. svr.wait_until_ready();
  8465. {
  8466. std::string data(1024 * 1024 * 2, '&');
  8467. std::stringstream buffer;
  8468. buffer << data;
  8469. Client cli("https://localhost:8080");
  8470. cli.enable_server_certificate_verification(false);
  8471. UploadFormDataItems items{
  8472. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8473. {"hello", "world", "", ""},
  8474. };
  8475. auto res = cli.Put("/put", items);
  8476. ASSERT_TRUE(res);
  8477. ASSERT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. }
  8480. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8482. svr.Put("/put_customboundary",
  8483. [&](const Request &req, const Response & /*res*/,
  8484. const ContentReader &content_reader) {
  8485. if (req.is_multipart_form_data()) {
  8486. std::vector<FormData> items;
  8487. content_reader(
  8488. [&](const FormData &file) {
  8489. items.push_back(file);
  8490. return true;
  8491. },
  8492. [&](const char *data, size_t data_length) {
  8493. items.back().content.append(data, data_length);
  8494. return true;
  8495. });
  8496. EXPECT_TRUE(std::string(items[0].name) == "document");
  8497. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8498. EXPECT_TRUE(items[0].filename == "2MB_data");
  8499. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8500. EXPECT_TRUE(items[1].name == "hello");
  8501. EXPECT_TRUE(items[1].content == "world");
  8502. EXPECT_TRUE(items[1].filename == "");
  8503. EXPECT_TRUE(items[1].content_type == "");
  8504. } else {
  8505. std::string body;
  8506. content_reader([&](const char *data, size_t data_length) {
  8507. body.append(data, data_length);
  8508. return true;
  8509. });
  8510. }
  8511. });
  8512. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8513. auto se = detail::scope_exit([&] {
  8514. svr.stop();
  8515. t.join();
  8516. ASSERT_FALSE(svr.is_running());
  8517. });
  8518. svr.wait_until_ready();
  8519. {
  8520. std::string data(1024 * 1024 * 2, '&');
  8521. std::stringstream buffer;
  8522. buffer << data;
  8523. Client cli("https://localhost:8080");
  8524. cli.enable_server_certificate_verification(false);
  8525. UploadFormDataItems items{
  8526. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8527. {"hello", "world", "", ""},
  8528. };
  8529. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8530. ASSERT_TRUE(res);
  8531. ASSERT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. }
  8534. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8535. std::string data(1024 * 1024 * 2, '&');
  8536. std::stringstream buffer;
  8537. buffer << data;
  8538. Client cli("https://localhost:8080");
  8539. cli.enable_server_certificate_verification(false);
  8540. UploadFormDataItems items{
  8541. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8542. {"hello", "world", "", ""},
  8543. };
  8544. for (const char &c : " \t\r\n") {
  8545. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8546. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8547. ASSERT_FALSE(res);
  8548. }
  8549. }
  8550. TEST(MultipartFormDataTest, AlternateFilename) {
  8551. auto handled = false;
  8552. Server svr;
  8553. svr.Post("/test", [&](const Request &req, Response &res) {
  8554. ASSERT_EQ(2u, req.form.files.size());
  8555. ASSERT_EQ(1u, req.form.fields.size());
  8556. // Test files
  8557. const auto &file1 = req.form.get_file("file1");
  8558. ASSERT_EQ("file1", file1.name);
  8559. ASSERT_EQ("A.txt", file1.filename);
  8560. ASSERT_EQ("text/plain", file1.content_type);
  8561. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8562. const auto &file2 = req.form.get_file("file2");
  8563. ASSERT_EQ("file2", file2.name);
  8564. ASSERT_EQ("a.html", file2.filename);
  8565. ASSERT_EQ("text/html", file2.content_type);
  8566. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8567. file2.content);
  8568. // Test text field
  8569. const auto &text = req.form.get_field("text");
  8570. ASSERT_EQ("text default", text);
  8571. res.set_content("ok", "text/plain");
  8572. handled = true;
  8573. });
  8574. thread t = thread([&] { svr.listen(HOST, PORT); });
  8575. auto se = detail::scope_exit([&] {
  8576. svr.stop();
  8577. t.join();
  8578. ASSERT_FALSE(svr.is_running());
  8579. ASSERT_TRUE(handled);
  8580. });
  8581. svr.wait_until_ready();
  8582. auto req = "POST /test HTTP/1.1\r\n"
  8583. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8584. "Content-Length: 399\r\n"
  8585. "\r\n"
  8586. "----------\r\n"
  8587. "Content-Disposition: form-data; name=\"text\"\r\n"
  8588. "\r\n"
  8589. "text default\r\n"
  8590. "----------\r\n"
  8591. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8592. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8593. "Content-Type: text/plain\r\n"
  8594. "\r\n"
  8595. "Content of a.txt.\r\n"
  8596. "\r\n"
  8597. "----------\r\n"
  8598. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8599. "\"a.html\"\r\n"
  8600. "Content-Type: text/html\r\n"
  8601. "\r\n"
  8602. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8603. "\r\n"
  8604. "------------\r\n";
  8605. ASSERT_TRUE(send_request(1, req));
  8606. }
  8607. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8608. auto handled = false;
  8609. Server svr;
  8610. svr.Post("/test", [&](const Request &req, Response &) {
  8611. ASSERT_EQ(2u, req.form.fields.size());
  8612. const auto &text1 = req.form.get_field("text1");
  8613. ASSERT_EQ("text1", text1);
  8614. const auto &text2 = req.form.get_field("text2");
  8615. ASSERT_EQ("text2", text2);
  8616. handled = true;
  8617. });
  8618. thread t = thread([&] { svr.listen(HOST, PORT); });
  8619. auto se = detail::scope_exit([&] {
  8620. svr.stop();
  8621. t.join();
  8622. ASSERT_FALSE(svr.is_running());
  8623. ASSERT_TRUE(handled);
  8624. });
  8625. svr.wait_until_ready();
  8626. auto req = "POST /test HTTP/1.1\r\n"
  8627. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8628. "Content-Length: 146\r\n"
  8629. "\r\n----------\r\n"
  8630. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8631. "\r\n"
  8632. "text1"
  8633. "\r\n----------\r\n"
  8634. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8635. "\r\n"
  8636. "text2"
  8637. "\r\n------------";
  8638. std::string response;
  8639. ASSERT_TRUE(send_request(1, req, &response));
  8640. ASSERT_EQ("200", response.substr(9, 3));
  8641. }
  8642. TEST(MultipartFormDataTest, ContentLength) {
  8643. auto handled = false;
  8644. Server svr;
  8645. svr.Post("/test", [&](const Request &req, Response &) {
  8646. ASSERT_EQ(2u, req.form.fields.size());
  8647. const auto &text1 = req.form.get_field("text1");
  8648. ASSERT_EQ("text1", text1);
  8649. const auto &text2 = req.form.get_field("text2");
  8650. ASSERT_EQ("text2", text2);
  8651. handled = true;
  8652. });
  8653. thread t = thread([&] { svr.listen(HOST, PORT); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. t.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. ASSERT_TRUE(handled);
  8659. });
  8660. svr.wait_until_ready();
  8661. auto req = "POST /test HTTP/1.1\r\n"
  8662. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8663. "Content-Length: 167\r\n"
  8664. "\r\n----------\r\n"
  8665. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8666. "Content-Length: 5\r\n"
  8667. "\r\n"
  8668. "text1"
  8669. "\r\n----------\r\n"
  8670. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8671. "\r\n"
  8672. "text2"
  8673. "\r\n------------\r\n";
  8674. std::string response;
  8675. ASSERT_TRUE(send_request(1, req, &response));
  8676. ASSERT_EQ("200", response.substr(9, 3));
  8677. }
  8678. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8679. auto handled = false;
  8680. Server svr;
  8681. svr.Post("/test", [&](const Request &req, Response &) {
  8682. ASSERT_EQ(2u, req.form.fields.size());
  8683. const auto &text1 = req.form.get_field("text1");
  8684. ASSERT_EQ("text1", text1);
  8685. // TODO: Add header access for text fields if needed
  8686. const auto &text2 = req.form.get_field("text2");
  8687. ASSERT_EQ("text2", text2);
  8688. // TODO: Header access for text fields needs to be implemented
  8689. // auto &headers = it->second.headers;
  8690. // ASSERT_EQ(3U, headers.size());
  8691. // auto custom_header = headers.find("x-whatever");
  8692. // ASSERT_TRUE(custom_header != headers.end());
  8693. // ASSERT_NE("customvalue", custom_header->second);
  8694. // ASSERT_EQ("CustomValue", custom_header->second);
  8695. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8696. handled = true;
  8697. });
  8698. thread t = thread([&] { svr.listen(HOST, PORT); });
  8699. auto se = detail::scope_exit([&] {
  8700. svr.stop();
  8701. t.join();
  8702. ASSERT_FALSE(svr.is_running());
  8703. ASSERT_TRUE(handled);
  8704. });
  8705. svr.wait_until_ready();
  8706. auto req = "POST /test HTTP/1.1\r\n"
  8707. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8708. "Content-Length: 232\r\n"
  8709. "\r\n----------\r\n"
  8710. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8711. "Content-Length: 5\r\n"
  8712. "X-Test: 1\r\n"
  8713. "\r\n"
  8714. "text1"
  8715. "\r\n----------\r\n"
  8716. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8717. "Content-Type: text/plain\r\n"
  8718. "X-Whatever: CustomValue\r\n"
  8719. "\r\n"
  8720. "text2"
  8721. "\r\n------------\r\n"
  8722. "That should be disregarded. Not even read";
  8723. std::string response;
  8724. ASSERT_TRUE(send_request(1, req, &response));
  8725. ASSERT_EQ("200", response.substr(9, 3));
  8726. }
  8727. #endif
  8728. TEST(MultipartFormDataTest, LargeHeader) {
  8729. auto handled = false;
  8730. Server svr;
  8731. svr.Post("/test", [&](const Request &req, Response &) {
  8732. ASSERT_EQ(1u, req.form.fields.size());
  8733. const auto &text = req.form.get_field("name1");
  8734. ASSERT_EQ("text1", text);
  8735. handled = true;
  8736. });
  8737. thread t = thread([&] { svr.listen(HOST, PORT); });
  8738. auto se = detail::scope_exit([&] {
  8739. svr.stop();
  8740. t.join();
  8741. ASSERT_FALSE(svr.is_running());
  8742. ASSERT_TRUE(handled);
  8743. });
  8744. svr.wait_until_ready();
  8745. auto boundary = std::string("cpp-httplib-multipart-data");
  8746. std::string content = "--" + boundary +
  8747. "\r\n"
  8748. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8749. "\r\n"
  8750. "text1\r\n"
  8751. "--" +
  8752. boundary + "--\r\n";
  8753. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8754. "Content-Type: multipart/form-data;boundary=" +
  8755. boundary +
  8756. "\r\n"
  8757. "Content-Length: " +
  8758. std::to_string(content.size()) +
  8759. "\r\n"
  8760. "Dummy-Header: ";
  8761. std::string header_suffix = "\r\n"
  8762. "\r\n";
  8763. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8764. size_t header_dummy_size =
  8765. read_buff_size -
  8766. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8767. auto header_dummy = std::string(header_dummy_size, '@');
  8768. auto req = header_prefix + header_dummy + header_suffix + content;
  8769. std::string response;
  8770. ASSERT_TRUE(send_request(1, req, &response));
  8771. ASSERT_EQ("200", response.substr(9, 3));
  8772. }
  8773. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8774. static constexpr unsigned int number_of_tasks{1000000};
  8775. std::atomic_uint count{0};
  8776. std::unique_ptr<TaskQueue> task_queue{
  8777. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8778. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8779. auto queued = task_queue->enqueue(
  8780. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8781. EXPECT_TRUE(queued);
  8782. }
  8783. EXPECT_NO_THROW(task_queue->shutdown());
  8784. EXPECT_EQ(number_of_tasks, count.load());
  8785. }
  8786. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8787. static constexpr unsigned int number_of_tasks{1000000};
  8788. static constexpr unsigned int qlimit{2};
  8789. unsigned int queued_count{0};
  8790. std::atomic_uint count{0};
  8791. std::unique_ptr<TaskQueue> task_queue{
  8792. new ThreadPool{/*num_threads=*/1, qlimit}};
  8793. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8794. if (task_queue->enqueue(
  8795. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8796. queued_count++;
  8797. }
  8798. }
  8799. EXPECT_NO_THROW(task_queue->shutdown());
  8800. EXPECT_EQ(queued_count, count.load());
  8801. EXPECT_TRUE(queued_count <= number_of_tasks);
  8802. EXPECT_TRUE(queued_count >= qlimit);
  8803. }
  8804. TEST(TaskQueueTest, MaxQueuedRequests) {
  8805. static constexpr unsigned int qlimit{3};
  8806. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8807. std::condition_variable sem_cv;
  8808. std::mutex sem_mtx;
  8809. int credits = 0;
  8810. bool queued;
  8811. /* Fill up the queue with tasks that will block until we give them credits to
  8812. * complete. */
  8813. for (unsigned int n = 0; n <= qlimit;) {
  8814. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8815. std::unique_lock<std::mutex> lock(sem_mtx);
  8816. while (credits <= 0) {
  8817. sem_cv.wait(lock);
  8818. }
  8819. /* Consume the credit and signal the test code if they are all gone. */
  8820. if (--credits == 0) { sem_cv.notify_one(); }
  8821. });
  8822. if (n < qlimit) {
  8823. /* The first qlimit enqueues must succeed. */
  8824. EXPECT_TRUE(queued);
  8825. } else {
  8826. /* The last one will succeed only when the worker thread
  8827. * starts and dequeues the first blocking task. Although
  8828. * not necessary for the correctness of this test, we sleep for
  8829. * a short while to avoid busy waiting. */
  8830. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8831. }
  8832. if (queued) { n++; }
  8833. }
  8834. /* Further enqueues must fail since the queue is full. */
  8835. for (auto i = 0; i < 4; i++) {
  8836. queued = task_queue->enqueue([] {});
  8837. EXPECT_FALSE(queued);
  8838. }
  8839. /* Give the credits to allow the previous tasks to complete. */
  8840. {
  8841. std::unique_lock<std::mutex> lock(sem_mtx);
  8842. credits += qlimit + 1;
  8843. }
  8844. sem_cv.notify_all();
  8845. /* Wait for all the credits to be consumed. */
  8846. {
  8847. std::unique_lock<std::mutex> lock(sem_mtx);
  8848. while (credits > 0) {
  8849. sem_cv.wait(lock);
  8850. }
  8851. }
  8852. /* Check that we are able again to enqueue at least qlimit tasks. */
  8853. for (unsigned int i = 0; i < qlimit; i++) {
  8854. queued = task_queue->enqueue([] {});
  8855. EXPECT_TRUE(queued);
  8856. }
  8857. EXPECT_NO_THROW(task_queue->shutdown());
  8858. }
  8859. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8860. Server svr;
  8861. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8862. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8863. });
  8864. svr.Get("/hello", [](const Request &req, Response &res) {
  8865. res.set_content(req.get_param_value("key"), "text/plain");
  8866. });
  8867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8868. auto se = detail::scope_exit([&] {
  8869. svr.stop();
  8870. thread.join();
  8871. ASSERT_FALSE(svr.is_running());
  8872. });
  8873. svr.wait_until_ready();
  8874. {
  8875. Client cli(HOST, PORT);
  8876. cli.set_follow_location(true);
  8877. auto res = cli.Get("/");
  8878. ASSERT_TRUE(res);
  8879. EXPECT_EQ(StatusCode::OK_200, res->status);
  8880. EXPECT_EQ("val&key2=val2", res->body);
  8881. }
  8882. }
  8883. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8884. Server svr;
  8885. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8886. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8887. });
  8888. svr.Get("/hello", [](const Request &req, Response &res) {
  8889. res.set_content(req.get_param_value("key"), "text/plain");
  8890. });
  8891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8892. auto se = detail::scope_exit([&] {
  8893. svr.stop();
  8894. thread.join();
  8895. ASSERT_FALSE(svr.is_running());
  8896. });
  8897. svr.wait_until_ready();
  8898. {
  8899. Client cli(HOST, PORT);
  8900. cli.set_follow_location(true);
  8901. auto res = cli.Get("/");
  8902. ASSERT_TRUE(res);
  8903. EXPECT_EQ(StatusCode::OK_200, res->status);
  8904. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8905. }
  8906. }
  8907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8908. TEST(RedirectTest, Issue2185_Online) {
  8909. SSLClient client("github.com");
  8910. client.set_follow_location(true);
  8911. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8912. "Coollab-Windows.zip");
  8913. ASSERT_TRUE(res);
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. EXPECT_EQ(9920427U, res->body.size());
  8916. }
  8917. #endif
  8918. TEST(VulnerabilityTest, CRLFInjection) {
  8919. Server svr;
  8920. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8921. res.set_content("Hello 1", "text/plain");
  8922. });
  8923. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8924. res.set_content("Hello 2", "text/plain");
  8925. });
  8926. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8927. res.set_content("Hello 3", "text/plain");
  8928. });
  8929. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8930. res.set_content("Hello 4", "text/plain");
  8931. });
  8932. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8933. for (const auto &x : req.headers) {
  8934. auto key = x.first;
  8935. EXPECT_STRNE("evil", key.c_str());
  8936. }
  8937. });
  8938. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8939. auto se = detail::scope_exit([&] {
  8940. svr.stop();
  8941. thread.join();
  8942. ASSERT_FALSE(svr.is_running());
  8943. });
  8944. svr.wait_until_ready();
  8945. {
  8946. Client cli(HOST, PORT);
  8947. cli.Post("/test1", "A=B",
  8948. "application/x-www-form-urlencoded\r\nevil: hello1");
  8949. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8950. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8951. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8952. }
  8953. }
  8954. TEST(PathParamsTest, StaticMatch) {
  8955. const auto pattern = "/users/all";
  8956. detail::PathParamsMatcher matcher(pattern);
  8957. Request request;
  8958. request.path = "/users/all";
  8959. ASSERT_TRUE(matcher.match(request));
  8960. std::unordered_map<std::string, std::string> expected_params = {};
  8961. EXPECT_EQ(request.path_params, expected_params);
  8962. }
  8963. TEST(PathParamsTest, StaticMismatch) {
  8964. const auto pattern = "/users/all";
  8965. detail::PathParamsMatcher matcher(pattern);
  8966. Request request;
  8967. request.path = "/users/1";
  8968. ASSERT_FALSE(matcher.match(request));
  8969. }
  8970. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8971. const auto pattern = "/users/:id/subscriptions";
  8972. detail::PathParamsMatcher matcher(pattern);
  8973. Request request;
  8974. request.path = "/users/42/subscriptions";
  8975. ASSERT_TRUE(matcher.match(request));
  8976. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8977. EXPECT_EQ(request.path_params, expected_params);
  8978. }
  8979. TEST(PathParamsTest, SingleParamInTheEnd) {
  8980. const auto pattern = "/users/:id";
  8981. detail::PathParamsMatcher matcher(pattern);
  8982. Request request;
  8983. request.path = "/users/24";
  8984. ASSERT_TRUE(matcher.match(request));
  8985. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8986. EXPECT_EQ(request.path_params, expected_params);
  8987. }
  8988. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8989. const auto pattern = "/users/:id/";
  8990. detail::PathParamsMatcher matcher(pattern);
  8991. Request request;
  8992. request.path = "/users/42/";
  8993. ASSERT_TRUE(matcher.match(request));
  8994. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8995. EXPECT_EQ(request.path_params, expected_params);
  8996. }
  8997. TEST(PathParamsTest, EmptyParam) {
  8998. const auto pattern = "/users/:id/";
  8999. detail::PathParamsMatcher matcher(pattern);
  9000. Request request;
  9001. request.path = "/users//";
  9002. ASSERT_TRUE(matcher.match(request));
  9003. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9004. EXPECT_EQ(request.path_params, expected_params);
  9005. }
  9006. TEST(PathParamsTest, FragmentMismatch) {
  9007. const auto pattern = "/users/:id/";
  9008. detail::PathParamsMatcher matcher(pattern);
  9009. Request request;
  9010. request.path = "/admins/24/";
  9011. ASSERT_FALSE(matcher.match(request));
  9012. }
  9013. TEST(PathParamsTest, ExtraFragments) {
  9014. const auto pattern = "/users/:id";
  9015. detail::PathParamsMatcher matcher(pattern);
  9016. Request request;
  9017. request.path = "/users/42/subscriptions";
  9018. ASSERT_FALSE(matcher.match(request));
  9019. }
  9020. TEST(PathParamsTest, MissingTrailingParam) {
  9021. const auto pattern = "/users/:id";
  9022. detail::PathParamsMatcher matcher(pattern);
  9023. Request request;
  9024. request.path = "/users";
  9025. ASSERT_FALSE(matcher.match(request));
  9026. }
  9027. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9028. const auto pattern = "/users/:id/subscriptions";
  9029. detail::PathParamsMatcher matcher(pattern);
  9030. Request request;
  9031. request.path = "/users/subscriptions";
  9032. ASSERT_FALSE(matcher.match(request));
  9033. }
  9034. TEST(PathParamsTest, MultipleParams) {
  9035. const auto pattern = "/users/:userid/subscriptions/:subid";
  9036. detail::PathParamsMatcher matcher(pattern);
  9037. Request request;
  9038. request.path = "/users/42/subscriptions/2";
  9039. ASSERT_TRUE(matcher.match(request));
  9040. std::unordered_map<std::string, std::string> expected_params = {
  9041. {"userid", "42"}, {"subid", "2"}};
  9042. EXPECT_EQ(request.path_params, expected_params);
  9043. }
  9044. TEST(PathParamsTest, SequenceOfParams) {
  9045. const auto pattern = "/values/:x/:y/:z";
  9046. detail::PathParamsMatcher matcher(pattern);
  9047. Request request;
  9048. request.path = "/values/1/2/3";
  9049. ASSERT_TRUE(matcher.match(request));
  9050. std::unordered_map<std::string, std::string> expected_params = {
  9051. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9052. EXPECT_EQ(request.path_params, expected_params);
  9053. }
  9054. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9055. const auto pattern = "/prefix:suffix";
  9056. detail::PathParamsMatcher matcher(pattern);
  9057. Request request;
  9058. request.path = "/prefix:suffix";
  9059. ASSERT_TRUE(matcher.match(request));
  9060. const std::unordered_map<std::string, std::string> expected_params = {};
  9061. EXPECT_EQ(request.path_params, expected_params);
  9062. }
  9063. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9064. // If ipv6 regex working, regex match codepath is taken.
  9065. // else port will default to 80 in Client impl
  9066. int clientImplMagicPort = 80;
  9067. int port = 4321;
  9068. // above ports must be different to avoid false negative
  9069. EXPECT_NE(clientImplMagicPort, port);
  9070. std::string ipV6TestURL = "http://[ff06::c3]";
  9071. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9072. CLIENT_PRIVATE_KEY_FILE);
  9073. EXPECT_EQ(cli.port(), port);
  9074. }
  9075. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9076. auto file_path = "./www/dir/index.html";
  9077. auto dir_path = "./www/dir";
  9078. detail::FileStat stat_file(file_path);
  9079. EXPECT_TRUE(stat_file.is_file());
  9080. EXPECT_FALSE(stat_file.is_dir());
  9081. detail::FileStat stat_dir(dir_path);
  9082. EXPECT_FALSE(stat_dir.is_file());
  9083. EXPECT_TRUE(stat_dir.is_dir());
  9084. }
  9085. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9086. // IPv4 with default HTTP port (80)
  9087. EXPECT_EQ("example.com",
  9088. detail::make_host_and_port_string("example.com", 80, false));
  9089. // IPv4 with default HTTPS port (443)
  9090. EXPECT_EQ("example.com",
  9091. detail::make_host_and_port_string("example.com", 443, true));
  9092. // IPv4 with non-default HTTP port
  9093. EXPECT_EQ("example.com:8080",
  9094. detail::make_host_and_port_string("example.com", 8080, false));
  9095. // IPv4 with non-default HTTPS port
  9096. EXPECT_EQ("example.com:8443",
  9097. detail::make_host_and_port_string("example.com", 8443, true));
  9098. // IPv6 with default HTTP port (80)
  9099. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9100. // IPv6 with default HTTPS port (443)
  9101. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9102. // IPv6 with non-default HTTP port
  9103. EXPECT_EQ("[::1]:8080",
  9104. detail::make_host_and_port_string("::1", 8080, false));
  9105. // IPv6 with non-default HTTPS port
  9106. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9107. // IPv6 full address with default port
  9108. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9109. detail::make_host_and_port_string(
  9110. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9111. // IPv6 full address with non-default port
  9112. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9113. detail::make_host_and_port_string(
  9114. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9115. // IPv6 localhost with non-default port
  9116. EXPECT_EQ("[::1]:3000",
  9117. detail::make_host_and_port_string("::1", 3000, false));
  9118. // IPv6 with zone ID (link-local address) with default port
  9119. EXPECT_EQ("[fe80::1%eth0]",
  9120. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9121. // IPv6 with zone ID (link-local address) with non-default port
  9122. EXPECT_EQ("[fe80::1%eth0]:8080",
  9123. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9124. // Edge case: Port 443 with is_ssl=false (should add port)
  9125. EXPECT_EQ("example.com:443",
  9126. detail::make_host_and_port_string("example.com", 443, false));
  9127. // Edge case: Port 80 with is_ssl=true (should add port)
  9128. EXPECT_EQ("example.com:80",
  9129. detail::make_host_and_port_string("example.com", 80, true));
  9130. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9131. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9132. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9133. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9134. // Security fix: Already bracketed IPv6 should not get double brackets
  9135. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9136. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9137. EXPECT_EQ("[::1]:8080",
  9138. detail::make_host_and_port_string("[::1]", 8080, false));
  9139. EXPECT_EQ("[2001:db8::1]:8080",
  9140. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9141. EXPECT_EQ("[fe80::1%eth0]",
  9142. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9143. EXPECT_EQ("[fe80::1%eth0]:8080",
  9144. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9145. // Edge case: Empty host (should return as-is)
  9146. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9147. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9148. // This is a known limitation but shouldn't crash
  9149. EXPECT_EQ("[host:name]",
  9150. detail::make_host_and_port_string("host:name", 80, false));
  9151. // Port number edge cases (no validation, but should not crash)
  9152. EXPECT_EQ("example.com:0",
  9153. detail::make_host_and_port_string("example.com", 0, false));
  9154. EXPECT_EQ("example.com:-1",
  9155. detail::make_host_and_port_string("example.com", -1, false));
  9156. EXPECT_EQ("example.com:65535",
  9157. detail::make_host_and_port_string("example.com", 65535, false));
  9158. EXPECT_EQ("example.com:65536",
  9159. detail::make_host_and_port_string("example.com", 65536, false));
  9160. }
  9161. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9162. Server svr;
  9163. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9164. EXPECT_EQ(res.status, 400);
  9165. });
  9166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9167. auto se = detail::scope_exit([&] {
  9168. svr.stop();
  9169. thread.join();
  9170. ASSERT_FALSE(svr.is_running());
  9171. });
  9172. svr.wait_until_ready();
  9173. Client cli(HOST, PORT);
  9174. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9175. }
  9176. TEST(InvalidHeaderCharsTest, is_field_name) {
  9177. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9178. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9179. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9180. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9181. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9182. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9183. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9184. EXPECT_FALSE(detail::fields::is_field_name(""));
  9185. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9186. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9187. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9188. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9189. }
  9190. TEST(InvalidHeaderCharsTest, is_field_value) {
  9191. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9192. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9193. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9194. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9195. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9196. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9197. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9198. EXPECT_TRUE(detail::fields::is_field_value(""));
  9199. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9200. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9201. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9202. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9203. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9204. }
  9205. TEST(InvalidHeaderCharsTest, OnServer) {
  9206. Server svr;
  9207. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9208. std::string header = "Not Set";
  9209. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9210. res.set_header(header, "value");
  9211. res.set_content("Page Content Page Content", "text/plain");
  9212. });
  9213. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9214. std::string header = "Not Set";
  9215. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9216. res.set_header("X-Test", header);
  9217. res.set_content("Page Content Page Content", "text/plain");
  9218. });
  9219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9220. auto se = detail::scope_exit([&] {
  9221. svr.stop();
  9222. thread.join();
  9223. ASSERT_FALSE(svr.is_running());
  9224. });
  9225. svr.wait_until_ready();
  9226. Client cli(HOST, PORT);
  9227. {
  9228. auto res = cli.Get(
  9229. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9230. ASSERT_TRUE(res);
  9231. EXPECT_EQ("Page Content Page Content", res->body);
  9232. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9233. }
  9234. {
  9235. auto res = cli.Get(
  9236. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9237. ASSERT_TRUE(res);
  9238. EXPECT_EQ("Page Content Page Content", res->body);
  9239. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9240. }
  9241. }
  9242. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9243. auto handled = false;
  9244. Server svr;
  9245. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9246. thread t = thread([&] { svr.listen(HOST, PORT); });
  9247. auto se = detail::scope_exit([&] {
  9248. svr.stop();
  9249. t.join();
  9250. ASSERT_FALSE(svr.is_running());
  9251. ASSERT_FALSE(handled);
  9252. });
  9253. svr.wait_until_ready();
  9254. auto req = "POST /test HTTP/1.1\r\n"
  9255. "Content-Length: x\r\n"
  9256. "\r\n";
  9257. std::string response;
  9258. ASSERT_TRUE(send_request(1, req, &response));
  9259. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9260. response.substr(0, response.find("\r\n")));
  9261. }
  9262. #ifndef _WIN32
  9263. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9264. static constexpr char reject[] = "Unauthorized";
  9265. static constexpr char accept[] = "Upload accepted";
  9266. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9267. Server svr;
  9268. svr.set_expect_100_continue_handler(
  9269. [](const Request & /*req*/, Response &res) {
  9270. res.status = StatusCode::Unauthorized_401;
  9271. res.set_content(reject, "text/plain");
  9272. return res.status;
  9273. });
  9274. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9275. res.set_content(accept, "text/plain");
  9276. });
  9277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9278. auto se = detail::scope_exit([&] {
  9279. svr.stop();
  9280. thread.join();
  9281. ASSERT_FALSE(svr.is_running());
  9282. });
  9283. svr.wait_until_ready();
  9284. {
  9285. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9286. curl_easy_init(), &curl_easy_cleanup};
  9287. ASSERT_NE(curl, nullptr);
  9288. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9289. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9290. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9291. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9292. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9293. &curl_slist_free_all};
  9294. ASSERT_NE(list, nullptr);
  9295. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9296. struct read_data {
  9297. size_t read_size;
  9298. size_t total_size;
  9299. } data = {0, total_size};
  9300. using read_callback_t =
  9301. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9302. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9303. void *userdata) -> size_t {
  9304. read_data *data = (read_data *)userdata;
  9305. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9306. std::fill_n(ptr, size * nmemb, 'A');
  9307. data->read_size += size * nmemb;
  9308. return size * nmemb;
  9309. };
  9310. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9311. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9312. std::vector<char> buffer;
  9313. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9314. using write_callback_t =
  9315. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9316. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9317. void *userdata) -> size_t {
  9318. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9319. buffer->reserve(buffer->size() + size * nmemb + 1);
  9320. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9321. return size * nmemb;
  9322. };
  9323. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9324. {
  9325. const auto res = curl_easy_perform(curl.get());
  9326. ASSERT_EQ(res, CURLE_OK);
  9327. }
  9328. {
  9329. auto response_code = long{};
  9330. const auto res =
  9331. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9332. ASSERT_EQ(res, CURLE_OK);
  9333. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9334. }
  9335. {
  9336. auto dl = curl_off_t{};
  9337. const auto res =
  9338. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9339. ASSERT_EQ(res, CURLE_OK);
  9340. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9341. }
  9342. {
  9343. buffer.push_back('\0');
  9344. ASSERT_STRCASEEQ(buffer.data(), reject);
  9345. }
  9346. }
  9347. }
  9348. #endif
  9349. template <typename S, typename C>
  9350. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9351. svr.Get("/stream", [&](const Request &, Response &res) {
  9352. auto data = new std::string("01234567890123456789");
  9353. res.set_content_provider(
  9354. data->size(), "text/plain",
  9355. [&, data](size_t offset, size_t length, DataSink &sink) {
  9356. const size_t DATA_CHUNK_SIZE = 4;
  9357. const auto &d = *data;
  9358. std::this_thread::sleep_for(std::chrono::seconds(1));
  9359. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9360. return true;
  9361. },
  9362. [data](bool success) {
  9363. EXPECT_FALSE(success);
  9364. delete data;
  9365. });
  9366. });
  9367. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9368. auto i = new size_t(0);
  9369. res.set_content_provider(
  9370. "text/plain",
  9371. [i](size_t, DataSink &sink) {
  9372. if (*i < 5) {
  9373. std::this_thread::sleep_for(std::chrono::seconds(1));
  9374. sink.write("abcd", 4);
  9375. (*i)++;
  9376. } else {
  9377. sink.done();
  9378. }
  9379. return true;
  9380. },
  9381. [i](bool success) {
  9382. EXPECT_FALSE(success);
  9383. delete i;
  9384. });
  9385. });
  9386. svr.Get("/chunked", [&](const Request &, Response &res) {
  9387. auto i = new size_t(0);
  9388. res.set_chunked_content_provider(
  9389. "text/plain",
  9390. [i](size_t, DataSink &sink) {
  9391. if (*i < 5) {
  9392. std::this_thread::sleep_for(std::chrono::seconds(1));
  9393. sink.os << "abcd";
  9394. (*i)++;
  9395. } else {
  9396. sink.done();
  9397. }
  9398. return true;
  9399. },
  9400. [i](bool success) {
  9401. EXPECT_FALSE(success);
  9402. delete i;
  9403. });
  9404. });
  9405. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9406. auto se = detail::scope_exit([&] {
  9407. svr.stop();
  9408. listen_thread.join();
  9409. ASSERT_FALSE(svr.is_running());
  9410. });
  9411. svr.wait_until_ready();
  9412. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9413. {
  9414. auto start = std::chrono::steady_clock::now();
  9415. auto res = cli.Get("/stream");
  9416. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9417. std::chrono::steady_clock::now() - start)
  9418. .count();
  9419. ASSERT_FALSE(res);
  9420. EXPECT_EQ(Error::Read, res.error());
  9421. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9422. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9423. }
  9424. {
  9425. auto start = std::chrono::steady_clock::now();
  9426. auto res = cli.Get("/stream_without_length");
  9427. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9428. std::chrono::steady_clock::now() - start)
  9429. .count();
  9430. ASSERT_FALSE(res);
  9431. EXPECT_EQ(Error::Read, res.error());
  9432. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9433. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9434. }
  9435. {
  9436. auto start = std::chrono::steady_clock::now();
  9437. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9438. EXPECT_EQ("abcd", string(data, data_length));
  9439. return true;
  9440. });
  9441. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9442. std::chrono::steady_clock::now() - start)
  9443. .count();
  9444. ASSERT_FALSE(res);
  9445. EXPECT_EQ(Error::Read, res.error());
  9446. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9447. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9448. }
  9449. }
  9450. TEST(MaxTimeoutTest, ContentStream) {
  9451. time_t timeout = 2000;
  9452. time_t threshold = 200;
  9453. Server svr;
  9454. Client cli("localhost", PORT);
  9455. max_timeout_test(svr, cli, timeout, threshold);
  9456. }
  9457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9458. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9459. time_t timeout = 2000;
  9460. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9462. SSLClient cli("localhost", PORT);
  9463. cli.enable_server_certificate_verification(false);
  9464. max_timeout_test(svr, cli, timeout, threshold);
  9465. }
  9466. #endif
  9467. class EventDispatcher {
  9468. public:
  9469. EventDispatcher() {}
  9470. bool wait_event(DataSink *sink) {
  9471. unique_lock<mutex> lk(m_);
  9472. int id = id_;
  9473. // Wait with timeout to prevent hanging if client disconnects
  9474. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9475. [&] { return cid_ == id; })) {
  9476. return false; // Timeout occurred
  9477. }
  9478. sink->write(message_.data(), message_.size());
  9479. return true;
  9480. }
  9481. void send_event(const string &message) {
  9482. lock_guard<mutex> lk(m_);
  9483. cid_ = id_++;
  9484. message_ = message;
  9485. cv_.notify_all();
  9486. }
  9487. private:
  9488. mutex m_;
  9489. condition_variable cv_;
  9490. atomic_int id_{0};
  9491. atomic_int cid_{-1};
  9492. string message_;
  9493. };
  9494. TEST(ClientInThreadTest, Issue2068) {
  9495. EventDispatcher ed;
  9496. Server svr;
  9497. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9498. res.set_chunked_content_provider("text/event-stream",
  9499. [&](size_t /*offset*/, DataSink &sink) {
  9500. return ed.wait_event(&sink);
  9501. });
  9502. });
  9503. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9504. svr.wait_until_ready();
  9505. thread event_thread([&] {
  9506. int id = 0;
  9507. while (svr.is_running()) {
  9508. this_thread::sleep_for(chrono::milliseconds(500));
  9509. std::stringstream ss;
  9510. ss << "data: " << id << "\n\n";
  9511. ed.send_event(ss.str());
  9512. id++;
  9513. }
  9514. });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. listen_thread.join();
  9518. event_thread.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. });
  9521. {
  9522. auto client = detail::make_unique<Client>(HOST, PORT);
  9523. client->set_read_timeout(std::chrono::minutes(10));
  9524. std::atomic<bool> stop{false};
  9525. std::thread t([&] {
  9526. client->Get("/event1",
  9527. [&](const char *, size_t) -> bool { return !stop; });
  9528. });
  9529. std::this_thread::sleep_for(std::chrono::seconds(2));
  9530. stop = true;
  9531. client->stop();
  9532. t.join();
  9533. // Reset client after thread has finished
  9534. client.reset();
  9535. }
  9536. }
  9537. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9538. Server svr;
  9539. svr.Get("/", [](const Request &req, Response &res) {
  9540. EXPECT_EQ(2U, req.trailers.size());
  9541. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9542. // Denied
  9543. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9544. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9545. // Accepted
  9546. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9547. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9548. EXPECT_TRUE(req.has_trailer("X-World"));
  9549. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9550. res.set_content("ok", "text/plain");
  9551. });
  9552. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. t.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. const std::string req = "GET / HTTP/1.1\r\n"
  9560. "Transfer-Encoding: chunked\r\n"
  9561. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9562. "\r\n"
  9563. "0\r\n"
  9564. "Content-Length: 10\r\n"
  9565. "Host: internal.local\r\n"
  9566. "Content-Type: malicious/content\r\n"
  9567. "Cookie: any\r\n"
  9568. "Set-Cookie: any\r\n"
  9569. "X-Forwarded-For: attacker.com\r\n"
  9570. "X-Real-Ip: 1.1.1.1\r\n"
  9571. "X-Hello: hello\r\n"
  9572. "X-World: world\r\n"
  9573. "\r\n";
  9574. std::string res;
  9575. ASSERT_TRUE(send_request(1, req, &res));
  9576. }
  9577. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9578. Server svr;
  9579. std::string observed_remote_addr;
  9580. std::string observed_xff;
  9581. svr.Get("/ip", [&](const Request &req, Response &res) {
  9582. observed_remote_addr = req.remote_addr;
  9583. observed_xff = req.get_header_value("X-Forwarded-For");
  9584. res.set_content("ok", "text/plain");
  9585. });
  9586. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9587. auto se = detail::scope_exit([&] {
  9588. svr.stop();
  9589. t.join();
  9590. ASSERT_FALSE(svr.is_running());
  9591. });
  9592. svr.wait_until_ready();
  9593. Client cli(HOST, PORT);
  9594. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9595. ASSERT_TRUE(res);
  9596. EXPECT_EQ(StatusCode::OK_200, res->status);
  9597. EXPECT_EQ(observed_xff, "203.0.113.66");
  9598. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9599. observed_remote_addr == "127.0.0.1");
  9600. }
  9601. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9602. Server svr;
  9603. svr.set_trusted_proxies({"203.0.113.66"});
  9604. std::string observed_remote_addr;
  9605. std::string observed_xff;
  9606. svr.Get("/ip", [&](const Request &req, Response &res) {
  9607. observed_remote_addr = req.remote_addr;
  9608. observed_xff = req.get_header_value("X-Forwarded-For");
  9609. res.set_content("ok", "text/plain");
  9610. });
  9611. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9612. auto se = detail::scope_exit([&] {
  9613. svr.stop();
  9614. t.join();
  9615. ASSERT_FALSE(svr.is_running());
  9616. });
  9617. svr.wait_until_ready();
  9618. Client cli(HOST, PORT);
  9619. auto res = cli.Get("/ip");
  9620. ASSERT_TRUE(res);
  9621. EXPECT_EQ(StatusCode::OK_200, res->status);
  9622. EXPECT_EQ(observed_xff, "");
  9623. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9624. observed_remote_addr == "127.0.0.1");
  9625. }
  9626. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9627. Server svr;
  9628. svr.set_trusted_proxies({"203.0.113.66"});
  9629. std::string observed_remote_addr;
  9630. std::string observed_xff;
  9631. svr.Get("/ip", [&](const Request &req, Response &res) {
  9632. observed_remote_addr = req.remote_addr;
  9633. observed_xff = req.get_header_value("X-Forwarded-For");
  9634. res.set_content("ok", "text/plain");
  9635. });
  9636. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9637. auto se = detail::scope_exit([&] {
  9638. svr.stop();
  9639. t.join();
  9640. ASSERT_FALSE(svr.is_running());
  9641. });
  9642. svr.wait_until_ready();
  9643. Client cli(HOST, PORT);
  9644. auto res =
  9645. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9646. ASSERT_TRUE(res);
  9647. EXPECT_EQ(StatusCode::OK_200, res->status);
  9648. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9649. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9650. }
  9651. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9652. Server svr;
  9653. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9654. std::string observed_remote_addr;
  9655. std::string observed_xff;
  9656. svr.Get("/ip", [&](const Request &req, Response &res) {
  9657. observed_remote_addr = req.remote_addr;
  9658. observed_xff = req.get_header_value("X-Forwarded-For");
  9659. res.set_content("ok", "text/plain");
  9660. });
  9661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. ASSERT_FALSE(svr.is_running());
  9666. });
  9667. svr.wait_until_ready();
  9668. Client cli(HOST, PORT);
  9669. auto res = cli.Get(
  9670. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9671. ASSERT_TRUE(res);
  9672. EXPECT_EQ(StatusCode::OK_200, res->status);
  9673. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9674. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9675. }
  9676. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9677. Server svr;
  9678. svr.set_trusted_proxies({"192.0.2.45"});
  9679. std::string observed_remote_addr;
  9680. std::string observed_xff;
  9681. svr.Get("/ip", [&](const Request &req, Response &res) {
  9682. observed_remote_addr = req.remote_addr;
  9683. observed_xff = req.get_header_value("X-Forwarded-For");
  9684. res.set_content("ok", "text/plain");
  9685. });
  9686. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9687. auto se = detail::scope_exit([&] {
  9688. svr.stop();
  9689. t.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. });
  9692. svr.wait_until_ready();
  9693. Client cli(HOST, PORT);
  9694. auto res =
  9695. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9696. ASSERT_TRUE(res);
  9697. EXPECT_EQ(StatusCode::OK_200, res->status);
  9698. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9699. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9700. }
  9701. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9702. Server svr;
  9703. svr.set_trusted_proxies({"192.0.2.45"});
  9704. std::string observed_remote_addr;
  9705. std::string observed_xff;
  9706. svr.Get("/ip", [&](const Request &req, Response &res) {
  9707. observed_remote_addr = req.remote_addr;
  9708. observed_xff = req.get_header_value("X-Forwarded-For");
  9709. res.set_content("ok", "text/plain");
  9710. });
  9711. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9712. auto se = detail::scope_exit([&] {
  9713. svr.stop();
  9714. t.join();
  9715. ASSERT_FALSE(svr.is_running());
  9716. });
  9717. svr.wait_until_ready();
  9718. Client cli(HOST, PORT);
  9719. auto res = cli.Get(
  9720. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9721. ASSERT_TRUE(res);
  9722. EXPECT_EQ(StatusCode::OK_200, res->status);
  9723. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9724. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9725. }
  9726. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9727. Server svr;
  9728. svr.set_trusted_proxies({"192.0.2.45"});
  9729. std::string observed_remote_addr;
  9730. std::string observed_xff;
  9731. svr.Get("/ip", [&](const Request &req, Response &res) {
  9732. observed_remote_addr = req.remote_addr;
  9733. observed_xff = req.get_header_value("X-Forwarded-For");
  9734. res.set_content("ok", "text/plain");
  9735. });
  9736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9737. auto se = detail::scope_exit([&] {
  9738. svr.stop();
  9739. t.join();
  9740. ASSERT_FALSE(svr.is_running());
  9741. });
  9742. svr.wait_until_ready();
  9743. Client cli(HOST, PORT);
  9744. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9745. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9746. ASSERT_TRUE(res);
  9747. EXPECT_EQ(StatusCode::OK_200, res->status);
  9748. // Header parser trims surrounding whitespace of the header value
  9749. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9750. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9751. }
  9752. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9753. Server svr;
  9754. svr.Post("/post", [&](const Request &req, Response &res) {
  9755. res.set_content(req.body, "text/plain");
  9756. });
  9757. svr.Put("/put", [&](const Request &req, Response &res) {
  9758. res.set_content(req.body, "text/plain");
  9759. });
  9760. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9761. res.set_content(req.body, "text/plain");
  9762. });
  9763. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9764. res.set_content(req.body, "text/plain");
  9765. });
  9766. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9767. auto se = detail::scope_exit([&] {
  9768. svr.stop();
  9769. t.join();
  9770. ASSERT_FALSE(svr.is_running());
  9771. });
  9772. svr.wait_until_ready();
  9773. std::string resp;
  9774. // POST without Content-Length
  9775. ASSERT_TRUE(send_request(5,
  9776. "POST /post HTTP/1.1\r\n"
  9777. "Host: localhost\r\n"
  9778. "Connection: close\r\n"
  9779. "\r\n",
  9780. &resp));
  9781. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9782. // PUT without Content-Length
  9783. resp.clear();
  9784. ASSERT_TRUE(send_request(5,
  9785. "PUT /put HTTP/1.1\r\n"
  9786. "Host: localhost\r\n"
  9787. "Connection: close\r\n"
  9788. "\r\n",
  9789. &resp));
  9790. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9791. // PATCH without Content-Length
  9792. resp.clear();
  9793. ASSERT_TRUE(send_request(5,
  9794. "PATCH /patch HTTP/1.1\r\n"
  9795. "Host: localhost\r\n"
  9796. "Connection: close\r\n"
  9797. "\r\n",
  9798. &resp));
  9799. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9800. // DELETE without Content-Length
  9801. resp.clear();
  9802. ASSERT_TRUE(send_request(5,
  9803. "DELETE /delete HTTP/1.1\r\n"
  9804. "Host: localhost\r\n"
  9805. "Connection: close\r\n"
  9806. "\r\n",
  9807. &resp));
  9808. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9809. }
  9810. //==============================================================================
  9811. // open_stream() Tests
  9812. //==============================================================================
  9813. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9814. std::string result;
  9815. char buf[8192];
  9816. ssize_t n;
  9817. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9818. result.append(buf, static_cast<size_t>(n));
  9819. }
  9820. return result;
  9821. }
  9822. // Mock stream for unit tests
  9823. class MockStream : public Stream {
  9824. public:
  9825. std::string data;
  9826. size_t pos = 0;
  9827. ssize_t error_after = -1; // -1 = no error
  9828. explicit MockStream(const std::string &d, ssize_t err = -1)
  9829. : data(d), error_after(err) {}
  9830. bool is_readable() const override { return true; }
  9831. bool wait_readable() const override { return true; }
  9832. bool wait_writable() const override { return true; }
  9833. ssize_t read(char *ptr, size_t size) override {
  9834. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9835. if (pos >= data.size()) return 0;
  9836. size_t limit =
  9837. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9838. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9839. std::memcpy(ptr, data.data() + pos, to_read);
  9840. pos += to_read;
  9841. return static_cast<ssize_t>(to_read);
  9842. }
  9843. ssize_t write(const char *, size_t) override { return -1; }
  9844. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9845. ip = "127.0.0.1";
  9846. port = 0;
  9847. }
  9848. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9849. ip = "127.0.0.1";
  9850. port = 0;
  9851. }
  9852. socket_t socket() const override { return INVALID_SOCKET; }
  9853. time_t duration() const override { return 0; }
  9854. };
  9855. TEST(StreamHandleTest, Basic) {
  9856. ClientImpl::StreamHandle handle;
  9857. EXPECT_FALSE(handle.is_valid());
  9858. handle.response = detail::make_unique<Response>();
  9859. handle.error = Error::Connection;
  9860. EXPECT_FALSE(handle.is_valid());
  9861. handle.error = Error::Success;
  9862. EXPECT_TRUE(handle.is_valid());
  9863. }
  9864. TEST(BodyReaderTest, Basic) {
  9865. MockStream stream("Hello, World!");
  9866. detail::BodyReader reader;
  9867. reader.stream = &stream;
  9868. reader.content_length = 13;
  9869. char buf[32];
  9870. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9871. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9872. EXPECT_TRUE(reader.eof);
  9873. }
  9874. TEST(BodyReaderTest, NoStream) {
  9875. detail::BodyReader reader;
  9876. char buf[32];
  9877. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9878. EXPECT_EQ(Error::Connection, reader.last_error);
  9879. }
  9880. TEST(BodyReaderTest, Error) {
  9881. MockStream stream("Hello, World!", 5);
  9882. detail::BodyReader reader;
  9883. reader.stream = &stream;
  9884. reader.content_length = 13;
  9885. char buf[32];
  9886. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9887. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9888. EXPECT_EQ(Error::Read, reader.last_error);
  9889. }
  9890. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9891. // Mock-based StreamHandle tests relying on private internals are removed.
  9892. class OpenStreamTest : public ::testing::Test {
  9893. protected:
  9894. void SetUp() override {
  9895. svr_.Get("/hello", [](const Request &, Response &res) {
  9896. res.set_content("Hello World!", "text/plain");
  9897. });
  9898. svr_.Get("/large", [](const Request &, Response &res) {
  9899. res.set_content(std::string(10000, 'X'), "text/plain");
  9900. });
  9901. svr_.Get("/chunked", [](const Request &, Response &res) {
  9902. res.set_chunked_content_provider("text/plain",
  9903. [](size_t offset, DataSink &sink) {
  9904. if (offset < 15) {
  9905. sink.write("chunk", 5);
  9906. return true;
  9907. }
  9908. sink.done();
  9909. return true;
  9910. });
  9911. });
  9912. svr_.Get("/compressible", [](const Request &, Response &res) {
  9913. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9914. DataSink &sink) {
  9915. if (offset < 100 * 1024) {
  9916. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9917. sink.write(chunk.data(), chunk.size());
  9918. return true;
  9919. }
  9920. sink.done();
  9921. return true;
  9922. });
  9923. });
  9924. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9925. [](const Request & /*req*/, Response &res) {
  9926. auto i = new int(0);
  9927. res.set_header("Trailer", "Content-Length, X-Allowed");
  9928. res.set_chunked_content_provider(
  9929. "text/plain",
  9930. [i](size_t /*offset*/, DataSink &sink) {
  9931. switch (*i) {
  9932. case 0: sink.os << "123"; break;
  9933. case 1: sink.os << "456"; break;
  9934. case 2: sink.os << "789"; break;
  9935. case 3: {
  9936. sink.done_with_trailer(
  9937. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9938. } break;
  9939. }
  9940. (*i)++;
  9941. return true;
  9942. },
  9943. [i](bool success) {
  9944. EXPECT_TRUE(success);
  9945. delete i;
  9946. });
  9947. });
  9948. // Echo headers endpoint for header-related tests
  9949. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9950. std::string body;
  9951. for (const auto &h : req.headers) {
  9952. body.append(h.first);
  9953. body.push_back(':');
  9954. body.append(h.second);
  9955. body.push_back('\n');
  9956. }
  9957. res.set_content(body, "text/plain");
  9958. });
  9959. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9960. std::string body;
  9961. for (const auto &h : req.headers) {
  9962. body.append(h.first);
  9963. body.push_back(':');
  9964. body.append(h.second);
  9965. body.push_back('\n');
  9966. }
  9967. res.set_content(body, "text/plain");
  9968. });
  9969. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9970. svr_.wait_until_ready();
  9971. }
  9972. void TearDown() override {
  9973. svr_.stop();
  9974. if (thread_.joinable()) thread_.join();
  9975. }
  9976. Server svr_;
  9977. std::thread thread_;
  9978. };
  9979. TEST_F(OpenStreamTest, Basic) {
  9980. Client cli("127.0.0.1", 8787);
  9981. auto handle = cli.open_stream("GET", "/hello");
  9982. EXPECT_TRUE(handle.is_valid());
  9983. EXPECT_EQ("Hello World!", read_all(handle));
  9984. }
  9985. TEST_F(OpenStreamTest, SmallBuffer) {
  9986. Client cli("127.0.0.1", 8787);
  9987. auto handle = cli.open_stream("GET", "/hello");
  9988. std::string result;
  9989. char buf[4];
  9990. ssize_t n;
  9991. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9992. result.append(buf, static_cast<size_t>(n));
  9993. EXPECT_EQ("Hello World!", result);
  9994. }
  9995. TEST_F(OpenStreamTest, DefaultHeaders) {
  9996. Client cli("127.0.0.1", 8787);
  9997. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9998. {
  9999. auto handle = cli.open_stream("GET", "/echo-headers");
  10000. ASSERT_TRUE(handle.is_valid());
  10001. auto body = read_all(handle);
  10002. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10003. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10004. std::string::npos);
  10005. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10006. }
  10007. // open_stream POST with body and no explicit content_type should NOT add
  10008. // text/plain Content-Type (behavior differs from non-streaming path), but
  10009. // should include Content-Length
  10010. {
  10011. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10012. ASSERT_TRUE(handle.is_valid());
  10013. auto body = read_all(handle);
  10014. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10015. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10016. }
  10017. // open_stream POST with explicit Content-Type should preserve it
  10018. {
  10019. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10020. {{"Content-Type", "application/custom"}},
  10021. "{}", "application/custom");
  10022. ASSERT_TRUE(handle.is_valid());
  10023. auto body = read_all(handle);
  10024. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10025. }
  10026. // User-specified User-Agent must not be overwritten for stream API
  10027. {
  10028. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10029. {{"User-Agent", "MyAgent/1.2"}});
  10030. ASSERT_TRUE(handle.is_valid());
  10031. auto body = read_all(handle);
  10032. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10033. }
  10034. }
  10035. TEST_F(OpenStreamTest, Large) {
  10036. Client cli("127.0.0.1", 8787);
  10037. auto handle = cli.open_stream("GET", "/large");
  10038. EXPECT_EQ(10000u, read_all(handle).size());
  10039. }
  10040. TEST_F(OpenStreamTest, ConnectionError) {
  10041. Client cli("127.0.0.1", 9999);
  10042. auto handle = cli.open_stream("GET", "/hello");
  10043. EXPECT_FALSE(handle.is_valid());
  10044. }
  10045. TEST_F(OpenStreamTest, Chunked) {
  10046. Client cli("127.0.0.1", 8787);
  10047. auto handle = cli.open_stream("GET", "/chunked");
  10048. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10049. "Transfer-Encoding") == "chunked");
  10050. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10051. }
  10052. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10053. Client cli("127.0.0.1", 8787);
  10054. auto handle =
  10055. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10056. ASSERT_TRUE(handle.is_valid());
  10057. // Consume body to allow trailers to be received/parsed
  10058. auto body = read_all(handle);
  10059. // Explicitly parse trailers (ensure trailers are available for assertion)
  10060. handle.parse_trailers_if_needed();
  10061. EXPECT_EQ(std::string("123456789"), body);
  10062. // The response should include a Trailer header declaring both names
  10063. ASSERT_TRUE(handle.response);
  10064. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10065. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10066. handle.response->get_header_value("Trailer"));
  10067. // Prohibited trailer must not be present
  10068. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10069. // Allowed trailer should be present
  10070. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10071. EXPECT_EQ(std::string("yes"),
  10072. handle.response->get_trailer_value("X-Allowed"));
  10073. // Verify trailers are NOT present as regular headers
  10074. EXPECT_EQ(std::string(""),
  10075. handle.response->get_header_value("Content-Length"));
  10076. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10077. }
  10078. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10079. TEST_F(OpenStreamTest, Gzip) {
  10080. Client cli("127.0.0.1", 8787);
  10081. auto handle = cli.open_stream("GET", "/compressible", {},
  10082. {{"Accept-Encoding", "gzip"}});
  10083. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10084. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10085. }
  10086. #endif
  10087. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10088. TEST_F(OpenStreamTest, Brotli) {
  10089. Client cli("127.0.0.1", 8787);
  10090. auto handle =
  10091. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10092. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10093. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10094. }
  10095. #endif
  10096. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10097. TEST_F(OpenStreamTest, Zstd) {
  10098. Client cli("127.0.0.1", 8787);
  10099. auto handle = cli.open_stream("GET", "/compressible", {},
  10100. {{"Accept-Encoding", "zstd"}});
  10101. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10102. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10103. }
  10104. #endif
  10105. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10106. class SSLOpenStreamTest : public ::testing::Test {
  10107. protected:
  10108. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10109. void SetUp() override {
  10110. svr_.Get("/hello", [](const Request &, Response &res) {
  10111. res.set_content("Hello SSL World!", "text/plain");
  10112. });
  10113. svr_.Get("/chunked", [](const Request &, Response &res) {
  10114. res.set_chunked_content_provider("text/plain",
  10115. [](size_t offset, DataSink &sink) {
  10116. if (offset < 15) {
  10117. sink.write("chunk", 5);
  10118. return true;
  10119. }
  10120. sink.done();
  10121. return true;
  10122. });
  10123. });
  10124. svr_.Post("/echo", [](const Request &req, Response &res) {
  10125. res.set_content(req.body, req.get_header_value("Content-Type"));
  10126. });
  10127. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10128. std::string body = req.body;
  10129. res.set_chunked_content_provider(
  10130. "text/plain", [body](size_t offset, DataSink &sink) {
  10131. if (offset < body.size()) {
  10132. sink.write(body.data() + offset, body.size() - offset);
  10133. }
  10134. sink.done();
  10135. return true;
  10136. });
  10137. });
  10138. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10139. svr_.wait_until_ready();
  10140. }
  10141. void TearDown() override {
  10142. svr_.stop();
  10143. if (thread_.joinable()) thread_.join();
  10144. }
  10145. SSLServer svr_;
  10146. std::thread thread_;
  10147. };
  10148. TEST_F(SSLOpenStreamTest, Basic) {
  10149. SSLClient cli("127.0.0.1", 8788);
  10150. cli.enable_server_certificate_verification(false);
  10151. auto handle = cli.open_stream("GET", "/hello");
  10152. ASSERT_TRUE(handle.is_valid());
  10153. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10154. }
  10155. TEST_F(SSLOpenStreamTest, Chunked) {
  10156. SSLClient cli("127.0.0.1", 8788);
  10157. cli.enable_server_certificate_verification(false);
  10158. auto handle = cli.open_stream("GET", "/chunked");
  10159. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10160. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10161. "Transfer-Encoding") == "chunked");
  10162. auto body = read_all(handle);
  10163. EXPECT_EQ("chunkchunkchunk", body);
  10164. }
  10165. TEST_F(SSLOpenStreamTest, Post) {
  10166. SSLClient cli("127.0.0.1", 8788);
  10167. cli.enable_server_certificate_verification(false);
  10168. auto handle =
  10169. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10170. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10171. EXPECT_EQ(200, handle.response->status);
  10172. auto body = read_all(handle);
  10173. EXPECT_EQ("Hello SSL POST", body);
  10174. }
  10175. TEST_F(SSLOpenStreamTest, PostChunked) {
  10176. SSLClient cli("127.0.0.1", 8788);
  10177. cli.enable_server_certificate_verification(false);
  10178. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10179. "Chunked SSL Data", "text/plain");
  10180. ASSERT_TRUE(handle.is_valid());
  10181. EXPECT_EQ(200, handle.response->status);
  10182. auto body = read_all(handle);
  10183. EXPECT_EQ("Chunked SSL Data", body);
  10184. }
  10185. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10186. //==============================================================================
  10187. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10188. // results for various scenarios.
  10189. //==============================================================================
  10190. TEST(ParityTest, GetVsOpenStream) {
  10191. Server svr;
  10192. const std::string path = "/parity";
  10193. const std::string content = "Parity test content: hello world";
  10194. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10195. res.set_content(content, "text/plain");
  10196. });
  10197. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10198. auto se = detail::scope_exit([&] {
  10199. svr.stop();
  10200. t.join();
  10201. ASSERT_FALSE(svr.is_running());
  10202. });
  10203. svr.wait_until_ready();
  10204. Client cli(HOST, PORT);
  10205. // Non-stream path
  10206. auto r1 = cli.Get(path);
  10207. ASSERT_TRUE(r1);
  10208. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10209. // Stream path
  10210. auto h = cli.open_stream("GET", path);
  10211. ASSERT_TRUE(h.is_valid());
  10212. EXPECT_EQ(r1->body, read_all(h));
  10213. }
  10214. // Helper to compress data with provided compressor type T
  10215. template <typename Compressor>
  10216. static std::string compress_payload_for_parity(const std::string &in) {
  10217. std::string out;
  10218. Compressor compressor;
  10219. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10220. [&](const char *data, size_t n) {
  10221. out.append(data, n);
  10222. return true;
  10223. });
  10224. EXPECT_TRUE(ok);
  10225. return out;
  10226. }
  10227. // Helper function for compression parity tests
  10228. template <typename Compressor>
  10229. static void test_compression_parity(const std::string &original,
  10230. const std::string &path,
  10231. const std::string &encoding) {
  10232. const std::string compressed =
  10233. compress_payload_for_parity<Compressor>(original);
  10234. Server svr;
  10235. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10236. res.set_content(compressed, "application/octet-stream");
  10237. res.set_header("Content-Encoding", encoding);
  10238. });
  10239. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. t.join();
  10243. ASSERT_FALSE(svr.is_running());
  10244. });
  10245. svr.wait_until_ready();
  10246. Client cli("localhost", 1234);
  10247. // Non-streaming
  10248. {
  10249. auto res = cli.Get(path);
  10250. ASSERT_TRUE(res);
  10251. EXPECT_EQ(StatusCode::OK_200, res->status);
  10252. EXPECT_EQ(original, res->body);
  10253. }
  10254. // Streaming
  10255. {
  10256. auto h = cli.open_stream("GET", path);
  10257. ASSERT_TRUE(h.is_valid());
  10258. EXPECT_EQ(original, read_all(h));
  10259. }
  10260. }
  10261. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10262. TEST(ParityTest, Gzip) {
  10263. test_compression_parity<detail::gzip_compressor>(
  10264. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10265. }
  10266. #endif
  10267. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10268. TEST(ParityTest, Brotli) {
  10269. test_compression_parity<detail::brotli_compressor>(
  10270. "Hello, brotli parity test payload", "/parity-br", "br");
  10271. }
  10272. #endif
  10273. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10274. TEST(ParityTest, Zstd) {
  10275. test_compression_parity<detail::zstd_compressor>(
  10276. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10277. }
  10278. #endif
  10279. //==============================================================================
  10280. // New Stream API Tests
  10281. //==============================================================================
  10282. inline std::string read_body(httplib::stream::Result &result) {
  10283. std::string body;
  10284. while (result.next()) {
  10285. body.append(result.data(), result.size());
  10286. }
  10287. return body;
  10288. }
  10289. TEST(ClientConnectionTest, Basic) {
  10290. httplib::ClientConnection conn;
  10291. EXPECT_FALSE(conn.is_open());
  10292. conn.sock = 1;
  10293. EXPECT_TRUE(conn.is_open());
  10294. httplib::ClientConnection conn2(std::move(conn));
  10295. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10296. conn2.sock = INVALID_SOCKET;
  10297. }
  10298. // Unified test server for all stream::* tests
  10299. class StreamApiTest : public ::testing::Test {
  10300. protected:
  10301. void SetUp() override {
  10302. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10303. res.set_content("Hello World!", "text/plain");
  10304. });
  10305. svr_.Get("/echo-params",
  10306. [](const httplib::Request &req, httplib::Response &res) {
  10307. std::string r;
  10308. for (const auto &p : req.params) {
  10309. if (!r.empty()) r += "&";
  10310. r += p.first + "=" + p.second;
  10311. }
  10312. res.set_content(r, "text/plain");
  10313. });
  10314. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10315. res.set_content(req.body, req.get_header_value("Content-Type"));
  10316. });
  10317. svr_.Post("/echo-headers",
  10318. [](const httplib::Request &req, httplib::Response &res) {
  10319. std::string r;
  10320. for (const auto &h : req.headers)
  10321. r += h.first + ": " + h.second + "\n";
  10322. res.set_content(r, "text/plain");
  10323. });
  10324. svr_.Post("/echo-params",
  10325. [](const httplib::Request &req, httplib::Response &res) {
  10326. std::string r = "params:";
  10327. for (const auto &p : req.params)
  10328. r += p.first + "=" + p.second + ";";
  10329. res.set_content(r + " body:" + req.body, "text/plain");
  10330. });
  10331. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10332. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10333. });
  10334. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10335. res.set_content("PUT:" + req.body, "text/plain");
  10336. });
  10337. svr_.Patch("/echo",
  10338. [](const httplib::Request &req, httplib::Response &res) {
  10339. res.set_content("PATCH:" + req.body, "text/plain");
  10340. });
  10341. svr_.Delete(
  10342. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10343. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10344. "text/plain");
  10345. });
  10346. svr_.Get("/head-test",
  10347. [](const httplib::Request &, httplib::Response &res) {
  10348. res.set_content("body for HEAD", "text/plain");
  10349. });
  10350. svr_.Options("/options",
  10351. [](const httplib::Request &, httplib::Response &res) {
  10352. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10353. });
  10354. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10355. svr_.wait_until_ready();
  10356. }
  10357. void TearDown() override {
  10358. svr_.stop();
  10359. if (thread_.joinable()) thread_.join();
  10360. }
  10361. httplib::Server svr_;
  10362. std::thread thread_;
  10363. };
  10364. // stream::Get tests
  10365. TEST_F(StreamApiTest, GetBasic) {
  10366. httplib::Client cli("localhost", 8790);
  10367. auto result = httplib::stream::Get(cli, "/hello");
  10368. ASSERT_TRUE(result.is_valid());
  10369. EXPECT_EQ(200, result.status());
  10370. EXPECT_EQ("Hello World!", read_body(result));
  10371. }
  10372. TEST_F(StreamApiTest, GetWithParams) {
  10373. httplib::Client cli("localhost", 8790);
  10374. httplib::Params params{{"foo", "bar"}};
  10375. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10376. ASSERT_TRUE(result.is_valid());
  10377. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10378. }
  10379. TEST_F(StreamApiTest, GetConnectionError) {
  10380. httplib::Client cli("localhost", 9999);
  10381. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10382. }
  10383. TEST_F(StreamApiTest, Get404) {
  10384. httplib::Client cli("localhost", 8790);
  10385. auto result = httplib::stream::Get(cli, "/nonexistent");
  10386. EXPECT_TRUE(result.is_valid());
  10387. EXPECT_EQ(404, result.status());
  10388. }
  10389. // stream::Post tests
  10390. TEST_F(StreamApiTest, PostBasic) {
  10391. httplib::Client cli("localhost", 8790);
  10392. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10393. "application/json");
  10394. ASSERT_TRUE(result.is_valid());
  10395. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10396. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10397. }
  10398. TEST_F(StreamApiTest, PostWithHeaders) {
  10399. httplib::Client cli("localhost", 8790);
  10400. httplib::Headers headers{{"X-Custom", "value"}};
  10401. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10402. "text/plain");
  10403. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10404. }
  10405. TEST_F(StreamApiTest, PostWithParams) {
  10406. httplib::Client cli("localhost", 8790);
  10407. httplib::Params params{{"k", "v"}};
  10408. auto result =
  10409. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10410. auto body = read_body(result);
  10411. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10412. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10413. }
  10414. TEST_F(StreamApiTest, PostLarge) {
  10415. httplib::Client cli("localhost", 8790);
  10416. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10417. size_t total = 0;
  10418. while (result.next()) {
  10419. total += result.size();
  10420. }
  10421. EXPECT_EQ(100u * 1024u, total);
  10422. }
  10423. // stream::Put/Patch tests
  10424. TEST_F(StreamApiTest, PutAndPatch) {
  10425. httplib::Client cli("localhost", 8790);
  10426. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10427. EXPECT_EQ("PUT:test", read_body(put));
  10428. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10429. EXPECT_EQ("PATCH:test", read_body(patch));
  10430. }
  10431. // stream::Delete tests
  10432. TEST_F(StreamApiTest, Delete) {
  10433. httplib::Client cli("localhost", 8790);
  10434. auto del1 = httplib::stream::Delete(cli, "/resource");
  10435. EXPECT_EQ("Deleted", read_body(del1));
  10436. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10437. EXPECT_EQ("Deleted:data", read_body(del2));
  10438. }
  10439. // stream::Head/Options tests
  10440. TEST_F(StreamApiTest, HeadAndOptions) {
  10441. httplib::Client cli("localhost", 8790);
  10442. auto head = httplib::stream::Head(cli, "/head-test");
  10443. EXPECT_TRUE(head.is_valid());
  10444. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10445. auto opts = httplib::stream::Options(cli, "/options");
  10446. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10447. }
  10448. // SSL stream::* tests
  10449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10450. class SSLStreamApiTest : public ::testing::Test {
  10451. protected:
  10452. void SetUp() override {
  10453. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10454. res.set_content("Hello SSL!", "text/plain");
  10455. });
  10456. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10457. res.set_content(req.body, "text/plain");
  10458. });
  10459. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10460. svr_.wait_until_ready();
  10461. }
  10462. void TearDown() override {
  10463. svr_.stop();
  10464. if (thread_.joinable()) thread_.join();
  10465. }
  10466. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10467. std::thread thread_;
  10468. };
  10469. TEST_F(SSLStreamApiTest, GetAndPost) {
  10470. httplib::SSLClient cli("127.0.0.1", 8803);
  10471. cli.enable_server_certificate_verification(false);
  10472. auto get = httplib::stream::Get(cli, "/hello");
  10473. EXPECT_EQ("Hello SSL!", read_body(get));
  10474. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10475. EXPECT_EQ("test", read_body(post));
  10476. }
  10477. #endif
  10478. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10479. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10480. // BodyReader
  10481. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10482. // Test that read timeout during streaming is detected
  10483. // Use a large content-length response where server delays mid-stream
  10484. Server svr;
  10485. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10486. // Send a large response with delay in the middle
  10487. res.set_content_provider(
  10488. 1000, // content_length
  10489. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10490. if (offset < 100) {
  10491. // Send first 100 bytes immediately
  10492. std::string data(100, 'A');
  10493. sink.write(data.c_str(), data.size());
  10494. return true;
  10495. }
  10496. // Then delay longer than client timeout
  10497. std::this_thread::sleep_for(std::chrono::seconds(3));
  10498. std::string data(900, 'B');
  10499. sink.write(data.c_str(), data.size());
  10500. return true;
  10501. });
  10502. });
  10503. auto port = 8091;
  10504. std::thread t([&]() { svr.listen("localhost", port); });
  10505. svr.wait_until_ready();
  10506. Client cli("localhost", port);
  10507. cli.set_read_timeout(1, 0); // 1 second timeout
  10508. auto handle = cli.open_stream("GET", "/slow-stream");
  10509. ASSERT_TRUE(handle.is_valid());
  10510. char buf[256];
  10511. ssize_t total = 0;
  10512. ssize_t n;
  10513. bool got_error = false;
  10514. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10515. total += n;
  10516. }
  10517. if (n < 0) {
  10518. got_error = true;
  10519. // Should be timeout or read error
  10520. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10521. handle.get_read_error() == Error::Read)
  10522. << "Actual error: " << to_string(handle.get_read_error());
  10523. }
  10524. // Either we got an error, or we got less data than expected
  10525. EXPECT_TRUE(got_error || total < 1000)
  10526. << "Expected timeout but got all " << total << " bytes";
  10527. svr.stop();
  10528. t.join();
  10529. }
  10530. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10531. // Test connection closed detection via BodyReader
  10532. Server svr;
  10533. std::atomic<bool> close_now{false};
  10534. svr.Get("/will-close", [&](const Request &, Response &res) {
  10535. res.set_content_provider(
  10536. 10000, // Large content_length that we won't fully send
  10537. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10538. if (offset < 100) {
  10539. std::string data(100, 'X');
  10540. sink.write(data.c_str(), data.size());
  10541. return true;
  10542. }
  10543. // Wait for signal then abort
  10544. while (!close_now) {
  10545. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10546. }
  10547. return false; // Abort - server will close connection
  10548. });
  10549. });
  10550. auto port = 8092;
  10551. std::thread t([&]() { svr.listen("localhost", port); });
  10552. svr.wait_until_ready();
  10553. Client cli("localhost", port);
  10554. auto handle = cli.open_stream("GET", "/will-close");
  10555. ASSERT_TRUE(handle.is_valid());
  10556. char buf[256];
  10557. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10558. EXPECT_GT(n, 0) << "First read should succeed";
  10559. // Signal server to close
  10560. close_now = true;
  10561. // Keep reading until error or EOF
  10562. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10563. // Keep reading
  10564. }
  10565. // Should get an error since content_length wasn't satisfied
  10566. if (n < 0) {
  10567. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10568. handle.get_read_error() == Error::Read)
  10569. << "Actual error: " << to_string(handle.get_read_error());
  10570. }
  10571. svr.stop();
  10572. t.join();
  10573. }
  10574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10575. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10576. // Test that read timeout during SSL streaming is detected
  10577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10578. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10579. res.set_content_provider(
  10580. 1000, "text/plain",
  10581. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10582. if (offset < 100) {
  10583. std::string data(100, 'A');
  10584. sink.write(data.c_str(), data.size());
  10585. return true;
  10586. }
  10587. std::this_thread::sleep_for(std::chrono::seconds(3));
  10588. std::string data(900, 'B');
  10589. sink.write(data.c_str(), data.size());
  10590. return true;
  10591. });
  10592. });
  10593. auto port = 8093;
  10594. std::thread t([&]() { svr.listen("localhost", port); });
  10595. svr.wait_until_ready();
  10596. SSLClient cli("localhost", port);
  10597. cli.enable_server_certificate_verification(false);
  10598. cli.set_read_timeout(1, 0); // 1 second timeout
  10599. auto handle = cli.open_stream("GET", "/slow-stream");
  10600. ASSERT_TRUE(handle.is_valid());
  10601. char buf[256];
  10602. ssize_t total = 0;
  10603. ssize_t n;
  10604. bool got_error = false;
  10605. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10606. total += n;
  10607. }
  10608. if (n < 0) {
  10609. got_error = true;
  10610. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10611. handle.get_read_error() == Error::Read)
  10612. << "Actual error: " << to_string(handle.get_read_error());
  10613. }
  10614. EXPECT_TRUE(got_error || total < 1000)
  10615. << "Expected timeout but got all " << total << " bytes";
  10616. svr.stop();
  10617. t.join();
  10618. }
  10619. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10620. // Test SSL connection closed detection
  10621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10622. std::atomic<bool> close_now{false};
  10623. svr.Get("/will-close", [&](const Request &, Response &res) {
  10624. res.set_content_provider(
  10625. 10000, "text/plain",
  10626. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10627. if (offset < 100) {
  10628. std::string data(100, 'X');
  10629. sink.write(data.c_str(), data.size());
  10630. return true;
  10631. }
  10632. while (!close_now) {
  10633. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10634. }
  10635. return false;
  10636. });
  10637. });
  10638. auto port = 8094;
  10639. std::thread t([&]() { svr.listen("localhost", port); });
  10640. svr.wait_until_ready();
  10641. SSLClient cli("localhost", port);
  10642. cli.enable_server_certificate_verification(false);
  10643. auto handle = cli.open_stream("GET", "/will-close");
  10644. ASSERT_TRUE(handle.is_valid());
  10645. char buf[256];
  10646. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10647. EXPECT_GT(n, 0);
  10648. // Signal server to close
  10649. close_now = true;
  10650. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10651. // Keep reading
  10652. }
  10653. if (n < 0) {
  10654. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10655. handle.get_read_error() == Error::Read)
  10656. << "Actual error: " << to_string(handle.get_read_error());
  10657. }
  10658. svr.stop();
  10659. t.join();
  10660. }
  10661. #endif
  10662. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10663. using namespace httplib;
  10664. // Create a test file
  10665. const char *fname = "etag_testfile.txt";
  10666. const char *content = "etag-content";
  10667. {
  10668. std::ofstream ofs(fname);
  10669. ofs << content;
  10670. ASSERT_TRUE(ofs.good());
  10671. }
  10672. Server svr;
  10673. svr.set_mount_point("/static", ".");
  10674. auto t = std::thread([&]() { svr.listen("localhost", 8087); });
  10675. svr.wait_until_ready();
  10676. Client cli("localhost", 8087);
  10677. // First request: should get 200 with ETag header
  10678. auto res1 = cli.Get("/static/etag_testfile.txt");
  10679. ASSERT_TRUE(res1);
  10680. ASSERT_EQ(200, res1->status);
  10681. ASSERT_TRUE(res1->has_header("ETag"));
  10682. std::string etag = res1->get_header_value("ETag");
  10683. EXPECT_FALSE(etag.empty());
  10684. // Verify ETag format: W/"hex-hex"
  10685. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10686. EXPECT_EQ('W', etag[0]);
  10687. EXPECT_EQ('/', etag[1]);
  10688. EXPECT_EQ('"', etag[2]);
  10689. EXPECT_EQ('"', etag.back());
  10690. // Exact match: expect 304 Not Modified
  10691. Headers h2 = {{"If-None-Match", etag}};
  10692. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10693. ASSERT_TRUE(res2);
  10694. EXPECT_EQ(304, res2->status);
  10695. // Wildcard match: expect 304 Not Modified
  10696. Headers h3 = {{"If-None-Match", "*"}};
  10697. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10698. ASSERT_TRUE(res3);
  10699. EXPECT_EQ(304, res3->status);
  10700. // Non-matching ETag: expect 200
  10701. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10702. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10703. ASSERT_TRUE(res4);
  10704. EXPECT_EQ(200, res4->status);
  10705. // Multiple ETags with one matching: expect 304
  10706. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10707. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10708. ASSERT_TRUE(res5);
  10709. EXPECT_EQ(304, res5->status);
  10710. svr.stop();
  10711. t.join();
  10712. std::remove(fname);
  10713. }
  10714. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10715. using namespace httplib;
  10716. Server svr;
  10717. svr.set_mount_point("/static", ".");
  10718. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10719. svr.wait_until_ready();
  10720. Client cli("localhost", 8090);
  10721. // Send If-None-Match: * to a non-existent file
  10722. Headers h = {{"If-None-Match", "*"}};
  10723. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10724. ASSERT_TRUE(res);
  10725. EXPECT_EQ(404, res->status);
  10726. svr.stop();
  10727. t.join();
  10728. }
  10729. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10730. using namespace httplib;
  10731. // Create a test file
  10732. const char *fname = "ims_testfile.txt";
  10733. const char *content = "if-modified-since-test";
  10734. {
  10735. std::ofstream ofs(fname);
  10736. ofs << content;
  10737. ASSERT_TRUE(ofs.good());
  10738. }
  10739. Server svr;
  10740. svr.set_mount_point("/static", ".");
  10741. auto t = std::thread([&]() { svr.listen("localhost", 8088); });
  10742. svr.wait_until_ready();
  10743. Client cli("localhost", 8088);
  10744. // First request: should get 200 with Last-Modified header
  10745. auto res1 = cli.Get("/static/ims_testfile.txt");
  10746. ASSERT_TRUE(res1);
  10747. ASSERT_EQ(200, res1->status);
  10748. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10749. std::string last_modified = res1->get_header_value("Last-Modified");
  10750. EXPECT_FALSE(last_modified.empty());
  10751. // If-Modified-Since with same time: expect 304
  10752. Headers h2 = {{"If-Modified-Since", last_modified}};
  10753. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10754. ASSERT_TRUE(res2);
  10755. EXPECT_EQ(304, res2->status);
  10756. // If-Modified-Since with future time: expect 304
  10757. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10758. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10759. ASSERT_TRUE(res3);
  10760. EXPECT_EQ(304, res3->status);
  10761. // If-Modified-Since with past time: expect 200
  10762. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10763. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10764. ASSERT_TRUE(res4);
  10765. EXPECT_EQ(200, res4->status);
  10766. // If-None-Match takes precedence over If-Modified-Since
  10767. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10768. ASSERT_TRUE(res1->has_header("ETag"));
  10769. std::string etag = res1->get_header_value("ETag");
  10770. Headers h5 = {{"If-None-Match", etag},
  10771. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10772. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10773. ASSERT_TRUE(res5);
  10774. EXPECT_EQ(304, res5->status);
  10775. svr.stop();
  10776. t.join();
  10777. std::remove(fname);
  10778. }
  10779. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10780. using namespace httplib;
  10781. Server svr;
  10782. // Endpoint that returns compressible content
  10783. svr.Get("/compressible", [](const Request &, Response &res) {
  10784. // Return a large enough body to trigger compression
  10785. std::string body(1000, 'a');
  10786. res.set_content(body, "text/plain");
  10787. });
  10788. auto t = std::thread([&]() { svr.listen("localhost", 8089); });
  10789. svr.wait_until_ready();
  10790. Client cli("localhost", 8089);
  10791. // Request with gzip support: should get Vary header when compressed
  10792. cli.set_compress(true);
  10793. auto res1 = cli.Get("/compressible");
  10794. ASSERT_TRUE(res1);
  10795. EXPECT_EQ(200, res1->status);
  10796. // If Content-Encoding is set, Vary should also be set
  10797. if (res1->has_header("Content-Encoding")) {
  10798. EXPECT_TRUE(res1->has_header("Vary"));
  10799. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10800. }
  10801. // Request without Accept-Encoding header: should not have compression
  10802. Headers h_no_compress;
  10803. auto res2 = cli.Get("/compressible", h_no_compress);
  10804. ASSERT_TRUE(res2);
  10805. EXPECT_EQ(200, res2->status);
  10806. // Verify Vary header is present when compression is applied
  10807. // (the exact behavior depends on server configuration)
  10808. svr.stop();
  10809. t.join();
  10810. }
  10811. TEST(ETagTest, IfRangeWithETag) {
  10812. using namespace httplib;
  10813. // Create a test file with known content
  10814. const char *fname = "if_range_testfile.txt";
  10815. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10816. {
  10817. std::ofstream ofs(fname);
  10818. ofs << content;
  10819. ASSERT_TRUE(ofs.good());
  10820. }
  10821. Server svr;
  10822. svr.set_mount_point("/static", ".");
  10823. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10824. svr.wait_until_ready();
  10825. Client cli("localhost", 8090);
  10826. // First request: get ETag
  10827. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10828. ASSERT_TRUE(res1);
  10829. ASSERT_EQ(200, res1->status);
  10830. ASSERT_TRUE(res1->has_header("ETag"));
  10831. std::string etag = res1->get_header_value("ETag");
  10832. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10833. // Since our server generates weak ETags (W/"..."), If-Range with our
  10834. // ETag should NOT result in partial content - it should return full content.
  10835. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10836. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10837. ASSERT_TRUE(res2);
  10838. // Weak ETag in If-Range -> full content (200), not partial (206)
  10839. EXPECT_EQ(200, res2->status);
  10840. EXPECT_EQ(content, res2->body);
  10841. EXPECT_FALSE(res2->has_header("Content-Range"));
  10842. // Range request with non-matching If-Range (ETag): should get 200 (full
  10843. // content)
  10844. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10845. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10846. ASSERT_TRUE(res3);
  10847. EXPECT_EQ(200, res3->status);
  10848. EXPECT_EQ(content, res3->body);
  10849. EXPECT_FALSE(res3->has_header("Content-Range"));
  10850. // Range request with strong ETag (hypothetical - our server doesn't generate
  10851. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10852. // should return full content)
  10853. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10854. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10855. ASSERT_TRUE(res4);
  10856. EXPECT_EQ(200, res4->status);
  10857. EXPECT_EQ(content, res4->body);
  10858. EXPECT_FALSE(res4->has_header("Content-Range"));
  10859. svr.stop();
  10860. t.join();
  10861. std::remove(fname);
  10862. }
  10863. TEST(ETagTest, IfRangeWithDate) {
  10864. using namespace httplib;
  10865. // Create a test file
  10866. const char *fname = "if_range_date_testfile.txt";
  10867. const std::string content = "ABCDEFGHIJ0123456789"; // 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("localhost", 8091); });
  10876. svr.wait_until_ready();
  10877. Client cli("localhost", 8091);
  10878. // First request: get Last-Modified
  10879. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10880. ASSERT_TRUE(res1);
  10881. ASSERT_EQ(200, res1->status);
  10882. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10883. std::string last_modified = res1->get_header_value("Last-Modified");
  10884. // Range request with matching If-Range (date): should get 206
  10885. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10886. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10887. ASSERT_TRUE(res2);
  10888. EXPECT_EQ(206, res2->status);
  10889. EXPECT_EQ("FGHIJ", res2->body);
  10890. // Range request with old If-Range date: should get 200 (full content)
  10891. Headers h3 = {{"Range", "bytes=5-9"},
  10892. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10893. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10894. ASSERT_TRUE(res3);
  10895. EXPECT_EQ(200, res3->status);
  10896. EXPECT_EQ(content, res3->body);
  10897. // Range request with future If-Range date: should get 206
  10898. Headers h4 = {{"Range", "bytes=0-4"},
  10899. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10900. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10901. ASSERT_TRUE(res4);
  10902. EXPECT_EQ(206, res4->status);
  10903. EXPECT_EQ("ABCDE", res4->body);
  10904. svr.stop();
  10905. t.join();
  10906. std::remove(fname);
  10907. }
  10908. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10909. using namespace httplib;
  10910. const char *fname = "etag_malformed.txt";
  10911. const char *content = "malformed-etag";
  10912. {
  10913. std::ofstream ofs(fname);
  10914. ofs << content;
  10915. ASSERT_TRUE(ofs.good());
  10916. }
  10917. Server svr;
  10918. svr.set_mount_point("/static", ".");
  10919. auto t = std::thread([&]() { svr.listen("localhost", 8092); });
  10920. svr.wait_until_ready();
  10921. Client cli("localhost", 8092);
  10922. // baseline: should get 200 and an ETag
  10923. auto res1 = cli.Get("/static/etag_malformed.txt");
  10924. ASSERT_TRUE(res1);
  10925. ASSERT_EQ(200, res1->status);
  10926. ASSERT_TRUE(res1->has_header("ETag"));
  10927. // Malformed ETag value (missing quotes) should be treated as non-matching
  10928. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10929. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10930. ASSERT_TRUE(res_bad);
  10931. EXPECT_EQ(200, res_bad->status);
  10932. // Whitespace-only header value should be considered invalid / non-matching
  10933. Headers h_space = {{"If-None-Match", " "}};
  10934. auto res_space = cli.Get("/static/etag_malformed.txt", h_space);
  10935. ASSERT_TRUE(res_space);
  10936. EXPECT_EQ(200, res_space->status);
  10937. svr.stop();
  10938. t.join();
  10939. std::remove(fname);
  10940. }
  10941. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10942. using namespace httplib;
  10943. const char *fname = "ims_invalid_format.txt";
  10944. const char *content = "ims-bad-format";
  10945. {
  10946. std::ofstream ofs(fname);
  10947. ofs << content;
  10948. ASSERT_TRUE(ofs.good());
  10949. }
  10950. Server svr;
  10951. svr.set_mount_point("/static", ".");
  10952. auto t = std::thread([&]() { svr.listen("localhost", 8093); });
  10953. svr.wait_until_ready();
  10954. Client cli("localhost", 8093);
  10955. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10956. ASSERT_TRUE(res1);
  10957. ASSERT_EQ(200, res1->status);
  10958. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10959. // If-Modified-Since with invalid format should not result in 304
  10960. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  10961. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  10962. ASSERT_TRUE(res_bad);
  10963. EXPECT_EQ(200, res_bad->status);
  10964. // If-Range with invalid date format should be treated as mismatch -> full
  10965. // content (200)
  10966. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  10967. {"If-Range", "invalid-date"}};
  10968. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  10969. ASSERT_TRUE(res_ifrange);
  10970. EXPECT_EQ(200, res_ifrange->status);
  10971. svr.stop();
  10972. t.join();
  10973. std::remove(fname);
  10974. }
  10975. TEST(ETagTest, IfRangeWithMalformedETag) {
  10976. using namespace httplib;
  10977. const char *fname = "ifrange_malformed.txt";
  10978. const std::string content = "0123456789";
  10979. {
  10980. std::ofstream ofs(fname);
  10981. ofs << content;
  10982. ASSERT_TRUE(ofs.good());
  10983. }
  10984. Server svr;
  10985. svr.set_mount_point("/static", ".");
  10986. auto t = std::thread([&]() { svr.listen("localhost", 8094); });
  10987. svr.wait_until_ready();
  10988. Client cli("localhost", 8094);
  10989. // First request: get ETag
  10990. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  10991. ASSERT_TRUE(res1);
  10992. ASSERT_EQ(200, res1->status);
  10993. ASSERT_TRUE(res1->has_header("ETag"));
  10994. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  10995. // full content (200)
  10996. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  10997. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  10998. ASSERT_TRUE(res2);
  10999. EXPECT_EQ(200, res2->status);
  11000. EXPECT_EQ(content, res2->body);
  11001. svr.stop();
  11002. t.join();
  11003. std::remove(fname);
  11004. }
  11005. TEST(ETagTest, ExtremeLargeDateValues) {
  11006. using namespace httplib;
  11007. const char *fname = "ims_extreme_date.txt";
  11008. const char *content = "ims-extreme-date";
  11009. {
  11010. std::ofstream ofs(fname);
  11011. ofs << content;
  11012. ASSERT_TRUE(ofs.good());
  11013. }
  11014. Server svr;
  11015. svr.set_mount_point("/static", ".");
  11016. auto t = std::thread([&]() { svr.listen("localhost", 8095); });
  11017. svr.wait_until_ready();
  11018. Client cli("localhost", 8095);
  11019. auto res1 = cli.Get(std::string("/static/") + fname);
  11020. ASSERT_TRUE(res1);
  11021. ASSERT_EQ(200, res1->status);
  11022. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11023. // Extremely large year that may overflow date parsing routines.
  11024. Headers h_large_date = {
  11025. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11026. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11027. ASSERT_TRUE(res_bad);
  11028. // Expect server to treat this as invalid/mismatch and return full content
  11029. EXPECT_EQ(200, res_bad->status);
  11030. // If-Range with extremely large date should be treated as mismatch -> full
  11031. // content (200)
  11032. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11033. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11034. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11035. ASSERT_TRUE(res_ifrange);
  11036. EXPECT_EQ(200, res_ifrange->status);
  11037. svr.stop();
  11038. t.join();
  11039. std::remove(fname);
  11040. }
  11041. TEST(ETagTest, NegativeFileModificationTime) {
  11042. using namespace httplib;
  11043. const char *fname = "ims_negative_mtime.txt";
  11044. const std::string content = "negative-mtime";
  11045. {
  11046. std::ofstream ofs(fname);
  11047. ofs << content;
  11048. ASSERT_TRUE(ofs.good());
  11049. }
  11050. // Try to set file mtime to a negative value. This may fail on some
  11051. // platforms/filesystems; if it fails, the test will still verify server
  11052. // behaves safely by performing a regular conditional request.
  11053. #if defined(__APPLE__) || defined(__linux__)
  11054. bool set_negative = false;
  11055. do {
  11056. struct timeval times[2];
  11057. // access time: now
  11058. times[0].tv_sec = time(nullptr);
  11059. times[0].tv_usec = 0;
  11060. // modification time: negative (e.g., -1)
  11061. times[1].tv_sec = -1;
  11062. times[1].tv_usec = 0;
  11063. if (utimes(fname, times) == 0) { set_negative = true; }
  11064. } while (0);
  11065. #else
  11066. bool set_negative = false;
  11067. #endif
  11068. Server svr;
  11069. svr.set_mount_point("/static", ".");
  11070. auto t = std::thread([&]() { svr.listen("localhost", 8096); });
  11071. svr.wait_until_ready();
  11072. Client cli("localhost", 8096);
  11073. auto res1 = cli.Get(std::string("/static/") + fname);
  11074. ASSERT_TRUE(res1);
  11075. ASSERT_EQ(200, res1->status);
  11076. bool has_last_modified = res1->has_header("Last-Modified");
  11077. std::string last_modified;
  11078. if (has_last_modified) {
  11079. last_modified = res1->get_header_value("Last-Modified");
  11080. }
  11081. if (set_negative) {
  11082. // If we successfully set a negative mtime, ensure server returns a
  11083. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11084. // with an old date and ensure server handles it without crash.
  11085. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11086. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11087. ASSERT_TRUE(res2);
  11088. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11089. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11090. } else {
  11091. // Could not set negative mtime on this platform; fall back to verifying
  11092. // that normal invalid/malformed dates are treated safely (non-304).
  11093. Headers h_bad_date = {
  11094. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11095. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11096. ASSERT_TRUE(res_bad);
  11097. EXPECT_EQ(200, res_bad->status);
  11098. }
  11099. svr.stop();
  11100. t.join();
  11101. std::remove(fname);
  11102. }