test.cc 345 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <future>
  18. #include <limits>
  19. #include <memory>
  20. #include <sstream>
  21. #include <stdexcept>
  22. #include <thread>
  23. #include <type_traits>
  24. #include <vector>
  25. #define SERVER_CERT_FILE "./cert.pem"
  26. #define SERVER_CERT2_FILE "./cert2.pem"
  27. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  28. #define CA_CERT_FILE "./ca-bundle.crt"
  29. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  30. #define CLIENT_CA_CERT_DIR "."
  31. #define CLIENT_CERT_FILE "./client.cert.pem"
  32. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  33. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  35. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  36. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  38. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  39. using namespace std;
  40. using namespace httplib;
  41. const char *HOST = "localhost";
  42. const int PORT = 1234;
  43. const string LONG_QUERY_VALUE = string(25000, '@');
  44. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  45. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  46. const string TOO_LONG_QUERY_URL =
  47. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  48. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  49. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  50. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  51. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  52. return file.name == key;
  53. });
  54. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  55. return *it;
  56. #else
  57. if (it != items.end()) { return *it; }
  58. throw std::runtime_error("invalid multipart form data name error");
  59. #endif
  60. }
  61. static void read_file(const std::string &path, std::string &out) {
  62. std::ifstream fs(path, std::ios_base::binary);
  63. if (!fs) throw std::runtime_error("File not found: " + path);
  64. fs.seekg(0, std::ios_base::end);
  65. auto size = fs.tellg();
  66. fs.seekg(0);
  67. out.resize(static_cast<size_t>(size));
  68. fs.read(&out[0], static_cast<std::streamsize>(size));
  69. }
  70. void performance_test(const char *host) {
  71. auto port = 1234;
  72. Server svr;
  73. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  74. res.set_content("Benchmark Response", "text/plain");
  75. });
  76. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  77. auto se = detail::scope_exit([&] {
  78. svr.stop();
  79. listen_thread.join();
  80. ASSERT_FALSE(svr.is_running());
  81. });
  82. svr.wait_until_ready();
  83. Client cli(host, port);
  84. // Warm-up request to establish connection and resolve DNS
  85. auto warmup_res = cli.Get("/benchmark");
  86. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  87. // Run multiple trials and collect timings
  88. const int num_trials = 20;
  89. std::vector<int64_t> timings;
  90. timings.reserve(num_trials);
  91. for (int i = 0; i < num_trials; i++) {
  92. auto start = std::chrono::high_resolution_clock::now();
  93. auto res = cli.Get("/benchmark");
  94. auto end = std::chrono::high_resolution_clock::now();
  95. auto elapsed =
  96. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  97. .count();
  98. // Assertions after timing measurement to avoid overhead
  99. ASSERT_TRUE(res);
  100. EXPECT_EQ(StatusCode::OK_200, res->status);
  101. timings.push_back(elapsed);
  102. }
  103. // Calculate 25th percentile (lower quartile)
  104. std::sort(timings.begin(), timings.end());
  105. auto p25 = timings[num_trials / 4];
  106. // Format timings for output
  107. std::ostringstream timings_str;
  108. timings_str << "[";
  109. for (size_t i = 0; i < timings.size(); i++) {
  110. if (i > 0) timings_str << ", ";
  111. timings_str << timings[i];
  112. }
  113. timings_str << "]";
  114. // Localhost HTTP GET should be fast even in CI environments
  115. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  116. << "ms (Issue #1777). Timings: " << timings_str.str();
  117. }
  118. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  119. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  120. class UnixSocketTest : public ::testing::Test {
  121. protected:
  122. void TearDown() override { std::remove(pathname_.c_str()); }
  123. void client_GET(const std::string &addr) {
  124. httplib::Client cli{addr};
  125. cli.set_address_family(AF_UNIX);
  126. ASSERT_TRUE(cli.is_valid());
  127. const auto &result = cli.Get(pattern_);
  128. ASSERT_TRUE(result) << "error: " << result.error();
  129. const auto &resp = result.value();
  130. EXPECT_EQ(resp.status, StatusCode::OK_200);
  131. EXPECT_EQ(resp.body, content_);
  132. }
  133. const std::string pathname_{"./httplib-server.sock"};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. }
  154. #if defined(__linux__) || \
  155. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  156. TEST_F(UnixSocketTest, PeerPid) {
  157. httplib::Server svr;
  158. std::string remote_port_val;
  159. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. remote_port_val = req.get_header_value("REMOTE_PORT");
  162. });
  163. std::thread t{[&] {
  164. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  165. }};
  166. auto se = detail::scope_exit([&] {
  167. svr.stop();
  168. t.join();
  169. ASSERT_FALSE(svr.is_running());
  170. });
  171. svr.wait_until_ready();
  172. ASSERT_TRUE(svr.is_running());
  173. client_GET(pathname_);
  174. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  175. }
  176. #endif
  177. #ifdef __linux__
  178. TEST_F(UnixSocketTest, abstract) {
  179. constexpr char svr_path[]{"\x00httplib-server.sock"};
  180. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  181. httplib::Server svr;
  182. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  183. res.set_content(content_, "text/plain");
  184. });
  185. std::thread t{[&] {
  186. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  187. }};
  188. auto se = detail::scope_exit([&] {
  189. svr.stop();
  190. t.join();
  191. ASSERT_FALSE(svr.is_running());
  192. });
  193. svr.wait_until_ready();
  194. ASSERT_TRUE(svr.is_running());
  195. client_GET(abstract_addr);
  196. }
  197. #endif
  198. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  199. httplib::Server svr;
  200. std::string received_host_header;
  201. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  202. // Capture the Host header sent by the client
  203. auto host_iter = req.headers.find("Host");
  204. if (host_iter != req.headers.end()) {
  205. received_host_header = host_iter->second;
  206. }
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. // Test that Host header is automatically set to "localhost" for Unix socket
  220. // connections
  221. httplib::Client cli{pathname_};
  222. cli.set_address_family(AF_UNIX);
  223. ASSERT_TRUE(cli.is_valid());
  224. const auto &result = cli.Get(pattern_);
  225. ASSERT_TRUE(result) << "error: " << result.error();
  226. const auto &resp = result.value();
  227. EXPECT_EQ(resp.status, StatusCode::OK_200);
  228. EXPECT_EQ(resp.body, content_);
  229. // Verify that Host header was automatically set to "localhost"
  230. EXPECT_EQ(received_host_header, "localhost");
  231. }
  232. #ifndef _WIN32
  233. TEST(SocketStream, wait_writable_UNIX) {
  234. int fds[2];
  235. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  236. const auto asSocketStream = [&](socket_t fd,
  237. std::function<bool(Stream &)> func) {
  238. return detail::process_client_socket(
  239. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  240. };
  241. asSocketStream(fds[0], [&](Stream &s0) {
  242. EXPECT_EQ(s0.socket(), fds[0]);
  243. EXPECT_TRUE(s0.wait_writable());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.wait_writable());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(PORT + 1);
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  261. ASSERT_EQ(0, listen(s, 1));
  262. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  263. ASSERT_EQ(0, close(s));
  264. }};
  265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  266. std::thread cli{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, close(s));
  271. }};
  272. cli.join();
  273. svr.join();
  274. ASSERT_NE(disconnected_svr_sock, -1);
  275. const auto asSocketStream = [&](socket_t fd,
  276. std::function<bool(Stream &)> func) {
  277. return detail::process_client_socket(
  278. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  279. };
  280. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  281. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  282. EXPECT_FALSE(ss.wait_writable());
  283. return true;
  284. });
  285. ASSERT_EQ(0, close(disconnected_svr_sock));
  286. }
  287. #endif // #ifndef _WIN32
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. u8"descrip=Gastos áéíóúñÑ 6");
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  317. string unescapedCharacters = "-_.!~*'()";
  318. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  319. }
  320. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  321. string reservedCharacters = ";,/?:@&=+$";
  322. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  323. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  324. }
  325. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  326. string chineseCharacters = u8"中国語";
  327. string russianCharacters = u8"дом";
  328. string brazilianCharacters = u8"óculos";
  329. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  330. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  331. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  332. "%D0%B4%D0%BE%D0%BC");
  333. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  334. }
  335. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  336. string unescapedCharacters = "-_.!~*'()";
  337. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  338. }
  339. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  340. string reservedCharacters = ";,/?:@&=+$";
  341. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  342. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  343. }
  344. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  345. string chineseCharacters = u8"中国語";
  346. string russianCharacters = u8"дом";
  347. string brazilianCharacters = u8"óculos";
  348. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  349. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  350. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  351. "%D0%B4%D0%BE%D0%BC");
  352. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  353. }
  354. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  355. // Issue #2082 use case: encoding path component with ampersand
  356. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  357. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  358. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  359. }
  360. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$#";
  366. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  367. }
  368. TEST(EncodeUriTest, TestUTF8Characters) {
  369. string chineseCharacters = u8"中国語";
  370. string russianCharacters = u8"дом";
  371. string brazilianCharacters = u8"óculos";
  372. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  373. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  374. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  375. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  376. }
  377. TEST(EncodeUriTest, TestCompleteUri) {
  378. string uri =
  379. "https://example.com/path/to/resource?query=value&param=test#fragment";
  380. EXPECT_EQ(
  381. httplib::encode_uri(uri),
  382. "https://example.com/path/to/resource?query=value&param=test#fragment");
  383. }
  384. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  385. string uri =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. EXPECT_EQ(httplib::encode_uri(uri),
  388. "https://example.com/path%20with%20spaces/"
  389. "file%20name.html?q=hello%20world");
  390. }
  391. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  392. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  393. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  394. }
  395. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  400. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  401. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  402. string encodedBrazilian = "%C3%B3culos";
  403. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  404. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  405. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  406. }
  407. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  408. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  409. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  410. "Piri Tommy Villiers - on & on");
  411. }
  412. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  413. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  414. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  415. }
  416. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  418. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  419. }
  420. TEST(DecodeUriTest, TestUTF8Characters) {
  421. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  422. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  423. string encodedBrazilian = "%C3%B3culos";
  424. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  425. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  426. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  427. }
  428. TEST(DecodeUriTest, TestCompleteUri) {
  429. string encodedUri = "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world";
  431. EXPECT_EQ(
  432. httplib::decode_uri(encodedUri),
  433. "https://example.com/path with spaces/file name.html?q=hello world");
  434. }
  435. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  436. string original =
  437. "https://example.com/path with spaces/file name.html?q=hello world";
  438. string encoded = httplib::encode_uri(original);
  439. string decoded = httplib::decode_uri(encoded);
  440. EXPECT_EQ(decoded, original);
  441. }
  442. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  443. string original = "Piri Tommy Villiers - on & on";
  444. string encoded = httplib::encode_uri_component(original);
  445. string decoded = httplib::decode_uri_component(encoded);
  446. EXPECT_EQ(decoded, original);
  447. }
  448. TEST(TrimTests, TrimStringTests) {
  449. EXPECT_EQ("abc", detail::trim_copy("abc"));
  450. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  451. EXPECT_TRUE(detail::trim_copy("").empty());
  452. }
  453. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  454. // Simple case without quality values
  455. std::vector<std::string> result1;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html,application/json,text/plain", result1));
  458. EXPECT_EQ(result1.size(), 3U);
  459. EXPECT_EQ(result1[0], "text/html");
  460. EXPECT_EQ(result1[1], "application/json");
  461. EXPECT_EQ(result1[2], "text/plain");
  462. // With quality values
  463. std::vector<std::string> result2;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  466. EXPECT_EQ(result2.size(), 3U);
  467. EXPECT_EQ(result2[0], "application/json"); // highest q value
  468. EXPECT_EQ(result2[1], "text/html");
  469. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  470. }
  471. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  472. // Mixed with and without quality values
  473. std::vector<std::string> result;
  474. EXPECT_TRUE(detail::parse_accept_header(
  475. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  476. EXPECT_EQ(result.size(), 3U);
  477. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  478. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  479. EXPECT_EQ(result[2], "application/json"); // q=0.5
  480. }
  481. TEST(ParseAcceptHeaderTest, EdgeCases) {
  482. // Empty header
  483. std::vector<std::string> empty_result;
  484. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  485. EXPECT_TRUE(empty_result.empty());
  486. // Single type
  487. std::vector<std::string> single_result;
  488. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  489. EXPECT_EQ(single_result.size(), 1U);
  490. EXPECT_EQ(single_result[0], "application/json");
  491. // Wildcard types
  492. std::vector<std::string> wildcard_result;
  493. EXPECT_TRUE(detail::parse_accept_header(
  494. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  495. EXPECT_EQ(wildcard_result.size(), 3U);
  496. EXPECT_EQ(wildcard_result[0], "application/json");
  497. EXPECT_EQ(wildcard_result[1], "text/*");
  498. EXPECT_EQ(wildcard_result[2], "*/*");
  499. }
  500. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  501. // Common browser Accept header
  502. std::vector<std::string> browser_result;
  503. EXPECT_TRUE(
  504. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  505. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  506. browser_result));
  507. EXPECT_EQ(browser_result.size(), 6U);
  508. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  509. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  510. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  513. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  514. // API client header
  515. std::vector<std::string> api_result;
  516. EXPECT_TRUE(detail::parse_accept_header(
  517. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  518. api_result));
  519. EXPECT_EQ(api_result.size(), 3U);
  520. EXPECT_EQ(api_result[0], "application/json");
  521. EXPECT_EQ(api_result[1], "application/xml");
  522. EXPECT_EQ(api_result[2], "text/plain");
  523. }
  524. TEST(ParseAcceptHeaderTest, SpecialCases) {
  525. // Quality value with 3 decimal places
  526. std::vector<std::string> decimal_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  529. EXPECT_EQ(decimal_result.size(), 2U);
  530. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  531. EXPECT_EQ(decimal_result[1], "text/html");
  532. // Zero quality (should still be included but with lowest priority)
  533. std::vector<std::string> zero_q_result;
  534. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  535. zero_q_result));
  536. EXPECT_EQ(zero_q_result.size(), 2U);
  537. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  538. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  539. // No spaces around commas
  540. std::vector<std::string> no_space_result;
  541. EXPECT_TRUE(detail::parse_accept_header(
  542. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  543. no_space_result));
  544. EXPECT_EQ(no_space_result.size(), 3U);
  545. EXPECT_EQ(no_space_result[0], "text/html");
  546. EXPECT_EQ(no_space_result[1], "application/json");
  547. EXPECT_EQ(no_space_result[2], "text/plain");
  548. }
  549. TEST(ParseAcceptHeaderTest, InvalidCases) {
  550. std::vector<std::string> result;
  551. // Invalid quality value (> 1.0)
  552. EXPECT_FALSE(
  553. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  554. // Invalid quality value (< 0.0)
  555. EXPECT_FALSE(
  556. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  557. // Invalid quality value (not a number)
  558. EXPECT_FALSE(detail::parse_accept_header(
  559. "text/html;q=invalid,application/json", result));
  560. // Empty quality value
  561. EXPECT_FALSE(
  562. detail::parse_accept_header("text/html;q=,application/json", result));
  563. // Invalid media type format (no slash and not wildcard)
  564. EXPECT_FALSE(
  565. detail::parse_accept_header("invalidtype,application/json", result));
  566. // Empty media type
  567. result.clear();
  568. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  569. // Only commas
  570. result.clear();
  571. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  572. // Valid cases should still work
  573. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  574. EXPECT_EQ(result.size(), 1U);
  575. EXPECT_EQ(result[0], "*/*");
  576. EXPECT_TRUE(detail::parse_accept_header("*", result));
  577. EXPECT_EQ(result.size(), 1U);
  578. EXPECT_EQ(result[0], "*");
  579. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  580. EXPECT_EQ(result.size(), 1U);
  581. EXPECT_EQ(result[0], "text/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  584. Server svr;
  585. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  586. EXPECT_EQ(req.accept_content_types.size(), 3U);
  587. EXPECT_EQ(req.accept_content_types[0], "application/json");
  588. EXPECT_EQ(req.accept_content_types[1], "text/html");
  589. EXPECT_EQ(req.accept_content_types[2], "*/*");
  590. res.set_content("ok", "text/plain");
  591. });
  592. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  593. EXPECT_TRUE(false);
  594. res.set_content("bad request", "text/plain");
  595. });
  596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  597. auto se = detail::scope_exit([&] {
  598. svr.stop();
  599. listen_thread.join();
  600. ASSERT_FALSE(svr.is_running());
  601. });
  602. svr.wait_until_ready();
  603. Client cli("localhost", PORT);
  604. {
  605. auto res =
  606. cli.Get("/accept_ok",
  607. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  608. ASSERT_TRUE(res);
  609. EXPECT_EQ(StatusCode::OK_200, res->status);
  610. }
  611. {
  612. auto res = cli.Get("/accept_bad_request",
  613. {{"Accept", "text/html;q=abc,application/json"}});
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  616. }
  617. }
  618. TEST(DivideTest, DivideStringTests) {
  619. auto divide = [](const std::string &str, char d) {
  620. std::string lhs;
  621. std::string rhs;
  622. detail::divide(str, d,
  623. [&](const char *lhs_data, std::size_t lhs_size,
  624. const char *rhs_data, std::size_t rhs_size) {
  625. lhs.assign(lhs_data, lhs_size);
  626. rhs.assign(rhs_data, rhs_size);
  627. });
  628. return std::make_pair(std::move(lhs), std::move(rhs));
  629. };
  630. {
  631. const auto res = divide("", '=');
  632. EXPECT_EQ(res.first, "");
  633. EXPECT_EQ(res.second, "");
  634. }
  635. {
  636. const auto res = divide("=", '=');
  637. EXPECT_EQ(res.first, "");
  638. EXPECT_EQ(res.second, "");
  639. }
  640. {
  641. const auto res = divide(" ", '=');
  642. EXPECT_EQ(res.first, " ");
  643. EXPECT_EQ(res.second, "");
  644. }
  645. {
  646. const auto res = divide("a", '=');
  647. EXPECT_EQ(res.first, "a");
  648. EXPECT_EQ(res.second, "");
  649. }
  650. {
  651. const auto res = divide("a=", '=');
  652. EXPECT_EQ(res.first, "a");
  653. EXPECT_EQ(res.second, "");
  654. }
  655. {
  656. const auto res = divide("=b", '=');
  657. EXPECT_EQ(res.first, "");
  658. EXPECT_EQ(res.second, "b");
  659. }
  660. {
  661. const auto res = divide("a=b", '=');
  662. EXPECT_EQ(res.first, "a");
  663. EXPECT_EQ(res.second, "b");
  664. }
  665. {
  666. const auto res = divide("a=b=", '=');
  667. EXPECT_EQ(res.first, "a");
  668. EXPECT_EQ(res.second, "b=");
  669. }
  670. {
  671. const auto res = divide("a=b=c", '=');
  672. EXPECT_EQ(res.first, "a");
  673. EXPECT_EQ(res.second, "b=c");
  674. }
  675. }
  676. TEST(SplitTest, ParseQueryString) {
  677. string s = "key1=val1&key2=val2&key3=val3";
  678. Params dic;
  679. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  680. [&](const char *b, const char *e) {
  681. string key, val;
  682. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  683. if (key.empty()) {
  684. key.assign(b2, e2);
  685. } else {
  686. val.assign(b2, e2);
  687. }
  688. });
  689. dic.emplace(key, val);
  690. });
  691. EXPECT_EQ("val1", dic.find("key1")->second);
  692. EXPECT_EQ("val2", dic.find("key2")->second);
  693. EXPECT_EQ("val3", dic.find("key3")->second);
  694. }
  695. TEST(SplitTest, ParseInvalidQueryTests) {
  696. {
  697. string s = " ";
  698. Params dict;
  699. detail::parse_query_text(s, dict);
  700. EXPECT_TRUE(dict.empty());
  701. }
  702. {
  703. string s = " = =";
  704. Params dict;
  705. detail::parse_query_text(s, dict);
  706. EXPECT_TRUE(dict.empty());
  707. }
  708. }
  709. TEST(ParseQueryTest, ParseQueryString) {
  710. {
  711. std::string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::parse_query_text(s, dic);
  714. EXPECT_EQ("val1", dic.find("key1")->second);
  715. EXPECT_EQ("val2", dic.find("key2")->second);
  716. EXPECT_EQ("val3", dic.find("key3")->second);
  717. }
  718. {
  719. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  720. Params dic;
  721. detail::parse_query_text(s, dic);
  722. EXPECT_EQ("", dic.find("key1")->second);
  723. EXPECT_EQ("val1", dic.find("key2")->second);
  724. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  725. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  726. }
  727. }
  728. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  729. Params dic;
  730. EXPECT_EQ(detail::params_to_query_str(dic), "");
  731. dic.emplace("key1", "val1");
  732. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  733. dic.emplace("key2", "val2");
  734. dic.emplace("key3", "val3");
  735. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  736. }
  737. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  738. string content_type = "multipart/form-data; boundary=something";
  739. string boundary;
  740. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  741. EXPECT_TRUE(ret);
  742. EXPECT_EQ(boundary, "something");
  743. }
  744. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  745. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  746. string boundary;
  747. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  748. EXPECT_TRUE(ret);
  749. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  750. }
  751. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  752. string content_type =
  753. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  754. string boundary;
  755. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  756. EXPECT_TRUE(ret);
  757. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  758. }
  759. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  760. string content_type =
  761. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  762. string boundary;
  763. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  764. EXPECT_TRUE(ret);
  765. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  766. }
  767. TEST(GetHeaderValueTest, DefaultValue) {
  768. Headers headers = {{"Dummy", "Dummy"}};
  769. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  770. EXPECT_STREQ("text/plain", val);
  771. }
  772. TEST(GetHeaderValueTest, DefaultValueInt) {
  773. Headers headers = {{"Dummy", "Dummy"}};
  774. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  775. EXPECT_EQ(100ull, val);
  776. }
  777. TEST(GetHeaderValueTest, RegularValue) {
  778. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  779. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  780. EXPECT_STREQ("text/html", val);
  781. }
  782. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  783. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  784. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  785. EXPECT_STREQ("text/html", val);
  786. }
  787. TEST(GetHeaderValueTest, SetContent) {
  788. Response res;
  789. res.set_content("html", "text/html");
  790. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  791. res.set_content("text", "text/plain");
  792. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  793. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  794. }
  795. TEST(GetHeaderValueTest, RegularValueInt) {
  796. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  798. EXPECT_EQ(100ull, val);
  799. }
  800. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  801. Headers headers = {{"Content-Length", "x"}};
  802. auto is_invalid_value = false;
  803. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  804. is_invalid_value);
  805. EXPECT_EQ(0ull, val);
  806. EXPECT_TRUE(is_invalid_value);
  807. }
  808. TEST(GetHeaderValueTest, Range) {
  809. {
  810. Headers headers = {make_range_header({{1, -1}})};
  811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  812. EXPECT_STREQ("bytes=1-", val);
  813. }
  814. {
  815. Headers headers = {make_range_header({{-1, 1}})};
  816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  817. EXPECT_STREQ("bytes=-1", val);
  818. }
  819. {
  820. Headers headers = {make_range_header({{1, 10}})};
  821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  822. EXPECT_STREQ("bytes=1-10", val);
  823. }
  824. {
  825. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  827. EXPECT_STREQ("bytes=1-10, 100-", val);
  828. }
  829. {
  830. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  832. EXPECT_STREQ("bytes=1-10, 100-200", val);
  833. }
  834. {
  835. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  837. EXPECT_STREQ("bytes=0-0, -1", val);
  838. }
  839. }
  840. TEST(ParseHeaderValueTest, Range) {
  841. {
  842. Ranges ranges;
  843. auto ret = detail::parse_range_header("bytes=1-", ranges);
  844. EXPECT_TRUE(ret);
  845. EXPECT_EQ(1u, ranges.size());
  846. EXPECT_EQ(1u, ranges[0].first);
  847. EXPECT_EQ(-1, ranges[0].second);
  848. }
  849. {
  850. Ranges ranges;
  851. auto ret = detail::parse_range_header("bytes=-1", ranges);
  852. EXPECT_TRUE(ret);
  853. EXPECT_EQ(1u, ranges.size());
  854. EXPECT_EQ(-1, ranges[0].first);
  855. EXPECT_EQ(1u, ranges[0].second);
  856. }
  857. {
  858. Ranges ranges;
  859. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  860. EXPECT_TRUE(ret);
  861. EXPECT_EQ(1u, ranges.size());
  862. EXPECT_EQ(1u, ranges[0].first);
  863. EXPECT_EQ(10u, ranges[0].second);
  864. }
  865. {
  866. Ranges ranges;
  867. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  868. EXPECT_FALSE(ret);
  869. }
  870. {
  871. Ranges ranges;
  872. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  873. EXPECT_TRUE(ret);
  874. EXPECT_EQ(2u, ranges.size());
  875. EXPECT_EQ(1u, ranges[0].first);
  876. EXPECT_EQ(10u, ranges[0].second);
  877. EXPECT_EQ(100u, ranges[1].first);
  878. EXPECT_EQ(-1, ranges[1].second);
  879. }
  880. {
  881. Ranges ranges;
  882. auto ret =
  883. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  884. EXPECT_TRUE(ret);
  885. EXPECT_EQ(3u, ranges.size());
  886. EXPECT_EQ(1u, ranges[0].first);
  887. EXPECT_EQ(10u, ranges[0].second);
  888. EXPECT_EQ(100u, ranges[1].first);
  889. EXPECT_EQ(200u, ranges[1].second);
  890. EXPECT_EQ(300u, ranges[2].first);
  891. EXPECT_EQ(400u, ranges[2].second);
  892. }
  893. {
  894. Ranges ranges;
  895. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  896. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  897. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  908. EXPECT_TRUE(ranges.empty());
  909. }
  910. }
  911. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  912. Request req;
  913. req.set_header("Accept-Encoding", "gzip");
  914. Response res;
  915. res.set_header("Content-Type", "text/plain");
  916. auto ret = detail::encoding_type(req, res);
  917. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  918. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  919. #else
  920. EXPECT_TRUE(ret == detail::EncodingType::None);
  921. #endif
  922. }
  923. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  924. Request req;
  925. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  926. Response res;
  927. res.set_header("Content-Type", "text/plain");
  928. auto ret = detail::encoding_type(req, res);
  929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  930. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  931. #elif CPPHTTPLIB_ZLIB_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  933. #elif CPPHTTPLIB_ZSTD_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  935. #else
  936. EXPECT_TRUE(ret == detail::EncodingType::None);
  937. #endif
  938. }
  939. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding",
  942. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  943. Response res;
  944. res.set_header("Content-Type", "text/plain");
  945. auto ret = detail::encoding_type(req, res);
  946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  947. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  948. #elif CPPHTTPLIB_ZLIB_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  950. #elif CPPHTTPLIB_ZSTD_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  952. #else
  953. EXPECT_TRUE(ret == detail::EncodingType::None);
  954. #endif
  955. }
  956. TEST(BufferStreamTest, read) {
  957. detail::BufferStream strm1;
  958. Stream &strm = strm1;
  959. EXPECT_EQ(5, strm.write("hello"));
  960. char buf[512];
  961. EXPECT_EQ(2, strm.read(buf, 2));
  962. EXPECT_EQ('h', buf[0]);
  963. EXPECT_EQ('e', buf[1]);
  964. EXPECT_EQ(2, strm.read(buf, 2));
  965. EXPECT_EQ('l', buf[0]);
  966. EXPECT_EQ('l', buf[1]);
  967. EXPECT_EQ(1, strm.read(buf, 1));
  968. EXPECT_EQ('o', buf[0]);
  969. EXPECT_EQ(0, strm.read(buf, 1));
  970. }
  971. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  972. auto host = "www.httpwatch.com";
  973. auto ip = hosted_at(host);
  974. EXPECT_EQ("23.96.13.243", ip);
  975. std::vector<std::string> addrs;
  976. hosted_at(host, addrs);
  977. EXPECT_EQ(1u, addrs.size());
  978. }
  979. #if 0 // It depends on each test environment...
  980. TEST(HostnameToIPConversionTest, YouTube_Online) {
  981. auto host = "www.youtube.com";
  982. std::vector<std::string> addrs;
  983. hosted_at(host, addrs);
  984. EXPECT_EQ(20u, addrs.size());
  985. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  986. EXPECT_TRUE(it != addrs.end());
  987. }
  988. #endif
  989. class ChunkedEncodingTest : public ::testing::Test {
  990. protected:
  991. ChunkedEncodingTest()
  992. : cli_(HOST, PORT)
  993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  994. ,
  995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  996. #endif
  997. {
  998. cli_.set_connection_timeout(2);
  999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1000. cli_.enable_server_certificate_verification(false);
  1001. #endif
  1002. }
  1003. virtual void SetUp() {
  1004. read_file("./image.jpg", image_data_);
  1005. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1006. res.set_content("Hello World!", "text/plain");
  1007. });
  1008. svr_.Get(
  1009. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1010. res.set_chunked_content_provider(
  1011. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1012. size_t remaining = image_data_.size() - offset;
  1013. if (remaining == 0) {
  1014. sink.done();
  1015. } else {
  1016. constexpr size_t CHUNK_SIZE = 1024;
  1017. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1018. sink.write(&image_data_[offset], send_size);
  1019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1020. }
  1021. return true;
  1022. });
  1023. });
  1024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1025. svr_.wait_until_ready();
  1026. }
  1027. virtual void TearDown() {
  1028. svr_.stop();
  1029. if (!request_threads_.empty()) {
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. for (auto &t : request_threads_) {
  1032. t.join();
  1033. }
  1034. }
  1035. t_.join();
  1036. }
  1037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1038. SSLClient cli_;
  1039. SSLServer svr_;
  1040. #else
  1041. Client cli_;
  1042. Server svr_;
  1043. #endif
  1044. thread t_;
  1045. std::vector<thread> request_threads_;
  1046. std::string image_data_;
  1047. };
  1048. TEST_F(ChunkedEncodingTest, NormalGet) {
  1049. auto res = cli_.Get("/chunked");
  1050. ASSERT_TRUE(res);
  1051. std::string out;
  1052. read_file("./image.jpg", out);
  1053. EXPECT_EQ(StatusCode::OK_200, res->status);
  1054. EXPECT_EQ(out, res->body);
  1055. }
  1056. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1057. std::string body;
  1058. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1059. body.append(data, data_length);
  1060. return true;
  1061. });
  1062. ASSERT_TRUE(res);
  1063. std::string out;
  1064. read_file("./image.jpg", out);
  1065. EXPECT_EQ(StatusCode::OK_200, res->status);
  1066. EXPECT_EQ(out, body);
  1067. }
  1068. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1069. std::string body;
  1070. auto res = cli_.Get(
  1071. "/chunked",
  1072. [&](const Response &response) {
  1073. EXPECT_EQ(StatusCode::OK_200, response.status);
  1074. return true;
  1075. },
  1076. [&](const char *data, size_t data_length) {
  1077. body.append(data, data_length);
  1078. return true;
  1079. });
  1080. ASSERT_TRUE(res);
  1081. std::string out;
  1082. read_file("./image.jpg", out);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. EXPECT_EQ(out, body);
  1085. }
  1086. TEST(RangeTest, FromHTTPBin_Online) {
  1087. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1088. auto host = "httpbin.org";
  1089. auto path = std::string{"/range/32"};
  1090. #else
  1091. auto host = "nghttp2.org";
  1092. auto path = std::string{"/httpbin/range/32"};
  1093. #endif
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(5);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{1, -1}})};
  1110. auto res = cli.Get(path, headers);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto res = cli.Get(path, headers);
  1118. ASSERT_TRUE(res);
  1119. EXPECT_EQ("bcdefghijk", res->body);
  1120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 31}})};
  1124. auto res = cli.Get(path, headers);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1127. EXPECT_EQ(StatusCode::OK_200, res->status);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{0, -1}})};
  1131. auto res = cli.Get(path, headers);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{0, 32}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1141. }
  1142. }
  1143. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1144. auto host = "unresolvableaddress.local";
  1145. auto path = std::string{"/"};
  1146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1147. auto port = 443;
  1148. SSLClient cli(host, port);
  1149. #else
  1150. auto port = 80;
  1151. Client cli(host, port);
  1152. #endif
  1153. cli.set_connection_timeout(1);
  1154. {
  1155. auto res = cli.Get(path);
  1156. ASSERT_FALSE(res);
  1157. }
  1158. std::this_thread::sleep_for(std::chrono::seconds(8));
  1159. }
  1160. TEST(ConnectionErrorTest, InvalidHost) {
  1161. auto host = "-abcde.com";
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. auto port = 443;
  1164. SSLClient cli(host, port);
  1165. #else
  1166. auto port = 80;
  1167. Client cli(host, port);
  1168. #endif
  1169. cli.set_connection_timeout(std::chrono::seconds(2));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Connection, res.error());
  1173. }
  1174. TEST(ConnectionErrorTest, InvalidHost2) {
  1175. auto host = "httpbin.org/";
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. SSLClient cli(host);
  1178. #else
  1179. Client cli(host);
  1180. #endif
  1181. cli.set_connection_timeout(std::chrono::seconds(2));
  1182. auto res = cli.Get("/");
  1183. ASSERT_TRUE(!res);
  1184. EXPECT_EQ(Error::Connection, res.error());
  1185. }
  1186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1187. auto host = "httpbin.org/";
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. SSLClient cli(host);
  1190. #else
  1191. Client cli(host);
  1192. #endif
  1193. cli.set_connection_timeout(std::chrono::seconds(2));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(!res);
  1196. stringstream s;
  1197. s << "error code: " << res.error();
  1198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1199. }
  1200. TEST(ConnectionErrorTest, InvalidPort) {
  1201. auto host = "localhost";
  1202. auto port = 44380;
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host, port);
  1205. #else
  1206. Client cli(host, port);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_TRUE(Error::Connection == res.error() ||
  1212. Error::ConnectionTimeout == res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, Timeout_Online) {
  1215. auto host = "google.com";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. auto port = 44380;
  1218. SSLClient cli(host, port);
  1219. #else
  1220. auto port = 8080;
  1221. Client cli(host, port);
  1222. #endif
  1223. cli.set_connection_timeout(std::chrono::seconds(2));
  1224. // only probe one address type so that the error reason
  1225. // correlates to the timed-out IPv4, not the unsupported
  1226. // IPv6 connection attempt
  1227. cli.set_address_family(AF_INET);
  1228. auto res = cli.Get("/");
  1229. ASSERT_TRUE(!res);
  1230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1231. }
  1232. TEST(CancelTest, NoCancel_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpbin.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1249. ASSERT_TRUE(res);
  1250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1251. EXPECT_EQ(StatusCode::OK_200, res->status);
  1252. }
  1253. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1254. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1255. auto host = "httpbin.org";
  1256. auto path = std::string{"/range/32"};
  1257. #else
  1258. auto host = "nghttp2.org";
  1259. auto path = std::string{"/httpbin/range/32"};
  1260. #endif
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Canceled, res.error());
  1272. }
  1273. TEST(CancelTest, WithCancelLargePayload_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpbin.org";
  1276. auto path = std::string{"/range/65536"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/65536"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. uint32_t count = 0;
  1290. auto res =
  1291. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, NoCancelPost) {
  1296. Server svr;
  1297. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return true; });
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ("Hello World!", res->body);
  1314. EXPECT_EQ(StatusCode::OK_200, res->status);
  1315. }
  1316. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1317. Server svr;
  1318. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return false; });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, WithCancelLargePayloadPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content(LARGE_DATA, "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, NoCancelPut) {
  1357. Server svr;
  1358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content("Hello World!", "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return true; });
  1373. ASSERT_TRUE(res);
  1374. EXPECT_EQ("Hello World!", res->body);
  1375. EXPECT_EQ(StatusCode::OK_200, res->status);
  1376. }
  1377. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1378. Server svr;
  1379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, WithCancelLargePayloadPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content(LARGE_DATA, "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, NoCancelPatch) {
  1418. Server svr;
  1419. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content("Hello World!", "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return true; });
  1434. ASSERT_TRUE(res);
  1435. EXPECT_EQ("Hello World!", res->body);
  1436. EXPECT_EQ(StatusCode::OK_200, res->status);
  1437. }
  1438. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1439. Server svr;
  1440. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content("Hello World!", "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content(LARGE_DATA, "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return false; });
  1475. ASSERT_TRUE(!res);
  1476. EXPECT_EQ(Error::Canceled, res.error());
  1477. }
  1478. TEST(CancelTest, NoCancelDelete) {
  1479. Server svr;
  1480. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return true; });
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ("Hello World!", res->body);
  1497. EXPECT_EQ(StatusCode::OK_200, res->status);
  1498. }
  1499. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1500. Server svr;
  1501. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content("Hello World!", "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content(LARGE_DATA, "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return false; });
  1536. ASSERT_TRUE(!res);
  1537. EXPECT_EQ(Error::Canceled, res.error());
  1538. }
  1539. static std::string remove_whitespace(const std::string &input) {
  1540. std::string output;
  1541. output.reserve(input.size());
  1542. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1543. [](unsigned char c) { return !std::isspace(c); });
  1544. return output;
  1545. }
  1546. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1547. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1548. auto host = "httpbin.org";
  1549. auto path = std::string{"/basic-auth/hello/world"};
  1550. #else
  1551. auto host = "nghttp2.org";
  1552. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1553. #endif
  1554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1555. auto port = 443;
  1556. SSLClient cli(host, port);
  1557. #else
  1558. auto port = 80;
  1559. Client cli(host, port);
  1560. #endif
  1561. {
  1562. auto res = cli.Get(path);
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1565. }
  1566. {
  1567. auto res =
  1568. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1571. remove_whitespace(res->body));
  1572. EXPECT_EQ(StatusCode::OK_200, res->status);
  1573. }
  1574. {
  1575. cli.set_basic_auth("hello", "world");
  1576. auto res = cli.Get(path);
  1577. ASSERT_TRUE(res);
  1578. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1579. remove_whitespace(res->body));
  1580. EXPECT_EQ(StatusCode::OK_200, res->status);
  1581. }
  1582. {
  1583. cli.set_basic_auth("hello", "bad");
  1584. auto res = cli.Get(path);
  1585. ASSERT_TRUE(res);
  1586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1587. }
  1588. {
  1589. cli.set_basic_auth("bad", "world");
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. }
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1597. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1598. auto host = "httpbin.org";
  1599. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1600. auto paths = std::vector<std::string>{
  1601. "/digest-auth/auth/hello/world/MD5",
  1602. "/digest-auth/auth/hello/world/SHA-256",
  1603. "/digest-auth/auth/hello/world/SHA-512",
  1604. "/digest-auth/auth-int/hello/world/MD5",
  1605. };
  1606. #else
  1607. auto host = "nghttp2.org";
  1608. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1609. auto paths = std::vector<std::string>{
  1610. "/httpbin/digest-auth/auth/hello/world/MD5",
  1611. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1612. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1613. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1614. };
  1615. #endif
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. {
  1619. auto res = cli.Get(unauth_path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_digest_auth("hello", "world");
  1625. for (const auto &path : paths) {
  1626. auto res = cli.Get(path.c_str());
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. cli.set_digest_auth("hello", "bad");
  1633. for (const auto &path : paths) {
  1634. auto res = cli.Get(path.c_str());
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1637. }
  1638. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1639. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1640. // cli.set_digest_auth("bad", "world");
  1641. // for (const auto& path : paths) {
  1642. // auto res = cli.Get(path.c_str());
  1643. // ASSERT_TRUE(res);
  1644. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1645. // }
  1646. }
  1647. }
  1648. #endif
  1649. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1650. auto host = "google.com";
  1651. auto another_host = "example.com";
  1652. auto wrong_ip = "0.0.0.0";
  1653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. }
  1663. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1664. auto host = "google.com";
  1665. auto wrong_ip = "0.0.0.0";
  1666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1667. SSLClient cli(host);
  1668. #else
  1669. Client cli(host);
  1670. #endif
  1671. cli.set_hostname_addr_map({{host, wrong_ip}});
  1672. auto res = cli.Get("/");
  1673. ASSERT_TRUE(!res);
  1674. EXPECT_EQ(Error::Connection, res.error());
  1675. }
  1676. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1677. auto host = "nghttp2.org";
  1678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1679. SSLClient cli(host);
  1680. #else
  1681. Client cli(host);
  1682. #endif
  1683. cli.set_follow_location(true);
  1684. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(RedirectTest, Redirect_Online) {
  1689. auto host = "nghttp2.org";
  1690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1691. SSLClient cli(host);
  1692. #else
  1693. Client cli(host);
  1694. #endif
  1695. cli.set_follow_location(true);
  1696. auto res = cli.Get("/httpbin/redirect/3");
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(RelativeRedirectTest, Redirect_Online) {
  1701. auto host = "nghttp2.org";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_follow_location(true);
  1708. auto res = cli.Get("/httpbin/relative-redirect/3");
  1709. ASSERT_TRUE(res);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. }
  1712. TEST(TooManyRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/redirect/21");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1723. }
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. TEST(YahooRedirectTest, Redirect_Online) {
  1726. Client cli("yahoo.com");
  1727. auto res = cli.Get("/");
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1730. cli.set_follow_location(true);
  1731. res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(StatusCode::OK_200, res->status);
  1734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1735. }
  1736. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1737. #define REDIR_HOST "httpbingo.org"
  1738. #define REDIR_PATH "/redirect-to"
  1739. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1740. SSLClient cli(REDIR_HOST);
  1741. cli.set_follow_location(true);
  1742. auto res =
  1743. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1748. SSLClient cli(REDIR_HOST);
  1749. cli.set_follow_location(true);
  1750. Params params;
  1751. params.emplace("url", "http://example.com");
  1752. params.emplace("status_code", "302");
  1753. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1758. SSLClient cli(REDIR_HOST);
  1759. cli.set_follow_location(true);
  1760. Params params;
  1761. params.emplace("url", "http://example.com");
  1762. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::OK_200, res->status);
  1765. }
  1766. TEST(UrlWithSpace, Redirect_Online) {
  1767. SSLClient cli("edge.forgecdn.net");
  1768. cli.set_follow_location(true);
  1769. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1773. }
  1774. #endif
  1775. #if !defined(_WIN32) && !defined(_WIN64)
  1776. TEST(ReceiveSignals, Signal) {
  1777. auto setupSignalHandlers = []() {
  1778. struct sigaction act;
  1779. sigemptyset(&act.sa_mask);
  1780. act.sa_flags = SA_SIGINFO;
  1781. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1782. switch (sig) {
  1783. case SIGINT:
  1784. default: break;
  1785. }
  1786. };
  1787. ::sigaction(SIGINT, &act, nullptr);
  1788. };
  1789. Server svr;
  1790. int port = 0;
  1791. auto thread = std::thread([&]() {
  1792. setupSignalHandlers();
  1793. port = svr.bind_to_any_port("localhost");
  1794. svr.listen_after_bind();
  1795. });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. thread.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. svr.wait_until_ready();
  1802. ASSERT_TRUE(svr.is_running());
  1803. pthread_kill(thread.native_handle(), SIGINT);
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1805. ASSERT_TRUE(svr.is_running());
  1806. }
  1807. #endif
  1808. TEST(RedirectToDifferentPort, Redirect) {
  1809. Server svr1;
  1810. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1811. res.set_content("Hello World!", "text/plain");
  1812. });
  1813. int svr1_port = 0;
  1814. auto thread1 = std::thread([&]() {
  1815. svr1_port = svr1.bind_to_any_port("localhost");
  1816. svr1.listen_after_bind();
  1817. });
  1818. Server svr2;
  1819. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1820. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1821. });
  1822. int svr2_port = 0;
  1823. auto thread2 = std::thread([&]() {
  1824. svr2_port = svr2.bind_to_any_port("localhost");
  1825. svr2.listen_after_bind();
  1826. });
  1827. auto se = detail::scope_exit([&] {
  1828. svr2.stop();
  1829. thread2.join();
  1830. svr1.stop();
  1831. thread1.join();
  1832. ASSERT_FALSE(svr2.is_running());
  1833. ASSERT_FALSE(svr1.is_running());
  1834. });
  1835. svr1.wait_until_ready();
  1836. svr2.wait_until_ready();
  1837. Client cli("localhost", svr2_port);
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/2");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("Hello World!", res->body);
  1843. }
  1844. TEST(RedirectFromPageWithContent, Redirect) {
  1845. Server svr;
  1846. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("___", "text/plain");
  1848. res.set_redirect("/2");
  1849. });
  1850. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. th.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli("localhost", PORT);
  1862. cli.set_follow_location(true);
  1863. std::string body;
  1864. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1865. body.append(data, data_length);
  1866. return true;
  1867. });
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", body);
  1871. }
  1872. {
  1873. Client cli("localhost", PORT);
  1874. std::string body;
  1875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1876. body.append(data, data_length);
  1877. return true;
  1878. });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(StatusCode::Found_302, res->status);
  1881. EXPECT_EQ("___", body);
  1882. }
  1883. }
  1884. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1885. Server svr;
  1886. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("___", "text/plain");
  1888. // res.set_redirect("/2");
  1889. res.set_redirect("http://[::1]:1234/2");
  1890. });
  1891. svr.Get("/2", [&](const Request &req, Response &res) {
  1892. auto host_header = req.headers.find("Host");
  1893. ASSERT_TRUE(host_header != req.headers.end());
  1894. EXPECT_EQ("[::1]:1234", host_header->second);
  1895. res.set_content("Hello World!", "text/plain");
  1896. });
  1897. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. th.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1904. // actually starts anything, so the condition !svr.is_running() will
  1905. // always remain true, and the loop never stops.
  1906. // This basically counts how many milliseconds have passed since the
  1907. // call to svr.listen(), and if after 5 seconds nothing started yet
  1908. // aborts the test.
  1909. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1911. ASSERT_LT(milliseconds, 5000U);
  1912. }
  1913. {
  1914. Client cli("http://[::1]:1234");
  1915. cli.set_follow_location(true);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ("Hello World!", body);
  1924. }
  1925. {
  1926. Client cli("http://[::1]:1234");
  1927. std::string body;
  1928. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1929. body.append(data, data_length);
  1930. return true;
  1931. });
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::Found_302, res->status);
  1934. EXPECT_EQ("___", body);
  1935. }
  1936. }
  1937. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1938. Server svr;
  1939. svr.Get("/foo", [](const Request &req, Response &res) {
  1940. auto a = req.params.find("a");
  1941. if (a != req.params.end()) {
  1942. res.set_content((*a).second, "text/plain");
  1943. res.status = StatusCode::OK_200;
  1944. } else {
  1945. res.status = StatusCode::BadRequest_400;
  1946. }
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. cli.set_path_encode(false);
  1958. auto res = cli.Get("/foo?a=explicitly+encoded");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // This expects it back with a space, as the `+` won't have been
  1962. // url-encoded, and server-side the params get decoded turning `+`
  1963. // into spaces.
  1964. EXPECT_EQ("explicitly encoded", res->body);
  1965. }
  1966. }
  1967. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1968. Server svr;
  1969. svr.Get("/", [](const Request &req, Response &) {
  1970. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_path_encode(false);
  1982. auto res = cli.Get("/?something=%0A");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. }
  1987. TEST(BindServerTest, DISABLED_BindDualStack) {
  1988. Server svr;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("Hello World!", "text/plain");
  1991. });
  1992. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1993. auto se = detail::scope_exit([&] {
  1994. svr.stop();
  1995. thread.join();
  1996. ASSERT_FALSE(svr.is_running());
  1997. });
  1998. svr.wait_until_ready();
  1999. {
  2000. Client cli("127.0.0.1", PORT);
  2001. auto res = cli.Get("/1");
  2002. ASSERT_TRUE(res);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ("Hello World!", res->body);
  2005. }
  2006. {
  2007. Client cli("::1", PORT);
  2008. auto res = cli.Get("/1");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", res->body);
  2012. }
  2013. }
  2014. TEST(BindServerTest, BindAndListenSeparately) {
  2015. Server svr;
  2016. int port = svr.bind_to_any_port("0.0.0.0");
  2017. ASSERT_TRUE(svr.is_valid());
  2018. ASSERT_TRUE(port > 0);
  2019. svr.stop();
  2020. }
  2021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2022. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2024. CLIENT_CA_CERT_DIR);
  2025. int port = svr.bind_to_any_port("0.0.0.0");
  2026. ASSERT_TRUE(svr.is_valid());
  2027. ASSERT_TRUE(port > 0);
  2028. svr.stop();
  2029. }
  2030. #endif
  2031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2032. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2033. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2034. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2035. int port = svr.bind_to_any_port("0.0.0.0");
  2036. ASSERT_TRUE(svr.is_valid());
  2037. ASSERT_TRUE(port > 0);
  2038. svr.stop();
  2039. }
  2040. #endif
  2041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2042. X509 *readCertificate(const std::string &strFileName) {
  2043. std::ifstream inStream(strFileName);
  2044. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2045. std::istreambuf_iterator<char>());
  2046. if (strCertPEM.empty()) return (nullptr);
  2047. BIO *pbCert = BIO_new(BIO_s_mem());
  2048. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2049. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2050. BIO_free(pbCert);
  2051. return (pCert);
  2052. }
  2053. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2054. std::ifstream inStream(strFileName);
  2055. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2056. std::istreambuf_iterator<char>());
  2057. if (strPrivateKeyPEM.empty()) return (nullptr);
  2058. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2059. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2060. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2061. BIO_free(pbPrivKey);
  2062. return (pPrivateKey);
  2063. }
  2064. TEST(BindServerTest, UpdateCerts) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2070. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2071. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2072. ASSERT_TRUE(cert != nullptr);
  2073. ASSERT_TRUE(ca_cert != nullptr);
  2074. ASSERT_TRUE(key != nullptr);
  2075. X509_STORE *cert_store = X509_STORE_new();
  2076. X509_STORE_add_cert(cert_store, ca_cert);
  2077. svr.update_certs(cert, key, cert_store);
  2078. ASSERT_TRUE(svr.is_valid());
  2079. svr.stop();
  2080. X509_free(cert);
  2081. X509_free(ca_cert);
  2082. EVP_PKEY_free(key);
  2083. }
  2084. #endif
  2085. TEST(ErrorHandlerTest, ContentLength) {
  2086. Server svr;
  2087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2088. res.status = StatusCode::OK_200;
  2089. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2090. "text/html"); // <= Content-Length still 13
  2091. });
  2092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!\n", "text/plain");
  2094. res.status = 524;
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. {
  2104. Client cli(HOST, PORT);
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::OK_200, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. }
  2113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2114. TEST(ExceptionTest, WithoutExceptionHandler) {
  2115. Server svr;
  2116. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2117. throw std::runtime_error("exception...");
  2118. });
  2119. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2120. throw std::runtime_error("exception\r\n...");
  2121. });
  2122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2123. auto se = detail::scope_exit([&] {
  2124. svr.stop();
  2125. listen_thread.join();
  2126. ASSERT_FALSE(svr.is_running());
  2127. });
  2128. svr.wait_until_ready();
  2129. Client cli("localhost", PORT);
  2130. {
  2131. auto res = cli.Get("/exception");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2135. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2136. }
  2137. {
  2138. auto res = cli.Get("/unknown");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2141. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2142. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2143. }
  2144. }
  2145. TEST(ExceptionTest, WithExceptionHandler) {
  2146. Server svr;
  2147. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2148. std::exception_ptr ep) {
  2149. EXPECT_FALSE(ep == nullptr);
  2150. try {
  2151. std::rethrow_exception(ep);
  2152. } catch (std::exception &e) {
  2153. EXPECT_EQ("abc", std::string(e.what()));
  2154. } catch (...) {}
  2155. res.status = StatusCode::InternalServerError_500;
  2156. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2157. "text/html"); // <= Content-Length still 13 at this point
  2158. });
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!\n", "text/plain");
  2161. throw std::runtime_error("abc");
  2162. });
  2163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. for (size_t i = 0; i < 10; i++) {
  2171. Client cli(HOST, PORT);
  2172. for (size_t j = 0; j < 100; j++) {
  2173. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2179. }
  2180. cli.set_keep_alive(true);
  2181. for (size_t j = 0; j < 100; j++) {
  2182. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2186. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2187. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2188. }
  2189. }
  2190. }
  2191. TEST(ExceptionTest, AndErrorHandler) {
  2192. Server svr;
  2193. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2194. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2195. });
  2196. svr.set_exception_handler(
  2197. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. res.set_content(e.what(), "text/html");
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. });
  2206. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2207. throw std::runtime_error("EXCEPTION");
  2208. });
  2209. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2210. res.set_content("ERROR", "text/html");
  2211. res.status = StatusCode::InternalServerError_500;
  2212. });
  2213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2214. auto se = detail::scope_exit([&] {
  2215. svr.stop();
  2216. thread.join();
  2217. ASSERT_FALSE(svr.is_running());
  2218. });
  2219. svr.wait_until_ready();
  2220. Client cli(HOST, PORT);
  2221. {
  2222. auto res = cli.Get("/exception");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2225. EXPECT_EQ("EXCEPTION", res->body);
  2226. }
  2227. {
  2228. auto res = cli.Get("/error");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2231. EXPECT_EQ("ERROR", res->body);
  2232. }
  2233. {
  2234. auto res = cli.Get("/invalid");
  2235. ASSERT_TRUE(res);
  2236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2237. EXPECT_EQ("NOT_FOUND", res->body);
  2238. }
  2239. }
  2240. #endif
  2241. TEST(NoContentTest, ContentLength) {
  2242. Server svr;
  2243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2244. res.status = StatusCode::NoContent_204;
  2245. });
  2246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2247. auto se = detail::scope_exit([&] {
  2248. svr.stop();
  2249. thread.join();
  2250. ASSERT_FALSE(svr.is_running());
  2251. });
  2252. svr.wait_until_ready();
  2253. {
  2254. Client cli(HOST, PORT);
  2255. auto res = cli.Get("/hi");
  2256. ASSERT_TRUE(res);
  2257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2259. }
  2260. }
  2261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2264. ASSERT_TRUE(svr.is_valid());
  2265. #else
  2266. Server svr;
  2267. #endif
  2268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2269. if (req.path == "/routing_handler") {
  2270. res.set_header("PRE_ROUTING", "on");
  2271. res.set_content("Routing Handler", "text/plain");
  2272. return httplib::Server::HandlerResponse::Handled;
  2273. }
  2274. return httplib::Server::HandlerResponse::Unhandled;
  2275. });
  2276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2277. res.set_content("Error", "text/html");
  2278. });
  2279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2280. if (req.path == "/routing_handler") {
  2281. res.set_header("POST_ROUTING", "on");
  2282. }
  2283. });
  2284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!\n", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. {
  2295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2296. SSLClient cli(HOST, PORT);
  2297. cli.enable_server_certificate_verification(false);
  2298. #else
  2299. Client cli(HOST, PORT);
  2300. #endif
  2301. auto res = cli.Get("/routing_handler");
  2302. ASSERT_TRUE(res);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ("Routing Handler", res->body);
  2305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2309. }
  2310. {
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli(HOST, PORT);
  2313. cli.enable_server_certificate_verification(false);
  2314. #else
  2315. Client cli(HOST, PORT);
  2316. #endif
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!\n", res->body);
  2321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2323. }
  2324. {
  2325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2326. SSLClient cli(HOST, PORT);
  2327. cli.enable_server_certificate_verification(false);
  2328. #else
  2329. Client cli(HOST, PORT);
  2330. #endif
  2331. auto res = cli.Get("/aaa");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2334. EXPECT_EQ("Error", res->body);
  2335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2337. }
  2338. }
  2339. TEST(RequestHandlerTest, PreRequestHandler) {
  2340. auto route_path = "/user/:user";
  2341. Server svr;
  2342. svr.Get("/hi", [](const Request &, Response &res) {
  2343. res.set_content("hi", "text/plain");
  2344. });
  2345. svr.Get(route_path, [](const Request &req, Response &res) {
  2346. res.set_content(req.path_params.at("user"), "text/plain");
  2347. });
  2348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2349. if (req.matched_route == route_path) {
  2350. auto user = req.path_params.at("user");
  2351. if (user != "john") {
  2352. res.status = StatusCode::Forbidden_403;
  2353. res.set_content("error", "text/html");
  2354. return Server::HandlerResponse::Handled;
  2355. }
  2356. }
  2357. return Server::HandlerResponse::Unhandled;
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. {
  2368. auto res = cli.Get("/hi");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. EXPECT_EQ("hi", res->body);
  2372. }
  2373. {
  2374. auto res = cli.Get("/user/john");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("john", res->body);
  2378. }
  2379. {
  2380. auto res = cli.Get("/user/invalid-user");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2383. EXPECT_EQ("error", res->body);
  2384. }
  2385. }
  2386. TEST(InvalidFormatTest, StatusCode) {
  2387. Server svr;
  2388. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2389. res.set_content("Hello World!\n", "text/plain");
  2390. res.status = 9999; // Status should be a three-digit code...
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. {
  2400. Client cli(HOST, PORT);
  2401. auto res = cli.Get("/hi");
  2402. ASSERT_FALSE(res);
  2403. }
  2404. }
  2405. TEST(URLFragmentTest, WithFragment) {
  2406. Server svr;
  2407. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2408. EXPECT_TRUE(req.target == "/hi");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. {
  2418. Client cli(HOST, PORT);
  2419. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2420. EXPECT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. res = cli.Get("/hi%23key1=val1=key2=val2");
  2423. EXPECT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2425. }
  2426. }
  2427. TEST(HeaderWriter, SetHeaderWriter) {
  2428. Server svr;
  2429. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2430. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2431. return detail::write_headers(strm, hdrs);
  2432. });
  2433. svr.Get("/hi", [](const Request &req, Response &res) {
  2434. auto it = req.headers.find("CustomClientHeader");
  2435. EXPECT_TRUE(it != req.headers.end());
  2436. EXPECT_EQ(it->second, "CustomClientValue");
  2437. res.set_content("Hello World!\n", "text/plain");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2449. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2450. return detail::write_headers(strm, hdrs);
  2451. });
  2452. auto res = cli.Get("/hi");
  2453. EXPECT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::OK_200, res->status);
  2455. auto it = res->headers.find("CustomServerHeader");
  2456. EXPECT_TRUE(it != res->headers.end());
  2457. EXPECT_EQ(it->second, "CustomServerValue");
  2458. }
  2459. }
  2460. class ServerTest : public ::testing::Test {
  2461. protected:
  2462. ServerTest()
  2463. : cli_(HOST, PORT)
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. ,
  2466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2467. #endif
  2468. {
  2469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2470. cli_.enable_server_certificate_verification(false);
  2471. #endif
  2472. }
  2473. virtual void SetUp() {
  2474. svr_.set_mount_point("/", "./www");
  2475. svr_.set_mount_point("/mount", "./www2");
  2476. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2477. svr_.Get("/hi",
  2478. [&](const Request & /*req*/, Response &res) {
  2479. res.set_content("Hello World!", "text/plain");
  2480. })
  2481. .Get("/file_content",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_file_content("./www/dir/test.html");
  2484. })
  2485. .Get("/file_content_with_content_type",
  2486. [&](const Request & /*req*/, Response &res) {
  2487. res.set_file_content("./www/file", "text/plain");
  2488. })
  2489. .Get("/invalid_file_content",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_file_content("./www/dir/invalid_file_path");
  2492. })
  2493. .Get("/http_response_splitting",
  2494. [&](const Request & /*req*/, Response &res) {
  2495. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2496. EXPECT_EQ(0U, res.headers.size());
  2497. EXPECT_FALSE(res.has_header("a"));
  2498. res.set_header("a", "1\nSet-Cookie: a=1");
  2499. EXPECT_EQ(0U, res.headers.size());
  2500. EXPECT_FALSE(res.has_header("a"));
  2501. res.set_header("a", "1\rSet-Cookie: a=1");
  2502. EXPECT_EQ(0U, res.headers.size());
  2503. EXPECT_FALSE(res.has_header("a"));
  2504. res.set_header("a\r\nb", "0");
  2505. EXPECT_EQ(0U, res.headers.size());
  2506. EXPECT_FALSE(res.has_header("a"));
  2507. res.set_header("a\rb", "0");
  2508. EXPECT_EQ(0U, res.headers.size());
  2509. EXPECT_FALSE(res.has_header("a"));
  2510. res.set_header("a\nb", "0");
  2511. EXPECT_EQ(0U, res.headers.size());
  2512. EXPECT_FALSE(res.has_header("a"));
  2513. res.set_redirect("1\r\nSet-Cookie: a=1");
  2514. EXPECT_EQ(0U, res.headers.size());
  2515. EXPECT_FALSE(res.has_header("Location"));
  2516. })
  2517. .Get("/slow",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. std::this_thread::sleep_for(std::chrono::seconds(2));
  2520. res.set_content("slow", "text/plain");
  2521. })
  2522. #if 0
  2523. .Post("/slowpost",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. std::this_thread::sleep_for(std::chrono::seconds(2));
  2526. res.set_content("slow", "text/plain");
  2527. })
  2528. #endif
  2529. .Get("/remote_addr",
  2530. [&](const Request &req, Response &res) {
  2531. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2532. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2533. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2534. EXPECT_EQ(req.remote_port,
  2535. std::stoi(req.get_header_value("REMOTE_PORT")));
  2536. res.set_content(remote_addr.c_str(), "text/plain");
  2537. })
  2538. .Get("/local_addr",
  2539. [&](const Request &req, Response &res) {
  2540. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2541. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2542. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2543. auto local_port = req.get_header_value("LOCAL_PORT");
  2544. EXPECT_EQ(req.local_addr, local_addr);
  2545. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2546. res.set_content(local_addr.append(":").append(local_port),
  2547. "text/plain");
  2548. })
  2549. .Get("/endwith%",
  2550. [&](const Request & /*req*/, Response &res) {
  2551. res.set_content("Hello World!", "text/plain");
  2552. })
  2553. .Get("/a\\+\\+b",
  2554. [&](const Request &req, Response &res) {
  2555. ASSERT_TRUE(req.has_param("a +b"));
  2556. auto val = req.get_param_value("a +b");
  2557. res.set_content(val, "text/plain");
  2558. })
  2559. .Get("/", [&](const Request & /*req*/,
  2560. Response &res) { res.set_redirect("/hi"); })
  2561. .Post("/1",
  2562. [](const Request & /*req*/, Response &res) {
  2563. res.set_redirect("/2", StatusCode::SeeOther_303);
  2564. })
  2565. .Get("/2",
  2566. [](const Request & /*req*/, Response &res) {
  2567. res.set_content("redirected.", "text/plain");
  2568. res.status = StatusCode::OK_200;
  2569. })
  2570. .Post("/person",
  2571. [&](const Request &req, Response &res) {
  2572. if (req.has_param("name") && req.has_param("note")) {
  2573. persons_[req.get_param_value("name")] =
  2574. req.get_param_value("note");
  2575. } else {
  2576. res.status = StatusCode::BadRequest_400;
  2577. }
  2578. })
  2579. .Put("/person",
  2580. [&](const Request &req, Response &res) {
  2581. if (req.has_param("name") && req.has_param("note")) {
  2582. persons_[req.get_param_value("name")] =
  2583. req.get_param_value("note");
  2584. } else {
  2585. res.status = StatusCode::BadRequest_400;
  2586. }
  2587. })
  2588. .Get("/person/(.*)",
  2589. [&](const Request &req, Response &res) {
  2590. string name = req.matches[1];
  2591. if (persons_.find(name) != persons_.end()) {
  2592. auto note = persons_[name];
  2593. res.set_content(note, "text/plain");
  2594. } else {
  2595. res.status = StatusCode::NotFound_404;
  2596. }
  2597. })
  2598. .Delete("/person",
  2599. [&](const Request &req, Response &res) {
  2600. if (req.has_param("name")) {
  2601. string name = req.get_param_value("name");
  2602. if (persons_.find(name) != persons_.end()) {
  2603. persons_.erase(name);
  2604. res.set_content("DELETED", "text/plain");
  2605. } else {
  2606. res.status = StatusCode::NotFound_404;
  2607. }
  2608. } else {
  2609. res.status = StatusCode::BadRequest_400;
  2610. }
  2611. })
  2612. .Post("/x-www-form-urlencoded-json",
  2613. [&](const Request &req, Response &res) {
  2614. auto json = req.get_param_value("json");
  2615. ASSERT_EQ(JSON_DATA, json);
  2616. res.set_content(json, "appliation/json");
  2617. res.status = StatusCode::OK_200;
  2618. })
  2619. .Get("/streamed-chunked",
  2620. [&](const Request & /*req*/, Response &res) {
  2621. res.set_chunked_content_provider(
  2622. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2623. sink.os << "123";
  2624. sink.os << "456";
  2625. sink.os << "789";
  2626. sink.done();
  2627. return true;
  2628. });
  2629. })
  2630. .Get("/streamed-chunked2",
  2631. [&](const Request & /*req*/, Response &res) {
  2632. auto i = new int(0);
  2633. res.set_chunked_content_provider(
  2634. "text/plain",
  2635. [i](size_t /*offset*/, DataSink &sink) {
  2636. switch (*i) {
  2637. case 0: sink.os << "123"; break;
  2638. case 1: sink.os << "456"; break;
  2639. case 2: sink.os << "789"; break;
  2640. case 3: sink.done(); break;
  2641. }
  2642. (*i)++;
  2643. return true;
  2644. },
  2645. [i](bool success) {
  2646. EXPECT_TRUE(success);
  2647. delete i;
  2648. });
  2649. })
  2650. .Get("/streamed-chunked-with-trailer",
  2651. [&](const Request & /*req*/, Response &res) {
  2652. auto i = new int(0);
  2653. res.set_header("Trailer", "Dummy1, Dummy2");
  2654. res.set_chunked_content_provider(
  2655. "text/plain",
  2656. [i](size_t /*offset*/, DataSink &sink) {
  2657. switch (*i) {
  2658. case 0: sink.os << "123"; break;
  2659. case 1: sink.os << "456"; break;
  2660. case 2: sink.os << "789"; break;
  2661. case 3: {
  2662. sink.done_with_trailer(
  2663. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2664. } break;
  2665. }
  2666. (*i)++;
  2667. return true;
  2668. },
  2669. [i](bool success) {
  2670. EXPECT_TRUE(success);
  2671. delete i;
  2672. });
  2673. })
  2674. .Get("/streamed",
  2675. [&](const Request & /*req*/, Response &res) {
  2676. res.set_content_provider(
  2677. 6, "text/plain",
  2678. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2679. sink.os << (offset < 3 ? "a" : "b");
  2680. return true;
  2681. });
  2682. })
  2683. .Get("/streamed-with-range",
  2684. [&](const Request &req, Response &res) {
  2685. auto data = new std::string("abcdefg");
  2686. res.set_content_provider(
  2687. data->size(), "text/plain",
  2688. [data](size_t offset, size_t length, DataSink &sink) {
  2689. size_t DATA_CHUNK_SIZE = 4;
  2690. const auto &d = *data;
  2691. auto out_len =
  2692. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2693. auto ret =
  2694. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2695. EXPECT_TRUE(ret);
  2696. return true;
  2697. },
  2698. [data, &req](bool success) {
  2699. EXPECT_EQ(success, !req.has_param("error"));
  2700. delete data;
  2701. });
  2702. })
  2703. .Get("/streamed-cancel",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_content_provider(
  2706. size_t(-1), "text/plain",
  2707. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2708. sink.os << "data_chunk";
  2709. return true;
  2710. });
  2711. })
  2712. .Get("/regex-with-delimiter",
  2713. [&](const Request &req, Response & /*res*/) {
  2714. ASSERT_TRUE(req.has_param("key"));
  2715. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2716. })
  2717. .Get("/with-range",
  2718. [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("abcdefg", "text/plain");
  2720. })
  2721. .Get("/test-start-time",
  2722. [&](const Request &req, Response & /*res*/) {
  2723. EXPECT_NE(req.start_time_,
  2724. std::chrono::steady_clock::time_point::min());
  2725. })
  2726. .Get("/with-range-customized-response",
  2727. [&](const Request & /*req*/, Response &res) {
  2728. res.status = StatusCode::BadRequest_400;
  2729. res.set_content(JSON_DATA, "application/json");
  2730. })
  2731. .Post("/chunked",
  2732. [&](const Request &req, Response & /*res*/) {
  2733. EXPECT_EQ(req.body, "dechunked post body");
  2734. })
  2735. .Post("/large-chunked",
  2736. [&](const Request &req, Response & /*res*/) {
  2737. std::string expected(6 * 30 * 1024u, 'a');
  2738. EXPECT_EQ(req.body, expected);
  2739. })
  2740. .Post("/multipart",
  2741. [&](const Request &req, Response & /*res*/) {
  2742. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2743. req.form.get_field_count("text2") +
  2744. req.form.get_field_count("file3") +
  2745. req.form.get_field_count("file4"));
  2746. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2747. req.form.get_file_count("file2"));
  2748. ASSERT_TRUE(!req.form.has_file("???"));
  2749. ASSERT_TRUE(!req.form.has_field("???"));
  2750. ASSERT_TRUE(req.body.empty());
  2751. {
  2752. const auto &text = req.form.get_field("text1");
  2753. EXPECT_EQ("text default", text);
  2754. }
  2755. {
  2756. const auto &text = req.form.get_field("text2");
  2757. EXPECT_EQ("aωb", text);
  2758. }
  2759. {
  2760. const auto &file = req.form.get_file("file1");
  2761. EXPECT_EQ("hello.txt", file.filename);
  2762. EXPECT_EQ("text/plain", file.content_type);
  2763. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2764. }
  2765. {
  2766. const auto &file = req.form.get_file("file2");
  2767. EXPECT_EQ("world.json", file.filename);
  2768. EXPECT_EQ("application/json", file.content_type);
  2769. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2770. }
  2771. {
  2772. const auto &text = req.form.get_field("file3");
  2773. EXPECT_EQ(0u, text.size());
  2774. }
  2775. {
  2776. const auto &text = req.form.get_field("file4");
  2777. EXPECT_EQ(0u, text.size());
  2778. }
  2779. })
  2780. .Post("/multipart/multi_file_values",
  2781. [&](const Request &req, Response & /*res*/) {
  2782. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2783. req.form.get_field_count("multi_text1"));
  2784. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2785. ASSERT_TRUE(!req.form.has_file("???"));
  2786. ASSERT_TRUE(!req.form.has_field("???"));
  2787. ASSERT_TRUE(req.body.empty());
  2788. {
  2789. const auto &text = req.form.get_field("text");
  2790. EXPECT_EQ("default text", text);
  2791. }
  2792. {
  2793. const auto &text1_values = req.form.get_fields("multi_text1");
  2794. EXPECT_EQ(2u, text1_values.size());
  2795. EXPECT_EQ("aaaaa", text1_values[0]);
  2796. EXPECT_EQ("bbbbb", text1_values[1]);
  2797. }
  2798. {
  2799. const auto &file1_values = req.form.get_files("multi_file1");
  2800. EXPECT_EQ(2u, file1_values.size());
  2801. auto file1 = file1_values[0];
  2802. EXPECT_EQ(file1.filename, "hello.txt");
  2803. EXPECT_EQ(file1.content_type, "text/plain");
  2804. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2805. auto file2 = file1_values[1];
  2806. EXPECT_EQ(file2.filename, "world.json");
  2807. EXPECT_EQ(file2.content_type, "application/json");
  2808. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2809. }
  2810. })
  2811. .Post("/empty",
  2812. [&](const Request &req, Response &res) {
  2813. EXPECT_EQ(req.body, "");
  2814. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2815. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2816. res.set_content("empty", "text/plain");
  2817. })
  2818. .Post("/empty-no-content-type",
  2819. [&](const Request &req, Response &res) {
  2820. EXPECT_EQ(req.body, "");
  2821. EXPECT_FALSE(req.has_header("Content-Type"));
  2822. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2823. res.set_content("empty-no-content-type", "text/plain");
  2824. })
  2825. .Post("/path-only",
  2826. [&](const Request &req, Response &res) {
  2827. EXPECT_EQ(req.body, "");
  2828. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2829. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2830. res.set_content("path-only", "text/plain");
  2831. })
  2832. .Post("/path-headers-only",
  2833. [&](const Request &req, Response &res) {
  2834. EXPECT_EQ(req.body, "");
  2835. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2836. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2837. EXPECT_EQ("world", req.get_header_value("hello"));
  2838. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2839. res.set_content("path-headers-only", "text/plain");
  2840. })
  2841. .Post("/post-large",
  2842. [&](const Request &req, Response &res) {
  2843. EXPECT_EQ(req.body, LARGE_DATA);
  2844. res.set_content(req.body, "text/plain");
  2845. })
  2846. .Put("/empty-no-content-type",
  2847. [&](const Request &req, Response &res) {
  2848. EXPECT_EQ(req.body, "");
  2849. EXPECT_FALSE(req.has_header("Content-Type"));
  2850. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2851. res.set_content("empty-no-content-type", "text/plain");
  2852. })
  2853. .Put("/put",
  2854. [&](const Request &req, Response &res) {
  2855. EXPECT_EQ(req.body, "PUT");
  2856. res.set_content(req.body, "text/plain");
  2857. })
  2858. .Put("/put-large",
  2859. [&](const Request &req, Response &res) {
  2860. EXPECT_EQ(req.body, LARGE_DATA);
  2861. res.set_content(req.body, "text/plain");
  2862. })
  2863. .Patch("/patch",
  2864. [&](const Request &req, Response &res) {
  2865. EXPECT_EQ(req.body, "PATCH");
  2866. res.set_content(req.body, "text/plain");
  2867. })
  2868. .Delete("/delete",
  2869. [&](const Request & /*req*/, Response &res) {
  2870. res.set_content("DELETE", "text/plain");
  2871. })
  2872. .Delete("/delete-body",
  2873. [&](const Request &req, Response &res) {
  2874. EXPECT_EQ(req.body, "content");
  2875. res.set_content(req.body, "text/plain");
  2876. })
  2877. .Options(R"(\*)",
  2878. [&](const Request & /*req*/, Response &res) {
  2879. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2880. })
  2881. .Get("/request-target",
  2882. [&](const Request &req, Response & /*res*/) {
  2883. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2884. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2885. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2886. })
  2887. .Get("/long-query-value",
  2888. [&](const Request &req, Response & /*res*/) {
  2889. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2890. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2891. })
  2892. .Get("/too-long-query-value",
  2893. [&](const Request &req, Response & /*res*/) {
  2894. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2895. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2896. })
  2897. .Get("/array-param",
  2898. [&](const Request &req, Response & /*res*/) {
  2899. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2900. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2901. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2902. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2903. })
  2904. .Post("/validate-no-multiple-headers",
  2905. [&](const Request &req, Response & /*res*/) {
  2906. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2907. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2908. })
  2909. .Post("/content_receiver",
  2910. [&](const Request &req, Response &res,
  2911. const ContentReader &content_reader) {
  2912. if (req.is_multipart_form_data()) {
  2913. std::vector<FormData> items;
  2914. content_reader(
  2915. [&](const FormData &file) {
  2916. items.push_back(file);
  2917. return true;
  2918. },
  2919. [&](const char *data, size_t data_length) {
  2920. items.back().content.append(data, data_length);
  2921. return true;
  2922. });
  2923. EXPECT_EQ(5u, items.size());
  2924. {
  2925. const auto &file = get_file_value(items, "text1");
  2926. EXPECT_TRUE(file.filename.empty());
  2927. EXPECT_EQ("text default", file.content);
  2928. }
  2929. {
  2930. const auto &file = get_file_value(items, "text2");
  2931. EXPECT_TRUE(file.filename.empty());
  2932. EXPECT_EQ("aωb", file.content);
  2933. }
  2934. {
  2935. const auto &file = get_file_value(items, "file1");
  2936. EXPECT_EQ("hello.txt", file.filename);
  2937. EXPECT_EQ("text/plain", file.content_type);
  2938. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2939. }
  2940. {
  2941. const auto &file = get_file_value(items, "file2");
  2942. EXPECT_EQ("world.json", file.filename);
  2943. EXPECT_EQ("application/json", file.content_type);
  2944. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2945. }
  2946. {
  2947. const auto &file = get_file_value(items, "file3");
  2948. EXPECT_TRUE(file.filename.empty());
  2949. EXPECT_EQ("application/octet-stream", file.content_type);
  2950. EXPECT_EQ(0u, file.content.size());
  2951. }
  2952. } else {
  2953. std::string body;
  2954. content_reader([&](const char *data, size_t data_length) {
  2955. EXPECT_EQ(7U, data_length);
  2956. body.append(data, data_length);
  2957. return true;
  2958. });
  2959. EXPECT_EQ(body, "content");
  2960. res.set_content(body, "text/plain");
  2961. }
  2962. })
  2963. .Put("/content_receiver",
  2964. [&](const Request & /*req*/, Response &res,
  2965. const ContentReader &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. EXPECT_EQ(body, "content");
  2972. res.set_content(body, "text/plain");
  2973. })
  2974. .Patch("/content_receiver",
  2975. [&](const Request & /*req*/, Response &res,
  2976. const ContentReader &content_reader) {
  2977. std::string body;
  2978. content_reader([&](const char *data, size_t data_length) {
  2979. body.append(data, data_length);
  2980. return true;
  2981. });
  2982. EXPECT_EQ(body, "content");
  2983. res.set_content(body, "text/plain");
  2984. })
  2985. .Post("/query-string-and-body",
  2986. [&](const Request &req, Response & /*res*/) {
  2987. ASSERT_TRUE(req.has_param("key"));
  2988. EXPECT_EQ(req.get_param_value("key"), "value");
  2989. EXPECT_EQ(req.body, "content");
  2990. })
  2991. .Get("/last-request",
  2992. [&](const Request &req, Response & /*res*/) {
  2993. EXPECT_EQ("close", req.get_header_value("Connection"));
  2994. })
  2995. .Get(R"(/redirect/(\d+))",
  2996. [&](const Request &req, Response &res) {
  2997. auto num = std::stoi(req.matches[1]) + 1;
  2998. std::string url = "/redirect/" + std::to_string(num);
  2999. res.set_redirect(url);
  3000. })
  3001. .Post("/binary",
  3002. [&](const Request &req, Response &res) {
  3003. EXPECT_EQ(4U, req.body.size());
  3004. EXPECT_EQ("application/octet-stream",
  3005. req.get_header_value("Content-Type"));
  3006. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3007. res.set_content(req.body, "application/octet-stream");
  3008. })
  3009. .Put("/binary",
  3010. [&](const Request &req, Response &res) {
  3011. EXPECT_EQ(4U, req.body.size());
  3012. EXPECT_EQ("application/octet-stream",
  3013. req.get_header_value("Content-Type"));
  3014. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3015. res.set_content(req.body, "application/octet-stream");
  3016. })
  3017. .Patch("/binary",
  3018. [&](const Request &req, Response &res) {
  3019. EXPECT_EQ(4U, req.body.size());
  3020. EXPECT_EQ("application/octet-stream",
  3021. req.get_header_value("Content-Type"));
  3022. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3023. res.set_content(req.body, "application/octet-stream");
  3024. })
  3025. .Delete("/binary",
  3026. [&](const Request &req, Response &res) {
  3027. EXPECT_EQ(4U, req.body.size());
  3028. EXPECT_EQ("application/octet-stream",
  3029. req.get_header_value("Content-Type"));
  3030. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3031. res.set_content(req.body, "application/octet-stream");
  3032. })
  3033. .Get("/issue1772",
  3034. [&](const Request & /*req*/, Response &res) {
  3035. res.status = 401;
  3036. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3037. })
  3038. .Delete("/issue609",
  3039. [](const httplib::Request &, httplib::Response &res,
  3040. const httplib::ContentReader &) {
  3041. res.set_content("ok", "text/plain");
  3042. })
  3043. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3044. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3045. .Get("/compress",
  3046. [&](const Request & /*req*/, Response &res) {
  3047. res.set_content(
  3048. "12345678901234567890123456789012345678901234567890123456789"
  3049. "01234567890123456789012345678901234567890",
  3050. "text/plain");
  3051. })
  3052. .Get("/nocompress",
  3053. [&](const Request & /*req*/, Response &res) {
  3054. res.set_content(
  3055. "12345678901234567890123456789012345678901234567890123456789"
  3056. "01234567890123456789012345678901234567890",
  3057. "application/octet-stream");
  3058. })
  3059. .Post("/compress-multipart",
  3060. [&](const Request &req, Response & /*res*/) {
  3061. EXPECT_EQ(2u, req.form.fields.size());
  3062. ASSERT_TRUE(!req.form.has_field("???"));
  3063. {
  3064. const auto &text = req.form.get_field("key1");
  3065. EXPECT_EQ("test", text);
  3066. }
  3067. {
  3068. const auto &text = req.form.get_field("key2");
  3069. EXPECT_EQ("--abcdefg123", text);
  3070. }
  3071. })
  3072. #endif
  3073. ;
  3074. persons_["john"] = "programmer";
  3075. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3076. svr_.wait_until_ready();
  3077. }
  3078. virtual void TearDown() {
  3079. svr_.stop();
  3080. if (!request_threads_.empty()) {
  3081. std::this_thread::sleep_for(std::chrono::seconds(1));
  3082. for (auto &t : request_threads_) {
  3083. t.join();
  3084. }
  3085. }
  3086. t_.join();
  3087. }
  3088. map<string, string> persons_;
  3089. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3090. SSLClient cli_;
  3091. SSLServer svr_;
  3092. #else
  3093. Client cli_;
  3094. Server svr_;
  3095. #endif
  3096. thread t_;
  3097. std::vector<thread> request_threads_;
  3098. };
  3099. TEST_F(ServerTest, GetMethod200) {
  3100. auto res = cli_.Get("/hi");
  3101. ASSERT_TRUE(res);
  3102. EXPECT_EQ("HTTP/1.1", res->version);
  3103. EXPECT_EQ(StatusCode::OK_200, res->status);
  3104. EXPECT_EQ("OK", res->reason);
  3105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3106. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3107. EXPECT_EQ("Hello World!", res->body);
  3108. }
  3109. TEST_F(ServerTest, GetEmptyFile) {
  3110. auto res = cli_.Get("/empty_file");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3114. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3115. EXPECT_EQ("", res->body);
  3116. }
  3117. TEST_F(ServerTest, GetFileContent) {
  3118. auto res = cli_.Get("/file_content");
  3119. ASSERT_TRUE(res);
  3120. EXPECT_EQ(StatusCode::OK_200, res->status);
  3121. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3122. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3123. EXPECT_EQ("test.html", res->body);
  3124. }
  3125. TEST_F(ServerTest, GetFileContentWithRange) {
  3126. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3127. ASSERT_TRUE(res);
  3128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3129. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3130. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3131. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3132. EXPECT_EQ("est", res->body);
  3133. }
  3134. TEST_F(ServerTest, GetFileContentWithContentType) {
  3135. auto res = cli_.Get("/file_content_with_content_type");
  3136. ASSERT_TRUE(res);
  3137. EXPECT_EQ(StatusCode::OK_200, res->status);
  3138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3139. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3140. EXPECT_EQ("file\n", res->body);
  3141. }
  3142. TEST_F(ServerTest, GetInvalidFileContent) {
  3143. auto res = cli_.Get("/invalid_file_content");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3146. }
  3147. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3148. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3149. ASSERT_TRUE(res);
  3150. EXPECT_EQ("HTTP/1.1", res->version);
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3153. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3154. EXPECT_EQ("Hello World!", res->body);
  3155. }
  3156. TEST_F(ServerTest, GetMethod302) {
  3157. auto res = cli_.Get("/");
  3158. ASSERT_TRUE(res);
  3159. EXPECT_EQ(StatusCode::Found_302, res->status);
  3160. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3161. }
  3162. TEST_F(ServerTest, GetMethod302Redirect) {
  3163. cli_.set_follow_location(true);
  3164. auto res = cli_.Get("/");
  3165. ASSERT_TRUE(res);
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. EXPECT_EQ("Hello World!", res->body);
  3168. EXPECT_EQ("/hi", res->location);
  3169. }
  3170. TEST_F(ServerTest, GetMethod404) {
  3171. auto res = cli_.Get("/invalid");
  3172. ASSERT_TRUE(res);
  3173. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3174. }
  3175. TEST_F(ServerTest, HeadMethod200) {
  3176. auto res = cli_.Head("/hi");
  3177. ASSERT_TRUE(res);
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3180. EXPECT_TRUE(res->body.empty());
  3181. }
  3182. TEST_F(ServerTest, HeadMethod200Static) {
  3183. auto res = cli_.Head("/mount/dir/index.html");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ(StatusCode::OK_200, res->status);
  3186. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3187. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3188. EXPECT_TRUE(res->body.empty());
  3189. }
  3190. TEST_F(ServerTest, HeadMethod404) {
  3191. auto res = cli_.Head("/invalid");
  3192. ASSERT_TRUE(res);
  3193. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3194. EXPECT_TRUE(res->body.empty());
  3195. }
  3196. TEST_F(ServerTest, GetMethodPersonJohn) {
  3197. auto res = cli_.Get("/person/john");
  3198. ASSERT_TRUE(res);
  3199. EXPECT_EQ(StatusCode::OK_200, res->status);
  3200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3201. EXPECT_EQ("programmer", res->body);
  3202. }
  3203. TEST_F(ServerTest, PostMethod1) {
  3204. auto res = cli_.Get("/person/john1");
  3205. ASSERT_TRUE(res);
  3206. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3207. res = cli_.Post("/person", "name=john1&note=coder",
  3208. "application/x-www-form-urlencoded");
  3209. ASSERT_TRUE(res);
  3210. ASSERT_EQ(StatusCode::OK_200, res->status);
  3211. res = cli_.Get("/person/john1");
  3212. ASSERT_TRUE(res);
  3213. ASSERT_EQ(StatusCode::OK_200, res->status);
  3214. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3215. ASSERT_EQ("coder", res->body);
  3216. }
  3217. TEST_F(ServerTest, PostMethod2) {
  3218. auto res = cli_.Get("/person/john2");
  3219. ASSERT_TRUE(res);
  3220. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3221. Params params;
  3222. params.emplace("name", "john2");
  3223. params.emplace("note", "coder");
  3224. res = cli_.Post("/person", params);
  3225. ASSERT_TRUE(res);
  3226. ASSERT_EQ(StatusCode::OK_200, res->status);
  3227. res = cli_.Get("/person/john2");
  3228. ASSERT_TRUE(res);
  3229. ASSERT_EQ(StatusCode::OK_200, res->status);
  3230. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3231. ASSERT_EQ("coder", res->body);
  3232. }
  3233. TEST_F(ServerTest, PutMethod3) {
  3234. auto res = cli_.Get("/person/john3");
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3237. Params params;
  3238. params.emplace("name", "john3");
  3239. params.emplace("note", "coder");
  3240. res = cli_.Put("/person", params);
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. res = cli_.Get("/person/john3");
  3244. ASSERT_TRUE(res);
  3245. ASSERT_EQ(StatusCode::OK_200, res->status);
  3246. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3247. ASSERT_EQ("coder", res->body);
  3248. }
  3249. TEST_F(ServerTest, DeleteMethod1) {
  3250. auto res = cli_.Get("/person/john4");
  3251. ASSERT_TRUE(res);
  3252. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3253. Params params;
  3254. params.emplace("name", "john4");
  3255. params.emplace("note", "coder");
  3256. res = cli_.Post("/person", params);
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. res = cli_.Get("/person/john4");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::OK_200, res->status);
  3262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. ASSERT_EQ("coder", res->body);
  3264. Params delete_params;
  3265. delete_params.emplace("name", "john4");
  3266. res = cli_.Delete("/person", delete_params);
  3267. ASSERT_TRUE(res);
  3268. ASSERT_EQ(StatusCode::OK_200, res->status);
  3269. ASSERT_EQ("DELETED", res->body);
  3270. res = cli_.Get("/person/john4");
  3271. ASSERT_TRUE(res);
  3272. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3273. }
  3274. TEST_F(ServerTest, DeleteMethod2) {
  3275. auto res = cli_.Get("/person/john5");
  3276. ASSERT_TRUE(res);
  3277. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3278. Params params;
  3279. params.emplace("name", "john5");
  3280. params.emplace("note", "developer");
  3281. res = cli_.Post("/person", params);
  3282. ASSERT_TRUE(res);
  3283. ASSERT_EQ(StatusCode::OK_200, res->status);
  3284. res = cli_.Get("/person/john5");
  3285. ASSERT_TRUE(res);
  3286. ASSERT_EQ(StatusCode::OK_200, res->status);
  3287. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3288. ASSERT_EQ("developer", res->body);
  3289. Params delete_params;
  3290. delete_params.emplace("name", "john5");
  3291. Headers headers;
  3292. headers.emplace("Custom-Header", "test-value");
  3293. res = cli_.Delete("/person", headers, delete_params);
  3294. ASSERT_TRUE(res);
  3295. ASSERT_EQ(StatusCode::OK_200, res->status);
  3296. ASSERT_EQ("DELETED", res->body);
  3297. res = cli_.Get("/person/john5");
  3298. ASSERT_TRUE(res);
  3299. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3300. }
  3301. TEST_F(ServerTest, DeleteMethod3) {
  3302. auto res = cli_.Get("/person/john6");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3305. Params params;
  3306. params.emplace("name", "john6");
  3307. params.emplace("note", "tester");
  3308. res = cli_.Post("/person", params);
  3309. ASSERT_TRUE(res);
  3310. ASSERT_EQ(StatusCode::OK_200, res->status);
  3311. res = cli_.Get("/person/john6");
  3312. ASSERT_TRUE(res);
  3313. ASSERT_EQ(StatusCode::OK_200, res->status);
  3314. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3315. ASSERT_EQ("tester", res->body);
  3316. Params delete_params;
  3317. delete_params.emplace("name", "john6");
  3318. Headers headers;
  3319. headers.emplace("Custom-Header", "test-value");
  3320. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3321. ASSERT_TRUE(res);
  3322. ASSERT_EQ(StatusCode::OK_200, res->status);
  3323. ASSERT_EQ("DELETED", res->body);
  3324. res = cli_.Get("/person/john6");
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3327. }
  3328. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3329. Params params;
  3330. params.emplace("json", JSON_DATA);
  3331. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ(JSON_DATA, res->body);
  3335. }
  3336. TEST_F(ServerTest, PostEmptyContent) {
  3337. auto res = cli_.Post("/empty", "", "text/plain");
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. ASSERT_EQ("empty", res->body);
  3341. }
  3342. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3343. auto res = cli_.Post("/empty-no-content-type");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("empty-no-content-type", res->body);
  3347. }
  3348. TEST_F(ServerTest, PostPathOnly) {
  3349. auto res = cli_.Post("/path-only");
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("path-only", res->body);
  3353. }
  3354. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3355. auto res = cli_.Post("/path-headers-only",
  3356. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3357. ASSERT_TRUE(res);
  3358. ASSERT_EQ(StatusCode::OK_200, res->status);
  3359. ASSERT_EQ("path-headers-only", res->body);
  3360. }
  3361. TEST_F(ServerTest, PostLarge) {
  3362. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3363. ASSERT_TRUE(res);
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. EXPECT_EQ(LARGE_DATA, res->body);
  3366. }
  3367. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3368. auto res = cli_.Put("/empty-no-content-type");
  3369. ASSERT_TRUE(res);
  3370. ASSERT_EQ(StatusCode::OK_200, res->status);
  3371. ASSERT_EQ("empty-no-content-type", res->body);
  3372. }
  3373. TEST_F(ServerTest, GetMethodDir) {
  3374. auto res = cli_.Get("/dir/");
  3375. ASSERT_TRUE(res);
  3376. EXPECT_EQ(StatusCode::OK_200, res->status);
  3377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3378. auto body = R"(<html>
  3379. <head>
  3380. </head>
  3381. <body>
  3382. <a href="/dir/test.html">Test</a>
  3383. <a href="/hi">hi</a>
  3384. </body>
  3385. </html>
  3386. )";
  3387. EXPECT_EQ(body, res->body);
  3388. }
  3389. TEST_F(ServerTest, GetMethodDirTest) {
  3390. auto res = cli_.Get("/dir/test.html");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::OK_200, res->status);
  3393. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3394. EXPECT_EQ("test.html", res->body);
  3395. }
  3396. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3397. auto res = cli_.Get("/dir/../dir/test.html");
  3398. ASSERT_TRUE(res);
  3399. EXPECT_EQ(StatusCode::OK_200, res->status);
  3400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3401. EXPECT_EQ("test.html", res->body);
  3402. }
  3403. TEST_F(ServerTest, GetMethodInvalidPath) {
  3404. auto res = cli_.Get("/dir/../test.html");
  3405. ASSERT_TRUE(res);
  3406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3407. }
  3408. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3409. auto res = cli_.Get("/../www/dir/test.html");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3412. }
  3413. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3414. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3415. ASSERT_TRUE(res);
  3416. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3417. }
  3418. TEST_F(ServerTest, GetMethodDirMountTest) {
  3419. auto res = cli_.Get("/mount/dir/test.html");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3423. EXPECT_EQ("test.html", res->body);
  3424. }
  3425. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3426. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3427. ASSERT_TRUE(res);
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3430. EXPECT_EQ("test.html", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3433. auto res = cli_.Get("/mount/dir/../test.html");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3436. }
  3437. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3438. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3441. }
  3442. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3443. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3446. }
  3447. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3448. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3451. }
  3452. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3453. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3454. ASSERT_TRUE(res);
  3455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3456. }
  3457. TEST_F(ServerTest, PostMethod303) {
  3458. auto res = cli_.Post("/1", "body", "text/plain");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3461. EXPECT_EQ("/2", res->get_header_value("Location"));
  3462. }
  3463. TEST_F(ServerTest, PostMethod303Redirect) {
  3464. cli_.set_follow_location(true);
  3465. auto res = cli_.Post("/1", "body", "text/plain");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("redirected.", res->body);
  3469. EXPECT_EQ("/2", res->location);
  3470. }
  3471. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3472. auto res = cli_.Get("/dir/test.abcde");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(StatusCode::OK_200, res->status);
  3475. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3476. EXPECT_EQ("abcde", res->body);
  3477. }
  3478. TEST_F(ServerTest, StaticFileRange) {
  3479. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3480. ASSERT_TRUE(res);
  3481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3482. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3483. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3484. EXPECT_EQ(true, res->has_header("Content-Range"));
  3485. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3486. EXPECT_EQ(std::string("cd"), res->body);
  3487. }
  3488. TEST_F(ServerTest, StaticFileRanges) {
  3489. auto res =
  3490. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3491. ASSERT_TRUE(res);
  3492. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3493. EXPECT_TRUE(
  3494. res->get_header_value("Content-Type")
  3495. .find(
  3496. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3497. 0);
  3498. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3499. }
  3500. TEST_F(ServerTest, StaticFileRangeHead) {
  3501. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3504. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3505. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3506. EXPECT_EQ(true, res->has_header("Content-Range"));
  3507. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3508. }
  3509. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3510. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3513. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3515. EXPECT_EQ(true, res->has_header("Content-Range"));
  3516. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3517. res->get_header_value("Content-Range"));
  3518. EXPECT_EQ("LAST\n", res->body);
  3519. }
  3520. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3521. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3525. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3526. EXPECT_EQ(true, res->has_header("Content-Range"));
  3527. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3528. }
  3529. TEST_F(ServerTest, StaticFileBigFile) {
  3530. auto res = cli_.Get("/dir/1MB.txt");
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::OK_200, res->status);
  3533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3534. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3535. }
  3536. TEST_F(ServerTest, InvalidBaseDirMount) {
  3537. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3538. }
  3539. TEST_F(ServerTest, Binary) {
  3540. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3541. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3542. "application/octet-stream");
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::OK_200, res->status);
  3545. ASSERT_EQ(4U, res->body.size());
  3546. res = cli_.Put("/binary", binary.data(), binary.size(),
  3547. "application/octet-stream");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ(4U, res->body.size());
  3551. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3552. "application/octet-stream");
  3553. ASSERT_TRUE(res);
  3554. ASSERT_EQ(StatusCode::OK_200, res->status);
  3555. ASSERT_EQ(4U, res->body.size());
  3556. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3557. "application/octet-stream");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ(4U, res->body.size());
  3561. }
  3562. TEST_F(ServerTest, BinaryString) {
  3563. auto binary = std::string("\x00\x01\x02\x03", 4);
  3564. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3565. ASSERT_TRUE(res);
  3566. ASSERT_EQ(StatusCode::OK_200, res->status);
  3567. ASSERT_EQ(4U, res->body.size());
  3568. res = cli_.Put("/binary", binary, "application/octet-stream");
  3569. ASSERT_TRUE(res);
  3570. ASSERT_EQ(StatusCode::OK_200, res->status);
  3571. ASSERT_EQ(4U, res->body.size());
  3572. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3573. ASSERT_TRUE(res);
  3574. ASSERT_EQ(StatusCode::OK_200, res->status);
  3575. ASSERT_EQ(4U, res->body.size());
  3576. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ(4U, res->body.size());
  3580. }
  3581. TEST_F(ServerTest, EmptyRequest) {
  3582. auto res = cli_.Get("");
  3583. ASSERT_TRUE(!res);
  3584. EXPECT_EQ(Error::Connection, res.error());
  3585. }
  3586. TEST_F(ServerTest, LongRequest) {
  3587. std::string request;
  3588. for (size_t i = 0; i < 545; i++) {
  3589. request += "/TooLongRequest";
  3590. }
  3591. request += "OK";
  3592. auto res = cli_.Get(request.c_str());
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3595. }
  3596. TEST_F(ServerTest, TooLongRequest) {
  3597. std::string request;
  3598. for (size_t i = 0; i < 546; i++) {
  3599. request += "/TooLongRequest";
  3600. }
  3601. request += "_NG";
  3602. auto res = cli_.Get(request.c_str());
  3603. ASSERT_TRUE(res);
  3604. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3605. }
  3606. TEST_F(ServerTest, AlmostTooLongRequest) {
  3607. // test for #2046 - URI length check shouldn't include other content on req
  3608. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3609. // leading /, space, HTTP/1.1)
  3610. std::string request =
  3611. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3612. auto res = cli_.Get(request.c_str());
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3615. }
  3616. TEST_F(ServerTest, LongHeader) {
  3617. Request req;
  3618. req.method = "GET";
  3619. req.path = "/hi";
  3620. std::string host_and_port;
  3621. host_and_port += HOST;
  3622. host_and_port += ":";
  3623. host_and_port += std::to_string(PORT);
  3624. req.headers.emplace("Host", host_and_port.c_str());
  3625. req.headers.emplace("Accept", "*/*");
  3626. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3627. req.headers.emplace(
  3628. "Header-Name",
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3657. "@@@@@@@@@@@@@@@@");
  3658. auto res = std::make_shared<Response>();
  3659. auto error = Error::Success;
  3660. auto ret = cli_.send(req, *res, error);
  3661. ASSERT_TRUE(ret);
  3662. EXPECT_EQ(StatusCode::OK_200, res->status);
  3663. }
  3664. TEST_F(ServerTest, LongQueryValue) {
  3665. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3668. }
  3669. TEST_F(ServerTest, TooLongQueryValue) {
  3670. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3671. ASSERT_FALSE(res);
  3672. EXPECT_EQ(Error::Read, res.error());
  3673. }
  3674. TEST_F(ServerTest, TooLongHeader) {
  3675. Request req;
  3676. req.method = "GET";
  3677. req.path = "/hi";
  3678. std::string host_and_port;
  3679. host_and_port += HOST;
  3680. host_and_port += ":";
  3681. host_and_port += std::to_string(PORT);
  3682. req.headers.emplace("Host", host_and_port.c_str());
  3683. req.headers.emplace("Accept", "*/*");
  3684. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3685. req.headers.emplace(
  3686. "Header-Name",
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3715. "@@@@@@@@@@@@@@@@@");
  3716. auto res = std::make_shared<Response>();
  3717. auto error = Error::Success;
  3718. auto ret = cli_.send(req, *res, error);
  3719. ASSERT_TRUE(ret);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. }
  3722. TEST_F(ServerTest, HeaderCountAtLimit) {
  3723. // Test with headers just under the 100 limit
  3724. httplib::Headers headers;
  3725. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3726. // This should keep us just under the 100 header limit
  3727. for (int i = 0; i < 95; i++) {
  3728. std::string name = "X-Test-Header-" + std::to_string(i);
  3729. std::string value = "value" + std::to_string(i);
  3730. headers.emplace(name, value);
  3731. }
  3732. // This should work fine as we're under the limit
  3733. auto res = cli_.Get("/hi", headers);
  3734. EXPECT_TRUE(res);
  3735. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3736. }
  3737. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3738. // Test with many headers to exceed the 100 limit
  3739. httplib::Headers headers;
  3740. // Add 150 headers to definitely exceed the 100 limit
  3741. for (int i = 0; i < 150; i++) {
  3742. std::string name = "X-Test-Header-" + std::to_string(i);
  3743. std::string value = "value" + std::to_string(i);
  3744. headers.emplace(name, value);
  3745. }
  3746. // This should fail due to exceeding header count limit
  3747. auto res = cli_.Get("/hi", headers);
  3748. // The request should either fail or return 400 Bad Request
  3749. if (res) {
  3750. // If we get a response, it should be 400 Bad Request
  3751. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3752. } else {
  3753. // Or the request should fail entirely
  3754. EXPECT_FALSE(res);
  3755. }
  3756. }
  3757. TEST_F(ServerTest, PercentEncoding) {
  3758. auto res = cli_.Get("/e%6edwith%");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. }
  3762. TEST_F(ServerTest, PercentEncodingUnicode) {
  3763. auto res = cli_.Get("/e%u006edwith%");
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. }
  3767. TEST_F(ServerTest, InvalidPercentEncoding) {
  3768. auto res = cli_.Get("/%endwith%");
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3771. }
  3772. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3773. auto res = cli_.Get("/%uendwith%");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3776. }
  3777. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3778. auto res = cli_.Get("/hello?aaa=bbb%");
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3781. }
  3782. TEST_F(ServerTest, PlusSignEncoding) {
  3783. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3784. ASSERT_TRUE(res);
  3785. EXPECT_EQ(StatusCode::OK_200, res->status);
  3786. EXPECT_EQ("a +b", res->body);
  3787. }
  3788. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3789. // This test simulates a potential DoS attack using many headers
  3790. // to verify our security fix prevents memory exhaustion
  3791. httplib::Headers attack_headers;
  3792. // Attempt to add many headers like an attacker would (200 headers to far
  3793. // exceed limit)
  3794. for (int i = 0; i < 200; i++) {
  3795. std::string name = "X-Attack-Header-" + std::to_string(i);
  3796. std::string value = "attack_payload_" + std::to_string(i);
  3797. attack_headers.emplace(name, value);
  3798. }
  3799. // Try to POST with excessive headers
  3800. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3801. // Should either fail or return 400 Bad Request due to security limit
  3802. if (res) {
  3803. // If we get a response, it should be 400 Bad Request
  3804. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3805. } else {
  3806. // Request failed, which is the expected behavior for DoS protection
  3807. EXPECT_FALSE(res);
  3808. }
  3809. }
  3810. TEST_F(ServerTest, MultipartFormData) {
  3811. UploadFormDataItems items = {
  3812. {"text1", "text default", "", ""},
  3813. {"text2", "aωb", "", ""},
  3814. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3815. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3816. {"file3", "", "", "application/octet-stream"},
  3817. {"file4", "", "", " application/json tmp-string "}};
  3818. auto res = cli_.Post("/multipart", items);
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. }
  3822. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3823. UploadFormDataItems items = {
  3824. {"text", "default text", "", ""},
  3825. {"multi_text1", "aaaaa", "", ""},
  3826. {"multi_text1", "bbbbb", "", ""},
  3827. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3828. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3829. "application/json"},
  3830. };
  3831. auto res = cli_.Post("/multipart/multi_file_values", items);
  3832. ASSERT_TRUE(res);
  3833. EXPECT_EQ(StatusCode::OK_200, res->status);
  3834. }
  3835. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3836. auto res = cli_.Get("/hi");
  3837. ASSERT_TRUE(res);
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3840. EXPECT_EQ("Hello World!", res->body);
  3841. }
  3842. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3843. Request req;
  3844. req.method = "POST";
  3845. req.path = "/chunked";
  3846. std::string host_and_port;
  3847. host_and_port += HOST;
  3848. host_and_port += ":";
  3849. host_and_port += std::to_string(PORT);
  3850. req.headers.emplace("Host", host_and_port.c_str());
  3851. req.headers.emplace("Accept", "*/*");
  3852. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3853. req.headers.emplace("Content-Type", "text/plain");
  3854. req.headers.emplace("Content-Length", "0");
  3855. req.headers.emplace(
  3856. "Transfer-Encoding",
  3857. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3858. // Client does not chunk, so make a chunked body manually.
  3859. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3860. auto res = std::make_shared<Response>();
  3861. auto error = Error::Success;
  3862. auto ret = cli_.send(req, *res, error);
  3863. ASSERT_TRUE(ret);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetStreamed2) {
  3867. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3870. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3871. EXPECT_EQ(true, res->has_header("Content-Range"));
  3872. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3873. EXPECT_EQ(std::string("ab"), res->body);
  3874. }
  3875. TEST_F(ServerTest, GetStreamed) {
  3876. auto res = cli_.Get("/streamed");
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3880. EXPECT_EQ(std::string("aaabbb"), res->body);
  3881. }
  3882. TEST_F(ServerTest, GetStreamedWithRange1) {
  3883. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3884. ASSERT_TRUE(res);
  3885. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3886. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3887. EXPECT_EQ(true, res->has_header("Content-Range"));
  3888. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3889. EXPECT_EQ(std::string("def"), res->body);
  3890. }
  3891. TEST_F(ServerTest, GetStreamedWithRange2) {
  3892. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3896. EXPECT_EQ(true, res->has_header("Content-Range"));
  3897. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3898. EXPECT_EQ(std::string("bcdefg"), res->body);
  3899. }
  3900. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3901. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3904. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3905. EXPECT_EQ(true, res->has_header("Content-Range"));
  3906. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3907. EXPECT_EQ(std::string("efg"), res->body);
  3908. }
  3909. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3910. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3913. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3914. EXPECT_EQ(false, res->has_header("Content-Range"));
  3915. EXPECT_EQ(0U, res->body.size());
  3916. }
  3917. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3918. auto res = cli_.Get("/streamed-with-range",
  3919. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3920. "92233720368547758079223372036854775807"}});
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3923. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3924. EXPECT_EQ(false, res->has_header("Content-Range"));
  3925. EXPECT_EQ(0U, res->body.size());
  3926. }
  3927. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3928. auto res = cli_.Get(
  3929. "/with-range",
  3930. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3931. {"Accept-Encoding", ""}});
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3934. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3935. EXPECT_EQ(true, res->has_header("Content-Range"));
  3936. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3937. EXPECT_EQ(std::string("abcdefg"), res->body);
  3938. }
  3939. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3940. auto res = cli_.Get("/with-range", {
  3941. {"Range", "bytes=0-"},
  3942. {"Accept-Encoding", ""},
  3943. });
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3946. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3947. EXPECT_EQ(true, res->has_header("Content-Range"));
  3948. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3949. EXPECT_EQ(std::string("abcdefg"), res->body);
  3950. }
  3951. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3952. auto res =
  3953. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3956. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3957. EXPECT_EQ(false, res->has_header("Content-Range"));
  3958. EXPECT_EQ(267U, res->body.size());
  3959. // Check that both range contents are present
  3960. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3961. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3962. // Check that Content-Range headers are present for both ranges
  3963. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3964. std::string::npos);
  3965. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3966. std::string::npos);
  3967. }
  3968. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3969. Ranges ranges;
  3970. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3971. ranges.emplace_back(0, -1);
  3972. }
  3973. auto res =
  3974. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3977. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(false, res->has_header("Content-Range"));
  3979. EXPECT_EQ(0U, res->body.size());
  3980. }
  3981. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3982. auto res =
  3983. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3986. EXPECT_EQ(5U, res->body.size());
  3987. // Check that overlapping ranges are coalesced into a single range
  3988. EXPECT_EQ("bcdef", res->body);
  3989. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3990. // Should be single range, not multipart
  3991. EXPECT_TRUE(res->has_header("Content-Range"));
  3992. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3993. }
  3994. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3995. auto res =
  3996. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3999. EXPECT_EQ(268U, res->body.size());
  4000. // Check that both range contents are present
  4001. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4002. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4003. // Check that Content-Range headers are present for both ranges
  4004. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4005. std::string::npos);
  4006. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4007. std::string::npos);
  4008. }
  4009. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4010. auto res =
  4011. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4012. ASSERT_TRUE(res);
  4013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4014. EXPECT_EQ(269U, res->body.size());
  4015. // Check that both duplicate range contents are present
  4016. size_t first_abc = res->body.find("abc\r\n");
  4017. EXPECT_TRUE(first_abc != std::string::npos);
  4018. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4019. EXPECT_TRUE(second_abc != std::string::npos);
  4020. // Check that Content-Range headers are present for both ranges
  4021. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4022. EXPECT_TRUE(first_range != std::string::npos);
  4023. size_t second_range =
  4024. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4025. EXPECT_TRUE(second_range != std::string::npos);
  4026. }
  4027. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4028. auto res = cli_.Get("/streamed-with-range?error",
  4029. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4030. ASSERT_TRUE(res);
  4031. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4032. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4033. EXPECT_EQ(false, res->has_header("Content-Range"));
  4034. EXPECT_EQ(0U, res->body.size());
  4035. }
  4036. TEST_F(ServerTest, GetStreamedEndless) {
  4037. uint64_t offset = 0;
  4038. auto res = cli_.Get("/streamed-cancel",
  4039. [&](const char * /*data*/, uint64_t data_length) {
  4040. if (offset < 100) {
  4041. offset += data_length;
  4042. return true;
  4043. }
  4044. return false;
  4045. });
  4046. ASSERT_TRUE(!res);
  4047. EXPECT_EQ(Error::Canceled, res.error());
  4048. }
  4049. TEST_F(ServerTest, ClientStop) {
  4050. std::atomic_size_t count{4};
  4051. std::vector<std::thread> threads;
  4052. for (auto i = count.load(); i != 0; --i) {
  4053. threads.emplace_back([&]() {
  4054. auto res = cli_.Get("/streamed-cancel",
  4055. [&](const char *, uint64_t) { return true; });
  4056. --count;
  4057. ASSERT_TRUE(!res);
  4058. EXPECT_TRUE(res.error() == Error::Canceled ||
  4059. res.error() == Error::Read || res.error() == Error::Write);
  4060. });
  4061. }
  4062. std::this_thread::sleep_for(std::chrono::seconds(2));
  4063. while (count != 0) {
  4064. cli_.stop();
  4065. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4066. }
  4067. for (auto &t : threads) {
  4068. t.join();
  4069. }
  4070. }
  4071. TEST_F(ServerTest, GetWithRange1) {
  4072. auto res = cli_.Get("/with-range", {
  4073. make_range_header({{3, 5}}),
  4074. {"Accept-Encoding", ""},
  4075. });
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4079. EXPECT_EQ(true, res->has_header("Content-Range"));
  4080. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4081. EXPECT_EQ(std::string("def"), res->body);
  4082. }
  4083. TEST_F(ServerTest, GetWithRange2) {
  4084. auto res = cli_.Get("/with-range", {
  4085. make_range_header({{1, -1}}),
  4086. {"Accept-Encoding", ""},
  4087. });
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4090. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4091. EXPECT_EQ(true, res->has_header("Content-Range"));
  4092. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4093. EXPECT_EQ(std::string("bcdefg"), res->body);
  4094. }
  4095. TEST_F(ServerTest, GetWithRange3) {
  4096. auto res = cli_.Get("/with-range", {
  4097. make_range_header({{0, 0}}),
  4098. {"Accept-Encoding", ""},
  4099. });
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4102. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(true, res->has_header("Content-Range"));
  4104. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4105. EXPECT_EQ(std::string("a"), res->body);
  4106. }
  4107. TEST_F(ServerTest, GetWithRange4) {
  4108. auto res = cli_.Get("/with-range", {
  4109. make_range_header({{-1, 2}}),
  4110. {"Accept-Encoding", ""},
  4111. });
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4114. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4115. EXPECT_EQ(true, res->has_header("Content-Range"));
  4116. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4117. EXPECT_EQ(std::string("fg"), res->body);
  4118. }
  4119. TEST_F(ServerTest, GetWithRange5) {
  4120. auto res = cli_.Get("/with-range", {
  4121. make_range_header({{0, 5}}),
  4122. {"Accept-Encoding", ""},
  4123. });
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4126. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4127. EXPECT_EQ(true, res->has_header("Content-Range"));
  4128. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4129. EXPECT_EQ(std::string("abcdef"), res->body);
  4130. }
  4131. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4132. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4135. }
  4136. TEST_F(ServerTest, GetWithRangeMultipart) {
  4137. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4138. ASSERT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4140. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4141. EXPECT_EQ(false, res->has_header("Content-Range"));
  4142. EXPECT_EQ(267U, res->body.size());
  4143. }
  4144. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4145. auto res =
  4146. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4149. }
  4150. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4151. auto res = cli_.Get("/with-range-customized-response",
  4152. {{make_range_header({{1, 2}})}});
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4155. EXPECT_EQ(true, res->has_header("Content-Length"));
  4156. EXPECT_EQ(false, res->has_header("Content-Range"));
  4157. EXPECT_EQ(JSON_DATA, res->body);
  4158. }
  4159. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4160. auto res = cli_.Get("/with-range-customized-response",
  4161. {{make_range_header({{1, 2}, {4, 5}})}});
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4164. EXPECT_EQ(true, res->has_header("Content-Length"));
  4165. EXPECT_EQ(false, res->has_header("Content-Range"));
  4166. EXPECT_EQ(JSON_DATA, res->body);
  4167. }
  4168. TEST_F(ServerTest, Issue1772) {
  4169. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4170. ASSERT_TRUE(res);
  4171. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4172. }
  4173. TEST_F(ServerTest, Issue609) {
  4174. auto res = cli_.Delete("/issue609");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. EXPECT_EQ(std::string("ok"), res->body);
  4178. }
  4179. TEST_F(ServerTest, GetStreamedChunked) {
  4180. auto res = cli_.Get("/streamed-chunked");
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::OK_200, res->status);
  4183. EXPECT_EQ(std::string("123456789"), res->body);
  4184. }
  4185. TEST_F(ServerTest, GetStreamedChunked2) {
  4186. auto res = cli_.Get("/streamed-chunked2");
  4187. ASSERT_TRUE(res);
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ(std::string("123456789"), res->body);
  4190. }
  4191. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4192. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::OK_200, res->status);
  4195. EXPECT_EQ(std::string("123456789"), res->body);
  4196. EXPECT_TRUE(res->has_header("Trailer"));
  4197. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4198. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4199. // Trailers are now stored separately from headers (security fix)
  4200. EXPECT_EQ(2U, res->trailers.size());
  4201. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4202. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4203. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4204. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4205. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4206. // Verify trailers are NOT in headers (security verification)
  4207. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4208. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4209. }
  4210. TEST_F(ServerTest, LargeChunkedPost) {
  4211. Request req;
  4212. req.method = "POST";
  4213. req.path = "/large-chunked";
  4214. std::string host_and_port;
  4215. host_and_port += HOST;
  4216. host_and_port += ":";
  4217. host_and_port += std::to_string(PORT);
  4218. req.headers.emplace("Host", host_and_port.c_str());
  4219. req.headers.emplace("Accept", "*/*");
  4220. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4221. req.headers.emplace("Content-Type", "text/plain");
  4222. req.headers.emplace("Content-Length", "0");
  4223. req.headers.emplace("Transfer-Encoding", "chunked");
  4224. std::string long_string(30 * 1024u, 'a');
  4225. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4226. // Attempt to make a large enough post to exceed OS buffers, to test that
  4227. // the server handles short reads if the full chunk data isn't available.
  4228. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4229. auto res = std::make_shared<Response>();
  4230. auto error = Error::Success;
  4231. auto ret = cli_.send(req, *res, error);
  4232. ASSERT_TRUE(ret);
  4233. EXPECT_EQ(StatusCode::OK_200, res->status);
  4234. }
  4235. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4236. auto res = cli_.Get("/remote_addr");
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(StatusCode::OK_200, res->status);
  4239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4240. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4241. }
  4242. TEST_F(ServerTest, GetMethodLocalAddr) {
  4243. auto res = cli_.Get("/local_addr");
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::OK_200, res->status);
  4246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4247. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4248. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4249. }
  4250. TEST_F(ServerTest, HTTPResponseSplitting) {
  4251. auto res = cli_.Get("/http_response_splitting");
  4252. ASSERT_TRUE(res);
  4253. EXPECT_EQ(StatusCode::OK_200, res->status);
  4254. }
  4255. TEST_F(ServerTest, SlowRequest) {
  4256. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4257. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4258. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4259. }
  4260. #if 0
  4261. TEST_F(ServerTest, SlowPost) {
  4262. char buffer[64 * 1024];
  4263. memset(buffer, 0x42, sizeof(buffer));
  4264. auto res = cli_.Post(
  4265. "/slowpost", 64 * 1024 * 1024,
  4266. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4267. auto ret = sink.write(buffer, sizeof(buffer));
  4268. EXPECT_TRUE(ret);
  4269. return true;
  4270. },
  4271. "text/plain");
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. }
  4275. TEST_F(ServerTest, SlowPostFail) {
  4276. char buffer[64 * 1024];
  4277. memset(buffer, 0x42, sizeof(buffer));
  4278. cli_.set_write_timeout(std::chrono::seconds(0));
  4279. auto res = cli_.Post(
  4280. "/slowpost", 64 * 1024 * 1024,
  4281. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4282. sink.write(buffer, sizeof(buffer));
  4283. return true;
  4284. },
  4285. "text/plain");
  4286. ASSERT_TRUE(!res);
  4287. EXPECT_EQ(Error::Write, res.error());
  4288. }
  4289. #endif
  4290. TEST_F(ServerTest, Put) {
  4291. auto res = cli_.Put("/put", "PUT", "text/plain");
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::OK_200, res->status);
  4294. EXPECT_EQ("PUT", res->body);
  4295. }
  4296. TEST_F(ServerTest, PutWithContentProvider) {
  4297. auto res = cli_.Put(
  4298. "/put", 3,
  4299. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4300. sink.os << "PUT";
  4301. return true;
  4302. },
  4303. "text/plain");
  4304. ASSERT_TRUE(res);
  4305. EXPECT_EQ(StatusCode::OK_200, res->status);
  4306. EXPECT_EQ("PUT", res->body);
  4307. }
  4308. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4309. auto res = cli_.Post(
  4310. "/post", 42,
  4311. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4312. return false;
  4313. },
  4314. "text/plain");
  4315. ASSERT_TRUE(!res);
  4316. EXPECT_EQ(Error::Canceled, res.error());
  4317. }
  4318. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4319. auto res = cli_.Put(
  4320. "/put",
  4321. [](size_t /*offset*/, DataSink &sink) {
  4322. sink.os << "PUT";
  4323. sink.done();
  4324. return true;
  4325. },
  4326. "text/plain");
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. EXPECT_EQ("PUT", res->body);
  4330. }
  4331. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4332. auto res = cli_.Post(
  4333. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4334. "text/plain");
  4335. ASSERT_TRUE(!res);
  4336. EXPECT_EQ(Error::Canceled, res.error());
  4337. }
  4338. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4339. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4340. cli_.set_compress(true);
  4341. auto res = cli_.Put(
  4342. "/put", 3,
  4343. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4344. sink.os << "PUT";
  4345. return true;
  4346. },
  4347. "text/plain");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("PUT", res->body);
  4351. }
  4352. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4353. cli_.set_compress(true);
  4354. auto res = cli_.Post(
  4355. "/post", 42,
  4356. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4357. return false;
  4358. },
  4359. "text/plain");
  4360. ASSERT_TRUE(!res);
  4361. EXPECT_EQ(Error::Canceled, res.error());
  4362. }
  4363. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4364. cli_.set_compress(true);
  4365. auto res = cli_.Put(
  4366. "/put",
  4367. [](size_t /*offset*/, DataSink &sink) {
  4368. sink.os << "PUT";
  4369. sink.done();
  4370. return true;
  4371. },
  4372. "text/plain");
  4373. ASSERT_TRUE(res);
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. EXPECT_EQ("PUT", res->body);
  4376. }
  4377. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4378. cli_.set_compress(true);
  4379. auto res = cli_.Post(
  4380. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4381. "text/plain");
  4382. ASSERT_TRUE(!res);
  4383. EXPECT_EQ(Error::Canceled, res.error());
  4384. }
  4385. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4386. cli_.set_compress(true);
  4387. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ(LARGE_DATA, res->body);
  4391. }
  4392. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4393. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4394. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4395. Client cli(s.c_str());
  4396. cli.enable_server_certificate_verification(false);
  4397. #else
  4398. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4399. Client cli(s.c_str());
  4400. #endif
  4401. cli.set_compress(true);
  4402. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4403. ASSERT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ(LARGE_DATA, res->body);
  4406. // The compressed size should be less than a 10th of the original. May vary
  4407. // depending on the zlib library.
  4408. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4409. static_cast<uint64_t>(10 * 1024 * 1024));
  4410. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4411. }
  4412. TEST_F(ServerTest, PutContentWithDeflate) {
  4413. cli_.set_compress(false);
  4414. Headers headers;
  4415. headers.emplace("Content-Encoding", "deflate");
  4416. // PUT in deflate format:
  4417. auto res = cli_.Put("/put", headers,
  4418. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. EXPECT_EQ("PUT", res->body);
  4422. }
  4423. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4424. Headers headers;
  4425. headers.emplace("Accept-Encoding", "gzip, deflate");
  4426. auto res = cli_.Get("/streamed-chunked", headers);
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::OK_200, res->status);
  4429. EXPECT_EQ(std::string("123456789"), res->body);
  4430. }
  4431. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4432. Headers headers;
  4433. headers.emplace("Accept-Encoding", "gzip, deflate");
  4434. auto res = cli_.Get("/streamed-chunked2", headers);
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. EXPECT_EQ(std::string("123456789"), res->body);
  4438. }
  4439. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4440. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4441. ASSERT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::OK_200, res->status);
  4443. }
  4444. TEST(GzipDecompressor, ChunkedDecompression) {
  4445. std::string data;
  4446. for (size_t i = 0; i < 32 * 1024; ++i) {
  4447. data.push_back(static_cast<char>('a' + i % 26));
  4448. }
  4449. std::string compressed_data;
  4450. {
  4451. httplib::detail::gzip_compressor compressor;
  4452. bool result = compressor.compress(
  4453. data.data(), data.size(),
  4454. /*last=*/true,
  4455. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4456. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4457. compressed_data_size);
  4458. return true;
  4459. });
  4460. ASSERT_TRUE(result);
  4461. }
  4462. std::string decompressed_data;
  4463. {
  4464. httplib::detail::gzip_decompressor decompressor;
  4465. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4466. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4467. size_t chunk_size = 130;
  4468. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4469. chunk_begin += chunk_size) {
  4470. size_t current_chunk_size =
  4471. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4472. bool result = decompressor.decompress(
  4473. compressed_data.data() + chunk_begin, current_chunk_size,
  4474. [&](const char *decompressed_data_chunk,
  4475. size_t decompressed_data_chunk_size) {
  4476. decompressed_data.insert(decompressed_data.size(),
  4477. decompressed_data_chunk,
  4478. decompressed_data_chunk_size);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(result);
  4482. }
  4483. }
  4484. ASSERT_EQ(data, decompressed_data);
  4485. }
  4486. TEST(GzipDecompressor, DeflateDecompression) {
  4487. std::string original_text = "Raw deflate without gzip";
  4488. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4489. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4490. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4491. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4492. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4493. std::string decompressed_data;
  4494. {
  4495. httplib::detail::gzip_decompressor decompressor;
  4496. bool result = decompressor.decompress(
  4497. compressed_data.data(), compressed_data.size(),
  4498. [&](const char *decompressed_data_chunk,
  4499. size_t decompressed_data_chunk_size) {
  4500. decompressed_data.insert(decompressed_data.size(),
  4501. decompressed_data_chunk,
  4502. decompressed_data_chunk_size);
  4503. return true;
  4504. });
  4505. ASSERT_TRUE(result);
  4506. }
  4507. ASSERT_EQ(original_text, decompressed_data);
  4508. }
  4509. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4510. std::string original_text = "Raw deflate without gzip";
  4511. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4512. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4513. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4514. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4515. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4516. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4517. std::string decompressed_data;
  4518. {
  4519. httplib::detail::gzip_decompressor decompressor;
  4520. bool result = decompressor.decompress(
  4521. compressed_data.data(), compressed_data.size(),
  4522. [&](const char *decompressed_data_chunk,
  4523. size_t decompressed_data_chunk_size) {
  4524. decompressed_data.insert(decompressed_data.size(),
  4525. decompressed_data_chunk,
  4526. decompressed_data_chunk_size);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(result);
  4530. }
  4531. ASSERT_EQ(original_text, decompressed_data);
  4532. }
  4533. #ifdef _WIN32
  4534. TEST(GzipDecompressor, LargeRandomData) {
  4535. // prepare large random data that is difficult to be compressed and is
  4536. // expected to have large size even when compressed
  4537. std::random_device seed_gen;
  4538. std::mt19937 random(seed_gen());
  4539. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4540. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4541. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4542. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4543. // compress data over 4GiB
  4544. std::string compressed_data;
  4545. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4546. httplib::detail::gzip_compressor compressor;
  4547. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4548. data.size() * sizeof(std::uint32_t), true,
  4549. [&](const char *data, size_t size) {
  4550. compressed_data.insert(
  4551. compressed_data.size(), data, size);
  4552. return true;
  4553. });
  4554. ASSERT_TRUE(result);
  4555. // FIXME: compressed data size is expected to be greater than 4GiB,
  4556. // but there is no guarantee
  4557. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4558. // decompress data over 4GiB
  4559. std::string decompressed_data;
  4560. decompressed_data.reserve(data_size);
  4561. httplib::detail::gzip_decompressor decompressor;
  4562. result = decompressor.decompress(
  4563. compressed_data.data(), compressed_data.size(),
  4564. [&](const char *data, size_t size) {
  4565. decompressed_data.insert(decompressed_data.size(), data, size);
  4566. return true;
  4567. });
  4568. ASSERT_TRUE(result);
  4569. // compare
  4570. ASSERT_EQ(data_size, decompressed_data.size());
  4571. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4572. 0);
  4573. }
  4574. #endif
  4575. #endif
  4576. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4577. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4578. Headers headers;
  4579. headers.emplace("Accept-Encoding", "br");
  4580. auto res = cli_.Get("/streamed-chunked", headers);
  4581. ASSERT_TRUE(res);
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ(std::string("123456789"), res->body);
  4584. }
  4585. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4586. Headers headers;
  4587. headers.emplace("Accept-Encoding", "br");
  4588. auto res = cli_.Get("/streamed-chunked2", headers);
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ(std::string("123456789"), res->body);
  4592. }
  4593. #endif
  4594. TEST_F(ServerTest, Patch) {
  4595. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ("PATCH", res->body);
  4599. }
  4600. TEST_F(ServerTest, Delete) {
  4601. auto res = cli_.Delete("/delete");
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("DELETE", res->body);
  4605. }
  4606. TEST_F(ServerTest, DeleteContentReceiver) {
  4607. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ("content", res->body);
  4611. }
  4612. TEST_F(ServerTest, Options) {
  4613. auto res = cli_.Options("*");
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4617. EXPECT_TRUE(res->body.empty());
  4618. }
  4619. TEST_F(ServerTest, URL) {
  4620. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4621. ASSERT_TRUE(res);
  4622. EXPECT_EQ(StatusCode::OK_200, res->status);
  4623. }
  4624. TEST_F(ServerTest, ArrayParam) {
  4625. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::OK_200, res->status);
  4628. }
  4629. TEST_F(ServerTest, NoMultipleHeaders) {
  4630. Headers headers = {{"Content-Length", "5"}};
  4631. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4632. "text/plain");
  4633. ASSERT_TRUE(res);
  4634. EXPECT_EQ(StatusCode::OK_200, res->status);
  4635. }
  4636. TEST_F(ServerTest, PostContentReceiver) {
  4637. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4638. ASSERT_TRUE(res);
  4639. ASSERT_EQ(StatusCode::OK_200, res->status);
  4640. ASSERT_EQ("content", res->body);
  4641. }
  4642. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4643. UploadFormDataItems items = {
  4644. {"text1", "text default", "", ""},
  4645. {"text2", "aωb", "", ""},
  4646. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4647. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4648. {"file3", "", "", "application/octet-stream"},
  4649. };
  4650. auto res = cli_.Post("/content_receiver", items);
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. }
  4654. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4655. UploadFormDataItems items = {
  4656. {"text1", "text default", "", ""},
  4657. {"text2", "aωb", "", ""},
  4658. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4659. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4660. {"file3", "", "", "application/octet-stream"},
  4661. };
  4662. auto boundary = std::string("+++++");
  4663. std::string body;
  4664. for (const auto &item : items) {
  4665. body += "--" + boundary + "\r\n";
  4666. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4667. if (!item.filename.empty()) {
  4668. body += "; filename=\"" + item.filename + "\"";
  4669. }
  4670. body += "\r\n";
  4671. if (!item.content_type.empty()) {
  4672. body += "Content-Type: " + item.content_type + "\r\n";
  4673. }
  4674. body += "\r\n";
  4675. body += item.content + "\r\n";
  4676. }
  4677. body += "--" + boundary + "--\r\n";
  4678. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4679. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4680. ASSERT_TRUE(res);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. }
  4683. TEST_F(ServerTest, PostContentReceiverGzip) {
  4684. cli_.set_compress(true);
  4685. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4686. ASSERT_TRUE(res);
  4687. ASSERT_EQ(StatusCode::OK_200, res->status);
  4688. ASSERT_EQ("content", res->body);
  4689. }
  4690. TEST_F(ServerTest, PutContentReceiver) {
  4691. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4692. ASSERT_TRUE(res);
  4693. ASSERT_EQ(StatusCode::OK_200, res->status);
  4694. ASSERT_EQ("content", res->body);
  4695. }
  4696. TEST_F(ServerTest, PatchContentReceiver) {
  4697. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4698. ASSERT_TRUE(res);
  4699. ASSERT_EQ(StatusCode::OK_200, res->status);
  4700. ASSERT_EQ("content", res->body);
  4701. }
  4702. template <typename ClientType>
  4703. void TestWithHeadersAndContentReceiver(
  4704. ClientType &cli,
  4705. std::function<Result(ClientType &, const std::string &, const Headers &,
  4706. const std::string &, const std::string &,
  4707. ContentReceiver, DownloadProgress)>
  4708. request_func) {
  4709. Headers headers;
  4710. headers.emplace("X-Custom-Header", "test-value");
  4711. std::string received_body;
  4712. auto res = request_func(
  4713. cli, "/content_receiver", headers, "content", "application/json",
  4714. [&](const char *data, size_t data_length) {
  4715. received_body.append(data, data_length);
  4716. return true;
  4717. },
  4718. nullptr);
  4719. ASSERT_TRUE(res);
  4720. EXPECT_EQ(StatusCode::OK_200, res->status);
  4721. EXPECT_EQ("content", received_body);
  4722. }
  4723. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4725. using ClientT = SSLClient;
  4726. #else
  4727. using ClientT = Client;
  4728. #endif
  4729. TestWithHeadersAndContentReceiver<ClientT>(
  4730. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4731. const std::string &body, const std::string &content_type,
  4732. ContentReceiver receiver, DownloadProgress progress) {
  4733. return cli.Post(path, headers, body, content_type, receiver, progress);
  4734. });
  4735. }
  4736. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4738. using ClientT = SSLClient;
  4739. #else
  4740. using ClientT = Client;
  4741. #endif
  4742. TestWithHeadersAndContentReceiver<ClientT>(
  4743. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4744. const std::string &body, const std::string &content_type,
  4745. ContentReceiver receiver, DownloadProgress progress) {
  4746. return cli.Put(path, headers, body, content_type, receiver, progress);
  4747. });
  4748. }
  4749. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4751. using ClientT = SSLClient;
  4752. #else
  4753. using ClientT = Client;
  4754. #endif
  4755. TestWithHeadersAndContentReceiver<ClientT>(
  4756. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4757. const std::string &body, const std::string &content_type,
  4758. ContentReceiver receiver, DownloadProgress progress) {
  4759. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4760. });
  4761. }
  4762. template <typename ClientType>
  4763. void TestWithHeadersAndContentReceiverWithProgress(
  4764. ClientType &cli,
  4765. std::function<Result(ClientType &, const std::string &, const Headers &,
  4766. const std::string &, const std::string &,
  4767. ContentReceiver, DownloadProgress)>
  4768. request_func) {
  4769. Headers headers;
  4770. headers.emplace("X-Test-Header", "progress-test");
  4771. std::string received_body;
  4772. auto progress_called = false;
  4773. auto res = request_func(
  4774. cli, "/content_receiver", headers, "content", "text/plain",
  4775. [&](const char *data, size_t data_length) {
  4776. received_body.append(data, data_length);
  4777. return true;
  4778. },
  4779. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4780. progress_called = true;
  4781. return true;
  4782. });
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("content", received_body);
  4786. EXPECT_TRUE(progress_called);
  4787. }
  4788. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4790. using ClientT = SSLClient;
  4791. #else
  4792. using ClientT = Client;
  4793. #endif
  4794. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4795. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4796. const std::string &body, const std::string &content_type,
  4797. ContentReceiver receiver, DownloadProgress progress) {
  4798. return cli.Post(path, headers, body, content_type, receiver, progress);
  4799. });
  4800. }
  4801. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4803. using ClientT = SSLClient;
  4804. #else
  4805. using ClientT = Client;
  4806. #endif
  4807. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4808. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4809. const std::string &body, const std::string &content_type,
  4810. ContentReceiver receiver, DownloadProgress progress) {
  4811. return cli.Put(path, headers, body, content_type, receiver, progress);
  4812. });
  4813. }
  4814. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4816. using ClientT = SSLClient;
  4817. #else
  4818. using ClientT = Client;
  4819. #endif
  4820. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4821. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4822. const std::string &body, const std::string &content_type,
  4823. ContentReceiver receiver, DownloadProgress progress) {
  4824. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4825. });
  4826. }
  4827. template <typename ClientType>
  4828. void TestWithHeadersAndContentReceiverError(
  4829. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4830. const Headers &, const std::string &,
  4831. const std::string &, ContentReceiver)>
  4832. request_func) {
  4833. Headers headers;
  4834. headers.emplace("X-Error-Test", "true");
  4835. std::string received_body;
  4836. auto receiver_failed = false;
  4837. auto res =
  4838. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4839. [&](const char *data, size_t data_length) {
  4840. received_body.append(data, data_length);
  4841. receiver_failed = true;
  4842. return false;
  4843. });
  4844. ASSERT_FALSE(res);
  4845. EXPECT_TRUE(receiver_failed);
  4846. }
  4847. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4849. using ClientT = SSLClient;
  4850. #else
  4851. using ClientT = Client;
  4852. #endif
  4853. TestWithHeadersAndContentReceiverError<ClientT>(
  4854. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4855. const std::string &body, const std::string &content_type,
  4856. ContentReceiver receiver) {
  4857. return cli.Post(path, headers, body, content_type, receiver);
  4858. });
  4859. }
  4860. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4861. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4862. using ClientT = SSLClient;
  4863. #else
  4864. using ClientT = Client;
  4865. #endif
  4866. TestWithHeadersAndContentReceiverError<ClientT>(
  4867. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4868. const std::string &body, const std::string &content_type,
  4869. ContentReceiver receiver) {
  4870. return cli.Put(path, headers, body, content_type, receiver);
  4871. });
  4872. }
  4873. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4874. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4875. using ClientT = SSLClient;
  4876. #else
  4877. using ClientT = Client;
  4878. #endif
  4879. TestWithHeadersAndContentReceiverError<ClientT>(
  4880. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4881. const std::string &body, const std::string &content_type,
  4882. ContentReceiver receiver) {
  4883. return cli.Patch(path, headers, body, content_type, receiver);
  4884. });
  4885. }
  4886. TEST_F(ServerTest, PostQueryStringAndBody) {
  4887. auto res =
  4888. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4889. ASSERT_TRUE(res);
  4890. ASSERT_EQ(StatusCode::OK_200, res->status);
  4891. }
  4892. TEST_F(ServerTest, HTTP2Magic) {
  4893. Request req;
  4894. req.method = "PRI";
  4895. req.path = "*";
  4896. req.body = "SM";
  4897. auto res = std::make_shared<Response>();
  4898. auto error = Error::Success;
  4899. auto ret = cli_.send(req, *res, error);
  4900. ASSERT_TRUE(ret);
  4901. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4902. }
  4903. TEST_F(ServerTest, KeepAlive) {
  4904. auto res = cli_.Get("/hi");
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4908. EXPECT_EQ("Hello World!", res->body);
  4909. res = cli_.Get("/hi");
  4910. ASSERT_TRUE(res);
  4911. EXPECT_EQ(StatusCode::OK_200, res->status);
  4912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4913. EXPECT_EQ("Hello World!", res->body);
  4914. res = cli_.Get("/hi");
  4915. ASSERT_TRUE(res);
  4916. EXPECT_EQ(StatusCode::OK_200, res->status);
  4917. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4918. EXPECT_EQ("Hello World!", res->body);
  4919. res = cli_.Get("/not-exist");
  4920. ASSERT_TRUE(res);
  4921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4922. res = cli_.Post("/empty", "", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4926. EXPECT_EQ("empty", res->body);
  4927. EXPECT_EQ("close", res->get_header_value("Connection"));
  4928. res = cli_.Post(
  4929. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4930. "text/plain");
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4934. EXPECT_EQ("empty", res->body);
  4935. cli_.set_keep_alive(false);
  4936. res = cli_.Get("/last-request");
  4937. ASSERT_TRUE(res);
  4938. EXPECT_EQ(StatusCode::OK_200, res->status);
  4939. EXPECT_EQ("close", res->get_header_value("Connection"));
  4940. }
  4941. TEST_F(ServerTest, TooManyRedirect) {
  4942. cli_.set_follow_location(true);
  4943. auto res = cli_.Get("/redirect/0");
  4944. ASSERT_TRUE(!res);
  4945. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4946. }
  4947. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4948. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4949. TEST_F(ServerTest, Gzip) {
  4950. Headers headers;
  4951. headers.emplace("Accept-Encoding", "gzip, deflate");
  4952. auto res = cli_.Get("/compress", headers);
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4956. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4957. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4958. "7890123456789012345678901234567890",
  4959. res->body);
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. }
  4962. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4963. Headers headers;
  4964. headers.emplace("Accept-Encoding", "");
  4965. auto res = cli_.Get("/compress", headers);
  4966. ASSERT_TRUE(res);
  4967. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4969. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4970. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4971. "7890123456789012345678901234567890",
  4972. res->body);
  4973. EXPECT_EQ(StatusCode::OK_200, res->status);
  4974. }
  4975. TEST_F(ServerTest, GzipWithContentReceiver) {
  4976. Headers headers;
  4977. headers.emplace("Accept-Encoding", "gzip, deflate");
  4978. std::string body;
  4979. auto res = cli_.Get("/compress", headers,
  4980. [&](const char *data, uint64_t data_length) {
  4981. EXPECT_EQ(100U, data_length);
  4982. body.append(data, data_length);
  4983. return true;
  4984. });
  4985. ASSERT_TRUE(res);
  4986. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4988. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4990. "7890123456789012345678901234567890",
  4991. body);
  4992. EXPECT_EQ(StatusCode::OK_200, res->status);
  4993. }
  4994. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4995. Headers headers;
  4996. headers.emplace("Accept-Encoding", "gzip, deflate");
  4997. cli_.set_decompress(false);
  4998. auto res = cli_.Get("/compress", headers);
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5002. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5003. EXPECT_EQ(33U, res->body.size());
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. }
  5006. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5007. Headers headers;
  5008. headers.emplace("Accept-Encoding", "");
  5009. std::string body;
  5010. auto res = cli_.Get("/compress", headers,
  5011. [&](const char *data, uint64_t data_length) {
  5012. EXPECT_EQ(100U, data_length);
  5013. body.append(data, data_length);
  5014. return true;
  5015. });
  5016. ASSERT_TRUE(res);
  5017. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5019. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5021. "7890123456789012345678901234567890",
  5022. body);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. TEST_F(ServerTest, NoGzip) {
  5026. Headers headers;
  5027. headers.emplace("Accept-Encoding", "gzip, deflate");
  5028. auto res = cli_.Get("/nocompress", headers);
  5029. ASSERT_TRUE(res);
  5030. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5034. "7890123456789012345678901234567890",
  5035. res->body);
  5036. EXPECT_EQ(StatusCode::OK_200, res->status);
  5037. }
  5038. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5039. Headers headers;
  5040. headers.emplace("Accept-Encoding", "gzip, deflate");
  5041. std::string body;
  5042. auto res = cli_.Get("/nocompress", headers,
  5043. [&](const char *data, uint64_t data_length) {
  5044. EXPECT_EQ(100U, data_length);
  5045. body.append(data, data_length);
  5046. return true;
  5047. });
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5050. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5053. "7890123456789012345678901234567890",
  5054. body);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. }
  5057. TEST_F(ServerTest, MultipartFormDataGzip) {
  5058. UploadFormDataItems items = {
  5059. {"key1", "test", "", ""},
  5060. {"key2", "--abcdefg123", "", ""},
  5061. };
  5062. cli_.set_compress(true);
  5063. auto res = cli_.Post("/compress-multipart", items);
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. }
  5067. #endif
  5068. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5069. TEST_F(ServerTest, Brotli) {
  5070. Headers headers;
  5071. headers.emplace("Accept-Encoding", "br");
  5072. auto res = cli_.Get("/compress", headers);
  5073. ASSERT_TRUE(res);
  5074. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5076. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5077. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5078. "7890123456789012345678901234567890",
  5079. res->body);
  5080. EXPECT_EQ(StatusCode::OK_200, res->status);
  5081. }
  5082. #endif
  5083. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5084. TEST_F(ServerTest, Zstd) {
  5085. Headers headers;
  5086. headers.emplace("Accept-Encoding", "zstd");
  5087. auto res = cli_.Get("/compress", headers);
  5088. ASSERT_TRUE(res);
  5089. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5090. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5091. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5093. "7890123456789012345678901234567890",
  5094. res->body);
  5095. EXPECT_EQ(StatusCode::OK_200, res->status);
  5096. }
  5097. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5098. Headers headers;
  5099. headers.emplace("Accept-Encoding", "");
  5100. auto res = cli_.Get("/compress", headers);
  5101. ASSERT_TRUE(res);
  5102. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5103. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5104. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5105. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5106. "7890123456789012345678901234567890",
  5107. res->body);
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. }
  5110. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5111. Headers headers;
  5112. headers.emplace("Accept-Encoding", "zstd");
  5113. std::string body;
  5114. auto res = cli_.Get("/compress", headers,
  5115. [&](const char *data, uint64_t data_length) {
  5116. EXPECT_EQ(100U, data_length);
  5117. body.append(data, data_length);
  5118. return true;
  5119. });
  5120. ASSERT_TRUE(res);
  5121. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5122. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5123. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5125. "7890123456789012345678901234567890",
  5126. body);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. }
  5129. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5130. Headers headers;
  5131. headers.emplace("Accept-Encoding", "zstd");
  5132. cli_.set_decompress(false);
  5133. auto res = cli_.Get("/compress", headers);
  5134. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5135. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5136. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5137. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5138. ASSERT_TRUE(res);
  5139. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5141. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. ASSERT_EQ(26U, res->body.size());
  5144. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5145. 0);
  5146. }
  5147. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "");
  5150. std::string body;
  5151. auto res = cli_.Get("/compress", headers,
  5152. [&](const char *data, uint64_t data_length) {
  5153. EXPECT_EQ(100U, data_length);
  5154. body.append(data, data_length);
  5155. return true;
  5156. });
  5157. ASSERT_TRUE(res);
  5158. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5160. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5161. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5162. "7890123456789012345678901234567890",
  5163. body);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. }
  5166. TEST_F(ServerTest, NoZstd) {
  5167. Headers headers;
  5168. headers.emplace("Accept-Encoding", "zstd");
  5169. auto res = cli_.Get("/nocompress", headers);
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5172. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5173. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5174. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5175. "7890123456789012345678901234567890",
  5176. res->body);
  5177. EXPECT_EQ(StatusCode::OK_200, res->status);
  5178. }
  5179. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5180. Headers headers;
  5181. headers.emplace("Accept-Encoding", "zstd");
  5182. std::string body;
  5183. auto res = cli_.Get("/nocompress", headers,
  5184. [&](const char *data, uint64_t data_length) {
  5185. EXPECT_EQ(100U, data_length);
  5186. body.append(data, data_length);
  5187. return true;
  5188. });
  5189. ASSERT_TRUE(res);
  5190. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5191. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5193. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5194. "7890123456789012345678901234567890",
  5195. body);
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. }
  5198. // TODO: How to enable zstd ??
  5199. TEST_F(ServerTest, MultipartFormDataZstd) {
  5200. UploadFormDataItems items = {
  5201. {"key1", "test", "", ""},
  5202. {"key2", "--abcdefg123", "", ""},
  5203. };
  5204. Headers headers;
  5205. headers.emplace("Accept-Encoding", "zstd");
  5206. cli_.set_compress(true);
  5207. auto res = cli_.Post("/compress-multipart", headers, items);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. }
  5211. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5212. Headers headers;
  5213. headers.emplace("Accept-Encoding", "zstd");
  5214. cli_.set_compress(true);
  5215. auto res = cli_.Put(
  5216. "/put", headers, 3,
  5217. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5218. sink.os << "PUT";
  5219. return true;
  5220. },
  5221. "text/plain");
  5222. ASSERT_TRUE(res);
  5223. EXPECT_EQ(StatusCode::OK_200, res->status);
  5224. EXPECT_EQ("PUT", res->body);
  5225. }
  5226. // Pre-compression logging tests
  5227. TEST_F(ServerTest, PreCompressionLogging) {
  5228. // Test data for compression (matches the actual /compress endpoint content)
  5229. const std::string test_content =
  5230. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5231. "3456789012345678901234567890";
  5232. // Variables to capture logging data
  5233. std::string pre_compression_body;
  5234. std::string pre_compression_content_type;
  5235. std::string pre_compression_content_encoding;
  5236. std::string post_compression_body;
  5237. std::string post_compression_content_type;
  5238. std::string post_compression_content_encoding;
  5239. // Set up pre-compression logger
  5240. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5241. const Response &res) {
  5242. pre_compression_body = res.body;
  5243. pre_compression_content_type = res.get_header_value("Content-Type");
  5244. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5245. });
  5246. // Set up post-compression logger
  5247. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5248. post_compression_body = res.body;
  5249. post_compression_content_type = res.get_header_value("Content-Type");
  5250. post_compression_content_encoding =
  5251. res.get_header_value("Content-Encoding");
  5252. });
  5253. // Test with gzip compression
  5254. Headers headers;
  5255. headers.emplace("Accept-Encoding", "gzip");
  5256. auto res = cli_.Get("/compress", headers);
  5257. // Verify response was compressed
  5258. ASSERT_TRUE(res);
  5259. EXPECT_EQ(StatusCode::OK_200, res->status);
  5260. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5261. // Verify pre-compression logger captured uncompressed content
  5262. EXPECT_EQ(test_content, pre_compression_body);
  5263. EXPECT_EQ("text/plain", pre_compression_content_type);
  5264. EXPECT_TRUE(pre_compression_content_encoding
  5265. .empty()); // No encoding header before compression
  5266. // Verify post-compression logger captured compressed content
  5267. EXPECT_NE(test_content,
  5268. post_compression_body); // Should be different after compression
  5269. EXPECT_EQ("text/plain", post_compression_content_type);
  5270. EXPECT_EQ("gzip", post_compression_content_encoding);
  5271. // Verify compressed content is smaller
  5272. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5273. }
  5274. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5275. const std::string test_content =
  5276. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5277. "3456789012345678901234567890";
  5278. std::string pre_compression_body;
  5279. std::string post_compression_body;
  5280. svr_.set_pre_compression_logger(
  5281. [&](const Request & /*req*/, const Response &res) {
  5282. pre_compression_body = res.body;
  5283. });
  5284. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5285. post_compression_body = res.body;
  5286. });
  5287. Headers headers;
  5288. headers.emplace("Accept-Encoding", "br");
  5289. auto res = cli_.Get("/compress", headers);
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5293. // Verify pre-compression content is uncompressed
  5294. EXPECT_EQ(test_content, pre_compression_body);
  5295. // Verify post-compression content is compressed
  5296. EXPECT_NE(test_content, post_compression_body);
  5297. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5298. }
  5299. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5300. const std::string test_content =
  5301. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5302. "3456789012345678901234567890";
  5303. std::string pre_compression_body;
  5304. std::string post_compression_body;
  5305. svr_.set_pre_compression_logger(
  5306. [&](const Request & /*req*/, const Response &res) {
  5307. pre_compression_body = res.body;
  5308. });
  5309. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5310. post_compression_body = res.body;
  5311. });
  5312. // Request without compression (use /nocompress endpoint)
  5313. Headers headers;
  5314. auto res = cli_.Get("/nocompress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5318. // Pre-compression logger should not be called when no compression is applied
  5319. EXPECT_TRUE(
  5320. pre_compression_body.empty()); // Pre-compression logger not called
  5321. EXPECT_EQ(
  5322. test_content,
  5323. post_compression_body); // Post-compression logger captures final content
  5324. }
  5325. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5326. const std::string test_content =
  5327. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5328. "3456789012345678901234567890";
  5329. std::string pre_compression_body;
  5330. bool pre_logger_called = false;
  5331. // Set only pre-compression logger
  5332. svr_.set_pre_compression_logger(
  5333. [&](const Request & /*req*/, const Response &res) {
  5334. pre_compression_body = res.body;
  5335. pre_logger_called = true;
  5336. });
  5337. Headers headers;
  5338. headers.emplace("Accept-Encoding", "gzip");
  5339. auto res = cli_.Get("/compress", headers);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5343. // Verify pre-compression logger was called
  5344. EXPECT_TRUE(pre_logger_called);
  5345. EXPECT_EQ(test_content, pre_compression_body);
  5346. }
  5347. TEST(ZstdDecompressor, ChunkedDecompression) {
  5348. std::string data;
  5349. for (size_t i = 0; i < 32 * 1024; ++i) {
  5350. data.push_back(static_cast<char>('a' + i % 26));
  5351. }
  5352. std::string compressed_data;
  5353. {
  5354. httplib::detail::zstd_compressor compressor;
  5355. bool result = compressor.compress(
  5356. data.data(), data.size(),
  5357. /*last=*/true,
  5358. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5359. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5360. compressed_data_size);
  5361. return true;
  5362. });
  5363. ASSERT_TRUE(result);
  5364. }
  5365. std::string decompressed_data;
  5366. {
  5367. httplib::detail::zstd_decompressor decompressor;
  5368. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5369. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5370. size_t chunk_size = 130;
  5371. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5372. chunk_begin += chunk_size) {
  5373. size_t current_chunk_size =
  5374. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5375. bool result = decompressor.decompress(
  5376. compressed_data.data() + chunk_begin, current_chunk_size,
  5377. [&](const char *decompressed_data_chunk,
  5378. size_t decompressed_data_chunk_size) {
  5379. decompressed_data.insert(decompressed_data.size(),
  5380. decompressed_data_chunk,
  5381. decompressed_data_chunk_size);
  5382. return true;
  5383. });
  5384. ASSERT_TRUE(result);
  5385. }
  5386. }
  5387. ASSERT_EQ(data, decompressed_data);
  5388. }
  5389. TEST(ZstdDecompressor, Decompress) {
  5390. std::string original_text = "Compressed with ZSTD";
  5391. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5392. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5393. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5394. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5395. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5396. std::string decompressed_data;
  5397. {
  5398. httplib::detail::zstd_decompressor decompressor;
  5399. bool result = decompressor.decompress(
  5400. compressed_data.data(), compressed_data.size(),
  5401. [&](const char *decompressed_data_chunk,
  5402. size_t decompressed_data_chunk_size) {
  5403. decompressed_data.insert(decompressed_data.size(),
  5404. decompressed_data_chunk,
  5405. decompressed_data_chunk_size);
  5406. return true;
  5407. });
  5408. ASSERT_TRUE(result);
  5409. }
  5410. ASSERT_EQ(original_text, decompressed_data);
  5411. }
  5412. #endif
  5413. // Sends a raw request to a server listening at HOST:PORT.
  5414. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5415. std::string *resp = nullptr) {
  5416. auto error = Error::Success;
  5417. auto client_sock = detail::create_client_socket(
  5418. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5419. /*connection_timeout_sec=*/5, 0,
  5420. /*read_timeout_sec=*/5, 0,
  5421. /*write_timeout_sec=*/5, 0, std::string(), error);
  5422. if (client_sock == INVALID_SOCKET) { return false; }
  5423. auto ret = detail::process_client_socket(
  5424. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5425. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5426. if (req.size() !=
  5427. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5428. return false;
  5429. }
  5430. char buf[512];
  5431. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5432. while (line_reader.getline()) {
  5433. if (resp) { *resp += line_reader.ptr(); }
  5434. }
  5435. return true;
  5436. });
  5437. detail::close_socket(client_sock);
  5438. return ret;
  5439. }
  5440. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5441. Server svr;
  5442. std::string header_value;
  5443. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5444. header_value = req.get_header_value("foo");
  5445. res.set_content("ok", "text/plain");
  5446. });
  5447. thread t = thread([&] { svr.listen(HOST, PORT); });
  5448. auto se = detail::scope_exit([&] {
  5449. svr.stop();
  5450. t.join();
  5451. ASSERT_FALSE(svr.is_running());
  5452. });
  5453. svr.wait_until_ready();
  5454. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5455. // like characters are not treated the same - use vertical tab and escape.
  5456. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5457. "foo: \t \v bar \x1B\t \r\n"
  5458. "Connection: close\r\n"
  5459. "\r\n";
  5460. std::string res;
  5461. ASSERT_TRUE(send_request(5, req, &res));
  5462. EXPECT_EQ(header_value, "");
  5463. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5464. }
  5465. // Sends a raw request and verifies that there isn't a crash or exception.
  5466. static void test_raw_request(const std::string &req,
  5467. std::string *out = nullptr) {
  5468. Server svr;
  5469. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5470. res.set_content("ok", "text/plain");
  5471. });
  5472. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5473. res.set_content("ok", "text/plain");
  5474. });
  5475. svr.Get("/header_field_value_check",
  5476. [&](const Request & /*req*/, Response &res) {
  5477. res.set_content("ok", "text/plain");
  5478. });
  5479. // Server read timeout must be longer than the client read timeout for the
  5480. // bug to reproduce, probably to force the server to process a request
  5481. // without a trailing blank line.
  5482. const time_t client_read_timeout_sec = 1;
  5483. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5484. bool listen_thread_ok = false;
  5485. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5486. auto se = detail::scope_exit([&] {
  5487. svr.stop();
  5488. t.join();
  5489. ASSERT_FALSE(svr.is_running());
  5490. EXPECT_TRUE(listen_thread_ok);
  5491. });
  5492. svr.wait_until_ready();
  5493. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5494. }
  5495. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5496. // A certain header line causes an exception if the header property is parsed
  5497. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5498. test_raw_request(
  5499. "GET /hi HTTP/1.1\r\n"
  5500. " : "
  5501. " "
  5502. " ");
  5503. }
  5504. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5505. // A certain header line causes an exception if the header property *name* is
  5506. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5507. // greedy matcher and requires backtracking when there are a lot of ":"
  5508. // characters.
  5509. // This occurs with libc++ but not libstdc++.
  5510. test_raw_request(
  5511. "GET /hi HTTP/1.1\r\n"
  5512. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5513. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5514. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5515. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5516. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5517. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5518. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5519. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5520. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5521. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5522. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5523. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5524. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5525. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5526. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5527. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5528. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5529. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5530. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5531. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5532. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5533. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5534. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5535. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5536. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5537. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5538. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5539. "&&&%%%");
  5540. }
  5541. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5542. // Make sure this doesn't crash the server.
  5543. // In a previous version of the header line regex, the "\r" rendered the line
  5544. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5545. // a new position where the leading white space ended and the field value
  5546. // began.
  5547. // The crash occurs with libc++ but not libstdc++.
  5548. test_raw_request("GET /hi HTTP/1.1\r\n"
  5549. "a:" +
  5550. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5551. "\r\n"
  5552. "\r\n");
  5553. }
  5554. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5555. std::string out;
  5556. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5557. "Content-Type: text/plain\r\n"
  5558. "Transfer-Encoding: chunked\r\n"
  5559. "\r\n"
  5560. "nothex\r\n",
  5561. &out);
  5562. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5563. }
  5564. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5565. std::string out;
  5566. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5567. "Content-Type: text/plain\r\n"
  5568. "Transfer-Encoding: chunked\r\n"
  5569. "\r\n"
  5570. "3\r\n"
  5571. "xyz\r\n"
  5572. "NaN\r\n",
  5573. &out);
  5574. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5575. }
  5576. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5577. std::string out;
  5578. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5579. "Content-Type: text/plain\r\n"
  5580. "Transfer-Encoding: chunked\r\n"
  5581. "\r\n"
  5582. // Length is too large for 64 bits.
  5583. "1ffffffffffffffff\r\n"
  5584. "xyz\r\n",
  5585. &out);
  5586. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5587. }
  5588. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5589. test_raw_request("GET /hi HTTP/1.1\r\n"
  5590. "Content-Type: text/plain\r\n\r");
  5591. }
  5592. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5593. std::string out;
  5594. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5595. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5596. }
  5597. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5598. std::string out;
  5599. std::string request(
  5600. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5601. test_raw_request(request, &out);
  5602. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5603. }
  5604. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5605. std::string out;
  5606. std::string request(
  5607. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5608. test_raw_request(request, &out);
  5609. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5610. }
  5611. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5612. std::string out;
  5613. std::string request(
  5614. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5615. test_raw_request(request, &out);
  5616. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5617. }
  5618. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5619. std::string out;
  5620. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5621. "Test: \r\n\r\n",
  5622. &out);
  5623. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5624. }
  5625. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5626. Server svr;
  5627. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5628. res.set_header("Cache-Control", "no-cache");
  5629. res.set_chunked_content_provider(
  5630. "text/event-stream", [](size_t offset, DataSink &sink) {
  5631. std::string s = "data:";
  5632. s += std::to_string(offset);
  5633. s += "\n\n";
  5634. auto ret = sink.write(s.data(), s.size());
  5635. EXPECT_TRUE(ret);
  5636. std::this_thread::sleep_for(std::chrono::seconds(1));
  5637. return true;
  5638. });
  5639. });
  5640. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5641. svr.wait_until_ready();
  5642. Client client(HOST, PORT);
  5643. const Headers headers = {{"Accept", "text/event-stream"}};
  5644. auto get_thread = std::thread([&client, &headers]() {
  5645. auto res = client.Get(
  5646. "/events", headers,
  5647. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5648. });
  5649. auto se = detail::scope_exit([&] {
  5650. svr.stop();
  5651. get_thread.join();
  5652. listen_thread.join();
  5653. ASSERT_FALSE(svr.is_running());
  5654. });
  5655. // Give GET time to get a few messages.
  5656. std::this_thread::sleep_for(std::chrono::seconds(2));
  5657. }
  5658. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5659. httplib::Server svr;
  5660. svr.Post("/hi",
  5661. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5662. res.status = StatusCode::OK_200;
  5663. });
  5664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5665. svr.wait_until_ready();
  5666. Client cli(HOST, PORT);
  5667. auto res = cli.Post("/hi", "data", "text/plain");
  5668. ASSERT_TRUE(res);
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. svr.stop();
  5671. thread.join();
  5672. ASSERT_FALSE(svr.is_running());
  5673. res = cli.Post("/hi", "data", "text/plain");
  5674. ASSERT_FALSE(res);
  5675. }
  5676. TEST(ServerStopTest, ListenFailure) {
  5677. Server svr;
  5678. auto t = thread([&]() {
  5679. auto ret = svr.listen("????", PORT);
  5680. EXPECT_FALSE(ret);
  5681. });
  5682. svr.wait_until_ready();
  5683. svr.stop();
  5684. t.join();
  5685. }
  5686. TEST(ServerStopTest, Decommision) {
  5687. Server svr;
  5688. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5689. for (int i = 0; i < 4; i++) {
  5690. auto is_even = !(i % 2);
  5691. std::thread t{[&] {
  5692. try {
  5693. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5694. if (is_even) {
  5695. throw std::runtime_error("Some thing that happens to go wrong.");
  5696. }
  5697. svr.listen(HOST, PORT);
  5698. } catch (...) { svr.decommission(); }
  5699. }};
  5700. svr.wait_until_ready();
  5701. // Server is up
  5702. {
  5703. Client cli(HOST, PORT);
  5704. auto res = cli.Get("/hi");
  5705. if (is_even) {
  5706. EXPECT_FALSE(res);
  5707. } else {
  5708. EXPECT_TRUE(res);
  5709. EXPECT_EQ("hi...", res->body);
  5710. }
  5711. }
  5712. svr.stop();
  5713. t.join();
  5714. // Server is down...
  5715. {
  5716. Client cli(HOST, PORT);
  5717. auto res = cli.Get("/hi");
  5718. EXPECT_FALSE(res);
  5719. }
  5720. }
  5721. }
  5722. // Helper function for string body upload progress tests
  5723. template <typename SetupHandler, typename ClientCall>
  5724. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5725. ClientCall &&client_call,
  5726. const string &body) {
  5727. Server svr;
  5728. setup_handler(svr);
  5729. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5730. auto se = detail::scope_exit([&] {
  5731. svr.stop();
  5732. t.join();
  5733. });
  5734. svr.wait_until_ready();
  5735. Client cli(HOST, PORT);
  5736. vector<uint64_t> progress_values;
  5737. bool progress_called = false;
  5738. auto res =
  5739. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5740. progress_values.push_back(current);
  5741. progress_called = true;
  5742. return true;
  5743. });
  5744. ASSERT_TRUE(res);
  5745. EXPECT_EQ(200, res->status);
  5746. EXPECT_TRUE(progress_called);
  5747. }
  5748. TEST(UploadProgressTest, PostStringBodyBasic) {
  5749. TestStringBodyUploadProgress(
  5750. [](Server &svr) {
  5751. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5752. res.set_content("received", "text/plain");
  5753. });
  5754. },
  5755. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5756. return cli.Post("/test", body, "text/plain", progress_callback);
  5757. },
  5758. "test data for upload progress");
  5759. }
  5760. TEST(UploadProgressTest, PutStringBodyBasic) {
  5761. TestStringBodyUploadProgress(
  5762. [](Server &svr) {
  5763. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5764. res.set_content("put received", "text/plain");
  5765. });
  5766. },
  5767. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5768. return cli.Put("/test", body, "text/plain", progress_callback);
  5769. },
  5770. "put test data for upload progress");
  5771. }
  5772. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5773. TestStringBodyUploadProgress(
  5774. [](Server &svr) {
  5775. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5776. res.set_content("patch received", "text/plain");
  5777. });
  5778. },
  5779. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5780. return cli.Patch("/test", body, "text/plain", progress_callback);
  5781. },
  5782. "patch test data for upload progress");
  5783. }
  5784. // Helper function for content provider upload progress tests
  5785. template <typename SetupHandler, typename ClientCall>
  5786. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5787. ClientCall &&client_call) {
  5788. Server svr;
  5789. setup_handler(svr);
  5790. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5791. auto se = detail::scope_exit([&] {
  5792. svr.stop();
  5793. t.join();
  5794. });
  5795. svr.wait_until_ready();
  5796. Client cli(HOST, PORT);
  5797. vector<uint64_t> progress_values;
  5798. auto res =
  5799. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5800. progress_values.push_back(current);
  5801. return true;
  5802. });
  5803. ASSERT_TRUE(res);
  5804. EXPECT_EQ(200, res->status);
  5805. EXPECT_FALSE(progress_values.empty());
  5806. }
  5807. TEST(UploadProgressTest, PostContentProviderProgress) {
  5808. TestContentProviderUploadProgress(
  5809. [](Server &svr) {
  5810. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5811. res.set_content("provider received", "text/plain");
  5812. });
  5813. },
  5814. [](Client &cli, UploadProgress progress_callback) {
  5815. return cli.Post(
  5816. "/test", 10,
  5817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5818. sink.os << "test data";
  5819. return true;
  5820. },
  5821. "text/plain", progress_callback);
  5822. });
  5823. }
  5824. // Helper function for multipart upload progress tests
  5825. template <typename SetupHandler, typename ClientCall>
  5826. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5827. ClientCall &&client_call,
  5828. const string &endpoint) {
  5829. Server svr;
  5830. setup_handler(svr);
  5831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5832. auto se = detail::scope_exit([&] {
  5833. svr.stop();
  5834. t.join();
  5835. });
  5836. svr.wait_until_ready();
  5837. Client cli(HOST, PORT);
  5838. vector<uint64_t> progress_values;
  5839. UploadFormDataItems items = {
  5840. {"field1", "value1", "", ""},
  5841. {"field2", "longer value for progress tracking test", "", ""},
  5842. {"file1", "file content data for upload progress", "test.txt",
  5843. "text/plain"}};
  5844. auto res = client_call(cli, endpoint, items,
  5845. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5846. progress_values.push_back(current);
  5847. return true;
  5848. });
  5849. ASSERT_TRUE(res);
  5850. EXPECT_EQ(200, res->status);
  5851. EXPECT_FALSE(progress_values.empty());
  5852. }
  5853. TEST(UploadProgressTest, PostMultipartProgress) {
  5854. TestMultipartUploadProgress(
  5855. [](Server &svr) {
  5856. svr.Post("/multipart", [](const Request &req, Response &res) {
  5857. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5858. res.set_content("multipart received", "text/plain");
  5859. });
  5860. },
  5861. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5862. UploadProgress progress_callback) {
  5863. return cli.Post(endpoint, items, progress_callback);
  5864. },
  5865. "/multipart");
  5866. }
  5867. // Helper function for basic download progress tests
  5868. template <typename SetupHandler, typename ClientCall>
  5869. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5870. ClientCall &&client_call, const string &endpoint,
  5871. size_t expected_content_size) {
  5872. Server svr;
  5873. setup_handler(svr);
  5874. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5875. auto se = detail::scope_exit([&] {
  5876. svr.stop();
  5877. t.join();
  5878. });
  5879. svr.wait_until_ready();
  5880. Client cli(HOST, PORT);
  5881. vector<uint64_t> progress_values;
  5882. auto res = client_call(cli, endpoint,
  5883. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5884. progress_values.push_back(current);
  5885. return true;
  5886. });
  5887. ASSERT_TRUE(res);
  5888. EXPECT_EQ(200, res->status);
  5889. EXPECT_FALSE(progress_values.empty());
  5890. EXPECT_EQ(expected_content_size, res->body.size());
  5891. }
  5892. TEST(DownloadProgressTest, GetBasic) {
  5893. TestBasicDownloadProgress(
  5894. [](Server &svr) {
  5895. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5896. string content(1000, 'D');
  5897. res.set_content(content, "text/plain");
  5898. });
  5899. },
  5900. [](Client &cli, const string &endpoint,
  5901. DownloadProgress progress_callback) {
  5902. return cli.Get(endpoint, progress_callback);
  5903. },
  5904. "/download", 1000u);
  5905. }
  5906. // Helper function for content receiver download progress tests
  5907. template <typename SetupHandler, typename ClientCall>
  5908. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5909. ClientCall &&client_call,
  5910. const string &endpoint,
  5911. size_t expected_content_size) {
  5912. Server svr;
  5913. setup_handler(svr);
  5914. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5915. auto se = detail::scope_exit([&] {
  5916. svr.stop();
  5917. t.join();
  5918. });
  5919. svr.wait_until_ready();
  5920. Client cli(HOST, PORT);
  5921. vector<uint64_t> progress_values;
  5922. string received_body;
  5923. auto res = client_call(
  5924. cli, endpoint,
  5925. [&](const char *data, size_t data_length) -> bool {
  5926. received_body.append(data, data_length);
  5927. return true;
  5928. },
  5929. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5930. progress_values.push_back(current);
  5931. return true;
  5932. });
  5933. ASSERT_TRUE(res);
  5934. EXPECT_EQ(200, res->status);
  5935. EXPECT_FALSE(progress_values.empty());
  5936. EXPECT_EQ(expected_content_size, received_body.size());
  5937. EXPECT_TRUE(res->body.empty());
  5938. }
  5939. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5940. TestContentReceiverDownloadProgress(
  5941. [](Server &svr) {
  5942. svr.Get("/download-receiver",
  5943. [](const Request & /*req*/, Response &res) {
  5944. string content(2000, 'R');
  5945. res.set_content(content, "text/plain");
  5946. });
  5947. },
  5948. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5949. DownloadProgress progress_callback) {
  5950. return cli.Get(endpoint, content_receiver, progress_callback);
  5951. },
  5952. "/download-receiver", 2000u);
  5953. }
  5954. TEST(StreamingTest, NoContentLengthStreaming) {
  5955. Server svr;
  5956. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5957. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5958. if (offset < 6) {
  5959. sink.os << (offset < 3 ? "a" : "b");
  5960. } else {
  5961. sink.done();
  5962. }
  5963. return true;
  5964. });
  5965. });
  5966. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5967. auto listen_se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. listen_thread.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. Client client(HOST, PORT);
  5974. auto get_thread = std::thread([&client]() {
  5975. std::string s;
  5976. auto res =
  5977. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5978. s += std::string(data, len);
  5979. return true;
  5980. });
  5981. ASSERT_TRUE(res);
  5982. EXPECT_EQ(StatusCode::OK_200, res->status);
  5983. EXPECT_EQ("aaabbb", s);
  5984. });
  5985. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5986. // Give GET time to get a few messages.
  5987. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5988. }
  5989. TEST(MountTest, Unmount) {
  5990. Server svr;
  5991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5992. auto se = detail::scope_exit([&] {
  5993. svr.stop();
  5994. listen_thread.join();
  5995. ASSERT_FALSE(svr.is_running());
  5996. });
  5997. svr.wait_until_ready();
  5998. Client cli("localhost", PORT);
  5999. svr.set_mount_point("/mount2", "./www2");
  6000. auto res = cli.Get("/");
  6001. ASSERT_TRUE(res);
  6002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6003. res = cli.Get("/mount2/dir/test.html");
  6004. ASSERT_TRUE(res);
  6005. EXPECT_EQ(StatusCode::OK_200, res->status);
  6006. svr.set_mount_point("/", "./www");
  6007. res = cli.Get("/dir/");
  6008. ASSERT_TRUE(res);
  6009. EXPECT_EQ(StatusCode::OK_200, res->status);
  6010. svr.remove_mount_point("/");
  6011. res = cli.Get("/dir/");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6014. svr.remove_mount_point("/mount2");
  6015. res = cli.Get("/mount2/dir/test.html");
  6016. ASSERT_TRUE(res);
  6017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6018. }
  6019. TEST(MountTest, Redicect) {
  6020. Server svr;
  6021. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6022. auto se = detail::scope_exit([&] {
  6023. svr.stop();
  6024. listen_thread.join();
  6025. ASSERT_FALSE(svr.is_running());
  6026. });
  6027. svr.set_mount_point("/", "./www");
  6028. svr.wait_until_ready();
  6029. Client cli("localhost", PORT);
  6030. auto res = cli.Get("/dir/");
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. res = cli.Get("/dir");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6036. res = cli.Get("/file");
  6037. ASSERT_TRUE(res);
  6038. EXPECT_EQ(StatusCode::OK_200, res->status);
  6039. res = cli.Get("/file/");
  6040. ASSERT_TRUE(res);
  6041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6042. cli.set_follow_location(true);
  6043. res = cli.Get("/dir");
  6044. ASSERT_TRUE(res);
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. }
  6047. TEST(MountTest, MultibytesPathName) {
  6048. Server svr;
  6049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6050. auto se = detail::scope_exit([&] {
  6051. svr.stop();
  6052. listen_thread.join();
  6053. ASSERT_FALSE(svr.is_running());
  6054. });
  6055. svr.set_mount_point("/", "./www");
  6056. svr.wait_until_ready();
  6057. Client cli("localhost", PORT);
  6058. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6059. ASSERT_TRUE(res);
  6060. EXPECT_EQ(StatusCode::OK_200, res->status);
  6061. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6062. }
  6063. TEST(KeepAliveTest, ReadTimeout) {
  6064. Server svr;
  6065. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6066. std::this_thread::sleep_for(std::chrono::seconds(2));
  6067. res.set_content("a", "text/plain");
  6068. });
  6069. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6070. res.set_content("b", "text/plain");
  6071. });
  6072. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. listen_thread.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli("localhost", PORT);
  6080. cli.set_keep_alive(true);
  6081. cli.set_read_timeout(std::chrono::seconds(1));
  6082. auto resa = cli.Get("/a");
  6083. ASSERT_FALSE(resa);
  6084. EXPECT_EQ(Error::Read, resa.error());
  6085. auto resb = cli.Get("/b");
  6086. ASSERT_TRUE(resb);
  6087. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6088. EXPECT_EQ("b", resb->body);
  6089. }
  6090. TEST(KeepAliveTest, MaxCount) {
  6091. size_t keep_alive_max_count = 3;
  6092. Server svr;
  6093. svr.set_keep_alive_max_count(keep_alive_max_count);
  6094. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6095. res.set_content("Hello World!", "text/plain");
  6096. });
  6097. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6098. auto se = detail::scope_exit([&] {
  6099. svr.stop();
  6100. listen_thread.join();
  6101. ASSERT_FALSE(svr.is_running());
  6102. });
  6103. svr.wait_until_ready();
  6104. Client cli(HOST, PORT);
  6105. cli.set_keep_alive(true);
  6106. for (size_t i = 0; i < 5; i++) {
  6107. auto result = cli.Get("/hi");
  6108. ASSERT_TRUE(result);
  6109. EXPECT_EQ(StatusCode::OK_200, result->status);
  6110. if (i == keep_alive_max_count - 1) {
  6111. EXPECT_EQ("close", result->get_header_value("Connection"));
  6112. } else {
  6113. EXPECT_FALSE(result->has_header("Connection"));
  6114. }
  6115. }
  6116. }
  6117. TEST(KeepAliveTest, Issue1041) {
  6118. Server svr;
  6119. svr.set_keep_alive_timeout(3);
  6120. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6121. res.set_content("Hello World!", "text/plain");
  6122. });
  6123. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6124. auto se = detail::scope_exit([&] {
  6125. svr.stop();
  6126. listen_thread.join();
  6127. ASSERT_FALSE(svr.is_running());
  6128. });
  6129. svr.wait_until_ready();
  6130. Client cli(HOST, PORT);
  6131. cli.set_keep_alive(true);
  6132. auto result = cli.Get("/hi");
  6133. ASSERT_TRUE(result);
  6134. EXPECT_EQ(StatusCode::OK_200, result->status);
  6135. std::this_thread::sleep_for(std::chrono::seconds(5));
  6136. result = cli.Get("/hi");
  6137. ASSERT_TRUE(result);
  6138. EXPECT_EQ(StatusCode::OK_200, result->status);
  6139. }
  6140. TEST(KeepAliveTest, Issue1959) {
  6141. Server svr;
  6142. svr.set_keep_alive_timeout(5);
  6143. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6144. res.set_content("a", "text/plain");
  6145. });
  6146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6147. auto se = detail::scope_exit([&] {
  6148. if (!svr.is_running()) return;
  6149. svr.stop();
  6150. listen_thread.join();
  6151. ASSERT_FALSE(svr.is_running());
  6152. });
  6153. svr.wait_until_ready();
  6154. Client cli("localhost", PORT);
  6155. cli.set_keep_alive(true);
  6156. using namespace std::chrono;
  6157. auto start = steady_clock::now();
  6158. cli.Get("/a");
  6159. svr.stop();
  6160. listen_thread.join();
  6161. auto end = steady_clock::now();
  6162. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6163. EXPECT_LT(elapsed, 5000);
  6164. }
  6165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6166. TEST(KeepAliveTest, SSLClientReconnection) {
  6167. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6168. ASSERT_TRUE(svr.is_valid());
  6169. svr.set_keep_alive_timeout(1);
  6170. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6171. res.set_content("Hello World!", "text/plain");
  6172. });
  6173. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6174. auto se = detail::scope_exit([&] {
  6175. svr.stop();
  6176. listen_thread.join();
  6177. ASSERT_FALSE(svr.is_running());
  6178. });
  6179. svr.wait_until_ready();
  6180. SSLClient cli(HOST, PORT);
  6181. cli.enable_server_certificate_verification(false);
  6182. cli.set_keep_alive(true);
  6183. auto result = cli.Get("/hi");
  6184. ASSERT_TRUE(result);
  6185. EXPECT_EQ(StatusCode::OK_200, result->status);
  6186. result = cli.Get("/hi");
  6187. ASSERT_TRUE(result);
  6188. EXPECT_EQ(StatusCode::OK_200, result->status);
  6189. std::this_thread::sleep_for(std::chrono::seconds(2));
  6190. // Recoonect
  6191. result = cli.Get("/hi");
  6192. ASSERT_TRUE(result);
  6193. EXPECT_EQ(StatusCode::OK_200, result->status);
  6194. result = cli.Get("/hi");
  6195. ASSERT_TRUE(result);
  6196. EXPECT_EQ(StatusCode::OK_200, result->status);
  6197. }
  6198. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6200. ASSERT_TRUE(svr.is_valid());
  6201. svr.set_keep_alive_timeout(1);
  6202. std::string content = "reconnect";
  6203. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6204. res.set_content("Hello World!", "text/plain");
  6205. });
  6206. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6207. auto se = detail::scope_exit([&] {
  6208. svr.stop();
  6209. listen_thread.join();
  6210. ASSERT_FALSE(svr.is_running());
  6211. });
  6212. svr.wait_until_ready();
  6213. SSLClient cli(HOST, PORT);
  6214. cli.enable_server_certificate_verification(false);
  6215. cli.set_keep_alive(true);
  6216. auto result = cli.Post(
  6217. "/hi", content.size(),
  6218. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6219. sink.write(content.c_str(), content.size());
  6220. return true;
  6221. },
  6222. "text/plain");
  6223. ASSERT_TRUE(result);
  6224. EXPECT_EQ(200, result->status);
  6225. std::this_thread::sleep_for(std::chrono::seconds(2));
  6226. // Recoonect
  6227. result = cli.Post(
  6228. "/hi", content.size(),
  6229. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6230. sink.write(content.c_str(), content.size());
  6231. return true;
  6232. },
  6233. "text/plain");
  6234. ASSERT_TRUE(result);
  6235. EXPECT_EQ(200, result->status);
  6236. result = cli.Post(
  6237. "/hi", content.size(),
  6238. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6239. sink.write(content.c_str(), content.size());
  6240. return true;
  6241. },
  6242. "text/plain");
  6243. ASSERT_TRUE(result);
  6244. EXPECT_EQ(200, result->status);
  6245. }
  6246. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6247. {
  6248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6249. ASSERT_TRUE(svr.is_valid());
  6250. svr.Get("/sni", [&](const Request &req, Response &res) {
  6251. std::string expected;
  6252. if (req.ssl) {
  6253. if (const char *sni =
  6254. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6255. expected = sni;
  6256. }
  6257. }
  6258. EXPECT_EQ(expected, req.get_param_value("expected"));
  6259. res.set_content("ok", "text/plain");
  6260. });
  6261. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6262. auto se = detail::scope_exit([&] {
  6263. svr.stop();
  6264. listen_thread.join();
  6265. ASSERT_FALSE(svr.is_running());
  6266. });
  6267. svr.wait_until_ready();
  6268. {
  6269. SSLClient cli("localhost", PORT);
  6270. cli.enable_server_certificate_verification(false);
  6271. auto res = cli.Get("/sni?expected=localhost");
  6272. ASSERT_TRUE(res);
  6273. }
  6274. {
  6275. SSLClient cli("::1", PORT);
  6276. cli.enable_server_certificate_verification(false);
  6277. auto res = cli.Get("/sni?expected=");
  6278. ASSERT_TRUE(res);
  6279. }
  6280. }
  6281. }
  6282. #endif
  6283. TEST(ClientProblemDetectionTest, ContentProvider) {
  6284. Server svr;
  6285. size_t content_length = 1024 * 1024;
  6286. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6287. res.set_content_provider(
  6288. content_length, "text/plain",
  6289. [&](size_t offset, size_t length, DataSink &sink) {
  6290. auto out_len = std::min(length, static_cast<size_t>(1024));
  6291. std::string out(out_len, '@');
  6292. sink.write(out.data(), out_len);
  6293. return offset < 4096;
  6294. },
  6295. [](bool success) { ASSERT_FALSE(success); });
  6296. });
  6297. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6298. res.set_content_provider(
  6299. 0, "text/plain",
  6300. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6301. EXPECT_TRUE(false);
  6302. return true;
  6303. },
  6304. [](bool success) { ASSERT_FALSE(success); });
  6305. });
  6306. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6307. auto se = detail::scope_exit([&] {
  6308. svr.stop();
  6309. listen_thread.join();
  6310. ASSERT_FALSE(svr.is_running());
  6311. });
  6312. svr.wait_until_ready();
  6313. Client cli("localhost", PORT);
  6314. {
  6315. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6316. size_t /*data_length*/) { return false; });
  6317. ASSERT_FALSE(res);
  6318. }
  6319. {
  6320. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6321. size_t /*data_length*/) { return false; });
  6322. ASSERT_TRUE(res);
  6323. }
  6324. }
  6325. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6326. Server svr;
  6327. svr.set_error_handler([](Request const &, Response &res) -> void {
  6328. res.set_chunked_content_provider(
  6329. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6330. sink.os << "hello";
  6331. sink.os << "world";
  6332. sink.done();
  6333. return true;
  6334. });
  6335. });
  6336. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6337. auto se = detail::scope_exit([&] {
  6338. svr.stop();
  6339. listen_thread.join();
  6340. ASSERT_FALSE(svr.is_running());
  6341. });
  6342. svr.wait_until_ready();
  6343. Client cli("localhost", PORT);
  6344. auto res = cli.Get("/");
  6345. ASSERT_TRUE(res);
  6346. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6347. EXPECT_EQ("helloworld", res->body);
  6348. }
  6349. TEST(LongPollingTest, ClientCloseDetection) {
  6350. Server svr;
  6351. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6352. res.set_chunked_content_provider(
  6353. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6354. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6355. sink.os << "hello";
  6356. auto count = 10;
  6357. while (count > 0 && sink.is_writable()) {
  6358. this_thread::sleep_for(chrono::milliseconds(10));
  6359. count--;
  6360. }
  6361. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6362. return true;
  6363. });
  6364. });
  6365. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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("localhost", PORT);
  6373. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6374. EXPECT_EQ("hello", string(data, data_length));
  6375. return false; // close the socket immediately.
  6376. });
  6377. ASSERT_FALSE(res);
  6378. }
  6379. TEST(GetWithParametersTest, GetWithParameters) {
  6380. Server svr;
  6381. svr.Get("/", [&](const Request &req, Response &) {
  6382. EXPECT_EQ("world", req.get_param_value("hello"));
  6383. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6384. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6385. });
  6386. svr.Get("/params", [&](const Request &req, Response &) {
  6387. EXPECT_EQ("world", req.get_param_value("hello"));
  6388. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6389. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6390. });
  6391. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6392. EXPECT_EQ("resource-id", req.matches[1]);
  6393. EXPECT_EQ("foo", req.get_param_value("param1"));
  6394. EXPECT_EQ("bar", req.get_param_value("param2"));
  6395. });
  6396. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6397. EXPECT_EQ("user-id", req.path_params.at("id"));
  6398. EXPECT_EQ("foo", req.get_param_value("param1"));
  6399. EXPECT_EQ("bar", req.get_param_value("param2"));
  6400. });
  6401. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6402. auto se = detail::scope_exit([&] {
  6403. svr.stop();
  6404. listen_thread.join();
  6405. ASSERT_FALSE(svr.is_running());
  6406. });
  6407. svr.wait_until_ready();
  6408. {
  6409. Client cli(HOST, PORT);
  6410. Params params;
  6411. params.emplace("hello", "world");
  6412. params.emplace("hello2", "world2");
  6413. params.emplace("hello3", "world3");
  6414. auto res = cli.Get("/", params, Headers{});
  6415. ASSERT_TRUE(res);
  6416. EXPECT_EQ(StatusCode::OK_200, res->status);
  6417. }
  6418. {
  6419. Client cli(HOST, PORT);
  6420. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6421. ASSERT_TRUE(res);
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. {
  6425. Client cli(HOST, PORT);
  6426. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6427. ASSERT_TRUE(res);
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. }
  6430. {
  6431. Client cli(HOST, PORT);
  6432. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6433. ASSERT_TRUE(res);
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. }
  6436. }
  6437. TEST(GetWithParametersTest, GetWithParameters2) {
  6438. Server svr;
  6439. svr.Get("/", [&](const Request &req, Response &res) {
  6440. auto text = req.get_param_value("hello");
  6441. res.set_content(text, "text/plain");
  6442. });
  6443. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6444. auto se = detail::scope_exit([&] {
  6445. svr.stop();
  6446. listen_thread.join();
  6447. ASSERT_FALSE(svr.is_running());
  6448. });
  6449. svr.wait_until_ready();
  6450. Client cli("localhost", PORT);
  6451. Params params;
  6452. params.emplace("hello", "world");
  6453. std::string body;
  6454. auto res = cli.Get("/", params, Headers{},
  6455. [&](const char *data, size_t data_length) {
  6456. body.append(data, data_length);
  6457. return true;
  6458. });
  6459. ASSERT_TRUE(res);
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. EXPECT_EQ("world", body);
  6462. }
  6463. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6464. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6465. auto host = "httpbin.org";
  6466. auto path = std::string{"/range/32"};
  6467. #else
  6468. auto host = "nghttp2.org";
  6469. auto path = std::string{"/httpbin/range/32"};
  6470. #endif
  6471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6472. SSLClient cli(host);
  6473. #else
  6474. Client cli(host);
  6475. #endif
  6476. cli.set_default_headers({make_range_header({{1, 10}})});
  6477. cli.set_connection_timeout(5);
  6478. {
  6479. auto res = cli.Get(path);
  6480. ASSERT_TRUE(res);
  6481. EXPECT_EQ("bcdefghijk", res->body);
  6482. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6483. }
  6484. {
  6485. auto res = cli.Get(path);
  6486. ASSERT_TRUE(res);
  6487. EXPECT_EQ("bcdefghijk", res->body);
  6488. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6489. }
  6490. }
  6491. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6492. Server svr;
  6493. svr.set_default_headers({{"Hello", "World"}});
  6494. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6495. res.set_content("ok", "text/plain");
  6496. });
  6497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. listen_thread.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. Client cli("localhost", PORT);
  6505. auto res = cli.Get("/");
  6506. ASSERT_TRUE(res);
  6507. EXPECT_EQ(StatusCode::OK_200, res->status);
  6508. EXPECT_EQ("ok", res->body);
  6509. EXPECT_EQ("World", res->get_header_value("Hello"));
  6510. }
  6511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6512. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6514. ASSERT_TRUE(svr.is_valid());
  6515. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6516. std::this_thread::sleep_for(std::chrono::seconds(2));
  6517. res.set_content("a", "text/plain");
  6518. });
  6519. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6520. res.set_content("b", "text/plain");
  6521. });
  6522. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6523. auto se = detail::scope_exit([&] {
  6524. svr.stop();
  6525. listen_thread.join();
  6526. ASSERT_FALSE(svr.is_running());
  6527. });
  6528. svr.wait_until_ready();
  6529. SSLClient cli("localhost", PORT);
  6530. cli.enable_server_certificate_verification(false);
  6531. cli.set_keep_alive(true);
  6532. cli.set_read_timeout(std::chrono::seconds(1));
  6533. auto resa = cli.Get("/a");
  6534. ASSERT_TRUE(!resa);
  6535. EXPECT_EQ(Error::Read, resa.error());
  6536. auto resb = cli.Get("/b");
  6537. ASSERT_TRUE(resb);
  6538. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6539. EXPECT_EQ("b", resb->body);
  6540. }
  6541. #endif
  6542. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6543. protected:
  6544. ServerTestWithAI_PASSIVE()
  6545. : cli_(HOST, PORT)
  6546. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6547. ,
  6548. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6549. #endif
  6550. {
  6551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6552. cli_.enable_server_certificate_verification(false);
  6553. #endif
  6554. }
  6555. virtual void SetUp() {
  6556. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6557. res.set_content("Hello World!", "text/plain");
  6558. });
  6559. t_ = thread(
  6560. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6561. svr_.wait_until_ready();
  6562. }
  6563. virtual void TearDown() {
  6564. svr_.stop();
  6565. t_.join();
  6566. }
  6567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6568. SSLClient cli_;
  6569. SSLServer svr_;
  6570. #else
  6571. Client cli_;
  6572. Server svr_;
  6573. #endif
  6574. thread t_;
  6575. };
  6576. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6577. auto res = cli_.Get("/hi");
  6578. ASSERT_TRUE(res);
  6579. EXPECT_EQ(StatusCode::OK_200, res->status);
  6580. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6581. EXPECT_EQ("Hello World!", res->body);
  6582. }
  6583. class ServerUpDownTest : public ::testing::Test {
  6584. protected:
  6585. ServerUpDownTest() : cli_(HOST, PORT) {}
  6586. virtual void SetUp() {
  6587. t_ = thread([&]() {
  6588. svr_.bind_to_any_port(HOST);
  6589. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6590. ASSERT_TRUE(svr_.listen_after_bind());
  6591. });
  6592. svr_.wait_until_ready();
  6593. }
  6594. virtual void TearDown() {
  6595. svr_.stop();
  6596. t_.join();
  6597. }
  6598. Client cli_;
  6599. Server svr_;
  6600. thread t_;
  6601. };
  6602. TEST_F(ServerUpDownTest, QuickStartStop) {
  6603. // Should not crash, especially when run with
  6604. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6605. }
  6606. class PayloadMaxLengthTest : public ::testing::Test {
  6607. protected:
  6608. PayloadMaxLengthTest()
  6609. : cli_(HOST, PORT)
  6610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6611. ,
  6612. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6613. #endif
  6614. {
  6615. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6616. cli_.enable_server_certificate_verification(false);
  6617. #endif
  6618. }
  6619. virtual void SetUp() {
  6620. svr_.set_payload_max_length(8);
  6621. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6622. res.set_content("test", "text/plain");
  6623. });
  6624. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6625. svr_.wait_until_ready();
  6626. }
  6627. virtual void TearDown() {
  6628. svr_.stop();
  6629. t_.join();
  6630. }
  6631. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6632. SSLClient cli_;
  6633. SSLServer svr_;
  6634. #else
  6635. Client cli_;
  6636. Server svr_;
  6637. #endif
  6638. thread t_;
  6639. };
  6640. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6641. auto res = cli_.Post("/test", "123456789", "text/plain");
  6642. ASSERT_TRUE(res);
  6643. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6644. res = cli_.Post("/test", "12345678", "text/plain");
  6645. ASSERT_TRUE(res);
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. }
  6648. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6649. // Test chunked encoding with payload exceeding the 8-byte limit
  6650. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6651. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6652. ASSERT_TRUE(res);
  6653. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6654. }
  6655. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6656. // Test chunked encoding with payload within the 8-byte limit
  6657. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6658. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6659. ASSERT_TRUE(res);
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. }
  6662. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6663. // Test using send_request to send chunked data exceeding payload limit
  6664. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6665. "Host: " +
  6666. std::string(HOST) + ":" + std::to_string(PORT) +
  6667. "\r\n"
  6668. "Transfer-Encoding: chunked\r\n"
  6669. "Connection: close\r\n"
  6670. "\r\n"
  6671. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6672. "0123456789\r\n"
  6673. "0\r\n" // End chunk
  6674. "\r\n";
  6675. std::string response;
  6676. bool result = send_request(1, chunked_request, &response);
  6677. if (!result) {
  6678. // If send_request fails, it might be because the server closed the
  6679. // connection due to payload limit enforcement, which is acceptable
  6680. SUCCEED()
  6681. << "Server rejected oversized chunked request (connection closed)";
  6682. } else {
  6683. // If we got a response, check if it's an error response or connection was
  6684. // closed early Short response length indicates connection was closed due to
  6685. // payload limit
  6686. if (response.length() <= 10) {
  6687. SUCCEED() << "Server closed connection for oversized chunked request";
  6688. } else {
  6689. // Check for error status codes
  6690. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6691. response.find("Payload Too Large") != std::string::npos ||
  6692. response.find("400") != std::string::npos);
  6693. }
  6694. }
  6695. }
  6696. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6697. // Test request without Content-Length header exceeding payload limit
  6698. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6699. "Host: " +
  6700. std::string(HOST) + ":" +
  6701. std::to_string(PORT) +
  6702. "\r\n"
  6703. "Connection: close\r\n"
  6704. "\r\n";
  6705. // Add payload exceeding the 8-byte limit
  6706. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6707. request_without_content_length += large_payload;
  6708. std::string response;
  6709. bool result = send_request(1, request_without_content_length, &response);
  6710. if (!result) {
  6711. // If send_request fails, server likely closed connection due to payload
  6712. // limit
  6713. SUCCEED() << "Server rejected oversized request without Content-Length "
  6714. "(connection closed)";
  6715. } else {
  6716. // Check if server responded with error or closed connection early
  6717. if (response.length() <= 10) {
  6718. SUCCEED() << "Server closed connection for oversized request without "
  6719. "Content-Length";
  6720. } else {
  6721. // Check for error status codes
  6722. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6723. response.find("Payload Too Large") != std::string::npos ||
  6724. response.find("400") != std::string::npos);
  6725. }
  6726. }
  6727. }
  6728. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6729. // Test request without Content-Length header within payload limit
  6730. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6731. "Host: " +
  6732. std::string(HOST) + ":" +
  6733. std::to_string(PORT) +
  6734. "\r\n"
  6735. "Connection: close\r\n"
  6736. "\r\n";
  6737. // Add payload within the 8-byte limit
  6738. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6739. request_without_content_length += small_payload;
  6740. std::string response;
  6741. bool result = send_request(1, request_without_content_length, &response);
  6742. // For requests without Content-Length, the server may have different behavior
  6743. // The key is that it should not reject due to payload limit for small
  6744. // payloads
  6745. if (result) {
  6746. // Check for any HTTP response (success or error, but not connection closed)
  6747. if (response.length() > 10) {
  6748. SUCCEED()
  6749. << "Server processed request without Content-Length within limit";
  6750. } else {
  6751. // Short response might indicate connection closed, which is acceptable
  6752. SUCCEED() << "Server closed connection for request without "
  6753. "Content-Length (acceptable behavior)";
  6754. }
  6755. } else {
  6756. // Connection failure might be due to protocol requirements
  6757. SUCCEED() << "Connection issue with request without Content-Length "
  6758. "(environment-specific)";
  6759. }
  6760. }
  6761. class LargePayloadMaxLengthTest : public ::testing::Test {
  6762. protected:
  6763. LargePayloadMaxLengthTest()
  6764. : cli_(HOST, PORT)
  6765. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6766. ,
  6767. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6768. #endif
  6769. {
  6770. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6771. cli_.enable_server_certificate_verification(false);
  6772. #endif
  6773. }
  6774. virtual void SetUp() {
  6775. // Set 10MB payload limit
  6776. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6777. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6778. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6779. res.set_content("Large payload test", "text/plain");
  6780. });
  6781. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6782. svr_.wait_until_ready();
  6783. }
  6784. virtual void TearDown() {
  6785. svr_.stop();
  6786. t_.join();
  6787. }
  6788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6789. SSLClient cli_;
  6790. SSLServer svr_;
  6791. #else
  6792. Client cli_;
  6793. Server svr_;
  6794. #endif
  6795. thread t_;
  6796. };
  6797. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6798. // Test chunked encoding with payload within 10MB limit
  6799. std::string medium_payload(5 * 1024 * 1024,
  6800. 'A'); // 5MB payload, within 10MB limit
  6801. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6802. ASSERT_TRUE(res);
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. }
  6805. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6806. // Test chunked encoding with payload exceeding 10MB limit
  6807. std::string large_payload(12 * 1024 * 1024,
  6808. 'B'); // 12MB payload, exceeds 10MB limit
  6809. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6810. ASSERT_TRUE(res);
  6811. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6812. }
  6813. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6814. // Test request without Content-Length header within 10MB limit
  6815. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6816. "Host: " +
  6817. std::string(HOST) + ":" +
  6818. std::to_string(PORT) +
  6819. "\r\n"
  6820. "Connection: close\r\n"
  6821. "\r\n";
  6822. // Add 1MB payload (within 10MB limit)
  6823. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6824. request_without_content_length += medium_payload;
  6825. std::string response;
  6826. bool result = send_request(5, request_without_content_length, &response);
  6827. if (result) {
  6828. // Should get a proper HTTP response for payloads within limit
  6829. if (response.length() > 10) {
  6830. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6831. "10MB limit";
  6832. } else {
  6833. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6834. "Content-Length)";
  6835. }
  6836. } else {
  6837. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6838. }
  6839. }
  6840. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6841. // Test request without Content-Length header exceeding 10MB limit
  6842. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6843. "Host: " +
  6844. std::string(HOST) + ":" +
  6845. std::to_string(PORT) +
  6846. "\r\n"
  6847. "Connection: close\r\n"
  6848. "\r\n";
  6849. // Add 12MB payload (exceeds 10MB limit)
  6850. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6851. request_without_content_length += large_payload;
  6852. std::string response;
  6853. bool result = send_request(10, request_without_content_length, &response);
  6854. if (!result) {
  6855. // Server should close connection due to payload limit
  6856. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6857. "(connection closed)";
  6858. } else {
  6859. // Check for error response
  6860. if (response.length() <= 10) {
  6861. SUCCEED()
  6862. << "Server closed connection for 12MB request exceeding 10MB limit";
  6863. } else {
  6864. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6865. response.find("Payload Too Large") != std::string::npos ||
  6866. response.find("400") != std::string::npos);
  6867. }
  6868. }
  6869. }
  6870. TEST(HostAndPortPropertiesTest, NoSSL) {
  6871. httplib::Client cli("www.google.com", 1234);
  6872. ASSERT_EQ("www.google.com", cli.host());
  6873. ASSERT_EQ(1234, cli.port());
  6874. }
  6875. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6876. httplib::Client cli("www.google.com:1234");
  6877. ASSERT_EQ("www.google.com", cli.host());
  6878. ASSERT_EQ(1234, cli.port());
  6879. }
  6880. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6881. TEST(HostAndPortPropertiesTest, SSL) {
  6882. httplib::SSLClient cli("www.google.com");
  6883. ASSERT_EQ("www.google.com", cli.host());
  6884. ASSERT_EQ(443, cli.port());
  6885. }
  6886. #endif
  6887. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6888. TEST(SSLClientTest, UpdateCAStore) {
  6889. httplib::SSLClient httplib_client("www.google.com");
  6890. auto ca_store_1 = X509_STORE_new();
  6891. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6892. nullptr);
  6893. httplib_client.set_ca_cert_store(ca_store_1);
  6894. auto ca_store_2 = X509_STORE_new();
  6895. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6896. nullptr);
  6897. httplib_client.set_ca_cert_store(ca_store_2);
  6898. }
  6899. TEST(SSLClientTest, ServerNameIndication_Online) {
  6900. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6901. auto host = "httpbin.org";
  6902. auto path = std::string{"/get"};
  6903. #else
  6904. auto host = "nghttp2.org";
  6905. auto path = std::string{"/httpbin/get"};
  6906. #endif
  6907. SSLClient cli(host, 443);
  6908. auto res = cli.Get(path);
  6909. ASSERT_TRUE(res);
  6910. ASSERT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6913. // Use a site that will cause SSL verification failure due to self-signed cert
  6914. SSLClient cli("self-signed.badssl.com", 443);
  6915. cli.enable_server_certificate_verification(true);
  6916. auto res = cli.Get("/");
  6917. ASSERT_TRUE(!res);
  6918. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6919. // For SSL server verification errors, ssl_error should be 0, only
  6920. // ssl_openssl_error should be set
  6921. EXPECT_EQ(0, res.ssl_error());
  6922. // Verify OpenSSL error is captured for SSLServerVerification
  6923. // This occurs when SSL_get_verify_result() returns a verification failure
  6924. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6925. res.ssl_openssl_error());
  6926. }
  6927. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6928. // Use a site where hostname doesn't match the certificate
  6929. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6930. SSLClient cli("wrong.host.badssl.com", 443);
  6931. cli.enable_server_certificate_verification(true);
  6932. cli.enable_server_hostname_verification(true);
  6933. auto res = cli.Get("/");
  6934. ASSERT_TRUE(!res);
  6935. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6936. // For SSL hostname verification errors, ssl_error should be 0, only
  6937. // ssl_openssl_error should be set
  6938. EXPECT_EQ(0, res.ssl_error());
  6939. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6940. // This occurs when verify_host() fails due to hostname mismatch
  6941. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6942. res.ssl_openssl_error());
  6943. }
  6944. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6945. Client cli("https://google.com");
  6946. auto res = cli.Get("/");
  6947. ASSERT_TRUE(res);
  6948. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6949. }
  6950. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6951. SSLClient cli("google.com");
  6952. cli.set_ca_cert_path(CA_CERT_FILE);
  6953. auto res = cli.Get("/");
  6954. ASSERT_TRUE(res);
  6955. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6956. }
  6957. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6958. SSLClient cli("google.com");
  6959. cli.enable_server_certificate_verification(true);
  6960. cli.set_ca_cert_path("hello");
  6961. auto res = cli.Get("/");
  6962. ASSERT_TRUE(!res);
  6963. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6964. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6965. // should be set
  6966. EXPECT_EQ(0, res.ssl_error());
  6967. // Verify OpenSSL error is captured for SSLLoadingCerts
  6968. // This error occurs when SSL_CTX_load_verify_locations() fails
  6969. // > openssl errstr 0x80000002
  6970. // error:80000002:system library::No such file or directory
  6971. // > openssl errstr 0xA000126
  6972. // error:0A000126:SSL routines::unexpected eof while reading
  6973. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6974. res.ssl_openssl_error() == 0xA000126);
  6975. }
  6976. TEST(SSLClientTest, ServerCertificateVerification4) {
  6977. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6978. ASSERT_TRUE(svr.is_valid());
  6979. svr.Get("/test", [&](const Request &, Response &res) {
  6980. res.set_content("test", "text/plain");
  6981. svr.stop();
  6982. ASSERT_TRUE(true);
  6983. });
  6984. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6985. auto se = detail::scope_exit([&] {
  6986. t.join();
  6987. ASSERT_FALSE(svr.is_running());
  6988. });
  6989. svr.wait_until_ready();
  6990. SSLClient cli("127.0.0.1", PORT);
  6991. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6992. cli.enable_server_certificate_verification(true);
  6993. cli.set_connection_timeout(30);
  6994. auto res = cli.Get("/test");
  6995. ASSERT_TRUE(res);
  6996. ASSERT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6999. std::string cert;
  7000. read_file(CA_CERT_FILE, cert);
  7001. SSLClient cli("google.com");
  7002. cli.load_ca_cert_store(cert.data(), cert.size());
  7003. const auto res = cli.Get("/");
  7004. ASSERT_TRUE(res);
  7005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7006. }
  7007. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7008. // clang-format off
  7009. static constexpr char cert[] =
  7010. "GlobalSign Root CA\n"
  7011. "==================\n"
  7012. "-----BEGIN CERTIFICATE-----\n"
  7013. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7014. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7015. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7016. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7017. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7018. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7019. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7020. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7021. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7022. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7023. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7024. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7025. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7026. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7027. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7028. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7029. "-----END CERTIFICATE-----\n";
  7030. // clang-format on
  7031. SSLClient cli("google.com");
  7032. cli.load_ca_cert_store(cert, sizeof(cert));
  7033. const auto res = cli.Get("/");
  7034. ASSERT_TRUE(res);
  7035. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7036. }
  7037. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7038. SSLClient cli("www.youtube.com");
  7039. cli.set_ca_cert_path(CA_CERT_FILE);
  7040. cli.enable_server_certificate_verification(true);
  7041. cli.set_follow_location(true);
  7042. auto res = cli.Get("/");
  7043. ASSERT_TRUE(res);
  7044. ASSERT_EQ(StatusCode::OK_200, res->status);
  7045. }
  7046. TEST(SSLClientTest, Issue2004_Online) {
  7047. Client client("https://google.com");
  7048. client.set_follow_location(true);
  7049. auto res = client.Get("/");
  7050. ASSERT_TRUE(res);
  7051. ASSERT_EQ(StatusCode::OK_200, res->status);
  7052. auto body = res->body;
  7053. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7054. }
  7055. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7056. // Create SSLClient with invalid cert/key to make is_valid() return false
  7057. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7058. "nonexistent_key.pem");
  7059. // is_valid() should be false due to cert loading failure
  7060. ASSERT_FALSE(cli.is_valid());
  7061. auto res = cli.Get("/");
  7062. ASSERT_FALSE(res);
  7063. EXPECT_EQ(Error::SSLConnection, res.error());
  7064. }
  7065. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7066. // Test for Issue #2251: SSL error not properly reported when client cert
  7067. // and key paths are swapped or mismatched
  7068. // This simulates the scenario where user accidentally swaps the cert and key
  7069. // files
  7070. // Using client cert file as private key and vice versa (completely wrong)
  7071. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7072. // Should fail validation due to cert/key mismatch
  7073. ASSERT_FALSE(cli.is_valid());
  7074. // Attempt to make a request should fail with proper error
  7075. auto res = cli.Get("/");
  7076. ASSERT_FALSE(res);
  7077. EXPECT_EQ(Error::SSLConnection, res.error());
  7078. // SSL error should be recorded in the Result object (this is the key fix for
  7079. // Issue #2251)
  7080. auto openssl_error = res.ssl_openssl_error();
  7081. EXPECT_NE(0u, openssl_error);
  7082. }
  7083. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7084. // Another variant: using valid file paths but with mismatched cert/key pair
  7085. // This tests the case where files exist but contain incompatible key material
  7086. // Using client cert with wrong key (cert2 key)
  7087. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7088. // Should fail validation
  7089. ASSERT_FALSE(cli.is_valid());
  7090. auto res = cli.Get("/");
  7091. ASSERT_FALSE(res);
  7092. // Must report error properly, not appear as success
  7093. EXPECT_EQ(Error::SSLConnection, res.error());
  7094. // OpenSSL error should be captured in Result
  7095. EXPECT_NE(0u, res.ssl_openssl_error());
  7096. }
  7097. #if 0
  7098. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7099. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7100. ASSERT_TRUE(cli != nullptr);
  7101. cli->set_address_family(AF_INET6);
  7102. cli->set_interface("en0");
  7103. auto res = cli->Get("/get");
  7104. ASSERT_TRUE(res);
  7105. ASSERT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. #endif
  7108. void ClientCertPresent(
  7109. const std::string &client_cert_file,
  7110. const std::string &client_private_key_file,
  7111. const std::string &client_encrypted_private_key_pass = std::string()) {
  7112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7113. CLIENT_CA_CERT_DIR);
  7114. ASSERT_TRUE(svr.is_valid());
  7115. svr.Get("/test", [&](const Request &req, Response &res) {
  7116. res.set_content("test", "text/plain");
  7117. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7118. ASSERT_TRUE(peer_cert != nullptr);
  7119. auto subject_name = X509_get_subject_name(peer_cert);
  7120. ASSERT_TRUE(subject_name != nullptr);
  7121. std::string common_name;
  7122. {
  7123. char name[BUFSIZ];
  7124. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7125. name, sizeof(name));
  7126. common_name.assign(name, static_cast<size_t>(name_len));
  7127. }
  7128. EXPECT_EQ("Common Name", common_name);
  7129. X509_free(peer_cert);
  7130. });
  7131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7132. auto se = detail::scope_exit([&] {
  7133. svr.stop();
  7134. t.join();
  7135. ASSERT_FALSE(svr.is_running());
  7136. });
  7137. svr.wait_until_ready();
  7138. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7139. client_encrypted_private_key_pass);
  7140. cli.enable_server_certificate_verification(false);
  7141. cli.set_connection_timeout(30);
  7142. auto res = cli.Get("/test");
  7143. ASSERT_TRUE(res);
  7144. ASSERT_EQ(StatusCode::OK_200, res->status);
  7145. }
  7146. TEST(SSLClientServerTest, ClientCertPresent) {
  7147. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7148. }
  7149. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7150. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7151. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7152. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7153. }
  7154. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7155. void MemoryClientCertPresent(
  7156. const std::string &client_cert_file,
  7157. const std::string &client_private_key_file,
  7158. const std::string &client_encrypted_private_key_pass = std::string()) {
  7159. auto f = fopen(SERVER_CERT_FILE, "r+");
  7160. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7161. fclose(f);
  7162. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7163. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7164. fclose(f);
  7165. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7166. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7167. auto client_ca_cert_store = X509_STORE_new();
  7168. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7169. X509_free(client_cert);
  7170. fclose(f);
  7171. f = fopen(client_cert_file.c_str(), "r+");
  7172. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7173. fclose(f);
  7174. f = fopen(client_private_key_file.c_str(), "r+");
  7175. auto client_private_key = PEM_read_PrivateKey(
  7176. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7177. fclose(f);
  7178. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7179. ASSERT_TRUE(svr.is_valid());
  7180. svr.Get("/test", [&](const Request &req, Response &res) {
  7181. res.set_content("test", "text/plain");
  7182. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7183. ASSERT_TRUE(peer_cert != nullptr);
  7184. auto subject_name = X509_get_subject_name(peer_cert);
  7185. ASSERT_TRUE(subject_name != nullptr);
  7186. std::string common_name;
  7187. {
  7188. char name[BUFSIZ];
  7189. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7190. name, sizeof(name));
  7191. common_name.assign(name, static_cast<size_t>(name_len));
  7192. }
  7193. EXPECT_EQ("Common Name", common_name);
  7194. X509_free(peer_cert);
  7195. });
  7196. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7197. auto se = detail::scope_exit([&] {
  7198. svr.stop();
  7199. t.join();
  7200. ASSERT_FALSE(svr.is_running());
  7201. });
  7202. svr.wait_until_ready();
  7203. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7204. client_encrypted_private_key_pass);
  7205. cli.enable_server_certificate_verification(false);
  7206. cli.set_connection_timeout(30);
  7207. auto res = cli.Get("/test");
  7208. ASSERT_TRUE(res);
  7209. ASSERT_EQ(StatusCode::OK_200, res->status);
  7210. X509_free(server_cert);
  7211. EVP_PKEY_free(server_private_key);
  7212. X509_free(client_cert);
  7213. EVP_PKEY_free(client_private_key);
  7214. }
  7215. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7216. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7217. }
  7218. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7219. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7220. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7221. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7222. }
  7223. #endif
  7224. TEST(SSLClientServerTest, ClientCertMissing) {
  7225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7226. CLIENT_CA_CERT_DIR);
  7227. ASSERT_TRUE(svr.is_valid());
  7228. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7230. auto se = detail::scope_exit([&] {
  7231. svr.stop();
  7232. t.join();
  7233. ASSERT_FALSE(svr.is_running());
  7234. });
  7235. svr.wait_until_ready();
  7236. SSLClient cli(HOST, PORT);
  7237. cli.set_connection_timeout(30);
  7238. auto res = cli.Get("/test");
  7239. ASSERT_TRUE(!res);
  7240. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7241. // For SSL server verification errors, ssl_error should be 0, only
  7242. // ssl_openssl_error should be set
  7243. EXPECT_EQ(0, res.ssl_error());
  7244. // Verify OpenSSL error is captured for SSLServerVerification
  7245. // Note: This test may have different error codes depending on the exact
  7246. // verification failure
  7247. EXPECT_NE(0UL, res.ssl_openssl_error());
  7248. }
  7249. TEST(SSLClientServerTest, TrustDirOptional) {
  7250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7251. ASSERT_TRUE(svr.is_valid());
  7252. svr.Get("/test", [&](const Request &, Response &res) {
  7253. res.set_content("test", "text/plain");
  7254. });
  7255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7256. auto se = detail::scope_exit([&] {
  7257. svr.stop();
  7258. t.join();
  7259. ASSERT_FALSE(svr.is_running());
  7260. });
  7261. svr.wait_until_ready();
  7262. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7263. cli.enable_server_certificate_verification(false);
  7264. cli.set_connection_timeout(30);
  7265. auto res = cli.Get("/test");
  7266. ASSERT_TRUE(res);
  7267. ASSERT_EQ(StatusCode::OK_200, res->status);
  7268. }
  7269. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7270. class NoListenSSLServer : public SSLServer {
  7271. public:
  7272. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7273. const char *client_ca_cert_file_path,
  7274. const char *client_ca_cert_dir_path = nullptr)
  7275. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7276. client_ca_cert_dir_path),
  7277. stop_(false) {}
  7278. std::atomic_bool stop_;
  7279. private:
  7280. bool process_and_close_socket(socket_t /*sock*/) override {
  7281. // Don't create SSL context
  7282. while (!stop_.load()) {
  7283. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7284. }
  7285. return true;
  7286. }
  7287. };
  7288. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7289. CLIENT_CA_CERT_FILE);
  7290. ASSERT_TRUE(svr.is_valid());
  7291. svr.Get("/test", [&](const Request &, Response &res) {
  7292. res.set_content("test", "text/plain");
  7293. });
  7294. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7295. auto se = detail::scope_exit([&] {
  7296. svr.stop_ = true;
  7297. svr.stop();
  7298. t.join();
  7299. ASSERT_FALSE(svr.is_running());
  7300. });
  7301. svr.wait_until_ready();
  7302. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7303. cli.enable_server_certificate_verification(false);
  7304. cli.set_connection_timeout(1);
  7305. auto res = cli.Get("/test");
  7306. ASSERT_TRUE(!res);
  7307. EXPECT_EQ(Error::SSLConnection, res.error());
  7308. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7309. }
  7310. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7311. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7312. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7313. SSL_CTX_set_options(&ssl_ctx,
  7314. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7315. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7316. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7317. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7318. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7319. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7320. "ECDHE-DSS-AES128-SHA256:"
  7321. "ECDHE-RSA-AES256-SHA256:"
  7322. "ECDHE-DSS-AES256-SHA256:";
  7323. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7324. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7325. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7326. SSL_FILETYPE_PEM) != 1) {
  7327. return false;
  7328. }
  7329. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7330. CLIENT_CA_CERT_DIR);
  7331. SSL_CTX_set_verify(
  7332. &ssl_ctx,
  7333. SSL_VERIFY_PEER |
  7334. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7335. nullptr);
  7336. return true;
  7337. };
  7338. SSLServer svr(setup_ssl_ctx_callback);
  7339. ASSERT_TRUE(svr.is_valid());
  7340. svr.Get("/test", [&](const Request &req, Response &res) {
  7341. res.set_content("test", "text/plain");
  7342. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7343. ASSERT_TRUE(peer_cert != nullptr);
  7344. auto subject_name = X509_get_subject_name(peer_cert);
  7345. ASSERT_TRUE(subject_name != nullptr);
  7346. std::string common_name;
  7347. {
  7348. char name[BUFSIZ];
  7349. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7350. name, sizeof(name));
  7351. common_name.assign(name, static_cast<size_t>(name_len));
  7352. }
  7353. EXPECT_EQ("Common Name", common_name);
  7354. X509_free(peer_cert);
  7355. });
  7356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7357. auto se = detail::scope_exit([&] {
  7358. svr.stop();
  7359. t.join();
  7360. ASSERT_FALSE(svr.is_running());
  7361. });
  7362. svr.wait_until_ready();
  7363. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7364. cli.enable_server_certificate_verification(false);
  7365. cli.set_connection_timeout(30);
  7366. auto res = cli.Get("/test");
  7367. ASSERT_TRUE(res);
  7368. ASSERT_EQ(StatusCode::OK_200, res->status);
  7369. }
  7370. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7372. ASSERT_TRUE(svr.is_valid());
  7373. // Set up a handler to verify client certificate is present
  7374. bool client_cert_verified = false;
  7375. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7376. // Verify that client certificate was provided
  7377. client_cert_verified = true;
  7378. res.set_content("success", "text/plain");
  7379. });
  7380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. // Client with certificate
  7388. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7389. cli.enable_server_certificate_verification(false);
  7390. cli.set_connection_timeout(30);
  7391. auto res = cli.Get("/test");
  7392. ASSERT_TRUE(res);
  7393. ASSERT_EQ(StatusCode::OK_200, res->status);
  7394. ASSERT_TRUE(client_cert_verified);
  7395. EXPECT_EQ("success", res->body);
  7396. }
  7397. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7398. // Test that when client CA cert file is provided,
  7399. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7400. // Create a server with client authentication
  7401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7402. ASSERT_TRUE(svr.is_valid());
  7403. // We can't directly access the SSL_CTX from SSLServer to verify,
  7404. // but we can test that the server properly requests client certificates
  7405. // and accepts valid ones from the specified CA
  7406. bool handler_called = false;
  7407. svr.Get("/test", [&](const Request &req, Response &res) {
  7408. handler_called = true;
  7409. // Verify that a client certificate was provided
  7410. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7411. ASSERT_TRUE(peer_cert != nullptr);
  7412. // Get the issuer name
  7413. auto issuer_name = X509_get_issuer_name(peer_cert);
  7414. ASSERT_TRUE(issuer_name != nullptr);
  7415. char issuer_buf[256];
  7416. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7417. // The client certificate should be issued by our test CA
  7418. std::string issuer_str(issuer_buf);
  7419. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7420. X509_free(peer_cert);
  7421. res.set_content("authenticated", "text/plain");
  7422. });
  7423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7424. auto se = detail::scope_exit([&] {
  7425. svr.stop();
  7426. t.join();
  7427. ASSERT_FALSE(svr.is_running());
  7428. });
  7429. svr.wait_until_ready();
  7430. // Connect with a client certificate issued by the CA
  7431. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7432. cli.enable_server_certificate_verification(false);
  7433. cli.set_connection_timeout(30);
  7434. auto res = cli.Get("/test");
  7435. ASSERT_TRUE(res);
  7436. ASSERT_EQ(StatusCode::OK_200, res->status);
  7437. ASSERT_TRUE(handler_called);
  7438. EXPECT_EQ("authenticated", res->body);
  7439. }
  7440. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7441. // Test 1: Valid CA file - no error should be recorded
  7442. {
  7443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7444. CLIENT_CA_CERT_FILE);
  7445. ASSERT_TRUE(svr.is_valid());
  7446. // With valid setup, last_ssl_error should be 0
  7447. EXPECT_EQ(0, svr.ssl_last_error());
  7448. }
  7449. // Test 2: Invalid CA file content
  7450. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7451. {
  7452. // Create a temporary file with completely invalid content
  7453. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7454. {
  7455. std::ofstream ofs(temp_invalid_ca);
  7456. ofs << "This is not a certificate file at all\n";
  7457. ofs << "Just plain text content\n";
  7458. }
  7459. // Create server with invalid CA file
  7460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7461. // Clean up temporary file
  7462. std::remove(temp_invalid_ca);
  7463. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7464. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7465. // Note: SSL_CTX_load_verify_locations typically fails first,
  7466. // but our error handling code path is still exercised
  7467. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7468. }
  7469. }
  7470. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7471. // Test SSL server using X509_STORE constructor with client CA certificates
  7472. // This test verifies that Phase 2 implementation correctly extracts CA names
  7473. // from an X509_STORE and sets them in the SSL context
  7474. // Load the CA certificate into memory
  7475. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7476. ASSERT_NE(nullptr, bio);
  7477. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7478. BIO_free(bio);
  7479. ASSERT_NE(nullptr, ca_cert);
  7480. // Create an X509_STORE and add the CA certificate
  7481. auto store = X509_STORE_new();
  7482. ASSERT_NE(nullptr, store);
  7483. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7484. // Load server certificate and private key
  7485. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7486. ASSERT_NE(nullptr, cert_bio);
  7487. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7488. BIO_free(cert_bio);
  7489. ASSERT_NE(nullptr, server_cert);
  7490. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7491. ASSERT_NE(nullptr, key_bio);
  7492. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7493. BIO_free(key_bio);
  7494. ASSERT_NE(nullptr, server_key);
  7495. // Create SSLServer with X509_STORE constructor
  7496. // Note: X509_STORE ownership is transferred to SSL_CTX
  7497. SSLServer svr(server_cert, server_key, store);
  7498. ASSERT_TRUE(svr.is_valid());
  7499. // No SSL error should be recorded for valid setup
  7500. EXPECT_EQ(0, svr.ssl_last_error());
  7501. // Set up server endpoints
  7502. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7503. res.set_content("ok", "text/plain");
  7504. });
  7505. // Start server in a thread
  7506. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7507. svr.wait_until_ready();
  7508. // Connect with client certificate (using constructor with paths)
  7509. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7510. cli.enable_server_certificate_verification(false);
  7511. auto res = cli.Get("/test-x509store");
  7512. ASSERT_TRUE(res);
  7513. EXPECT_EQ(200, res->status);
  7514. EXPECT_EQ("ok", res->body);
  7515. // Clean up
  7516. X509_free(server_cert);
  7517. EVP_PKEY_free(server_key);
  7518. X509_free(ca_cert);
  7519. svr.stop();
  7520. server_thread.join();
  7521. }
  7522. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7523. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7524. // prepare large data
  7525. std::random_device seed_gen;
  7526. std::mt19937 random(seed_gen());
  7527. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7528. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7529. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7530. // server
  7531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7532. ASSERT_TRUE(svr.is_valid());
  7533. svr.Post("/binary", [&](const Request &req, Response &res) {
  7534. EXPECT_EQ(large_size_byte, req.body.size());
  7535. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7536. res.set_content(req.body, "application/octet-stream");
  7537. });
  7538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7539. auto se = detail::scope_exit([&] {
  7540. svr.stop();
  7541. listen_thread.join();
  7542. ASSERT_FALSE(svr.is_running());
  7543. });
  7544. svr.wait_until_ready();
  7545. // client POST
  7546. SSLClient cli("localhost", PORT);
  7547. cli.enable_server_certificate_verification(false);
  7548. cli.set_read_timeout(std::chrono::seconds(100));
  7549. cli.set_write_timeout(std::chrono::seconds(100));
  7550. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7551. large_size_byte, "application/octet-stream");
  7552. // compare
  7553. EXPECT_EQ(StatusCode::OK_200, res->status);
  7554. EXPECT_EQ(large_size_byte, res->body.size());
  7555. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7556. }
  7557. #endif
  7558. #ifdef _WIN32
  7559. TEST(CleanupTest, WSACleanup) {
  7560. int ret = WSACleanup();
  7561. ASSERT_EQ(0, ret);
  7562. }
  7563. #endif
  7564. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7565. TEST(NoSSLSupport, SimpleInterface) {
  7566. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7567. }
  7568. #endif
  7569. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7570. TEST(InvalidScheme, SimpleInterface) {
  7571. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7572. }
  7573. #endif
  7574. TEST(NoScheme, SimpleInterface) {
  7575. Client cli("yahoo.com:80");
  7576. ASSERT_TRUE(cli.is_valid());
  7577. }
  7578. TEST(SendAPI, SimpleInterface_Online) {
  7579. Client cli("http://yahoo.com");
  7580. Request req;
  7581. req.method = "GET";
  7582. req.path = "/";
  7583. auto res = cli.send(req);
  7584. ASSERT_TRUE(res);
  7585. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7586. }
  7587. TEST(SendAPI, WithParamsInRequest) {
  7588. Server svr;
  7589. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7590. EXPECT_TRUE(req.has_param("test"));
  7591. EXPECT_EQ("test_value", req.get_param_value("test"));
  7592. });
  7593. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7594. auto se = detail::scope_exit([&] {
  7595. svr.stop();
  7596. t.join();
  7597. ASSERT_FALSE(svr.is_running());
  7598. });
  7599. svr.wait_until_ready();
  7600. Client cli(HOST, PORT);
  7601. {
  7602. Request req;
  7603. req.method = "GET";
  7604. req.path = "/";
  7605. req.params.emplace("test", "test_value");
  7606. auto res = cli.send(req);
  7607. ASSERT_TRUE(res);
  7608. }
  7609. {
  7610. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7611. ASSERT_TRUE(res);
  7612. }
  7613. }
  7614. TEST(ClientImplMethods, GetSocketTest) {
  7615. httplib::Server svr;
  7616. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7617. res.status = StatusCode::OK_200;
  7618. });
  7619. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7620. auto se = detail::scope_exit([&] {
  7621. svr.stop();
  7622. thread.join();
  7623. ASSERT_FALSE(svr.is_running());
  7624. });
  7625. svr.wait_until_ready();
  7626. {
  7627. httplib::Client cli("http://127.0.0.1:3333");
  7628. cli.set_keep_alive(true);
  7629. // Use the behavior of cpp-httplib of opening the connection
  7630. // only when the first request happens. If that changes,
  7631. // this test would be obsolete.
  7632. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7633. // This also implicitly tests the server. But other tests would fail much
  7634. // earlier than this one to be considered.
  7635. auto res = cli.Get("/");
  7636. ASSERT_TRUE(res);
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7639. }
  7640. }
  7641. // Disabled due to out-of-memory problem on GitHub Actions
  7642. #ifdef _WIN64
  7643. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7644. // allocate content size larger than 2GB in memory
  7645. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7646. char *content = (char *)malloc(content_size);
  7647. ASSERT_TRUE(content);
  7648. Server svr;
  7649. svr.Get("/foo",
  7650. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7651. res.set_content(content, content_size, "application/octet-stream");
  7652. });
  7653. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7654. auto se = detail::scope_exit([&] {
  7655. svr.stop();
  7656. listen_thread.join();
  7657. if (content) free(content);
  7658. ASSERT_FALSE(svr.is_running());
  7659. });
  7660. svr.wait_until_ready();
  7661. Client cli(HOST, PORT);
  7662. auto res = cli.Get("/foo");
  7663. ASSERT_TRUE(res);
  7664. EXPECT_EQ(StatusCode::OK_200, res->status);
  7665. EXPECT_EQ(content_size, res->body.length());
  7666. }
  7667. #endif
  7668. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7669. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7670. Client cli("http://yahoo.com");
  7671. auto res = cli.Get("/");
  7672. ASSERT_TRUE(res);
  7673. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7674. cli.set_follow_location(true);
  7675. res = cli.Get("/");
  7676. ASSERT_TRUE(res);
  7677. EXPECT_EQ(StatusCode::OK_200, res->status);
  7678. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7679. }
  7680. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7681. Client cli("https://yahoo.com");
  7682. auto res = cli.Get("/");
  7683. ASSERT_TRUE(res);
  7684. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7685. cli.set_follow_location(true);
  7686. res = cli.Get("/");
  7687. ASSERT_TRUE(res);
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7690. }
  7691. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7692. Client cli("https://yahoo.com");
  7693. auto res = cli.Get("/");
  7694. ASSERT_TRUE(res);
  7695. ASSERT_FALSE(!res);
  7696. ASSERT_TRUE(res);
  7697. ASSERT_FALSE(res == nullptr);
  7698. ASSERT_TRUE(res != nullptr);
  7699. EXPECT_EQ(Error::Success, res.error());
  7700. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7701. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7703. cli.set_follow_location(true);
  7704. res = cli.Get("/");
  7705. ASSERT_TRUE(res);
  7706. EXPECT_EQ(Error::Success, res.error());
  7707. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7708. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7709. EXPECT_EQ(StatusCode::OK_200, res->status);
  7710. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7711. }
  7712. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7713. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7714. Client cli("https://cdnjs.cloudflare.com");
  7715. auto res =
  7716. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7717. ASSERT_TRUE(res);
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ(287630U, res->body.size());
  7720. EXPECT_EQ("application/javascript; charset=utf-8",
  7721. res->get_header_value("Content-Type"));
  7722. }
  7723. #endif
  7724. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7725. #undef REDIR_HOST // Silence compiler warning
  7726. #define REDIR_HOST "https://httpbingo.org"
  7727. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7728. Client cli(REDIR_HOST);
  7729. cli.set_follow_location(true);
  7730. auto res =
  7731. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7732. ASSERT_TRUE(res);
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. }
  7735. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7736. Client cli(REDIR_HOST);
  7737. cli.set_follow_location(true);
  7738. Params params;
  7739. params.emplace("url", "http://example.com");
  7740. params.emplace("status_code", "302");
  7741. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7742. ASSERT_TRUE(res);
  7743. EXPECT_EQ(StatusCode::OK_200, res->status);
  7744. }
  7745. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7746. Client cli(REDIR_HOST);
  7747. cli.set_follow_location(true);
  7748. Params params;
  7749. params.emplace("url", "http://example.com");
  7750. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7751. ASSERT_TRUE(res);
  7752. EXPECT_EQ(StatusCode::OK_200, res->status);
  7753. }
  7754. TEST(HttpToHttpsRedirectTest, CertFile) {
  7755. Server svr;
  7756. ASSERT_TRUE(svr.is_valid());
  7757. svr.Get("/index", [&](const Request &, Response &res) {
  7758. res.set_redirect("https://127.0.0.1:1235/index");
  7759. svr.stop();
  7760. });
  7761. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7762. ASSERT_TRUE(ssl_svr.is_valid());
  7763. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7764. res.set_content("test", "text/plain");
  7765. ssl_svr.stop();
  7766. });
  7767. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7768. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7769. auto se = detail::scope_exit([&] {
  7770. t2.join();
  7771. t.join();
  7772. ASSERT_FALSE(svr.is_running());
  7773. });
  7774. svr.wait_until_ready();
  7775. ssl_svr.wait_until_ready();
  7776. Client cli("127.0.0.1", PORT);
  7777. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7778. cli.enable_server_certificate_verification(true);
  7779. cli.set_follow_location(true);
  7780. cli.set_connection_timeout(30);
  7781. auto res = cli.Get("/index");
  7782. ASSERT_TRUE(res);
  7783. ASSERT_EQ(StatusCode::OK_200, res->status);
  7784. }
  7785. TEST(SSLClientRedirectTest, CertFile) {
  7786. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7787. ASSERT_TRUE(ssl_svr1.is_valid());
  7788. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7789. res.set_redirect("https://127.0.0.1:1235/index");
  7790. ssl_svr1.stop();
  7791. });
  7792. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7793. ASSERT_TRUE(ssl_svr2.is_valid());
  7794. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7795. res.set_content("test", "text/plain");
  7796. ssl_svr2.stop();
  7797. });
  7798. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7799. thread t2 =
  7800. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7801. auto se = detail::scope_exit([&] {
  7802. t2.join();
  7803. t.join();
  7804. ASSERT_FALSE(ssl_svr1.is_running());
  7805. });
  7806. ssl_svr1.wait_until_ready();
  7807. ssl_svr2.wait_until_ready();
  7808. SSLClient cli("127.0.0.1", PORT);
  7809. std::string cert;
  7810. read_file(SERVER_CERT2_FILE, cert);
  7811. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7812. cli.enable_server_certificate_verification(true);
  7813. cli.set_follow_location(true);
  7814. cli.set_connection_timeout(30);
  7815. auto res = cli.Get("/index");
  7816. ASSERT_TRUE(res);
  7817. ASSERT_EQ(StatusCode::OK_200, res->status);
  7818. }
  7819. TEST(MultipartFormDataTest, LargeData) {
  7820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7821. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7822. const ContentReader &content_reader) {
  7823. if (req.is_multipart_form_data()) {
  7824. std::vector<FormData> items;
  7825. content_reader(
  7826. [&](const FormData &file) {
  7827. items.push_back(file);
  7828. return true;
  7829. },
  7830. [&](const char *data, size_t data_length) {
  7831. items.back().content.append(data, data_length);
  7832. return true;
  7833. });
  7834. EXPECT_TRUE(std::string(items[0].name) == "document");
  7835. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7836. EXPECT_TRUE(items[0].filename == "2MB_data");
  7837. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7838. EXPECT_TRUE(items[1].name == "hello");
  7839. EXPECT_TRUE(items[1].content == "world");
  7840. EXPECT_TRUE(items[1].filename == "");
  7841. EXPECT_TRUE(items[1].content_type == "");
  7842. } else {
  7843. std::string body;
  7844. content_reader([&](const char *data, size_t data_length) {
  7845. body.append(data, data_length);
  7846. return true;
  7847. });
  7848. }
  7849. });
  7850. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7851. auto se = detail::scope_exit([&] {
  7852. svr.stop();
  7853. t.join();
  7854. ASSERT_FALSE(svr.is_running());
  7855. });
  7856. svr.wait_until_ready();
  7857. {
  7858. std::string data(1024 * 1024 * 2, '.');
  7859. std::stringstream buffer;
  7860. buffer << data;
  7861. Client cli("https://localhost:8080");
  7862. cli.enable_server_certificate_verification(false);
  7863. UploadFormDataItems items{
  7864. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7865. {"hello", "world", "", ""},
  7866. };
  7867. auto res = cli.Post("/post", items);
  7868. ASSERT_TRUE(res);
  7869. ASSERT_EQ(StatusCode::OK_200, res->status);
  7870. }
  7871. }
  7872. TEST(MultipartFormDataTest, DataProviderItems) {
  7873. std::random_device seed_gen;
  7874. std::mt19937 random(seed_gen());
  7875. std::string rand1;
  7876. rand1.resize(1000);
  7877. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7878. std::string rand2;
  7879. rand2.resize(3000);
  7880. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7882. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7883. const ContentReader &content_reader) {
  7884. ASSERT_FALSE(req.is_multipart_form_data());
  7885. std::string body;
  7886. content_reader([&](const char *data, size_t data_length) {
  7887. body.append(data, data_length);
  7888. return true;
  7889. });
  7890. EXPECT_EQ(body, "");
  7891. });
  7892. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7893. const ContentReader &content_reader) {
  7894. ASSERT_TRUE(req.is_multipart_form_data());
  7895. std::vector<FormData> items;
  7896. content_reader(
  7897. [&](const FormData &file) {
  7898. items.push_back(file);
  7899. return true;
  7900. },
  7901. [&](const char *data, size_t data_length) {
  7902. items.back().content.append(data, data_length);
  7903. return true;
  7904. });
  7905. ASSERT_TRUE(items.size() == 2);
  7906. EXPECT_EQ(std::string(items[0].name), "name1");
  7907. EXPECT_EQ(items[0].content, "Testing123");
  7908. EXPECT_EQ(items[0].filename, "filename1");
  7909. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7910. EXPECT_EQ(items[1].name, "name2");
  7911. EXPECT_EQ(items[1].content, "Testing456");
  7912. EXPECT_EQ(items[1].filename, "");
  7913. EXPECT_EQ(items[1].content_type, "");
  7914. });
  7915. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7916. const ContentReader &content_reader) {
  7917. ASSERT_TRUE(req.is_multipart_form_data());
  7918. std::vector<FormData> items;
  7919. content_reader(
  7920. [&](const FormData &file) {
  7921. items.push_back(file);
  7922. return true;
  7923. },
  7924. [&](const char *data, size_t data_length) {
  7925. items.back().content.append(data, data_length);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(items.size() == 2);
  7929. EXPECT_EQ(items[0].name, "name3");
  7930. EXPECT_EQ(items[0].content, rand1);
  7931. EXPECT_EQ(items[0].filename, "filename3");
  7932. EXPECT_EQ(items[0].content_type, "");
  7933. EXPECT_EQ(items[1].name, "name4");
  7934. EXPECT_EQ(items[1].content, rand2);
  7935. EXPECT_EQ(items[1].filename, "filename4");
  7936. EXPECT_EQ(items[1].content_type, "");
  7937. });
  7938. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7939. const ContentReader &content_reader) {
  7940. ASSERT_TRUE(req.is_multipart_form_data());
  7941. std::vector<FormData> items;
  7942. content_reader(
  7943. [&](const FormData &file) {
  7944. items.push_back(file);
  7945. return true;
  7946. },
  7947. [&](const char *data, size_t data_length) {
  7948. items.back().content.append(data, data_length);
  7949. return true;
  7950. });
  7951. ASSERT_TRUE(items.size() == 4);
  7952. EXPECT_EQ(std::string(items[0].name), "name1");
  7953. EXPECT_EQ(items[0].content, "Testing123");
  7954. EXPECT_EQ(items[0].filename, "filename1");
  7955. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7956. EXPECT_EQ(items[1].name, "name2");
  7957. EXPECT_EQ(items[1].content, "Testing456");
  7958. EXPECT_EQ(items[1].filename, "");
  7959. EXPECT_EQ(items[1].content_type, "");
  7960. EXPECT_EQ(items[2].name, "name3");
  7961. EXPECT_EQ(items[2].content, rand1);
  7962. EXPECT_EQ(items[2].filename, "filename3");
  7963. EXPECT_EQ(items[2].content_type, "");
  7964. EXPECT_EQ(items[3].name, "name4");
  7965. EXPECT_EQ(items[3].content, rand2);
  7966. EXPECT_EQ(items[3].filename, "filename4");
  7967. EXPECT_EQ(items[3].content_type, "");
  7968. });
  7969. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7970. auto se = detail::scope_exit([&] {
  7971. svr.stop();
  7972. t.join();
  7973. ASSERT_FALSE(svr.is_running());
  7974. });
  7975. svr.wait_until_ready();
  7976. {
  7977. Client cli("https://localhost:8080");
  7978. cli.enable_server_certificate_verification(false);
  7979. UploadFormDataItems items{
  7980. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7981. {"name2", "Testing456", "", ""}, // not a file
  7982. };
  7983. {
  7984. auto res = cli.Post("/post-none", {}, {}, {});
  7985. ASSERT_TRUE(res);
  7986. ASSERT_EQ(StatusCode::OK_200, res->status);
  7987. }
  7988. FormDataProviderItems providers;
  7989. {
  7990. auto res =
  7991. cli.Post("/post-items", {}, items, providers); // empty providers
  7992. ASSERT_TRUE(res);
  7993. ASSERT_EQ(StatusCode::OK_200, res->status);
  7994. }
  7995. providers.push_back({"name3",
  7996. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7997. // test the offset is given correctly at each step
  7998. if (!offset)
  7999. sink.os.write(rand1.data(), 30);
  8000. else if (offset == 30)
  8001. sink.os.write(rand1.data() + 30, 300);
  8002. else if (offset == 330)
  8003. sink.os.write(rand1.data() + 330, 670);
  8004. else if (offset == rand1.size())
  8005. sink.done();
  8006. return true;
  8007. },
  8008. "filename3",
  8009. {}});
  8010. providers.push_back({"name4",
  8011. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8012. // test the offset is given correctly at each step
  8013. if (!offset)
  8014. sink.os.write(rand2.data(), 2000);
  8015. else if (offset == 2000)
  8016. sink.os.write(rand2.data() + 2000, 1);
  8017. else if (offset == 2001)
  8018. sink.os.write(rand2.data() + 2001, 999);
  8019. else if (offset == rand2.size())
  8020. sink.done();
  8021. return true;
  8022. },
  8023. "filename4",
  8024. {}});
  8025. {
  8026. auto res = cli.Post("/post-providers", {}, {}, providers);
  8027. ASSERT_TRUE(res);
  8028. ASSERT_EQ(StatusCode::OK_200, res->status);
  8029. }
  8030. {
  8031. auto res = cli.Post("/post-both", {}, items, providers);
  8032. ASSERT_TRUE(res);
  8033. ASSERT_EQ(StatusCode::OK_200, res->status);
  8034. }
  8035. }
  8036. }
  8037. TEST(MultipartFormDataTest, BadHeader) {
  8038. Server svr;
  8039. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8040. res.set_content("ok", "text/plain");
  8041. });
  8042. thread t = thread([&] { svr.listen(HOST, PORT); });
  8043. auto se = detail::scope_exit([&] {
  8044. svr.stop();
  8045. t.join();
  8046. ASSERT_FALSE(svr.is_running());
  8047. });
  8048. svr.wait_until_ready();
  8049. const std::string body =
  8050. "This is the preamble. It is to be ignored, though it\r\n"
  8051. "is a handy place for composition agents to include an\r\n"
  8052. "explanatory note to non-MIME conformant readers.\r\n"
  8053. "\r\n"
  8054. "\r\n"
  8055. "--simple boundary\r\n"
  8056. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8057. ": BAD...\r\n"
  8058. "\r\n"
  8059. "value1\r\n"
  8060. "--simple boundary\r\n"
  8061. "Content-Disposition: form-data; name=\"field2\"; "
  8062. "filename=\"example.txt\"\r\n"
  8063. "\r\n"
  8064. "value2\r\n"
  8065. "--simple boundary--\r\n"
  8066. "This is the epilogue. It is also to be ignored.\r\n";
  8067. std::string content_type =
  8068. R"(multipart/form-data; boundary="simple boundary")";
  8069. Client cli(HOST, PORT);
  8070. auto res = cli.Post("/post", body, content_type.c_str());
  8071. ASSERT_TRUE(res);
  8072. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8073. }
  8074. TEST(MultipartFormDataTest, WithPreamble) {
  8075. Server svr;
  8076. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8077. res.set_content("ok", "text/plain");
  8078. });
  8079. thread t = thread([&] { svr.listen(HOST, PORT); });
  8080. auto se = detail::scope_exit([&] {
  8081. svr.stop();
  8082. t.join();
  8083. ASSERT_FALSE(svr.is_running());
  8084. });
  8085. svr.wait_until_ready();
  8086. const std::string body =
  8087. "This is the preamble. It is to be ignored, though it\r\n"
  8088. "is a handy place for composition agents to include an\r\n"
  8089. "explanatory note to non-MIME conformant readers.\r\n"
  8090. "\r\n"
  8091. "\r\n"
  8092. "--simple boundary\r\n"
  8093. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8094. "\r\n"
  8095. "value1\r\n"
  8096. "--simple boundary\r\n"
  8097. "Content-Disposition: form-data; name=\"field2\"; "
  8098. "filename=\"example.txt\"\r\n"
  8099. "\r\n"
  8100. "value2\r\n"
  8101. "--simple boundary--\r\n"
  8102. "This is the epilogue. It is also to be ignored.\r\n";
  8103. std::string content_type =
  8104. R"(multipart/form-data; boundary="simple boundary")";
  8105. Client cli(HOST, PORT);
  8106. auto res = cli.Post("/post", body, content_type.c_str());
  8107. ASSERT_TRUE(res);
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8112. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8113. const ContentReader &content_reader) {
  8114. if (req.is_multipart_form_data()) {
  8115. std::vector<FormData> items;
  8116. content_reader(
  8117. [&](const FormData &file) {
  8118. items.push_back(file);
  8119. return true;
  8120. },
  8121. [&](const char *data, size_t data_length) {
  8122. items.back().content.append(data, data_length);
  8123. return true;
  8124. });
  8125. EXPECT_TRUE(std::string(items[0].name) == "document");
  8126. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8127. EXPECT_TRUE(items[0].filename == "2MB_data");
  8128. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8129. EXPECT_TRUE(items[1].name == "hello");
  8130. EXPECT_TRUE(items[1].content == "world");
  8131. EXPECT_TRUE(items[1].filename == "");
  8132. EXPECT_TRUE(items[1].content_type == "");
  8133. } else {
  8134. std::string body;
  8135. content_reader([&](const char *data, size_t data_length) {
  8136. body.append(data, data_length);
  8137. return true;
  8138. });
  8139. }
  8140. });
  8141. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8142. auto se = detail::scope_exit([&] {
  8143. svr.stop();
  8144. t.join();
  8145. ASSERT_FALSE(svr.is_running());
  8146. });
  8147. svr.wait_until_ready();
  8148. {
  8149. std::string data(1024 * 1024 * 2, '.');
  8150. std::stringstream buffer;
  8151. buffer << data;
  8152. Client cli("https://localhost:8080");
  8153. cli.enable_server_certificate_verification(false);
  8154. UploadFormDataItems items{
  8155. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8156. {"hello", "world", "", ""},
  8157. };
  8158. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8159. ASSERT_TRUE(res);
  8160. ASSERT_EQ(StatusCode::OK_200, res->status);
  8161. }
  8162. }
  8163. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8164. std::string data(1024 * 1024 * 2, '&');
  8165. std::stringstream buffer;
  8166. buffer << data;
  8167. Client cli("https://localhost:8080");
  8168. UploadFormDataItems items{
  8169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8170. {"hello", "world", "", ""},
  8171. };
  8172. for (const char &c : " \t\r\n") {
  8173. auto res =
  8174. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8175. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8176. ASSERT_FALSE(res);
  8177. }
  8178. }
  8179. TEST(MultipartFormDataTest, PutFormData) {
  8180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8181. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8182. const ContentReader &content_reader) {
  8183. if (req.is_multipart_form_data()) {
  8184. std::vector<FormData> items;
  8185. content_reader(
  8186. [&](const FormData &file) {
  8187. items.push_back(file);
  8188. return true;
  8189. },
  8190. [&](const char *data, size_t data_length) {
  8191. items.back().content.append(data, data_length);
  8192. return true;
  8193. });
  8194. EXPECT_TRUE(std::string(items[0].name) == "document");
  8195. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8196. EXPECT_TRUE(items[0].filename == "2MB_data");
  8197. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8198. EXPECT_TRUE(items[1].name == "hello");
  8199. EXPECT_TRUE(items[1].content == "world");
  8200. EXPECT_TRUE(items[1].filename == "");
  8201. EXPECT_TRUE(items[1].content_type == "");
  8202. } else {
  8203. std::string body;
  8204. content_reader([&](const char *data, size_t data_length) {
  8205. body.append(data, data_length);
  8206. return true;
  8207. });
  8208. }
  8209. });
  8210. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8211. auto se = detail::scope_exit([&] {
  8212. svr.stop();
  8213. t.join();
  8214. ASSERT_FALSE(svr.is_running());
  8215. });
  8216. svr.wait_until_ready();
  8217. {
  8218. std::string data(1024 * 1024 * 2, '&');
  8219. std::stringstream buffer;
  8220. buffer << data;
  8221. Client cli("https://localhost:8080");
  8222. cli.enable_server_certificate_verification(false);
  8223. UploadFormDataItems items{
  8224. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8225. {"hello", "world", "", ""},
  8226. };
  8227. auto res = cli.Put("/put", items);
  8228. ASSERT_TRUE(res);
  8229. ASSERT_EQ(StatusCode::OK_200, res->status);
  8230. }
  8231. }
  8232. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8234. svr.Put("/put_customboundary",
  8235. [&](const Request &req, const Response & /*res*/,
  8236. const ContentReader &content_reader) {
  8237. if (req.is_multipart_form_data()) {
  8238. std::vector<FormData> items;
  8239. content_reader(
  8240. [&](const FormData &file) {
  8241. items.push_back(file);
  8242. return true;
  8243. },
  8244. [&](const char *data, size_t data_length) {
  8245. items.back().content.append(data, data_length);
  8246. return true;
  8247. });
  8248. EXPECT_TRUE(std::string(items[0].name) == "document");
  8249. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8250. EXPECT_TRUE(items[0].filename == "2MB_data");
  8251. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8252. EXPECT_TRUE(items[1].name == "hello");
  8253. EXPECT_TRUE(items[1].content == "world");
  8254. EXPECT_TRUE(items[1].filename == "");
  8255. EXPECT_TRUE(items[1].content_type == "");
  8256. } else {
  8257. std::string body;
  8258. content_reader([&](const char *data, size_t data_length) {
  8259. body.append(data, data_length);
  8260. return true;
  8261. });
  8262. }
  8263. });
  8264. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8265. auto se = detail::scope_exit([&] {
  8266. svr.stop();
  8267. t.join();
  8268. ASSERT_FALSE(svr.is_running());
  8269. });
  8270. svr.wait_until_ready();
  8271. {
  8272. std::string data(1024 * 1024 * 2, '&');
  8273. std::stringstream buffer;
  8274. buffer << data;
  8275. Client cli("https://localhost:8080");
  8276. cli.enable_server_certificate_verification(false);
  8277. UploadFormDataItems items{
  8278. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8279. {"hello", "world", "", ""},
  8280. };
  8281. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8282. ASSERT_TRUE(res);
  8283. ASSERT_EQ(StatusCode::OK_200, res->status);
  8284. }
  8285. }
  8286. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8287. std::string data(1024 * 1024 * 2, '&');
  8288. std::stringstream buffer;
  8289. buffer << data;
  8290. Client cli("https://localhost:8080");
  8291. cli.enable_server_certificate_verification(false);
  8292. UploadFormDataItems items{
  8293. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8294. {"hello", "world", "", ""},
  8295. };
  8296. for (const char &c : " \t\r\n") {
  8297. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8298. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8299. ASSERT_FALSE(res);
  8300. }
  8301. }
  8302. TEST(MultipartFormDataTest, AlternateFilename) {
  8303. auto handled = false;
  8304. Server svr;
  8305. svr.Post("/test", [&](const Request &req, Response &res) {
  8306. ASSERT_EQ(2u, req.form.files.size());
  8307. ASSERT_EQ(1u, req.form.fields.size());
  8308. // Test files
  8309. const auto &file1 = req.form.get_file("file1");
  8310. ASSERT_EQ("file1", file1.name);
  8311. ASSERT_EQ("A.txt", file1.filename);
  8312. ASSERT_EQ("text/plain", file1.content_type);
  8313. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8314. const auto &file2 = req.form.get_file("file2");
  8315. ASSERT_EQ("file2", file2.name);
  8316. ASSERT_EQ("a.html", file2.filename);
  8317. ASSERT_EQ("text/html", file2.content_type);
  8318. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8319. file2.content);
  8320. // Test text field
  8321. const auto &text = req.form.get_field("text");
  8322. ASSERT_EQ("text default", text);
  8323. res.set_content("ok", "text/plain");
  8324. handled = true;
  8325. });
  8326. thread t = thread([&] { svr.listen(HOST, PORT); });
  8327. auto se = detail::scope_exit([&] {
  8328. svr.stop();
  8329. t.join();
  8330. ASSERT_FALSE(svr.is_running());
  8331. ASSERT_TRUE(handled);
  8332. });
  8333. svr.wait_until_ready();
  8334. auto req = "POST /test HTTP/1.1\r\n"
  8335. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8336. "Content-Length: 399\r\n"
  8337. "\r\n"
  8338. "----------\r\n"
  8339. "Content-Disposition: form-data; name=\"text\"\r\n"
  8340. "\r\n"
  8341. "text default\r\n"
  8342. "----------\r\n"
  8343. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8344. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8345. "Content-Type: text/plain\r\n"
  8346. "\r\n"
  8347. "Content of a.txt.\r\n"
  8348. "\r\n"
  8349. "----------\r\n"
  8350. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8351. "\"a.html\"\r\n"
  8352. "Content-Type: text/html\r\n"
  8353. "\r\n"
  8354. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8355. "\r\n"
  8356. "------------\r\n";
  8357. ASSERT_TRUE(send_request(1, req));
  8358. }
  8359. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8360. auto handled = false;
  8361. Server svr;
  8362. svr.Post("/test", [&](const Request &req, Response &) {
  8363. ASSERT_EQ(2u, req.form.fields.size());
  8364. const auto &text1 = req.form.get_field("text1");
  8365. ASSERT_EQ("text1", text1);
  8366. const auto &text2 = req.form.get_field("text2");
  8367. ASSERT_EQ("text2", text2);
  8368. handled = true;
  8369. });
  8370. thread t = thread([&] { svr.listen(HOST, PORT); });
  8371. auto se = detail::scope_exit([&] {
  8372. svr.stop();
  8373. t.join();
  8374. ASSERT_FALSE(svr.is_running());
  8375. ASSERT_TRUE(handled);
  8376. });
  8377. svr.wait_until_ready();
  8378. auto req = "POST /test HTTP/1.1\r\n"
  8379. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8380. "Content-Length: 146\r\n"
  8381. "\r\n----------\r\n"
  8382. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8383. "\r\n"
  8384. "text1"
  8385. "\r\n----------\r\n"
  8386. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8387. "\r\n"
  8388. "text2"
  8389. "\r\n------------";
  8390. std::string response;
  8391. ASSERT_TRUE(send_request(1, req, &response));
  8392. ASSERT_EQ("200", response.substr(9, 3));
  8393. }
  8394. TEST(MultipartFormDataTest, ContentLength) {
  8395. auto handled = false;
  8396. Server svr;
  8397. svr.Post("/test", [&](const Request &req, Response &) {
  8398. ASSERT_EQ(2u, req.form.fields.size());
  8399. const auto &text1 = req.form.get_field("text1");
  8400. ASSERT_EQ("text1", text1);
  8401. const auto &text2 = req.form.get_field("text2");
  8402. ASSERT_EQ("text2", text2);
  8403. handled = true;
  8404. });
  8405. thread t = thread([&] { svr.listen(HOST, PORT); });
  8406. auto se = detail::scope_exit([&] {
  8407. svr.stop();
  8408. t.join();
  8409. ASSERT_FALSE(svr.is_running());
  8410. ASSERT_TRUE(handled);
  8411. });
  8412. svr.wait_until_ready();
  8413. auto req = "POST /test HTTP/1.1\r\n"
  8414. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8415. "Content-Length: 167\r\n"
  8416. "\r\n----------\r\n"
  8417. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8418. "Content-Length: 5\r\n"
  8419. "\r\n"
  8420. "text1"
  8421. "\r\n----------\r\n"
  8422. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8423. "\r\n"
  8424. "text2"
  8425. "\r\n------------\r\n";
  8426. std::string response;
  8427. ASSERT_TRUE(send_request(1, req, &response));
  8428. ASSERT_EQ("200", response.substr(9, 3));
  8429. }
  8430. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8431. auto handled = false;
  8432. Server svr;
  8433. svr.Post("/test", [&](const Request &req, Response &) {
  8434. ASSERT_EQ(2u, req.form.fields.size());
  8435. const auto &text1 = req.form.get_field("text1");
  8436. ASSERT_EQ("text1", text1);
  8437. // TODO: Add header access for text fields if needed
  8438. const auto &text2 = req.form.get_field("text2");
  8439. ASSERT_EQ("text2", text2);
  8440. // TODO: Header access for text fields needs to be implemented
  8441. // auto &headers = it->second.headers;
  8442. // ASSERT_EQ(3U, headers.size());
  8443. // auto custom_header = headers.find("x-whatever");
  8444. // ASSERT_TRUE(custom_header != headers.end());
  8445. // ASSERT_NE("customvalue", custom_header->second);
  8446. // ASSERT_EQ("CustomValue", custom_header->second);
  8447. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8448. handled = true;
  8449. });
  8450. thread t = thread([&] { svr.listen(HOST, PORT); });
  8451. auto se = detail::scope_exit([&] {
  8452. svr.stop();
  8453. t.join();
  8454. ASSERT_FALSE(svr.is_running());
  8455. ASSERT_TRUE(handled);
  8456. });
  8457. svr.wait_until_ready();
  8458. auto req = "POST /test HTTP/1.1\r\n"
  8459. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8460. "Content-Length: 232\r\n"
  8461. "\r\n----------\r\n"
  8462. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8463. "Content-Length: 5\r\n"
  8464. "X-Test: 1\r\n"
  8465. "\r\n"
  8466. "text1"
  8467. "\r\n----------\r\n"
  8468. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8469. "Content-Type: text/plain\r\n"
  8470. "X-Whatever: CustomValue\r\n"
  8471. "\r\n"
  8472. "text2"
  8473. "\r\n------------\r\n"
  8474. "That should be disregarded. Not even read";
  8475. std::string response;
  8476. ASSERT_TRUE(send_request(1, req, &response));
  8477. ASSERT_EQ("200", response.substr(9, 3));
  8478. }
  8479. #endif
  8480. TEST(MultipartFormDataTest, LargeHeader) {
  8481. auto handled = false;
  8482. Server svr;
  8483. svr.Post("/test", [&](const Request &req, Response &) {
  8484. ASSERT_EQ(1u, req.form.fields.size());
  8485. const auto &text = req.form.get_field("name1");
  8486. ASSERT_EQ("text1", text);
  8487. handled = true;
  8488. });
  8489. thread t = thread([&] { svr.listen(HOST, PORT); });
  8490. auto se = detail::scope_exit([&] {
  8491. svr.stop();
  8492. t.join();
  8493. ASSERT_FALSE(svr.is_running());
  8494. ASSERT_TRUE(handled);
  8495. });
  8496. svr.wait_until_ready();
  8497. auto boundary = std::string("cpp-httplib-multipart-data");
  8498. std::string content = "--" + boundary +
  8499. "\r\n"
  8500. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8501. "\r\n"
  8502. "text1\r\n"
  8503. "--" +
  8504. boundary + "--\r\n";
  8505. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8506. "Content-Type: multipart/form-data;boundary=" +
  8507. boundary +
  8508. "\r\n"
  8509. "Content-Length: " +
  8510. std::to_string(content.size()) +
  8511. "\r\n"
  8512. "Dummy-Header: ";
  8513. std::string header_suffix = "\r\n"
  8514. "\r\n";
  8515. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8516. size_t header_dummy_size =
  8517. read_buff_size -
  8518. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8519. auto header_dummy = std::string(header_dummy_size, '@');
  8520. auto req = header_prefix + header_dummy + header_suffix + content;
  8521. std::string response;
  8522. ASSERT_TRUE(send_request(1, req, &response));
  8523. ASSERT_EQ("200", response.substr(9, 3));
  8524. }
  8525. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8526. static constexpr unsigned int number_of_tasks{1000000};
  8527. std::atomic_uint count{0};
  8528. std::unique_ptr<TaskQueue> task_queue{
  8529. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8530. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8531. auto queued = task_queue->enqueue(
  8532. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8533. EXPECT_TRUE(queued);
  8534. }
  8535. EXPECT_NO_THROW(task_queue->shutdown());
  8536. EXPECT_EQ(number_of_tasks, count.load());
  8537. }
  8538. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8539. static constexpr unsigned int number_of_tasks{1000000};
  8540. static constexpr unsigned int qlimit{2};
  8541. unsigned int queued_count{0};
  8542. std::atomic_uint count{0};
  8543. std::unique_ptr<TaskQueue> task_queue{
  8544. new ThreadPool{/*num_threads=*/1, qlimit}};
  8545. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8546. if (task_queue->enqueue(
  8547. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8548. queued_count++;
  8549. }
  8550. }
  8551. EXPECT_NO_THROW(task_queue->shutdown());
  8552. EXPECT_EQ(queued_count, count.load());
  8553. EXPECT_TRUE(queued_count <= number_of_tasks);
  8554. EXPECT_TRUE(queued_count >= qlimit);
  8555. }
  8556. TEST(TaskQueueTest, MaxQueuedRequests) {
  8557. static constexpr unsigned int qlimit{3};
  8558. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8559. std::condition_variable sem_cv;
  8560. std::mutex sem_mtx;
  8561. int credits = 0;
  8562. bool queued;
  8563. /* Fill up the queue with tasks that will block until we give them credits to
  8564. * complete. */
  8565. for (unsigned int n = 0; n <= qlimit;) {
  8566. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8567. std::unique_lock<std::mutex> lock(sem_mtx);
  8568. while (credits <= 0) {
  8569. sem_cv.wait(lock);
  8570. }
  8571. /* Consume the credit and signal the test code if they are all gone. */
  8572. if (--credits == 0) { sem_cv.notify_one(); }
  8573. });
  8574. if (n < qlimit) {
  8575. /* The first qlimit enqueues must succeed. */
  8576. EXPECT_TRUE(queued);
  8577. } else {
  8578. /* The last one will succeed only when the worker thread
  8579. * starts and dequeues the first blocking task. Although
  8580. * not necessary for the correctness of this test, we sleep for
  8581. * a short while to avoid busy waiting. */
  8582. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8583. }
  8584. if (queued) { n++; }
  8585. }
  8586. /* Further enqueues must fail since the queue is full. */
  8587. for (auto i = 0; i < 4; i++) {
  8588. queued = task_queue->enqueue([] {});
  8589. EXPECT_FALSE(queued);
  8590. }
  8591. /* Give the credits to allow the previous tasks to complete. */
  8592. {
  8593. std::unique_lock<std::mutex> lock(sem_mtx);
  8594. credits += qlimit + 1;
  8595. }
  8596. sem_cv.notify_all();
  8597. /* Wait for all the credits to be consumed. */
  8598. {
  8599. std::unique_lock<std::mutex> lock(sem_mtx);
  8600. while (credits > 0) {
  8601. sem_cv.wait(lock);
  8602. }
  8603. }
  8604. /* Check that we are able again to enqueue at least qlimit tasks. */
  8605. for (unsigned int i = 0; i < qlimit; i++) {
  8606. queued = task_queue->enqueue([] {});
  8607. EXPECT_TRUE(queued);
  8608. }
  8609. EXPECT_NO_THROW(task_queue->shutdown());
  8610. }
  8611. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8612. Server svr;
  8613. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8614. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8615. });
  8616. svr.Get("/hello", [](const Request &req, Response &res) {
  8617. res.set_content(req.get_param_value("key"), "text/plain");
  8618. });
  8619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8620. auto se = detail::scope_exit([&] {
  8621. svr.stop();
  8622. thread.join();
  8623. ASSERT_FALSE(svr.is_running());
  8624. });
  8625. svr.wait_until_ready();
  8626. {
  8627. Client cli(HOST, PORT);
  8628. cli.set_follow_location(true);
  8629. auto res = cli.Get("/");
  8630. ASSERT_TRUE(res);
  8631. EXPECT_EQ(StatusCode::OK_200, res->status);
  8632. EXPECT_EQ("val&key2=val2", res->body);
  8633. }
  8634. }
  8635. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8636. Server svr;
  8637. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8638. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8639. });
  8640. svr.Get("/hello", [](const Request &req, Response &res) {
  8641. res.set_content(req.get_param_value("key"), "text/plain");
  8642. });
  8643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8644. auto se = detail::scope_exit([&] {
  8645. svr.stop();
  8646. thread.join();
  8647. ASSERT_FALSE(svr.is_running());
  8648. });
  8649. svr.wait_until_ready();
  8650. {
  8651. Client cli(HOST, PORT);
  8652. cli.set_follow_location(true);
  8653. auto res = cli.Get("/");
  8654. ASSERT_TRUE(res);
  8655. EXPECT_EQ(StatusCode::OK_200, res->status);
  8656. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8657. }
  8658. }
  8659. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8660. TEST(RedirectTest, Issue2185_Online) {
  8661. SSLClient client("github.com");
  8662. client.set_follow_location(true);
  8663. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8664. "Coollab-Windows.zip");
  8665. ASSERT_TRUE(res);
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ(9920427U, res->body.size());
  8668. }
  8669. #endif
  8670. TEST(VulnerabilityTest, CRLFInjection) {
  8671. Server svr;
  8672. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8673. res.set_content("Hello 1", "text/plain");
  8674. });
  8675. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8676. res.set_content("Hello 2", "text/plain");
  8677. });
  8678. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8679. res.set_content("Hello 3", "text/plain");
  8680. });
  8681. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8682. res.set_content("Hello 4", "text/plain");
  8683. });
  8684. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8685. for (const auto &x : req.headers) {
  8686. auto key = x.first;
  8687. EXPECT_STRNE("evil", key.c_str());
  8688. }
  8689. });
  8690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. thread.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. });
  8696. svr.wait_until_ready();
  8697. {
  8698. Client cli(HOST, PORT);
  8699. cli.Post("/test1", "A=B",
  8700. "application/x-www-form-urlencoded\r\nevil: hello1");
  8701. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8702. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8703. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8704. }
  8705. }
  8706. TEST(PathParamsTest, StaticMatch) {
  8707. const auto pattern = "/users/all";
  8708. detail::PathParamsMatcher matcher(pattern);
  8709. Request request;
  8710. request.path = "/users/all";
  8711. ASSERT_TRUE(matcher.match(request));
  8712. std::unordered_map<std::string, std::string> expected_params = {};
  8713. EXPECT_EQ(request.path_params, expected_params);
  8714. }
  8715. TEST(PathParamsTest, StaticMismatch) {
  8716. const auto pattern = "/users/all";
  8717. detail::PathParamsMatcher matcher(pattern);
  8718. Request request;
  8719. request.path = "/users/1";
  8720. ASSERT_FALSE(matcher.match(request));
  8721. }
  8722. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8723. const auto pattern = "/users/:id/subscriptions";
  8724. detail::PathParamsMatcher matcher(pattern);
  8725. Request request;
  8726. request.path = "/users/42/subscriptions";
  8727. ASSERT_TRUE(matcher.match(request));
  8728. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8729. EXPECT_EQ(request.path_params, expected_params);
  8730. }
  8731. TEST(PathParamsTest, SingleParamInTheEnd) {
  8732. const auto pattern = "/users/:id";
  8733. detail::PathParamsMatcher matcher(pattern);
  8734. Request request;
  8735. request.path = "/users/24";
  8736. ASSERT_TRUE(matcher.match(request));
  8737. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8738. EXPECT_EQ(request.path_params, expected_params);
  8739. }
  8740. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8741. const auto pattern = "/users/:id/";
  8742. detail::PathParamsMatcher matcher(pattern);
  8743. Request request;
  8744. request.path = "/users/42/";
  8745. ASSERT_TRUE(matcher.match(request));
  8746. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8747. EXPECT_EQ(request.path_params, expected_params);
  8748. }
  8749. TEST(PathParamsTest, EmptyParam) {
  8750. const auto pattern = "/users/:id/";
  8751. detail::PathParamsMatcher matcher(pattern);
  8752. Request request;
  8753. request.path = "/users//";
  8754. ASSERT_TRUE(matcher.match(request));
  8755. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8756. EXPECT_EQ(request.path_params, expected_params);
  8757. }
  8758. TEST(PathParamsTest, FragmentMismatch) {
  8759. const auto pattern = "/users/:id/";
  8760. detail::PathParamsMatcher matcher(pattern);
  8761. Request request;
  8762. request.path = "/admins/24/";
  8763. ASSERT_FALSE(matcher.match(request));
  8764. }
  8765. TEST(PathParamsTest, ExtraFragments) {
  8766. const auto pattern = "/users/:id";
  8767. detail::PathParamsMatcher matcher(pattern);
  8768. Request request;
  8769. request.path = "/users/42/subscriptions";
  8770. ASSERT_FALSE(matcher.match(request));
  8771. }
  8772. TEST(PathParamsTest, MissingTrailingParam) {
  8773. const auto pattern = "/users/:id";
  8774. detail::PathParamsMatcher matcher(pattern);
  8775. Request request;
  8776. request.path = "/users";
  8777. ASSERT_FALSE(matcher.match(request));
  8778. }
  8779. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8780. const auto pattern = "/users/:id/subscriptions";
  8781. detail::PathParamsMatcher matcher(pattern);
  8782. Request request;
  8783. request.path = "/users/subscriptions";
  8784. ASSERT_FALSE(matcher.match(request));
  8785. }
  8786. TEST(PathParamsTest, MultipleParams) {
  8787. const auto pattern = "/users/:userid/subscriptions/:subid";
  8788. detail::PathParamsMatcher matcher(pattern);
  8789. Request request;
  8790. request.path = "/users/42/subscriptions/2";
  8791. ASSERT_TRUE(matcher.match(request));
  8792. std::unordered_map<std::string, std::string> expected_params = {
  8793. {"userid", "42"}, {"subid", "2"}};
  8794. EXPECT_EQ(request.path_params, expected_params);
  8795. }
  8796. TEST(PathParamsTest, SequenceOfParams) {
  8797. const auto pattern = "/values/:x/:y/:z";
  8798. detail::PathParamsMatcher matcher(pattern);
  8799. Request request;
  8800. request.path = "/values/1/2/3";
  8801. ASSERT_TRUE(matcher.match(request));
  8802. std::unordered_map<std::string, std::string> expected_params = {
  8803. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8804. EXPECT_EQ(request.path_params, expected_params);
  8805. }
  8806. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8807. const auto pattern = "/prefix:suffix";
  8808. detail::PathParamsMatcher matcher(pattern);
  8809. Request request;
  8810. request.path = "/prefix:suffix";
  8811. ASSERT_TRUE(matcher.match(request));
  8812. const std::unordered_map<std::string, std::string> expected_params = {};
  8813. EXPECT_EQ(request.path_params, expected_params);
  8814. }
  8815. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8816. // If ipv6 regex working, regex match codepath is taken.
  8817. // else port will default to 80 in Client impl
  8818. int clientImplMagicPort = 80;
  8819. int port = 4321;
  8820. // above ports must be different to avoid false negative
  8821. EXPECT_NE(clientImplMagicPort, port);
  8822. std::string ipV6TestURL = "http://[ff06::c3]";
  8823. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8824. CLIENT_PRIVATE_KEY_FILE);
  8825. EXPECT_EQ(cli.port(), port);
  8826. }
  8827. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8828. auto file_path = "./www/dir/index.html";
  8829. auto dir_path = "./www/dir";
  8830. detail::FileStat stat_file(file_path);
  8831. EXPECT_TRUE(stat_file.is_file());
  8832. EXPECT_FALSE(stat_file.is_dir());
  8833. detail::FileStat stat_dir(dir_path);
  8834. EXPECT_FALSE(stat_dir.is_file());
  8835. EXPECT_TRUE(stat_dir.is_dir());
  8836. }
  8837. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8838. // IPv4 with default HTTP port (80)
  8839. EXPECT_EQ("example.com",
  8840. detail::make_host_and_port_string("example.com", 80, false));
  8841. // IPv4 with default HTTPS port (443)
  8842. EXPECT_EQ("example.com",
  8843. detail::make_host_and_port_string("example.com", 443, true));
  8844. // IPv4 with non-default HTTP port
  8845. EXPECT_EQ("example.com:8080",
  8846. detail::make_host_and_port_string("example.com", 8080, false));
  8847. // IPv4 with non-default HTTPS port
  8848. EXPECT_EQ("example.com:8443",
  8849. detail::make_host_and_port_string("example.com", 8443, true));
  8850. // IPv6 with default HTTP port (80)
  8851. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8852. // IPv6 with default HTTPS port (443)
  8853. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8854. // IPv6 with non-default HTTP port
  8855. EXPECT_EQ("[::1]:8080",
  8856. detail::make_host_and_port_string("::1", 8080, false));
  8857. // IPv6 with non-default HTTPS port
  8858. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8859. // IPv6 full address with default port
  8860. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8861. detail::make_host_and_port_string(
  8862. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8863. // IPv6 full address with non-default port
  8864. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8865. detail::make_host_and_port_string(
  8866. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8867. // IPv6 localhost with non-default port
  8868. EXPECT_EQ("[::1]:3000",
  8869. detail::make_host_and_port_string("::1", 3000, false));
  8870. // IPv6 with zone ID (link-local address) with default port
  8871. EXPECT_EQ("[fe80::1%eth0]",
  8872. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8873. // IPv6 with zone ID (link-local address) with non-default port
  8874. EXPECT_EQ("[fe80::1%eth0]:8080",
  8875. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8876. // Edge case: Port 443 with is_ssl=false (should add port)
  8877. EXPECT_EQ("example.com:443",
  8878. detail::make_host_and_port_string("example.com", 443, false));
  8879. // Edge case: Port 80 with is_ssl=true (should add port)
  8880. EXPECT_EQ("example.com:80",
  8881. detail::make_host_and_port_string("example.com", 80, true));
  8882. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8883. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8884. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8885. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8886. // Security fix: Already bracketed IPv6 should not get double brackets
  8887. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8888. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8889. EXPECT_EQ("[::1]:8080",
  8890. detail::make_host_and_port_string("[::1]", 8080, false));
  8891. EXPECT_EQ("[2001:db8::1]:8080",
  8892. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8893. EXPECT_EQ("[fe80::1%eth0]",
  8894. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8895. EXPECT_EQ("[fe80::1%eth0]:8080",
  8896. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8897. // Edge case: Empty host (should return as-is)
  8898. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8899. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8900. // This is a known limitation but shouldn't crash
  8901. EXPECT_EQ("[host:name]",
  8902. detail::make_host_and_port_string("host:name", 80, false));
  8903. // Port number edge cases (no validation, but should not crash)
  8904. EXPECT_EQ("example.com:0",
  8905. detail::make_host_and_port_string("example.com", 0, false));
  8906. EXPECT_EQ("example.com:-1",
  8907. detail::make_host_and_port_string("example.com", -1, false));
  8908. EXPECT_EQ("example.com:65535",
  8909. detail::make_host_and_port_string("example.com", 65535, false));
  8910. EXPECT_EQ("example.com:65536",
  8911. detail::make_host_and_port_string("example.com", 65536, false));
  8912. }
  8913. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8914. Server svr;
  8915. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8916. EXPECT_EQ(res.status, 400);
  8917. });
  8918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8919. auto se = detail::scope_exit([&] {
  8920. svr.stop();
  8921. thread.join();
  8922. ASSERT_FALSE(svr.is_running());
  8923. });
  8924. svr.wait_until_ready();
  8925. Client cli(HOST, PORT);
  8926. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8927. }
  8928. TEST(InvalidHeaderCharsTest, is_field_name) {
  8929. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8930. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8931. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8932. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8933. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8934. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8935. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8936. EXPECT_FALSE(detail::fields::is_field_name(""));
  8937. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8938. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8939. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8940. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8941. }
  8942. TEST(InvalidHeaderCharsTest, is_field_value) {
  8943. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8944. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8945. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8946. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8947. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8948. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8949. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8950. EXPECT_TRUE(detail::fields::is_field_value(""));
  8951. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8952. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8953. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8954. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8955. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8956. }
  8957. TEST(InvalidHeaderCharsTest, OnServer) {
  8958. Server svr;
  8959. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8960. std::string header = "Not Set";
  8961. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8962. res.set_header(header, "value");
  8963. res.set_content("Page Content Page Content", "text/plain");
  8964. });
  8965. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8966. std::string header = "Not Set";
  8967. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8968. res.set_header("X-Test", header);
  8969. res.set_content("Page Content Page Content", "text/plain");
  8970. });
  8971. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8972. auto se = detail::scope_exit([&] {
  8973. svr.stop();
  8974. thread.join();
  8975. ASSERT_FALSE(svr.is_running());
  8976. });
  8977. svr.wait_until_ready();
  8978. Client cli(HOST, PORT);
  8979. {
  8980. auto res = cli.Get(
  8981. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8982. ASSERT_TRUE(res);
  8983. EXPECT_EQ("Page Content Page Content", res->body);
  8984. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8985. }
  8986. {
  8987. auto res = cli.Get(
  8988. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8989. ASSERT_TRUE(res);
  8990. EXPECT_EQ("Page Content Page Content", res->body);
  8991. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8992. }
  8993. }
  8994. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8995. auto handled = false;
  8996. Server svr;
  8997. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8998. thread t = thread([&] { svr.listen(HOST, PORT); });
  8999. auto se = detail::scope_exit([&] {
  9000. svr.stop();
  9001. t.join();
  9002. ASSERT_FALSE(svr.is_running());
  9003. ASSERT_FALSE(handled);
  9004. });
  9005. svr.wait_until_ready();
  9006. auto req = "POST /test HTTP/1.1\r\n"
  9007. "Content-Length: x\r\n"
  9008. "\r\n";
  9009. std::string response;
  9010. ASSERT_TRUE(send_request(1, req, &response));
  9011. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9012. response.substr(0, response.find("\r\n")));
  9013. }
  9014. #ifndef _WIN32
  9015. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9016. static constexpr char reject[] = "Unauthorized";
  9017. static constexpr char accept[] = "Upload accepted";
  9018. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9019. Server svr;
  9020. svr.set_expect_100_continue_handler(
  9021. [](const Request & /*req*/, Response &res) {
  9022. res.status = StatusCode::Unauthorized_401;
  9023. res.set_content(reject, "text/plain");
  9024. return res.status;
  9025. });
  9026. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9027. res.set_content(accept, "text/plain");
  9028. });
  9029. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9030. auto se = detail::scope_exit([&] {
  9031. svr.stop();
  9032. thread.join();
  9033. ASSERT_FALSE(svr.is_running());
  9034. });
  9035. svr.wait_until_ready();
  9036. {
  9037. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9038. curl_easy_init(), &curl_easy_cleanup};
  9039. ASSERT_NE(curl, nullptr);
  9040. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9041. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9042. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9043. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9044. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9045. &curl_slist_free_all};
  9046. ASSERT_NE(list, nullptr);
  9047. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9048. struct read_data {
  9049. size_t read_size;
  9050. size_t total_size;
  9051. } data = {0, total_size};
  9052. using read_callback_t =
  9053. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9054. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9055. void *userdata) -> size_t {
  9056. read_data *data = (read_data *)userdata;
  9057. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9058. std::fill_n(ptr, size * nmemb, 'A');
  9059. data->read_size += size * nmemb;
  9060. return size * nmemb;
  9061. };
  9062. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9063. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9064. std::vector<char> buffer;
  9065. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9066. using write_callback_t =
  9067. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9068. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9069. void *userdata) -> size_t {
  9070. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9071. buffer->reserve(buffer->size() + size * nmemb + 1);
  9072. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9073. return size * nmemb;
  9074. };
  9075. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9076. {
  9077. const auto res = curl_easy_perform(curl.get());
  9078. ASSERT_EQ(res, CURLE_OK);
  9079. }
  9080. {
  9081. auto response_code = long{};
  9082. const auto res =
  9083. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9084. ASSERT_EQ(res, CURLE_OK);
  9085. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9086. }
  9087. {
  9088. auto dl = curl_off_t{};
  9089. const auto res =
  9090. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9091. ASSERT_EQ(res, CURLE_OK);
  9092. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9093. }
  9094. {
  9095. buffer.push_back('\0');
  9096. ASSERT_STRCASEEQ(buffer.data(), reject);
  9097. }
  9098. }
  9099. }
  9100. #endif
  9101. template <typename S, typename C>
  9102. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9103. svr.Get("/stream", [&](const Request &, Response &res) {
  9104. auto data = new std::string("01234567890123456789");
  9105. res.set_content_provider(
  9106. data->size(), "text/plain",
  9107. [&, data](size_t offset, size_t length, DataSink &sink) {
  9108. const size_t DATA_CHUNK_SIZE = 4;
  9109. const auto &d = *data;
  9110. std::this_thread::sleep_for(std::chrono::seconds(1));
  9111. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9112. return true;
  9113. },
  9114. [data](bool success) {
  9115. EXPECT_FALSE(success);
  9116. delete data;
  9117. });
  9118. });
  9119. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9120. auto i = new size_t(0);
  9121. res.set_content_provider(
  9122. "text/plain",
  9123. [i](size_t, DataSink &sink) {
  9124. if (*i < 5) {
  9125. std::this_thread::sleep_for(std::chrono::seconds(1));
  9126. sink.write("abcd", 4);
  9127. (*i)++;
  9128. } else {
  9129. sink.done();
  9130. }
  9131. return true;
  9132. },
  9133. [i](bool success) {
  9134. EXPECT_FALSE(success);
  9135. delete i;
  9136. });
  9137. });
  9138. svr.Get("/chunked", [&](const Request &, Response &res) {
  9139. auto i = new size_t(0);
  9140. res.set_chunked_content_provider(
  9141. "text/plain",
  9142. [i](size_t, DataSink &sink) {
  9143. if (*i < 5) {
  9144. std::this_thread::sleep_for(std::chrono::seconds(1));
  9145. sink.os << "abcd";
  9146. (*i)++;
  9147. } else {
  9148. sink.done();
  9149. }
  9150. return true;
  9151. },
  9152. [i](bool success) {
  9153. EXPECT_FALSE(success);
  9154. delete i;
  9155. });
  9156. });
  9157. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9158. auto se = detail::scope_exit([&] {
  9159. svr.stop();
  9160. listen_thread.join();
  9161. ASSERT_FALSE(svr.is_running());
  9162. });
  9163. svr.wait_until_ready();
  9164. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9165. {
  9166. auto start = std::chrono::steady_clock::now();
  9167. auto res = cli.Get("/stream");
  9168. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9169. std::chrono::steady_clock::now() - start)
  9170. .count();
  9171. ASSERT_FALSE(res);
  9172. EXPECT_EQ(Error::Read, res.error());
  9173. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9174. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9175. }
  9176. {
  9177. auto start = std::chrono::steady_clock::now();
  9178. auto res = cli.Get("/stream_without_length");
  9179. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9180. std::chrono::steady_clock::now() - start)
  9181. .count();
  9182. ASSERT_FALSE(res);
  9183. EXPECT_EQ(Error::Read, res.error());
  9184. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9185. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9186. }
  9187. {
  9188. auto start = std::chrono::steady_clock::now();
  9189. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9190. EXPECT_EQ("abcd", string(data, data_length));
  9191. return true;
  9192. });
  9193. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9194. std::chrono::steady_clock::now() - start)
  9195. .count();
  9196. ASSERT_FALSE(res);
  9197. EXPECT_EQ(Error::Read, res.error());
  9198. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9199. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9200. }
  9201. }
  9202. TEST(MaxTimeoutTest, ContentStream) {
  9203. time_t timeout = 2000;
  9204. time_t threshold = 200;
  9205. Server svr;
  9206. Client cli("localhost", PORT);
  9207. max_timeout_test(svr, cli, timeout, threshold);
  9208. }
  9209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9210. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9211. time_t timeout = 2000;
  9212. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9214. SSLClient cli("localhost", PORT);
  9215. cli.enable_server_certificate_verification(false);
  9216. max_timeout_test(svr, cli, timeout, threshold);
  9217. }
  9218. #endif
  9219. class EventDispatcher {
  9220. public:
  9221. EventDispatcher() {}
  9222. bool wait_event(DataSink *sink) {
  9223. unique_lock<mutex> lk(m_);
  9224. int id = id_;
  9225. // Wait with timeout to prevent hanging if client disconnects
  9226. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9227. [&] { return cid_ == id; })) {
  9228. return false; // Timeout occurred
  9229. }
  9230. sink->write(message_.data(), message_.size());
  9231. return true;
  9232. }
  9233. void send_event(const string &message) {
  9234. lock_guard<mutex> lk(m_);
  9235. cid_ = id_++;
  9236. message_ = message;
  9237. cv_.notify_all();
  9238. }
  9239. private:
  9240. mutex m_;
  9241. condition_variable cv_;
  9242. atomic_int id_{0};
  9243. atomic_int cid_{-1};
  9244. string message_;
  9245. };
  9246. TEST(ClientInThreadTest, Issue2068) {
  9247. EventDispatcher ed;
  9248. Server svr;
  9249. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9250. res.set_chunked_content_provider("text/event-stream",
  9251. [&](size_t /*offset*/, DataSink &sink) {
  9252. return ed.wait_event(&sink);
  9253. });
  9254. });
  9255. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9256. svr.wait_until_ready();
  9257. thread event_thread([&] {
  9258. int id = 0;
  9259. while (svr.is_running()) {
  9260. this_thread::sleep_for(chrono::milliseconds(500));
  9261. std::stringstream ss;
  9262. ss << "data: " << id << "\n\n";
  9263. ed.send_event(ss.str());
  9264. id++;
  9265. }
  9266. });
  9267. auto se = detail::scope_exit([&] {
  9268. svr.stop();
  9269. listen_thread.join();
  9270. event_thread.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. {
  9274. auto client = detail::make_unique<Client>(HOST, PORT);
  9275. client->set_read_timeout(std::chrono::minutes(10));
  9276. std::atomic<bool> stop{false};
  9277. std::thread t([&] {
  9278. client->Get("/event1",
  9279. [&](const char *, size_t) -> bool { return !stop; });
  9280. });
  9281. std::this_thread::sleep_for(std::chrono::seconds(2));
  9282. stop = true;
  9283. client->stop();
  9284. t.join();
  9285. // Reset client after thread has finished
  9286. client.reset();
  9287. }
  9288. }
  9289. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9290. Server svr;
  9291. svr.Get("/", [](const Request &req, Response &res) {
  9292. EXPECT_EQ(2U, req.trailers.size());
  9293. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9294. // Denied
  9295. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9296. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9297. // Accepted
  9298. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9299. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9300. EXPECT_TRUE(req.has_trailer("X-World"));
  9301. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9302. res.set_content("ok", "text/plain");
  9303. });
  9304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9305. auto se = detail::scope_exit([&] {
  9306. svr.stop();
  9307. t.join();
  9308. ASSERT_FALSE(svr.is_running());
  9309. });
  9310. svr.wait_until_ready();
  9311. const std::string req = "GET / HTTP/1.1\r\n"
  9312. "Transfer-Encoding: chunked\r\n"
  9313. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9314. "\r\n"
  9315. "0\r\n"
  9316. "Content-Length: 10\r\n"
  9317. "Host: internal.local\r\n"
  9318. "Content-Type: malicious/content\r\n"
  9319. "Cookie: any\r\n"
  9320. "Set-Cookie: any\r\n"
  9321. "X-Forwarded-For: attacker.com\r\n"
  9322. "X-Real-Ip: 1.1.1.1\r\n"
  9323. "X-Hello: hello\r\n"
  9324. "X-World: world\r\n"
  9325. "\r\n";
  9326. std::string res;
  9327. ASSERT_TRUE(send_request(1, req, &res));
  9328. }