1
0

test.cc 326 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634
  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 <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. #ifndef _WIN32
  147. TEST(SocketStream, wait_writable_UNIX) {
  148. int fds[2];
  149. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  150. const auto asSocketStream = [&](socket_t fd,
  151. std::function<bool(Stream &)> func) {
  152. return detail::process_client_socket(
  153. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  154. };
  155. asSocketStream(fds[0], [&](Stream &s0) {
  156. EXPECT_EQ(s0.socket(), fds[0]);
  157. EXPECT_TRUE(s0.wait_writable());
  158. EXPECT_EQ(0, close(fds[1]));
  159. EXPECT_FALSE(s0.wait_writable());
  160. return true;
  161. });
  162. EXPECT_EQ(0, close(fds[0]));
  163. }
  164. TEST(SocketStream, wait_writable_INET) {
  165. sockaddr_in addr;
  166. memset(&addr, 0, sizeof(addr));
  167. addr.sin_family = AF_INET;
  168. addr.sin_port = htons(PORT + 1);
  169. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  170. int disconnected_svr_sock = -1;
  171. std::thread svr{[&] {
  172. const int s = socket(AF_INET, SOCK_STREAM, 0);
  173. ASSERT_LE(0, s);
  174. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  175. ASSERT_EQ(0, listen(s, 1));
  176. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  177. ASSERT_EQ(0, close(s));
  178. }};
  179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  180. std::thread cli{[&] {
  181. const int s = socket(AF_INET, SOCK_STREAM, 0);
  182. ASSERT_LE(0, s);
  183. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  184. ASSERT_EQ(0, close(s));
  185. }};
  186. cli.join();
  187. svr.join();
  188. ASSERT_NE(disconnected_svr_sock, -1);
  189. const auto asSocketStream = [&](socket_t fd,
  190. std::function<bool(Stream &)> func) {
  191. return detail::process_client_socket(
  192. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  193. };
  194. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  195. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  196. EXPECT_FALSE(ss.wait_writable());
  197. return true;
  198. });
  199. ASSERT_EQ(0, close(disconnected_svr_sock));
  200. }
  201. #endif // #ifndef _WIN32
  202. TEST(ClientTest, MoveConstructible) {
  203. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  204. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  205. }
  206. TEST(ClientTest, MoveAssignable) {
  207. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  208. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  209. }
  210. #ifdef _WIN32
  211. TEST(StartupTest, WSAStartup) {
  212. WSADATA wsaData;
  213. int ret = WSAStartup(0x0002, &wsaData);
  214. ASSERT_EQ(0, ret);
  215. }
  216. #endif
  217. TEST(DecodePathTest, PercentCharacter) {
  218. EXPECT_EQ(
  219. detail::decode_path(
  220. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  221. false),
  222. u8"descrip=Gastos áéíóúñÑ 6");
  223. }
  224. TEST(DecodePathTest, PercentCharacterNUL) {
  225. string expected;
  226. expected.push_back('x');
  227. expected.push_back('\0');
  228. expected.push_back('x');
  229. EXPECT_EQ(detail::decode_path("x%00x", false), expected);
  230. }
  231. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  232. string unescapedCharacters = "-_.!~*'()";
  233. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  234. }
  235. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  236. string reservedCharacters = ";,/?:@&=+$";
  237. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  238. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  239. }
  240. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  241. string chineseCharacters = u8"中国語";
  242. string russianCharacters = u8"дом";
  243. string brazilianCharacters = u8"óculos";
  244. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  245. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  246. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  247. "%D0%B4%D0%BE%D0%BC");
  248. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  249. }
  250. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  251. string unescapedCharacters = "-_.!~*'()";
  252. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  253. }
  254. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  255. string reservedCharacters = ";,/?:@&=+$";
  256. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  257. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  258. }
  259. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  260. string chineseCharacters = u8"中国語";
  261. string russianCharacters = u8"дом";
  262. string brazilianCharacters = u8"óculos";
  263. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  264. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  265. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  266. "%D0%B4%D0%BE%D0%BC");
  267. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  268. }
  269. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  270. // Issue #2082 use case: encoding path component with ampersand
  271. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  272. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  273. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  274. }
  275. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  276. string unescapedCharacters = "-_.!~*'()";
  277. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  278. }
  279. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  280. string reservedCharacters = ";,/?:@&=+$#";
  281. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  282. }
  283. TEST(EncodeUriTest, TestUTF8Characters) {
  284. string chineseCharacters = u8"中国語";
  285. string russianCharacters = u8"дом";
  286. string brazilianCharacters = u8"óculos";
  287. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  288. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  289. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  290. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  291. }
  292. TEST(EncodeUriTest, TestCompleteUri) {
  293. string uri =
  294. "https://example.com/path/to/resource?query=value&param=test#fragment";
  295. EXPECT_EQ(
  296. httplib::encode_uri(uri),
  297. "https://example.com/path/to/resource?query=value&param=test#fragment");
  298. }
  299. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  300. string uri =
  301. "https://example.com/path with spaces/file name.html?q=hello world";
  302. EXPECT_EQ(httplib::encode_uri(uri),
  303. "https://example.com/path%20with%20spaces/"
  304. "file%20name.html?q=hello%20world");
  305. }
  306. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  307. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  308. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  309. }
  310. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  311. string unescapedCharacters = "-_.!~*'()";
  312. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  313. }
  314. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  315. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  316. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  317. string encodedBrazilian = "%C3%B3culos";
  318. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  319. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  320. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  321. }
  322. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  323. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  324. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  325. "Piri Tommy Villiers - on & on");
  326. }
  327. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  328. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  329. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  330. }
  331. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  333. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  334. }
  335. TEST(DecodeUriTest, TestUTF8Characters) {
  336. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  337. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  338. string encodedBrazilian = "%C3%B3culos";
  339. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  340. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  341. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  342. }
  343. TEST(DecodeUriTest, TestCompleteUri) {
  344. string encodedUri = "https://example.com/path%20with%20spaces/"
  345. "file%20name.html?q=hello%20world";
  346. EXPECT_EQ(
  347. httplib::decode_uri(encodedUri),
  348. "https://example.com/path with spaces/file name.html?q=hello world");
  349. }
  350. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  351. string original =
  352. "https://example.com/path with spaces/file name.html?q=hello world";
  353. string encoded = httplib::encode_uri(original);
  354. string decoded = httplib::decode_uri(encoded);
  355. EXPECT_EQ(decoded, original);
  356. }
  357. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  358. string original = "Piri Tommy Villiers - on & on";
  359. string encoded = httplib::encode_uri_component(original);
  360. string decoded = httplib::decode_uri_component(encoded);
  361. EXPECT_EQ(decoded, original);
  362. }
  363. TEST(TrimTests, TrimStringTests) {
  364. EXPECT_EQ("abc", detail::trim_copy("abc"));
  365. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  366. EXPECT_TRUE(detail::trim_copy("").empty());
  367. }
  368. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  369. // Simple case without quality values
  370. std::vector<std::string> result1;
  371. EXPECT_TRUE(detail::parse_accept_header(
  372. "text/html,application/json,text/plain", result1));
  373. EXPECT_EQ(result1.size(), 3U);
  374. EXPECT_EQ(result1[0], "text/html");
  375. EXPECT_EQ(result1[1], "application/json");
  376. EXPECT_EQ(result1[2], "text/plain");
  377. // With quality values
  378. std::vector<std::string> result2;
  379. EXPECT_TRUE(detail::parse_accept_header(
  380. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  381. EXPECT_EQ(result2.size(), 3U);
  382. EXPECT_EQ(result2[0], "application/json"); // highest q value
  383. EXPECT_EQ(result2[1], "text/html");
  384. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  385. }
  386. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  387. // Mixed with and without quality values
  388. std::vector<std::string> result;
  389. EXPECT_TRUE(detail::parse_accept_header(
  390. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  391. EXPECT_EQ(result.size(), 3U);
  392. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  393. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  394. EXPECT_EQ(result[2], "application/json"); // q=0.5
  395. }
  396. TEST(ParseAcceptHeaderTest, EdgeCases) {
  397. // Empty header
  398. std::vector<std::string> empty_result;
  399. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  400. EXPECT_TRUE(empty_result.empty());
  401. // Single type
  402. std::vector<std::string> single_result;
  403. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  404. EXPECT_EQ(single_result.size(), 1U);
  405. EXPECT_EQ(single_result[0], "application/json");
  406. // Wildcard types
  407. std::vector<std::string> wildcard_result;
  408. EXPECT_TRUE(detail::parse_accept_header(
  409. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  410. EXPECT_EQ(wildcard_result.size(), 3U);
  411. EXPECT_EQ(wildcard_result[0], "application/json");
  412. EXPECT_EQ(wildcard_result[1], "text/*");
  413. EXPECT_EQ(wildcard_result[2], "*/*");
  414. }
  415. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  416. // Common browser Accept header
  417. std::vector<std::string> browser_result;
  418. EXPECT_TRUE(
  419. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  420. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  421. browser_result));
  422. EXPECT_EQ(browser_result.size(), 6U);
  423. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  424. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  425. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  426. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  427. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  428. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  429. // API client header
  430. std::vector<std::string> api_result;
  431. EXPECT_TRUE(detail::parse_accept_header(
  432. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  433. api_result));
  434. EXPECT_EQ(api_result.size(), 3U);
  435. EXPECT_EQ(api_result[0], "application/json");
  436. EXPECT_EQ(api_result[1], "application/xml");
  437. EXPECT_EQ(api_result[2], "text/plain");
  438. }
  439. TEST(ParseAcceptHeaderTest, SpecialCases) {
  440. // Quality value with 3 decimal places
  441. std::vector<std::string> decimal_result;
  442. EXPECT_TRUE(detail::parse_accept_header(
  443. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  444. EXPECT_EQ(decimal_result.size(), 2U);
  445. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  446. EXPECT_EQ(decimal_result[1], "text/html");
  447. // Zero quality (should still be included but with lowest priority)
  448. std::vector<std::string> zero_q_result;
  449. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  450. zero_q_result));
  451. EXPECT_EQ(zero_q_result.size(), 2U);
  452. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  453. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  454. // No spaces around commas
  455. std::vector<std::string> no_space_result;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  458. no_space_result));
  459. EXPECT_EQ(no_space_result.size(), 3U);
  460. EXPECT_EQ(no_space_result[0], "text/html");
  461. EXPECT_EQ(no_space_result[1], "application/json");
  462. EXPECT_EQ(no_space_result[2], "text/plain");
  463. }
  464. TEST(ParseAcceptHeaderTest, InvalidCases) {
  465. std::vector<std::string> result;
  466. // Invalid quality value (> 1.0)
  467. EXPECT_FALSE(
  468. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  469. // Invalid quality value (< 0.0)
  470. EXPECT_FALSE(
  471. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  472. // Invalid quality value (not a number)
  473. EXPECT_FALSE(detail::parse_accept_header(
  474. "text/html;q=invalid,application/json", result));
  475. // Empty quality value
  476. EXPECT_FALSE(
  477. detail::parse_accept_header("text/html;q=,application/json", result));
  478. // Invalid media type format (no slash and not wildcard)
  479. EXPECT_FALSE(
  480. detail::parse_accept_header("invalidtype,application/json", result));
  481. // Empty media type
  482. result.clear();
  483. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  484. // Only commas
  485. result.clear();
  486. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  487. // Valid cases should still work
  488. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  489. EXPECT_EQ(result.size(), 1U);
  490. EXPECT_EQ(result[0], "*/*");
  491. EXPECT_TRUE(detail::parse_accept_header("*", result));
  492. EXPECT_EQ(result.size(), 1U);
  493. EXPECT_EQ(result[0], "*");
  494. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  495. EXPECT_EQ(result.size(), 1U);
  496. EXPECT_EQ(result[0], "text/*");
  497. }
  498. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  499. Server svr;
  500. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  501. EXPECT_EQ(req.accept_content_types.size(), 3U);
  502. EXPECT_EQ(req.accept_content_types[0], "application/json");
  503. EXPECT_EQ(req.accept_content_types[1], "text/html");
  504. EXPECT_EQ(req.accept_content_types[2], "*/*");
  505. res.set_content("ok", "text/plain");
  506. });
  507. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  508. EXPECT_TRUE(false);
  509. res.set_content("bad request", "text/plain");
  510. });
  511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  512. auto se = detail::scope_exit([&] {
  513. svr.stop();
  514. listen_thread.join();
  515. ASSERT_FALSE(svr.is_running());
  516. });
  517. svr.wait_until_ready();
  518. Client cli("localhost", PORT);
  519. {
  520. auto res =
  521. cli.Get("/accept_ok",
  522. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  523. ASSERT_TRUE(res);
  524. EXPECT_EQ(StatusCode::OK_200, res->status);
  525. }
  526. {
  527. auto res = cli.Get("/accept_bad_request",
  528. {{"Accept", "text/html;q=abc,application/json"}});
  529. ASSERT_TRUE(res);
  530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  531. }
  532. }
  533. TEST(DivideTest, DivideStringTests) {
  534. auto divide = [](const std::string &str, char d) {
  535. std::string lhs;
  536. std::string rhs;
  537. detail::divide(str, d,
  538. [&](const char *lhs_data, std::size_t lhs_size,
  539. const char *rhs_data, std::size_t rhs_size) {
  540. lhs.assign(lhs_data, lhs_size);
  541. rhs.assign(rhs_data, rhs_size);
  542. });
  543. return std::make_pair(std::move(lhs), std::move(rhs));
  544. };
  545. {
  546. const auto res = divide("", '=');
  547. EXPECT_EQ(res.first, "");
  548. EXPECT_EQ(res.second, "");
  549. }
  550. {
  551. const auto res = divide("=", '=');
  552. EXPECT_EQ(res.first, "");
  553. EXPECT_EQ(res.second, "");
  554. }
  555. {
  556. const auto res = divide(" ", '=');
  557. EXPECT_EQ(res.first, " ");
  558. EXPECT_EQ(res.second, "");
  559. }
  560. {
  561. const auto res = divide("a", '=');
  562. EXPECT_EQ(res.first, "a");
  563. EXPECT_EQ(res.second, "");
  564. }
  565. {
  566. const auto res = divide("a=", '=');
  567. EXPECT_EQ(res.first, "a");
  568. EXPECT_EQ(res.second, "");
  569. }
  570. {
  571. const auto res = divide("=b", '=');
  572. EXPECT_EQ(res.first, "");
  573. EXPECT_EQ(res.second, "b");
  574. }
  575. {
  576. const auto res = divide("a=b", '=');
  577. EXPECT_EQ(res.first, "a");
  578. EXPECT_EQ(res.second, "b");
  579. }
  580. {
  581. const auto res = divide("a=b=", '=');
  582. EXPECT_EQ(res.first, "a");
  583. EXPECT_EQ(res.second, "b=");
  584. }
  585. {
  586. const auto res = divide("a=b=c", '=');
  587. EXPECT_EQ(res.first, "a");
  588. EXPECT_EQ(res.second, "b=c");
  589. }
  590. }
  591. TEST(SplitTest, ParseQueryString) {
  592. string s = "key1=val1&key2=val2&key3=val3";
  593. Params dic;
  594. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  595. [&](const char *b, const char *e) {
  596. string key, val;
  597. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  598. if (key.empty()) {
  599. key.assign(b2, e2);
  600. } else {
  601. val.assign(b2, e2);
  602. }
  603. });
  604. dic.emplace(key, val);
  605. });
  606. EXPECT_EQ("val1", dic.find("key1")->second);
  607. EXPECT_EQ("val2", dic.find("key2")->second);
  608. EXPECT_EQ("val3", dic.find("key3")->second);
  609. }
  610. TEST(SplitTest, ParseInvalidQueryTests) {
  611. {
  612. string s = " ";
  613. Params dict;
  614. detail::parse_query_text(s, dict);
  615. EXPECT_TRUE(dict.empty());
  616. }
  617. {
  618. string s = " = =";
  619. Params dict;
  620. detail::parse_query_text(s, dict);
  621. EXPECT_TRUE(dict.empty());
  622. }
  623. }
  624. TEST(ParseQueryTest, ParseQueryString) {
  625. {
  626. std::string s = "key1=val1&key2=val2&key3=val3";
  627. Params dic;
  628. detail::parse_query_text(s, dic);
  629. EXPECT_EQ("val1", dic.find("key1")->second);
  630. EXPECT_EQ("val2", dic.find("key2")->second);
  631. EXPECT_EQ("val3", dic.find("key3")->second);
  632. }
  633. {
  634. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  635. Params dic;
  636. detail::parse_query_text(s, dic);
  637. EXPECT_EQ("", dic.find("key1")->second);
  638. EXPECT_EQ("val1", dic.find("key2")->second);
  639. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  640. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  641. }
  642. }
  643. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  644. Params dic;
  645. EXPECT_EQ(detail::params_to_query_str(dic), "");
  646. dic.emplace("key1", "val1");
  647. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  648. dic.emplace("key2", "val2");
  649. dic.emplace("key3", "val3");
  650. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  651. }
  652. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  653. string content_type = "multipart/form-data; boundary=something";
  654. string boundary;
  655. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  656. EXPECT_TRUE(ret);
  657. EXPECT_EQ(boundary, "something");
  658. }
  659. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  660. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  661. string boundary;
  662. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  665. }
  666. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  667. string content_type =
  668. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  669. string boundary;
  670. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  671. EXPECT_TRUE(ret);
  672. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  673. }
  674. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  675. string content_type =
  676. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  677. string boundary;
  678. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  679. EXPECT_TRUE(ret);
  680. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  681. }
  682. TEST(GetHeaderValueTest, DefaultValue) {
  683. Headers headers = {{"Dummy", "Dummy"}};
  684. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  685. EXPECT_STREQ("text/plain", val);
  686. }
  687. TEST(GetHeaderValueTest, DefaultValueInt) {
  688. Headers headers = {{"Dummy", "Dummy"}};
  689. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  690. EXPECT_EQ(100ull, val);
  691. }
  692. TEST(GetHeaderValueTest, RegularValue) {
  693. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  694. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  695. EXPECT_STREQ("text/html", val);
  696. }
  697. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  698. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  699. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  700. EXPECT_STREQ("text/html", val);
  701. }
  702. TEST(GetHeaderValueTest, SetContent) {
  703. Response res;
  704. res.set_content("html", "text/html");
  705. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  706. res.set_content("text", "text/plain");
  707. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  708. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  709. }
  710. TEST(GetHeaderValueTest, RegularValueInt) {
  711. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  712. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  713. EXPECT_EQ(100ull, val);
  714. }
  715. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  716. Headers headers = {{"Content-Length", "x"}};
  717. auto is_invalid_value = false;
  718. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  719. is_invalid_value);
  720. EXPECT_EQ(0ull, val);
  721. EXPECT_TRUE(is_invalid_value);
  722. }
  723. TEST(GetHeaderValueTest, Range) {
  724. {
  725. Headers headers = {make_range_header({{1, -1}})};
  726. auto val = detail::get_header_value(headers, "Range", 0, 0);
  727. EXPECT_STREQ("bytes=1-", val);
  728. }
  729. {
  730. Headers headers = {make_range_header({{-1, 1}})};
  731. auto val = detail::get_header_value(headers, "Range", 0, 0);
  732. EXPECT_STREQ("bytes=-1", val);
  733. }
  734. {
  735. Headers headers = {make_range_header({{1, 10}})};
  736. auto val = detail::get_header_value(headers, "Range", 0, 0);
  737. EXPECT_STREQ("bytes=1-10", val);
  738. }
  739. {
  740. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  741. auto val = detail::get_header_value(headers, "Range", 0, 0);
  742. EXPECT_STREQ("bytes=1-10, 100-", val);
  743. }
  744. {
  745. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  746. auto val = detail::get_header_value(headers, "Range", 0, 0);
  747. EXPECT_STREQ("bytes=1-10, 100-200", val);
  748. }
  749. {
  750. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  751. auto val = detail::get_header_value(headers, "Range", 0, 0);
  752. EXPECT_STREQ("bytes=0-0, -1", val);
  753. }
  754. }
  755. TEST(ParseHeaderValueTest, Range) {
  756. {
  757. Ranges ranges;
  758. auto ret = detail::parse_range_header("bytes=1-", ranges);
  759. EXPECT_TRUE(ret);
  760. EXPECT_EQ(1u, ranges.size());
  761. EXPECT_EQ(1u, ranges[0].first);
  762. EXPECT_EQ(-1, ranges[0].second);
  763. }
  764. {
  765. Ranges ranges;
  766. auto ret = detail::parse_range_header("bytes=-1", ranges);
  767. EXPECT_TRUE(ret);
  768. EXPECT_EQ(1u, ranges.size());
  769. EXPECT_EQ(-1, ranges[0].first);
  770. EXPECT_EQ(1u, ranges[0].second);
  771. }
  772. {
  773. Ranges ranges;
  774. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(1u, ranges.size());
  777. EXPECT_EQ(1u, ranges[0].first);
  778. EXPECT_EQ(10u, ranges[0].second);
  779. }
  780. {
  781. Ranges ranges;
  782. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  783. EXPECT_FALSE(ret);
  784. }
  785. {
  786. Ranges ranges;
  787. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(2u, ranges.size());
  790. EXPECT_EQ(1u, ranges[0].first);
  791. EXPECT_EQ(10u, ranges[0].second);
  792. EXPECT_EQ(100u, ranges[1].first);
  793. EXPECT_EQ(-1, ranges[1].second);
  794. }
  795. {
  796. Ranges ranges;
  797. auto ret =
  798. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(3u, ranges.size());
  801. EXPECT_EQ(1u, ranges[0].first);
  802. EXPECT_EQ(10u, ranges[0].second);
  803. EXPECT_EQ(100u, ranges[1].first);
  804. EXPECT_EQ(200u, ranges[1].second);
  805. EXPECT_EQ(300u, ranges[2].first);
  806. EXPECT_EQ(400u, ranges[2].second);
  807. }
  808. {
  809. Ranges ranges;
  810. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  811. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  812. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  813. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  814. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  815. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  816. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  817. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  818. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  819. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  820. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  821. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  822. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  823. EXPECT_TRUE(ranges.empty());
  824. }
  825. }
  826. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  827. Request req;
  828. req.set_header("Accept-Encoding", "gzip");
  829. Response res;
  830. res.set_header("Content-Type", "text/plain");
  831. auto ret = detail::encoding_type(req, res);
  832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  833. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  834. #else
  835. EXPECT_TRUE(ret == detail::EncodingType::None);
  836. #endif
  837. }
  838. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  839. Request req;
  840. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  841. Response res;
  842. res.set_header("Content-Type", "text/plain");
  843. auto ret = detail::encoding_type(req, res);
  844. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  845. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  846. #elif CPPHTTPLIB_ZLIB_SUPPORT
  847. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  848. #elif CPPHTTPLIB_ZSTD_SUPPORT
  849. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  850. #else
  851. EXPECT_TRUE(ret == detail::EncodingType::None);
  852. #endif
  853. }
  854. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  855. Request req;
  856. req.set_header("Accept-Encoding",
  857. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  858. Response res;
  859. res.set_header("Content-Type", "text/plain");
  860. auto ret = detail::encoding_type(req, res);
  861. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  862. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  863. #elif CPPHTTPLIB_ZLIB_SUPPORT
  864. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  865. #elif CPPHTTPLIB_ZSTD_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(BufferStreamTest, read) {
  872. detail::BufferStream strm1;
  873. Stream &strm = strm1;
  874. EXPECT_EQ(5, strm.write("hello"));
  875. char buf[512];
  876. EXPECT_EQ(2, strm.read(buf, 2));
  877. EXPECT_EQ('h', buf[0]);
  878. EXPECT_EQ('e', buf[1]);
  879. EXPECT_EQ(2, strm.read(buf, 2));
  880. EXPECT_EQ('l', buf[0]);
  881. EXPECT_EQ('l', buf[1]);
  882. EXPECT_EQ(1, strm.read(buf, 1));
  883. EXPECT_EQ('o', buf[0]);
  884. EXPECT_EQ(0, strm.read(buf, 1));
  885. }
  886. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  887. auto host = "www.httpwatch.com";
  888. auto ip = hosted_at(host);
  889. EXPECT_EQ("23.96.13.243", ip);
  890. std::vector<std::string> addrs;
  891. hosted_at(host, addrs);
  892. EXPECT_EQ(1u, addrs.size());
  893. }
  894. #if 0 // It depends on each test environment...
  895. TEST(HostnameToIPConversionTest, YouTube_Online) {
  896. auto host = "www.youtube.com";
  897. std::vector<std::string> addrs;
  898. hosted_at(host, addrs);
  899. EXPECT_EQ(20u, addrs.size());
  900. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  901. EXPECT_TRUE(it != addrs.end());
  902. }
  903. #endif
  904. class ChunkedEncodingTest : public ::testing::Test {
  905. protected:
  906. ChunkedEncodingTest()
  907. : cli_(HOST, PORT)
  908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  909. ,
  910. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  911. #endif
  912. {
  913. cli_.set_connection_timeout(2);
  914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  915. cli_.enable_server_certificate_verification(false);
  916. #endif
  917. }
  918. virtual void SetUp() {
  919. read_file("./image.jpg", image_data_);
  920. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  921. res.set_content("Hello World!", "text/plain");
  922. });
  923. svr_.Get(
  924. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  925. res.set_chunked_content_provider(
  926. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  927. size_t remaining = image_data_.size() - offset;
  928. if (remaining == 0) {
  929. sink.done();
  930. } else {
  931. constexpr size_t CHUNK_SIZE = 1024;
  932. size_t send_size = std::min(CHUNK_SIZE, remaining);
  933. sink.write(&image_data_[offset], send_size);
  934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  935. }
  936. return true;
  937. });
  938. });
  939. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  940. svr_.wait_until_ready();
  941. }
  942. virtual void TearDown() {
  943. svr_.stop();
  944. if (!request_threads_.empty()) {
  945. std::this_thread::sleep_for(std::chrono::seconds(1));
  946. for (auto &t : request_threads_) {
  947. t.join();
  948. }
  949. }
  950. t_.join();
  951. }
  952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  953. SSLClient cli_;
  954. SSLServer svr_;
  955. #else
  956. Client cli_;
  957. Server svr_;
  958. #endif
  959. thread t_;
  960. std::vector<thread> request_threads_;
  961. std::string image_data_;
  962. };
  963. TEST_F(ChunkedEncodingTest, NormalGet) {
  964. auto res = cli_.Get("/chunked");
  965. ASSERT_TRUE(res);
  966. std::string out;
  967. read_file("./image.jpg", out);
  968. EXPECT_EQ(StatusCode::OK_200, res->status);
  969. EXPECT_EQ(out, res->body);
  970. }
  971. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  972. std::string body;
  973. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  974. body.append(data, data_length);
  975. return true;
  976. });
  977. ASSERT_TRUE(res);
  978. std::string out;
  979. read_file("./image.jpg", out);
  980. EXPECT_EQ(StatusCode::OK_200, res->status);
  981. EXPECT_EQ(out, body);
  982. }
  983. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  984. std::string body;
  985. auto res = cli_.Get(
  986. "/chunked",
  987. [&](const Response &response) {
  988. EXPECT_EQ(StatusCode::OK_200, response.status);
  989. return true;
  990. },
  991. [&](const char *data, size_t data_length) {
  992. body.append(data, data_length);
  993. return true;
  994. });
  995. ASSERT_TRUE(res);
  996. std::string out;
  997. read_file("./image.jpg", out);
  998. EXPECT_EQ(StatusCode::OK_200, res->status);
  999. EXPECT_EQ(out, body);
  1000. }
  1001. TEST(RangeTest, FromHTTPBin_Online) {
  1002. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1003. auto host = "httpbin.org";
  1004. auto path = std::string{"/range/32"};
  1005. #else
  1006. auto host = "nghttp2.org";
  1007. auto path = std::string{"/httpbin/range/32"};
  1008. #endif
  1009. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1010. auto port = 443;
  1011. SSLClient cli(host, port);
  1012. #else
  1013. auto port = 80;
  1014. Client cli(host, port);
  1015. #endif
  1016. cli.set_connection_timeout(5);
  1017. {
  1018. auto res = cli.Get(path);
  1019. ASSERT_TRUE(res);
  1020. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1021. EXPECT_EQ(StatusCode::OK_200, res->status);
  1022. }
  1023. {
  1024. Headers headers = {make_range_header({{1, -1}})};
  1025. auto res = cli.Get(path, headers);
  1026. ASSERT_TRUE(res);
  1027. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1029. }
  1030. {
  1031. Headers headers = {make_range_header({{1, 10}})};
  1032. auto res = cli.Get(path, headers);
  1033. ASSERT_TRUE(res);
  1034. EXPECT_EQ("bcdefghijk", res->body);
  1035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1036. }
  1037. {
  1038. Headers headers = {make_range_header({{0, 31}})};
  1039. auto res = cli.Get(path, headers);
  1040. ASSERT_TRUE(res);
  1041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1042. EXPECT_EQ(StatusCode::OK_200, res->status);
  1043. }
  1044. {
  1045. Headers headers = {make_range_header({{0, -1}})};
  1046. auto res = cli.Get(path, headers);
  1047. ASSERT_TRUE(res);
  1048. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1049. EXPECT_EQ(StatusCode::OK_200, res->status);
  1050. }
  1051. {
  1052. Headers headers = {make_range_header({{0, 32}})};
  1053. auto res = cli.Get(path, headers);
  1054. ASSERT_TRUE(res);
  1055. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1056. }
  1057. }
  1058. TEST(ConnectionErrorTest, InvalidHost) {
  1059. auto host = "-abcde.com";
  1060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1061. auto port = 443;
  1062. SSLClient cli(host, port);
  1063. #else
  1064. auto port = 80;
  1065. Client cli(host, port);
  1066. #endif
  1067. cli.set_connection_timeout(std::chrono::seconds(2));
  1068. auto res = cli.Get("/");
  1069. ASSERT_TRUE(!res);
  1070. EXPECT_EQ(Error::Connection, res.error());
  1071. }
  1072. TEST(ConnectionErrorTest, InvalidHost2) {
  1073. auto host = "httpbin.org/";
  1074. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1075. SSLClient cli(host);
  1076. #else
  1077. Client cli(host);
  1078. #endif
  1079. cli.set_connection_timeout(std::chrono::seconds(2));
  1080. auto res = cli.Get("/");
  1081. ASSERT_TRUE(!res);
  1082. EXPECT_EQ(Error::Connection, res.error());
  1083. }
  1084. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1085. auto host = "httpbin.org/";
  1086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1087. SSLClient cli(host);
  1088. #else
  1089. Client cli(host);
  1090. #endif
  1091. cli.set_connection_timeout(std::chrono::seconds(2));
  1092. auto res = cli.Get("/");
  1093. ASSERT_TRUE(!res);
  1094. stringstream s;
  1095. s << "error code: " << res.error();
  1096. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1097. }
  1098. TEST(ConnectionErrorTest, InvalidPort) {
  1099. auto host = "localhost";
  1100. auto port = 44380;
  1101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1102. SSLClient cli(host, port);
  1103. #else
  1104. Client cli(host, port);
  1105. #endif
  1106. cli.set_connection_timeout(std::chrono::seconds(2));
  1107. auto res = cli.Get("/");
  1108. ASSERT_TRUE(!res);
  1109. EXPECT_TRUE(Error::Connection == res.error() ||
  1110. Error::ConnectionTimeout == res.error());
  1111. }
  1112. TEST(ConnectionErrorTest, Timeout_Online) {
  1113. auto host = "google.com";
  1114. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1115. auto port = 44380;
  1116. SSLClient cli(host, port);
  1117. #else
  1118. auto port = 8080;
  1119. Client cli(host, port);
  1120. #endif
  1121. cli.set_connection_timeout(std::chrono::seconds(2));
  1122. // only probe one address type so that the error reason
  1123. // correlates to the timed-out IPv4, not the unsupported
  1124. // IPv6 connection attempt
  1125. cli.set_address_family(AF_INET);
  1126. auto res = cli.Get("/");
  1127. ASSERT_TRUE(!res);
  1128. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1129. }
  1130. TEST(CancelTest, NoCancel_Online) {
  1131. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1132. auto host = "httpbin.org";
  1133. auto path = std::string{"/range/32"};
  1134. #else
  1135. auto host = "nghttp2.org";
  1136. auto path = std::string{"/httpbin/range/32"};
  1137. #endif
  1138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1139. auto port = 443;
  1140. SSLClient cli(host, port);
  1141. #else
  1142. auto port = 80;
  1143. Client cli(host, port);
  1144. #endif
  1145. cli.set_connection_timeout(std::chrono::seconds(5));
  1146. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1147. ASSERT_TRUE(res);
  1148. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1149. EXPECT_EQ(StatusCode::OK_200, res->status);
  1150. }
  1151. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1152. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1153. auto host = "httpbin.org";
  1154. auto path = std::string{"/range/32"};
  1155. #else
  1156. auto host = "nghttp2.org";
  1157. auto path = std::string{"/httpbin/range/32"};
  1158. #endif
  1159. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1160. auto port = 443;
  1161. SSLClient cli(host, port);
  1162. #else
  1163. auto port = 80;
  1164. Client cli(host, port);
  1165. #endif
  1166. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1167. cli.set_connection_timeout(std::chrono::seconds(5));
  1168. ASSERT_TRUE(!res);
  1169. EXPECT_EQ(Error::Canceled, res.error());
  1170. }
  1171. TEST(CancelTest, WithCancelLargePayload_Online) {
  1172. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1173. auto host = "httpbin.org";
  1174. auto path = std::string{"/range/65536"};
  1175. #else
  1176. auto host = "nghttp2.org";
  1177. auto path = std::string{"/httpbin/range/65536"};
  1178. #endif
  1179. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1180. auto port = 443;
  1181. SSLClient cli(host, port);
  1182. #else
  1183. auto port = 80;
  1184. Client cli(host, port);
  1185. #endif
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. uint32_t count = 0;
  1188. auto res =
  1189. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1190. ASSERT_TRUE(!res);
  1191. EXPECT_EQ(Error::Canceled, res.error());
  1192. }
  1193. TEST(CancelTest, NoCancelPost) {
  1194. Server svr;
  1195. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1196. res.set_content("Hello World!", "text/plain");
  1197. });
  1198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1199. auto se = detail::scope_exit([&] {
  1200. svr.stop();
  1201. thread.join();
  1202. ASSERT_FALSE(svr.is_running());
  1203. });
  1204. svr.wait_until_ready();
  1205. Client cli(HOST, PORT);
  1206. cli.set_connection_timeout(std::chrono::seconds(5));
  1207. auto res =
  1208. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1209. "application/json", [](uint64_t, uint64_t) { return true; });
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("Hello World!", res->body);
  1212. EXPECT_EQ(StatusCode::OK_200, res->status);
  1213. }
  1214. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1215. Server svr;
  1216. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1217. res.set_content("Hello World!", "text/plain");
  1218. });
  1219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1220. auto se = detail::scope_exit([&] {
  1221. svr.stop();
  1222. thread.join();
  1223. ASSERT_FALSE(svr.is_running());
  1224. });
  1225. svr.wait_until_ready();
  1226. Client cli(HOST, PORT);
  1227. cli.set_connection_timeout(std::chrono::seconds(5));
  1228. auto res =
  1229. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1230. "application/json", [](uint64_t, uint64_t) { return false; });
  1231. ASSERT_TRUE(!res);
  1232. EXPECT_EQ(Error::Canceled, res.error());
  1233. }
  1234. TEST(CancelTest, WithCancelLargePayloadPost) {
  1235. Server svr;
  1236. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1237. res.set_content(LARGE_DATA, "text/plain");
  1238. });
  1239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1240. auto se = detail::scope_exit([&] {
  1241. svr.stop();
  1242. thread.join();
  1243. ASSERT_FALSE(svr.is_running());
  1244. });
  1245. svr.wait_until_ready();
  1246. Client cli(HOST, PORT);
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res =
  1249. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1250. "application/json", [](uint64_t, uint64_t) { return false; });
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_EQ(Error::Canceled, res.error());
  1253. }
  1254. TEST(CancelTest, NoCancelPut) {
  1255. Server svr;
  1256. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1257. res.set_content("Hello World!", "text/plain");
  1258. });
  1259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1260. auto se = detail::scope_exit([&] {
  1261. svr.stop();
  1262. thread.join();
  1263. ASSERT_FALSE(svr.is_running());
  1264. });
  1265. svr.wait_until_ready();
  1266. Client cli(HOST, PORT);
  1267. cli.set_connection_timeout(std::chrono::seconds(5));
  1268. auto res =
  1269. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1270. "application/json", [](uint64_t, uint64_t) { return true; });
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ("Hello World!", res->body);
  1273. EXPECT_EQ(StatusCode::OK_200, res->status);
  1274. }
  1275. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1276. Server svr;
  1277. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1278. res.set_content("Hello World!", "text/plain");
  1279. });
  1280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1281. auto se = detail::scope_exit([&] {
  1282. svr.stop();
  1283. thread.join();
  1284. ASSERT_FALSE(svr.is_running());
  1285. });
  1286. svr.wait_until_ready();
  1287. Client cli(HOST, PORT);
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res =
  1290. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1291. "application/json", [](uint64_t, uint64_t) { return false; });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, WithCancelLargePayloadPut) {
  1296. Server svr;
  1297. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content(LARGE_DATA, "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.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return false; });
  1312. ASSERT_TRUE(!res);
  1313. EXPECT_EQ(Error::Canceled, res.error());
  1314. }
  1315. TEST(CancelTest, NoCancelPatch) {
  1316. Server svr;
  1317. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1318. res.set_content("Hello World!", "text/plain");
  1319. });
  1320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1321. auto se = detail::scope_exit([&] {
  1322. svr.stop();
  1323. thread.join();
  1324. ASSERT_FALSE(svr.is_running());
  1325. });
  1326. svr.wait_until_ready();
  1327. Client cli(HOST, PORT);
  1328. cli.set_connection_timeout(std::chrono::seconds(5));
  1329. auto res =
  1330. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1331. "application/json", [](uint64_t, uint64_t) { return true; });
  1332. ASSERT_TRUE(res);
  1333. EXPECT_EQ("Hello World!", res->body);
  1334. EXPECT_EQ(StatusCode::OK_200, res->status);
  1335. }
  1336. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1337. Server svr;
  1338. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "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.Patch("/", 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, WithCancelLargePayloadPatch) {
  1357. Server svr;
  1358. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content(LARGE_DATA, "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.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return false; });
  1373. ASSERT_TRUE(!res);
  1374. EXPECT_EQ(Error::Canceled, res.error());
  1375. }
  1376. TEST(CancelTest, NoCancelDelete) {
  1377. Server svr;
  1378. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1379. res.set_content("Hello World!", "text/plain");
  1380. });
  1381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. thread.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, PORT);
  1389. cli.set_connection_timeout(std::chrono::seconds(5));
  1390. auto res =
  1391. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1392. "application/json", [](uint64_t, uint64_t) { return true; });
  1393. ASSERT_TRUE(res);
  1394. EXPECT_EQ("Hello World!", res->body);
  1395. EXPECT_EQ(StatusCode::OK_200, res->status);
  1396. }
  1397. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1398. Server svr;
  1399. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content("Hello World!", "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.Delete("/", 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, WithCancelLargePayloadDelete) {
  1418. Server svr;
  1419. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content(LARGE_DATA, "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.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return false; });
  1434. ASSERT_TRUE(!res);
  1435. EXPECT_EQ(Error::Canceled, res.error());
  1436. }
  1437. static std::string remove_whitespace(const std::string &input) {
  1438. std::string output;
  1439. output.reserve(input.size());
  1440. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1441. [](unsigned char c) { return !std::isspace(c); });
  1442. return output;
  1443. }
  1444. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1445. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1446. auto host = "httpbin.org";
  1447. auto path = std::string{"/basic-auth/hello/world"};
  1448. #else
  1449. auto host = "nghttp2.org";
  1450. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1451. #endif
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. auto port = 443;
  1454. SSLClient cli(host, port);
  1455. #else
  1456. auto port = 80;
  1457. Client cli(host, port);
  1458. #endif
  1459. {
  1460. auto res = cli.Get(path);
  1461. ASSERT_TRUE(res);
  1462. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1463. }
  1464. {
  1465. auto res =
  1466. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1467. ASSERT_TRUE(res);
  1468. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1469. remove_whitespace(res->body));
  1470. EXPECT_EQ(StatusCode::OK_200, res->status);
  1471. }
  1472. {
  1473. cli.set_basic_auth("hello", "world");
  1474. auto res = cli.Get(path);
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1477. remove_whitespace(res->body));
  1478. EXPECT_EQ(StatusCode::OK_200, res->status);
  1479. }
  1480. {
  1481. cli.set_basic_auth("hello", "bad");
  1482. auto res = cli.Get(path);
  1483. ASSERT_TRUE(res);
  1484. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1485. }
  1486. {
  1487. cli.set_basic_auth("bad", "world");
  1488. auto res = cli.Get(path);
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1491. }
  1492. }
  1493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1494. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1495. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1496. auto host = "httpbin.org";
  1497. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1498. auto paths = std::vector<std::string>{
  1499. "/digest-auth/auth/hello/world/MD5",
  1500. "/digest-auth/auth/hello/world/SHA-256",
  1501. "/digest-auth/auth/hello/world/SHA-512",
  1502. "/digest-auth/auth-int/hello/world/MD5",
  1503. };
  1504. #else
  1505. auto host = "nghttp2.org";
  1506. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1507. auto paths = std::vector<std::string>{
  1508. "/httpbin/digest-auth/auth/hello/world/MD5",
  1509. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1510. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1511. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1512. };
  1513. #endif
  1514. auto port = 443;
  1515. SSLClient cli(host, port);
  1516. {
  1517. auto res = cli.Get(unauth_path);
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1520. }
  1521. {
  1522. cli.set_digest_auth("hello", "world");
  1523. for (const auto &path : paths) {
  1524. auto res = cli.Get(path.c_str());
  1525. ASSERT_TRUE(res);
  1526. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1527. remove_whitespace(res->body));
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. }
  1530. cli.set_digest_auth("hello", "bad");
  1531. for (const auto &path : paths) {
  1532. auto res = cli.Get(path.c_str());
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1535. }
  1536. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1537. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1538. // cli.set_digest_auth("bad", "world");
  1539. // for (const auto& path : paths) {
  1540. // auto res = cli.Get(path.c_str());
  1541. // ASSERT_TRUE(res);
  1542. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1543. // }
  1544. }
  1545. }
  1546. #endif
  1547. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1548. auto host = "google.com";
  1549. auto another_host = "example.com";
  1550. auto wrong_ip = "0.0.0.0";
  1551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1552. SSLClient cli(host);
  1553. #else
  1554. Client cli(host);
  1555. #endif
  1556. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1557. auto res = cli.Get("/");
  1558. ASSERT_TRUE(res);
  1559. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1560. }
  1561. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1562. auto host = "google.com";
  1563. auto wrong_ip = "0.0.0.0";
  1564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1565. SSLClient cli(host);
  1566. #else
  1567. Client cli(host);
  1568. #endif
  1569. cli.set_hostname_addr_map({{host, wrong_ip}});
  1570. auto res = cli.Get("/");
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Connection, res.error());
  1573. }
  1574. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1575. auto host = "nghttp2.org";
  1576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1577. SSLClient cli(host);
  1578. #else
  1579. Client cli(host);
  1580. #endif
  1581. cli.set_follow_location(true);
  1582. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1583. ASSERT_TRUE(res);
  1584. EXPECT_EQ(StatusCode::OK_200, res->status);
  1585. }
  1586. TEST(RedirectTest, Redirect_Online) {
  1587. auto host = "nghttp2.org";
  1588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1589. SSLClient cli(host);
  1590. #else
  1591. Client cli(host);
  1592. #endif
  1593. cli.set_follow_location(true);
  1594. auto res = cli.Get("/httpbin/redirect/3");
  1595. ASSERT_TRUE(res);
  1596. EXPECT_EQ(StatusCode::OK_200, res->status);
  1597. }
  1598. TEST(RelativeRedirectTest, Redirect_Online) {
  1599. auto host = "nghttp2.org";
  1600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1601. SSLClient cli(host);
  1602. #else
  1603. Client cli(host);
  1604. #endif
  1605. cli.set_follow_location(true);
  1606. auto res = cli.Get("/httpbin/relative-redirect/3");
  1607. ASSERT_TRUE(res);
  1608. EXPECT_EQ(StatusCode::OK_200, res->status);
  1609. }
  1610. TEST(TooManyRedirectTest, Redirect_Online) {
  1611. auto host = "nghttp2.org";
  1612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1613. SSLClient cli(host);
  1614. #else
  1615. Client cli(host);
  1616. #endif
  1617. cli.set_follow_location(true);
  1618. auto res = cli.Get("/httpbin/redirect/21");
  1619. ASSERT_TRUE(!res);
  1620. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1621. }
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. TEST(YahooRedirectTest, Redirect_Online) {
  1624. Client cli("yahoo.com");
  1625. auto res = cli.Get("/");
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1628. cli.set_follow_location(true);
  1629. res = cli.Get("/");
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ(StatusCode::OK_200, res->status);
  1632. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1633. }
  1634. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1635. #define REDIR_HOST "httpbingo.org"
  1636. #define REDIR_PATH "/redirect-to"
  1637. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1638. SSLClient cli(REDIR_HOST);
  1639. cli.set_follow_location(true);
  1640. auto res =
  1641. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1642. ASSERT_TRUE(res);
  1643. EXPECT_EQ(StatusCode::OK_200, res->status);
  1644. }
  1645. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1646. SSLClient cli(REDIR_HOST);
  1647. cli.set_follow_location(true);
  1648. Params params;
  1649. params.emplace("url", "http://example.com");
  1650. params.emplace("status_code", "302");
  1651. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::OK_200, res->status);
  1654. }
  1655. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1656. SSLClient cli(REDIR_HOST);
  1657. cli.set_follow_location(true);
  1658. Params params;
  1659. params.emplace("url", "http://example.com");
  1660. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ(StatusCode::OK_200, res->status);
  1663. }
  1664. TEST(UrlWithSpace, Redirect_Online) {
  1665. SSLClient cli("edge.forgecdn.net");
  1666. cli.set_follow_location(true);
  1667. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ(StatusCode::OK_200, res->status);
  1670. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1671. }
  1672. #endif
  1673. #if !defined(_WIN32) && !defined(_WIN64)
  1674. TEST(ReceiveSignals, Signal) {
  1675. auto setupSignalHandlers = []() {
  1676. struct sigaction act;
  1677. sigemptyset(&act.sa_mask);
  1678. act.sa_flags = SA_SIGINFO;
  1679. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1680. switch (sig) {
  1681. case SIGINT:
  1682. default: break;
  1683. }
  1684. };
  1685. ::sigaction(SIGINT, &act, nullptr);
  1686. };
  1687. Server svr;
  1688. int port = 0;
  1689. auto thread = std::thread([&]() {
  1690. setupSignalHandlers();
  1691. port = svr.bind_to_any_port("localhost");
  1692. svr.listen_after_bind();
  1693. });
  1694. auto se = detail::scope_exit([&] {
  1695. svr.stop();
  1696. thread.join();
  1697. ASSERT_FALSE(svr.is_running());
  1698. });
  1699. svr.wait_until_ready();
  1700. ASSERT_TRUE(svr.is_running());
  1701. pthread_kill(thread.native_handle(), SIGINT);
  1702. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1703. ASSERT_TRUE(svr.is_running());
  1704. }
  1705. #endif
  1706. TEST(RedirectToDifferentPort, Redirect) {
  1707. Server svr1;
  1708. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1709. res.set_content("Hello World!", "text/plain");
  1710. });
  1711. int svr1_port = 0;
  1712. auto thread1 = std::thread([&]() {
  1713. svr1_port = svr1.bind_to_any_port("localhost");
  1714. svr1.listen_after_bind();
  1715. });
  1716. Server svr2;
  1717. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1718. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1719. });
  1720. int svr2_port = 0;
  1721. auto thread2 = std::thread([&]() {
  1722. svr2_port = svr2.bind_to_any_port("localhost");
  1723. svr2.listen_after_bind();
  1724. });
  1725. auto se = detail::scope_exit([&] {
  1726. svr2.stop();
  1727. thread2.join();
  1728. svr1.stop();
  1729. thread1.join();
  1730. ASSERT_FALSE(svr2.is_running());
  1731. ASSERT_FALSE(svr1.is_running());
  1732. });
  1733. svr1.wait_until_ready();
  1734. svr2.wait_until_ready();
  1735. Client cli("localhost", svr2_port);
  1736. cli.set_follow_location(true);
  1737. auto res = cli.Get("/2");
  1738. ASSERT_TRUE(res);
  1739. EXPECT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_EQ("Hello World!", res->body);
  1741. }
  1742. TEST(RedirectFromPageWithContent, Redirect) {
  1743. Server svr;
  1744. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("___", "text/plain");
  1746. res.set_redirect("/2");
  1747. });
  1748. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1749. res.set_content("Hello World!", "text/plain");
  1750. });
  1751. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1752. auto se = detail::scope_exit([&] {
  1753. svr.stop();
  1754. th.join();
  1755. ASSERT_FALSE(svr.is_running());
  1756. });
  1757. svr.wait_until_ready();
  1758. {
  1759. Client cli("localhost", PORT);
  1760. cli.set_follow_location(true);
  1761. std::string body;
  1762. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1763. body.append(data, data_length);
  1764. return true;
  1765. });
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(StatusCode::OK_200, res->status);
  1768. EXPECT_EQ("Hello World!", body);
  1769. }
  1770. {
  1771. Client cli("localhost", PORT);
  1772. std::string body;
  1773. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1774. body.append(data, data_length);
  1775. return true;
  1776. });
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(StatusCode::Found_302, res->status);
  1779. EXPECT_EQ("___", body);
  1780. }
  1781. }
  1782. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1783. Server svr;
  1784. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1785. res.set_content("___", "text/plain");
  1786. // res.set_redirect("/2");
  1787. res.set_redirect("http://[::1]:1234/2");
  1788. });
  1789. svr.Get("/2", [&](const Request &req, Response &res) {
  1790. auto host_header = req.headers.find("Host");
  1791. ASSERT_TRUE(host_header != req.headers.end());
  1792. EXPECT_EQ("[::1]:1234", host_header->second);
  1793. res.set_content("Hello World!", "text/plain");
  1794. });
  1795. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. th.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1802. // actually starts anything, so the condition !svr.is_running() will
  1803. // always remain true, and the loop never stops.
  1804. // This basically counts how many milliseconds have passed since the
  1805. // call to svr.listen(), and if after 5 seconds nothing started yet
  1806. // aborts the test.
  1807. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1808. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1809. ASSERT_LT(milliseconds, 5000U);
  1810. }
  1811. {
  1812. Client cli("http://[::1]:1234");
  1813. cli.set_follow_location(true);
  1814. std::string body;
  1815. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1816. body.append(data, data_length);
  1817. return true;
  1818. });
  1819. ASSERT_TRUE(res);
  1820. EXPECT_EQ(StatusCode::OK_200, res->status);
  1821. EXPECT_EQ("Hello World!", body);
  1822. }
  1823. {
  1824. Client cli("http://[::1]:1234");
  1825. std::string body;
  1826. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1827. body.append(data, data_length);
  1828. return true;
  1829. });
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Found_302, res->status);
  1832. EXPECT_EQ("___", body);
  1833. }
  1834. }
  1835. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1836. Server svr;
  1837. svr.Get("/foo", [](const Request &req, Response &res) {
  1838. auto a = req.params.find("a");
  1839. if (a != req.params.end()) {
  1840. res.set_content((*a).second, "text/plain");
  1841. res.status = StatusCode::OK_200;
  1842. } else {
  1843. res.status = StatusCode::BadRequest_400;
  1844. }
  1845. });
  1846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1847. auto se = detail::scope_exit([&] {
  1848. svr.stop();
  1849. thread.join();
  1850. ASSERT_FALSE(svr.is_running());
  1851. });
  1852. svr.wait_until_ready();
  1853. {
  1854. Client cli(HOST, PORT);
  1855. cli.set_path_encode(false);
  1856. auto res = cli.Get("/foo?a=explicitly+encoded");
  1857. ASSERT_TRUE(res);
  1858. EXPECT_EQ(StatusCode::OK_200, res->status);
  1859. // This expects it back with a space, as the `+` won't have been
  1860. // url-encoded, and server-side the params get decoded turning `+`
  1861. // into spaces.
  1862. EXPECT_EQ("explicitly encoded", res->body);
  1863. }
  1864. }
  1865. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1866. Server svr;
  1867. svr.Get("/", [](const Request &req, Response &) {
  1868. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1869. });
  1870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1871. auto se = detail::scope_exit([&] {
  1872. svr.stop();
  1873. thread.join();
  1874. ASSERT_FALSE(svr.is_running());
  1875. });
  1876. svr.wait_until_ready();
  1877. {
  1878. Client cli(HOST, PORT);
  1879. cli.set_path_encode(false);
  1880. auto res = cli.Get("/?something=%0A");
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(StatusCode::OK_200, res->status);
  1883. }
  1884. }
  1885. TEST(BindServerTest, DISABLED_BindDualStack) {
  1886. Server svr;
  1887. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1888. res.set_content("Hello World!", "text/plain");
  1889. });
  1890. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1891. auto se = detail::scope_exit([&] {
  1892. svr.stop();
  1893. thread.join();
  1894. ASSERT_FALSE(svr.is_running());
  1895. });
  1896. svr.wait_until_ready();
  1897. {
  1898. Client cli("127.0.0.1", PORT);
  1899. auto res = cli.Get("/1");
  1900. ASSERT_TRUE(res);
  1901. EXPECT_EQ(StatusCode::OK_200, res->status);
  1902. EXPECT_EQ("Hello World!", res->body);
  1903. }
  1904. {
  1905. Client cli("::1", PORT);
  1906. auto res = cli.Get("/1");
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ("Hello World!", res->body);
  1910. }
  1911. }
  1912. TEST(BindServerTest, BindAndListenSeparately) {
  1913. Server svr;
  1914. int port = svr.bind_to_any_port("0.0.0.0");
  1915. ASSERT_TRUE(svr.is_valid());
  1916. ASSERT_TRUE(port > 0);
  1917. svr.stop();
  1918. }
  1919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1920. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1922. CLIENT_CA_CERT_DIR);
  1923. int port = svr.bind_to_any_port("0.0.0.0");
  1924. ASSERT_TRUE(svr.is_valid());
  1925. ASSERT_TRUE(port > 0);
  1926. svr.stop();
  1927. }
  1928. #endif
  1929. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1930. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1931. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1932. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1933. int port = svr.bind_to_any_port("0.0.0.0");
  1934. ASSERT_TRUE(svr.is_valid());
  1935. ASSERT_TRUE(port > 0);
  1936. svr.stop();
  1937. }
  1938. #endif
  1939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1940. X509 *readCertificate(const std::string &strFileName) {
  1941. std::ifstream inStream(strFileName);
  1942. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1943. std::istreambuf_iterator<char>());
  1944. if (strCertPEM.empty()) return (nullptr);
  1945. BIO *pbCert = BIO_new(BIO_s_mem());
  1946. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1947. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1948. BIO_free(pbCert);
  1949. return (pCert);
  1950. }
  1951. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1952. std::ifstream inStream(strFileName);
  1953. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1954. std::istreambuf_iterator<char>());
  1955. if (strPrivateKeyPEM.empty()) return (nullptr);
  1956. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1957. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1958. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1959. BIO_free(pbPrivKey);
  1960. return (pPrivateKey);
  1961. }
  1962. TEST(BindServerTest, UpdateCerts) {
  1963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1964. int port = svr.bind_to_any_port("0.0.0.0");
  1965. ASSERT_TRUE(svr.is_valid());
  1966. ASSERT_TRUE(port > 0);
  1967. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1968. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1969. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1970. ASSERT_TRUE(cert != nullptr);
  1971. ASSERT_TRUE(ca_cert != nullptr);
  1972. ASSERT_TRUE(key != nullptr);
  1973. X509_STORE *cert_store = X509_STORE_new();
  1974. X509_STORE_add_cert(cert_store, ca_cert);
  1975. svr.update_certs(cert, key, cert_store);
  1976. ASSERT_TRUE(svr.is_valid());
  1977. svr.stop();
  1978. X509_free(cert);
  1979. X509_free(ca_cert);
  1980. EVP_PKEY_free(key);
  1981. }
  1982. #endif
  1983. TEST(ErrorHandlerTest, ContentLength) {
  1984. Server svr;
  1985. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1986. res.status = StatusCode::OK_200;
  1987. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1988. "text/html"); // <= Content-Length still 13
  1989. });
  1990. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1991. res.set_content("Hello World!\n", "text/plain");
  1992. res.status = 524;
  1993. });
  1994. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1995. auto se = detail::scope_exit([&] {
  1996. svr.stop();
  1997. thread.join();
  1998. ASSERT_FALSE(svr.is_running());
  1999. });
  2000. svr.wait_until_ready();
  2001. {
  2002. Client cli(HOST, PORT);
  2003. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2004. ASSERT_TRUE(res);
  2005. EXPECT_EQ(StatusCode::OK_200, res->status);
  2006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2007. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2008. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2009. }
  2010. }
  2011. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2012. TEST(ExceptionTest, WithoutExceptionHandler) {
  2013. Server svr;
  2014. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2015. throw std::runtime_error("exception...");
  2016. });
  2017. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2018. throw std::runtime_error("exception\r\n...");
  2019. });
  2020. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. listen_thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. Client cli("localhost", PORT);
  2028. {
  2029. auto res = cli.Get("/exception");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2032. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2033. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2034. }
  2035. {
  2036. auto res = cli.Get("/unknown");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2039. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2040. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2041. }
  2042. }
  2043. TEST(ExceptionTest, WithExceptionHandler) {
  2044. Server svr;
  2045. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2046. std::exception_ptr ep) {
  2047. EXPECT_FALSE(ep == nullptr);
  2048. try {
  2049. std::rethrow_exception(ep);
  2050. } catch (std::exception &e) {
  2051. EXPECT_EQ("abc", std::string(e.what()));
  2052. } catch (...) {}
  2053. res.status = StatusCode::InternalServerError_500;
  2054. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2055. "text/html"); // <= Content-Length still 13 at this point
  2056. });
  2057. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2058. res.set_content("Hello World!\n", "text/plain");
  2059. throw std::runtime_error("abc");
  2060. });
  2061. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2062. auto se = detail::scope_exit([&] {
  2063. svr.stop();
  2064. thread.join();
  2065. ASSERT_FALSE(svr.is_running());
  2066. });
  2067. svr.wait_until_ready();
  2068. for (size_t i = 0; i < 10; i++) {
  2069. Client cli(HOST, PORT);
  2070. for (size_t j = 0; j < 100; j++) {
  2071. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2072. ASSERT_TRUE(res);
  2073. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2074. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2075. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2076. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2077. }
  2078. cli.set_keep_alive(true);
  2079. for (size_t j = 0; j < 100; j++) {
  2080. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2083. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2084. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2085. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2086. }
  2087. }
  2088. }
  2089. TEST(ExceptionTest, AndErrorHandler) {
  2090. Server svr;
  2091. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2092. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2093. });
  2094. svr.set_exception_handler(
  2095. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2096. EXPECT_FALSE(ep == nullptr);
  2097. try {
  2098. std::rethrow_exception(ep);
  2099. } catch (std::exception &e) {
  2100. res.set_content(e.what(), "text/html");
  2101. } catch (...) {}
  2102. res.status = StatusCode::InternalServerError_500;
  2103. });
  2104. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2105. throw std::runtime_error("EXCEPTION");
  2106. });
  2107. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2108. res.set_content("ERROR", "text/html");
  2109. res.status = StatusCode::InternalServerError_500;
  2110. });
  2111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2112. auto se = detail::scope_exit([&] {
  2113. svr.stop();
  2114. thread.join();
  2115. ASSERT_FALSE(svr.is_running());
  2116. });
  2117. svr.wait_until_ready();
  2118. Client cli(HOST, PORT);
  2119. {
  2120. auto res = cli.Get("/exception");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2123. EXPECT_EQ("EXCEPTION", res->body);
  2124. }
  2125. {
  2126. auto res = cli.Get("/error");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2129. EXPECT_EQ("ERROR", res->body);
  2130. }
  2131. {
  2132. auto res = cli.Get("/invalid");
  2133. ASSERT_TRUE(res);
  2134. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2135. EXPECT_EQ("NOT_FOUND", res->body);
  2136. }
  2137. }
  2138. #endif
  2139. TEST(NoContentTest, ContentLength) {
  2140. Server svr;
  2141. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2142. res.status = StatusCode::NoContent_204;
  2143. });
  2144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2145. auto se = detail::scope_exit([&] {
  2146. svr.stop();
  2147. thread.join();
  2148. ASSERT_FALSE(svr.is_running());
  2149. });
  2150. svr.wait_until_ready();
  2151. {
  2152. Client cli(HOST, PORT);
  2153. auto res = cli.Get("/hi");
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2157. }
  2158. }
  2159. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2162. ASSERT_TRUE(svr.is_valid());
  2163. #else
  2164. Server svr;
  2165. #endif
  2166. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2167. if (req.path == "/routing_handler") {
  2168. res.set_header("PRE_ROUTING", "on");
  2169. res.set_content("Routing Handler", "text/plain");
  2170. return httplib::Server::HandlerResponse::Handled;
  2171. }
  2172. return httplib::Server::HandlerResponse::Unhandled;
  2173. });
  2174. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2175. res.set_content("Error", "text/html");
  2176. });
  2177. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2178. if (req.path == "/routing_handler") {
  2179. res.set_header("POST_ROUTING", "on");
  2180. }
  2181. });
  2182. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2183. res.set_content("Hello World!\n", "text/plain");
  2184. });
  2185. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2186. auto se = detail::scope_exit([&] {
  2187. svr.stop();
  2188. thread.join();
  2189. ASSERT_FALSE(svr.is_running());
  2190. });
  2191. svr.wait_until_ready();
  2192. {
  2193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2194. SSLClient cli(HOST, PORT);
  2195. cli.enable_server_certificate_verification(false);
  2196. #else
  2197. Client cli(HOST, PORT);
  2198. #endif
  2199. auto res = cli.Get("/routing_handler");
  2200. ASSERT_TRUE(res);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ("Routing Handler", res->body);
  2203. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2204. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2205. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2206. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2207. }
  2208. {
  2209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2210. SSLClient cli(HOST, PORT);
  2211. cli.enable_server_certificate_verification(false);
  2212. #else
  2213. Client cli(HOST, PORT);
  2214. #endif
  2215. auto res = cli.Get("/hi");
  2216. ASSERT_TRUE(res);
  2217. EXPECT_EQ(StatusCode::OK_200, res->status);
  2218. EXPECT_EQ("Hello World!\n", res->body);
  2219. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2220. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2221. }
  2222. {
  2223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2224. SSLClient cli(HOST, PORT);
  2225. cli.enable_server_certificate_verification(false);
  2226. #else
  2227. Client cli(HOST, PORT);
  2228. #endif
  2229. auto res = cli.Get("/aaa");
  2230. ASSERT_TRUE(res);
  2231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2232. EXPECT_EQ("Error", res->body);
  2233. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2234. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2235. }
  2236. }
  2237. TEST(RequestHandlerTest, PreRequestHandler) {
  2238. auto route_path = "/user/:user";
  2239. Server svr;
  2240. svr.Get("/hi", [](const Request &, Response &res) {
  2241. res.set_content("hi", "text/plain");
  2242. });
  2243. svr.Get(route_path, [](const Request &req, Response &res) {
  2244. res.set_content(req.path_params.at("user"), "text/plain");
  2245. });
  2246. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2247. if (req.matched_route == route_path) {
  2248. auto user = req.path_params.at("user");
  2249. if (user != "john") {
  2250. res.status = StatusCode::Forbidden_403;
  2251. res.set_content("error", "text/html");
  2252. return Server::HandlerResponse::Handled;
  2253. }
  2254. }
  2255. return Server::HandlerResponse::Unhandled;
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. {
  2266. auto res = cli.Get("/hi");
  2267. ASSERT_TRUE(res);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ("hi", res->body);
  2270. }
  2271. {
  2272. auto res = cli.Get("/user/john");
  2273. ASSERT_TRUE(res);
  2274. EXPECT_EQ(StatusCode::OK_200, res->status);
  2275. EXPECT_EQ("john", res->body);
  2276. }
  2277. {
  2278. auto res = cli.Get("/user/invalid-user");
  2279. ASSERT_TRUE(res);
  2280. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2281. EXPECT_EQ("error", res->body);
  2282. }
  2283. }
  2284. TEST(InvalidFormatTest, StatusCode) {
  2285. Server svr;
  2286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2287. res.set_content("Hello World!\n", "text/plain");
  2288. res.status = 9999; // Status should be a three-digit code...
  2289. });
  2290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2291. auto se = detail::scope_exit([&] {
  2292. svr.stop();
  2293. thread.join();
  2294. ASSERT_FALSE(svr.is_running());
  2295. });
  2296. svr.wait_until_ready();
  2297. {
  2298. Client cli(HOST, PORT);
  2299. auto res = cli.Get("/hi");
  2300. ASSERT_FALSE(res);
  2301. }
  2302. }
  2303. TEST(URLFragmentTest, WithFragment) {
  2304. Server svr;
  2305. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2306. EXPECT_TRUE(req.target == "/hi");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. {
  2316. Client cli(HOST, PORT);
  2317. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2318. EXPECT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. res = cli.Get("/hi%23key1=val1=key2=val2");
  2321. EXPECT_TRUE(res);
  2322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2323. }
  2324. }
  2325. TEST(HeaderWriter, SetHeaderWriter) {
  2326. Server svr;
  2327. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2328. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2329. return detail::write_headers(strm, hdrs);
  2330. });
  2331. svr.Get("/hi", [](const Request &req, Response &res) {
  2332. auto it = req.headers.find("CustomClientHeader");
  2333. EXPECT_TRUE(it != req.headers.end());
  2334. EXPECT_EQ(it->second, "CustomClientValue");
  2335. res.set_content("Hello World!\n", "text/plain");
  2336. });
  2337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. thread.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. {
  2345. Client cli(HOST, PORT);
  2346. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2347. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2348. return detail::write_headers(strm, hdrs);
  2349. });
  2350. auto res = cli.Get("/hi");
  2351. EXPECT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. auto it = res->headers.find("CustomServerHeader");
  2354. EXPECT_TRUE(it != res->headers.end());
  2355. EXPECT_EQ(it->second, "CustomServerValue");
  2356. }
  2357. }
  2358. class ServerTest : public ::testing::Test {
  2359. protected:
  2360. ServerTest()
  2361. : cli_(HOST, PORT)
  2362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2363. ,
  2364. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2365. #endif
  2366. {
  2367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2368. cli_.enable_server_certificate_verification(false);
  2369. #endif
  2370. }
  2371. virtual void SetUp() {
  2372. svr_.set_mount_point("/", "./www");
  2373. svr_.set_mount_point("/mount", "./www2");
  2374. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2375. svr_.Get("/hi",
  2376. [&](const Request & /*req*/, Response &res) {
  2377. res.set_content("Hello World!", "text/plain");
  2378. })
  2379. .Get("/file_content",
  2380. [&](const Request & /*req*/, Response &res) {
  2381. res.set_file_content("./www/dir/test.html");
  2382. })
  2383. .Get("/file_content_with_content_type",
  2384. [&](const Request & /*req*/, Response &res) {
  2385. res.set_file_content("./www/file", "text/plain");
  2386. })
  2387. .Get("/invalid_file_content",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. res.set_file_content("./www/dir/invalid_file_path");
  2390. })
  2391. .Get("/http_response_splitting",
  2392. [&](const Request & /*req*/, Response &res) {
  2393. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2394. EXPECT_EQ(0U, res.headers.size());
  2395. EXPECT_FALSE(res.has_header("a"));
  2396. res.set_header("a", "1\nSet-Cookie: a=1");
  2397. EXPECT_EQ(0U, res.headers.size());
  2398. EXPECT_FALSE(res.has_header("a"));
  2399. res.set_header("a", "1\rSet-Cookie: a=1");
  2400. EXPECT_EQ(0U, res.headers.size());
  2401. EXPECT_FALSE(res.has_header("a"));
  2402. res.set_header("a\r\nb", "0");
  2403. EXPECT_EQ(0U, res.headers.size());
  2404. EXPECT_FALSE(res.has_header("a"));
  2405. res.set_header("a\rb", "0");
  2406. EXPECT_EQ(0U, res.headers.size());
  2407. EXPECT_FALSE(res.has_header("a"));
  2408. res.set_header("a\nb", "0");
  2409. EXPECT_EQ(0U, res.headers.size());
  2410. EXPECT_FALSE(res.has_header("a"));
  2411. res.set_redirect("1\r\nSet-Cookie: a=1");
  2412. EXPECT_EQ(0U, res.headers.size());
  2413. EXPECT_FALSE(res.has_header("Location"));
  2414. })
  2415. .Get("/slow",
  2416. [&](const Request & /*req*/, Response &res) {
  2417. std::this_thread::sleep_for(std::chrono::seconds(2));
  2418. res.set_content("slow", "text/plain");
  2419. })
  2420. #if 0
  2421. .Post("/slowpost",
  2422. [&](const Request & /*req*/, Response &res) {
  2423. std::this_thread::sleep_for(std::chrono::seconds(2));
  2424. res.set_content("slow", "text/plain");
  2425. })
  2426. #endif
  2427. .Get("/remote_addr",
  2428. [&](const Request &req, Response &res) {
  2429. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2430. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2431. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2432. EXPECT_EQ(req.remote_port,
  2433. std::stoi(req.get_header_value("REMOTE_PORT")));
  2434. res.set_content(remote_addr.c_str(), "text/plain");
  2435. })
  2436. .Get("/local_addr",
  2437. [&](const Request &req, Response &res) {
  2438. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2439. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2440. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2441. auto local_port = req.get_header_value("LOCAL_PORT");
  2442. EXPECT_EQ(req.local_addr, local_addr);
  2443. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2444. res.set_content(local_addr.append(":").append(local_port),
  2445. "text/plain");
  2446. })
  2447. .Get("/endwith%",
  2448. [&](const Request & /*req*/, Response &res) {
  2449. res.set_content("Hello World!", "text/plain");
  2450. })
  2451. .Get("/a\\+\\+b",
  2452. [&](const Request &req, Response &res) {
  2453. ASSERT_TRUE(req.has_param("a +b"));
  2454. auto val = req.get_param_value("a +b");
  2455. res.set_content(val, "text/plain");
  2456. })
  2457. .Get("/", [&](const Request & /*req*/,
  2458. Response &res) { res.set_redirect("/hi"); })
  2459. .Post("/1",
  2460. [](const Request & /*req*/, Response &res) {
  2461. res.set_redirect("/2", StatusCode::SeeOther_303);
  2462. })
  2463. .Get("/2",
  2464. [](const Request & /*req*/, Response &res) {
  2465. res.set_content("redirected.", "text/plain");
  2466. res.status = StatusCode::OK_200;
  2467. })
  2468. .Post("/person",
  2469. [&](const Request &req, Response &res) {
  2470. if (req.has_param("name") && req.has_param("note")) {
  2471. persons_[req.get_param_value("name")] =
  2472. req.get_param_value("note");
  2473. } else {
  2474. res.status = StatusCode::BadRequest_400;
  2475. }
  2476. })
  2477. .Put("/person",
  2478. [&](const Request &req, Response &res) {
  2479. if (req.has_param("name") && req.has_param("note")) {
  2480. persons_[req.get_param_value("name")] =
  2481. req.get_param_value("note");
  2482. } else {
  2483. res.status = StatusCode::BadRequest_400;
  2484. }
  2485. })
  2486. .Get("/person/(.*)",
  2487. [&](const Request &req, Response &res) {
  2488. string name = req.matches[1];
  2489. if (persons_.find(name) != persons_.end()) {
  2490. auto note = persons_[name];
  2491. res.set_content(note, "text/plain");
  2492. } else {
  2493. res.status = StatusCode::NotFound_404;
  2494. }
  2495. })
  2496. .Delete("/person",
  2497. [&](const Request &req, Response &res) {
  2498. if (req.has_param("name")) {
  2499. string name = req.get_param_value("name");
  2500. if (persons_.find(name) != persons_.end()) {
  2501. persons_.erase(name);
  2502. res.set_content("DELETED", "text/plain");
  2503. } else {
  2504. res.status = StatusCode::NotFound_404;
  2505. }
  2506. } else {
  2507. res.status = StatusCode::BadRequest_400;
  2508. }
  2509. })
  2510. .Post("/x-www-form-urlencoded-json",
  2511. [&](const Request &req, Response &res) {
  2512. auto json = req.get_param_value("json");
  2513. ASSERT_EQ(JSON_DATA, json);
  2514. res.set_content(json, "appliation/json");
  2515. res.status = StatusCode::OK_200;
  2516. })
  2517. .Get("/streamed-chunked",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_chunked_content_provider(
  2520. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2521. sink.os << "123";
  2522. sink.os << "456";
  2523. sink.os << "789";
  2524. sink.done();
  2525. return true;
  2526. });
  2527. })
  2528. .Get("/streamed-chunked2",
  2529. [&](const Request & /*req*/, Response &res) {
  2530. auto i = new int(0);
  2531. res.set_chunked_content_provider(
  2532. "text/plain",
  2533. [i](size_t /*offset*/, DataSink &sink) {
  2534. switch (*i) {
  2535. case 0: sink.os << "123"; break;
  2536. case 1: sink.os << "456"; break;
  2537. case 2: sink.os << "789"; break;
  2538. case 3: sink.done(); break;
  2539. }
  2540. (*i)++;
  2541. return true;
  2542. },
  2543. [i](bool success) {
  2544. EXPECT_TRUE(success);
  2545. delete i;
  2546. });
  2547. })
  2548. .Get("/streamed-chunked-with-trailer",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. auto i = new int(0);
  2551. res.set_header("Trailer", "Dummy1, Dummy2");
  2552. res.set_chunked_content_provider(
  2553. "text/plain",
  2554. [i](size_t /*offset*/, DataSink &sink) {
  2555. switch (*i) {
  2556. case 0: sink.os << "123"; break;
  2557. case 1: sink.os << "456"; break;
  2558. case 2: sink.os << "789"; break;
  2559. case 3: {
  2560. sink.done_with_trailer(
  2561. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2562. } break;
  2563. }
  2564. (*i)++;
  2565. return true;
  2566. },
  2567. [i](bool success) {
  2568. EXPECT_TRUE(success);
  2569. delete i;
  2570. });
  2571. })
  2572. .Get("/streamed",
  2573. [&](const Request & /*req*/, Response &res) {
  2574. res.set_content_provider(
  2575. 6, "text/plain",
  2576. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2577. sink.os << (offset < 3 ? "a" : "b");
  2578. return true;
  2579. });
  2580. })
  2581. .Get("/streamed-with-range",
  2582. [&](const Request &req, Response &res) {
  2583. auto data = new std::string("abcdefg");
  2584. res.set_content_provider(
  2585. data->size(), "text/plain",
  2586. [data](size_t offset, size_t length, DataSink &sink) {
  2587. size_t DATA_CHUNK_SIZE = 4;
  2588. const auto &d = *data;
  2589. auto out_len =
  2590. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2591. auto ret =
  2592. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2593. EXPECT_TRUE(ret);
  2594. return true;
  2595. },
  2596. [data, &req](bool success) {
  2597. EXPECT_EQ(success, !req.has_param("error"));
  2598. delete data;
  2599. });
  2600. })
  2601. .Get("/streamed-cancel",
  2602. [&](const Request & /*req*/, Response &res) {
  2603. res.set_content_provider(
  2604. size_t(-1), "text/plain",
  2605. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2606. sink.os << "data_chunk";
  2607. return true;
  2608. });
  2609. })
  2610. .Get("/regex-with-delimiter",
  2611. [&](const Request &req, Response & /*res*/) {
  2612. ASSERT_TRUE(req.has_param("key"));
  2613. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2614. })
  2615. .Get("/with-range",
  2616. [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("abcdefg", "text/plain");
  2618. })
  2619. .Get("/with-range-customized-response",
  2620. [&](const Request & /*req*/, Response &res) {
  2621. res.status = StatusCode::BadRequest_400;
  2622. res.set_content(JSON_DATA, "application/json");
  2623. })
  2624. .Post("/chunked",
  2625. [&](const Request &req, Response & /*res*/) {
  2626. EXPECT_EQ(req.body, "dechunked post body");
  2627. })
  2628. .Post("/large-chunked",
  2629. [&](const Request &req, Response & /*res*/) {
  2630. std::string expected(6 * 30 * 1024u, 'a');
  2631. EXPECT_EQ(req.body, expected);
  2632. })
  2633. .Post("/multipart",
  2634. [&](const Request &req, Response & /*res*/) {
  2635. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2636. req.form.get_field_count("text2") +
  2637. req.form.get_field_count("file3") +
  2638. req.form.get_field_count("file4"));
  2639. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2640. req.form.get_file_count("file2"));
  2641. ASSERT_TRUE(!req.form.has_file("???"));
  2642. ASSERT_TRUE(!req.form.has_field("???"));
  2643. ASSERT_TRUE(req.body.empty());
  2644. {
  2645. const auto &text = req.form.get_field("text1");
  2646. EXPECT_EQ("text default", text);
  2647. }
  2648. {
  2649. const auto &text = req.form.get_field("text2");
  2650. EXPECT_EQ("aωb", text);
  2651. }
  2652. {
  2653. const auto &file = req.form.get_file("file1");
  2654. EXPECT_EQ("hello.txt", file.filename);
  2655. EXPECT_EQ("text/plain", file.content_type);
  2656. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2657. }
  2658. {
  2659. const auto &file = req.form.get_file("file2");
  2660. EXPECT_EQ("world.json", file.filename);
  2661. EXPECT_EQ("application/json", file.content_type);
  2662. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2663. }
  2664. {
  2665. const auto &text = req.form.get_field("file3");
  2666. EXPECT_EQ(0u, text.size());
  2667. }
  2668. {
  2669. const auto &text = req.form.get_field("file4");
  2670. EXPECT_EQ(0u, text.size());
  2671. }
  2672. })
  2673. .Post("/multipart/multi_file_values",
  2674. [&](const Request &req, Response & /*res*/) {
  2675. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2676. req.form.get_field_count("multi_text1"));
  2677. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2678. ASSERT_TRUE(!req.form.has_file("???"));
  2679. ASSERT_TRUE(!req.form.has_field("???"));
  2680. ASSERT_TRUE(req.body.empty());
  2681. {
  2682. const auto &text = req.form.get_field("text");
  2683. EXPECT_EQ("default text", text);
  2684. }
  2685. {
  2686. const auto &text1_values = req.form.get_fields("multi_text1");
  2687. EXPECT_EQ(2u, text1_values.size());
  2688. EXPECT_EQ("aaaaa", text1_values[0]);
  2689. EXPECT_EQ("bbbbb", text1_values[1]);
  2690. }
  2691. {
  2692. const auto &file1_values = req.form.get_files("multi_file1");
  2693. EXPECT_EQ(2u, file1_values.size());
  2694. auto file1 = file1_values[0];
  2695. EXPECT_EQ(file1.filename, "hello.txt");
  2696. EXPECT_EQ(file1.content_type, "text/plain");
  2697. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2698. auto file2 = file1_values[1];
  2699. EXPECT_EQ(file2.filename, "world.json");
  2700. EXPECT_EQ(file2.content_type, "application/json");
  2701. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2702. }
  2703. })
  2704. .Post("/empty",
  2705. [&](const Request &req, Response &res) {
  2706. EXPECT_EQ(req.body, "");
  2707. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2708. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2709. res.set_content("empty", "text/plain");
  2710. })
  2711. .Post("/empty-no-content-type",
  2712. [&](const Request &req, Response &res) {
  2713. EXPECT_EQ(req.body, "");
  2714. EXPECT_FALSE(req.has_header("Content-Type"));
  2715. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2716. res.set_content("empty-no-content-type", "text/plain");
  2717. })
  2718. .Post("/path-only",
  2719. [&](const Request &req, Response &res) {
  2720. EXPECT_EQ(req.body, "");
  2721. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2723. res.set_content("path-only", "text/plain");
  2724. })
  2725. .Post("/path-headers-only",
  2726. [&](const Request &req, Response &res) {
  2727. EXPECT_EQ(req.body, "");
  2728. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2729. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2730. EXPECT_EQ("world", req.get_header_value("hello"));
  2731. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2732. res.set_content("path-headers-only", "text/plain");
  2733. })
  2734. .Post("/post-large",
  2735. [&](const Request &req, Response &res) {
  2736. EXPECT_EQ(req.body, LARGE_DATA);
  2737. res.set_content(req.body, "text/plain");
  2738. })
  2739. .Put("/empty-no-content-type",
  2740. [&](const Request &req, Response &res) {
  2741. EXPECT_EQ(req.body, "");
  2742. EXPECT_FALSE(req.has_header("Content-Type"));
  2743. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2744. res.set_content("empty-no-content-type", "text/plain");
  2745. })
  2746. .Put("/put",
  2747. [&](const Request &req, Response &res) {
  2748. EXPECT_EQ(req.body, "PUT");
  2749. res.set_content(req.body, "text/plain");
  2750. })
  2751. .Put("/put-large",
  2752. [&](const Request &req, Response &res) {
  2753. EXPECT_EQ(req.body, LARGE_DATA);
  2754. res.set_content(req.body, "text/plain");
  2755. })
  2756. .Patch("/patch",
  2757. [&](const Request &req, Response &res) {
  2758. EXPECT_EQ(req.body, "PATCH");
  2759. res.set_content(req.body, "text/plain");
  2760. })
  2761. .Delete("/delete",
  2762. [&](const Request & /*req*/, Response &res) {
  2763. res.set_content("DELETE", "text/plain");
  2764. })
  2765. .Delete("/delete-body",
  2766. [&](const Request &req, Response &res) {
  2767. EXPECT_EQ(req.body, "content");
  2768. res.set_content(req.body, "text/plain");
  2769. })
  2770. .Options(R"(\*)",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2773. })
  2774. .Get("/request-target",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2777. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2778. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2779. })
  2780. .Get("/long-query-value",
  2781. [&](const Request &req, Response & /*res*/) {
  2782. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2783. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2784. })
  2785. .Get("/too-long-query-value",
  2786. [&](const Request &req, Response & /*res*/) {
  2787. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2788. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2789. })
  2790. .Get("/array-param",
  2791. [&](const Request &req, Response & /*res*/) {
  2792. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2793. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2794. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2795. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2796. })
  2797. .Post("/validate-no-multiple-headers",
  2798. [&](const Request &req, Response & /*res*/) {
  2799. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2800. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2801. })
  2802. .Post("/content_receiver",
  2803. [&](const Request &req, Response &res,
  2804. const ContentReader &content_reader) {
  2805. if (req.is_multipart_form_data()) {
  2806. std::vector<FormData> items;
  2807. content_reader(
  2808. [&](const FormData &file) {
  2809. items.push_back(file);
  2810. return true;
  2811. },
  2812. [&](const char *data, size_t data_length) {
  2813. items.back().content.append(data, data_length);
  2814. return true;
  2815. });
  2816. EXPECT_EQ(5u, items.size());
  2817. {
  2818. const auto &file = get_file_value(items, "text1");
  2819. EXPECT_TRUE(file.filename.empty());
  2820. EXPECT_EQ("text default", file.content);
  2821. }
  2822. {
  2823. const auto &file = get_file_value(items, "text2");
  2824. EXPECT_TRUE(file.filename.empty());
  2825. EXPECT_EQ("aωb", file.content);
  2826. }
  2827. {
  2828. const auto &file = get_file_value(items, "file1");
  2829. EXPECT_EQ("hello.txt", file.filename);
  2830. EXPECT_EQ("text/plain", file.content_type);
  2831. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2832. }
  2833. {
  2834. const auto &file = get_file_value(items, "file2");
  2835. EXPECT_EQ("world.json", file.filename);
  2836. EXPECT_EQ("application/json", file.content_type);
  2837. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2838. }
  2839. {
  2840. const auto &file = get_file_value(items, "file3");
  2841. EXPECT_TRUE(file.filename.empty());
  2842. EXPECT_EQ("application/octet-stream", file.content_type);
  2843. EXPECT_EQ(0u, file.content.size());
  2844. }
  2845. } else {
  2846. std::string body;
  2847. content_reader([&](const char *data, size_t data_length) {
  2848. EXPECT_EQ(7U, data_length);
  2849. body.append(data, data_length);
  2850. return true;
  2851. });
  2852. EXPECT_EQ(body, "content");
  2853. res.set_content(body, "text/plain");
  2854. }
  2855. })
  2856. .Put("/content_receiver",
  2857. [&](const Request & /*req*/, Response &res,
  2858. const ContentReader &content_reader) {
  2859. std::string body;
  2860. content_reader([&](const char *data, size_t data_length) {
  2861. body.append(data, data_length);
  2862. return true;
  2863. });
  2864. EXPECT_EQ(body, "content");
  2865. res.set_content(body, "text/plain");
  2866. })
  2867. .Patch("/content_receiver",
  2868. [&](const Request & /*req*/, Response &res,
  2869. const ContentReader &content_reader) {
  2870. std::string body;
  2871. content_reader([&](const char *data, size_t data_length) {
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. EXPECT_EQ(body, "content");
  2876. res.set_content(body, "text/plain");
  2877. })
  2878. .Post("/query-string-and-body",
  2879. [&](const Request &req, Response & /*res*/) {
  2880. ASSERT_TRUE(req.has_param("key"));
  2881. EXPECT_EQ(req.get_param_value("key"), "value");
  2882. EXPECT_EQ(req.body, "content");
  2883. })
  2884. .Get("/last-request",
  2885. [&](const Request &req, Response & /*res*/) {
  2886. EXPECT_EQ("close", req.get_header_value("Connection"));
  2887. })
  2888. .Get(R"(/redirect/(\d+))",
  2889. [&](const Request &req, Response &res) {
  2890. auto num = std::stoi(req.matches[1]) + 1;
  2891. std::string url = "/redirect/" + std::to_string(num);
  2892. res.set_redirect(url);
  2893. })
  2894. .Post("/binary",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(4U, req.body.size());
  2897. EXPECT_EQ("application/octet-stream",
  2898. req.get_header_value("Content-Type"));
  2899. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2900. res.set_content(req.body, "application/octet-stream");
  2901. })
  2902. .Put("/binary",
  2903. [&](const Request &req, Response &res) {
  2904. EXPECT_EQ(4U, req.body.size());
  2905. EXPECT_EQ("application/octet-stream",
  2906. req.get_header_value("Content-Type"));
  2907. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2908. res.set_content(req.body, "application/octet-stream");
  2909. })
  2910. .Patch("/binary",
  2911. [&](const Request &req, Response &res) {
  2912. EXPECT_EQ(4U, req.body.size());
  2913. EXPECT_EQ("application/octet-stream",
  2914. req.get_header_value("Content-Type"));
  2915. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2916. res.set_content(req.body, "application/octet-stream");
  2917. })
  2918. .Delete("/binary",
  2919. [&](const Request &req, Response &res) {
  2920. EXPECT_EQ(4U, req.body.size());
  2921. EXPECT_EQ("application/octet-stream",
  2922. req.get_header_value("Content-Type"));
  2923. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2924. res.set_content(req.body, "application/octet-stream");
  2925. })
  2926. .Get("/issue1772",
  2927. [&](const Request & /*req*/, Response &res) {
  2928. res.status = 401;
  2929. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2930. })
  2931. .Delete("/issue609",
  2932. [](const httplib::Request &, httplib::Response &res,
  2933. const httplib::ContentReader &) {
  2934. res.set_content("ok", "text/plain");
  2935. })
  2936. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2937. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2938. .Get("/compress",
  2939. [&](const Request & /*req*/, Response &res) {
  2940. res.set_content(
  2941. "12345678901234567890123456789012345678901234567890123456789"
  2942. "01234567890123456789012345678901234567890",
  2943. "text/plain");
  2944. })
  2945. .Get("/nocompress",
  2946. [&](const Request & /*req*/, Response &res) {
  2947. res.set_content(
  2948. "12345678901234567890123456789012345678901234567890123456789"
  2949. "01234567890123456789012345678901234567890",
  2950. "application/octet-stream");
  2951. })
  2952. .Post("/compress-multipart",
  2953. [&](const Request &req, Response & /*res*/) {
  2954. EXPECT_EQ(2u, req.form.fields.size());
  2955. ASSERT_TRUE(!req.form.has_field("???"));
  2956. {
  2957. const auto &text = req.form.get_field("key1");
  2958. EXPECT_EQ("test", text);
  2959. }
  2960. {
  2961. const auto &text = req.form.get_field("key2");
  2962. EXPECT_EQ("--abcdefg123", text);
  2963. }
  2964. })
  2965. #endif
  2966. ;
  2967. persons_["john"] = "programmer";
  2968. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2969. svr_.wait_until_ready();
  2970. }
  2971. virtual void TearDown() {
  2972. svr_.stop();
  2973. if (!request_threads_.empty()) {
  2974. std::this_thread::sleep_for(std::chrono::seconds(1));
  2975. for (auto &t : request_threads_) {
  2976. t.join();
  2977. }
  2978. }
  2979. t_.join();
  2980. }
  2981. map<string, string> persons_;
  2982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2983. SSLClient cli_;
  2984. SSLServer svr_;
  2985. #else
  2986. Client cli_;
  2987. Server svr_;
  2988. #endif
  2989. thread t_;
  2990. std::vector<thread> request_threads_;
  2991. };
  2992. TEST_F(ServerTest, GetMethod200) {
  2993. auto res = cli_.Get("/hi");
  2994. ASSERT_TRUE(res);
  2995. EXPECT_EQ("HTTP/1.1", res->version);
  2996. EXPECT_EQ(StatusCode::OK_200, res->status);
  2997. EXPECT_EQ("OK", res->reason);
  2998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2999. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3000. EXPECT_EQ("Hello World!", res->body);
  3001. }
  3002. void performance_test(const char *host) {
  3003. auto port = 1234;
  3004. Server svr;
  3005. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3006. res.set_content("Benchmark Response", "text/plain");
  3007. });
  3008. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. listen_thread.join();
  3012. ASSERT_FALSE(svr.is_running());
  3013. });
  3014. svr.wait_until_ready();
  3015. Client cli(host, port);
  3016. auto start = std::chrono::high_resolution_clock::now();
  3017. auto res = cli.Get("/benchmark");
  3018. ASSERT_TRUE(res);
  3019. EXPECT_EQ(StatusCode::OK_200, res->status);
  3020. auto end = std::chrono::high_resolution_clock::now();
  3021. auto elapsed =
  3022. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3023. .count();
  3024. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3025. << "ms (Issue #1777)";
  3026. }
  3027. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3028. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3029. TEST_F(ServerTest, GetEmptyFile) {
  3030. auto res = cli_.Get("/empty_file");
  3031. ASSERT_TRUE(res);
  3032. EXPECT_EQ(StatusCode::OK_200, res->status);
  3033. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3034. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3035. EXPECT_EQ("", res->body);
  3036. }
  3037. TEST_F(ServerTest, GetFileContent) {
  3038. auto res = cli_.Get("/file_content");
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(StatusCode::OK_200, res->status);
  3041. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3042. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3043. EXPECT_EQ("test.html", res->body);
  3044. }
  3045. TEST_F(ServerTest, GetFileContentWithRange) {
  3046. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3047. ASSERT_TRUE(res);
  3048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3050. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3051. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3052. EXPECT_EQ("est", res->body);
  3053. }
  3054. TEST_F(ServerTest, GetFileContentWithContentType) {
  3055. auto res = cli_.Get("/file_content_with_content_type");
  3056. ASSERT_TRUE(res);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3059. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3060. EXPECT_EQ("file\n", res->body);
  3061. }
  3062. TEST_F(ServerTest, GetInvalidFileContent) {
  3063. auto res = cli_.Get("/invalid_file_content");
  3064. ASSERT_TRUE(res);
  3065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3066. }
  3067. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3068. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ("HTTP/1.1", res->version);
  3071. EXPECT_EQ(StatusCode::OK_200, res->status);
  3072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3073. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3074. EXPECT_EQ("Hello World!", res->body);
  3075. }
  3076. TEST_F(ServerTest, GetMethod302) {
  3077. auto res = cli_.Get("/");
  3078. ASSERT_TRUE(res);
  3079. EXPECT_EQ(StatusCode::Found_302, res->status);
  3080. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3081. }
  3082. TEST_F(ServerTest, GetMethod302Redirect) {
  3083. cli_.set_follow_location(true);
  3084. auto res = cli_.Get("/");
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. EXPECT_EQ("Hello World!", res->body);
  3088. EXPECT_EQ("/hi", res->location);
  3089. }
  3090. TEST_F(ServerTest, GetMethod404) {
  3091. auto res = cli_.Get("/invalid");
  3092. ASSERT_TRUE(res);
  3093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3094. }
  3095. TEST_F(ServerTest, HeadMethod200) {
  3096. auto res = cli_.Head("/hi");
  3097. ASSERT_TRUE(res);
  3098. EXPECT_EQ(StatusCode::OK_200, res->status);
  3099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3100. EXPECT_TRUE(res->body.empty());
  3101. }
  3102. TEST_F(ServerTest, HeadMethod200Static) {
  3103. auto res = cli_.Head("/mount/dir/index.html");
  3104. ASSERT_TRUE(res);
  3105. EXPECT_EQ(StatusCode::OK_200, res->status);
  3106. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3107. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3108. EXPECT_TRUE(res->body.empty());
  3109. }
  3110. TEST_F(ServerTest, HeadMethod404) {
  3111. auto res = cli_.Head("/invalid");
  3112. ASSERT_TRUE(res);
  3113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3114. EXPECT_TRUE(res->body.empty());
  3115. }
  3116. TEST_F(ServerTest, GetMethodPersonJohn) {
  3117. auto res = cli_.Get("/person/john");
  3118. ASSERT_TRUE(res);
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3121. EXPECT_EQ("programmer", res->body);
  3122. }
  3123. TEST_F(ServerTest, PostMethod1) {
  3124. auto res = cli_.Get("/person/john1");
  3125. ASSERT_TRUE(res);
  3126. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3127. res = cli_.Post("/person", "name=john1&note=coder",
  3128. "application/x-www-form-urlencoded");
  3129. ASSERT_TRUE(res);
  3130. ASSERT_EQ(StatusCode::OK_200, res->status);
  3131. res = cli_.Get("/person/john1");
  3132. ASSERT_TRUE(res);
  3133. ASSERT_EQ(StatusCode::OK_200, res->status);
  3134. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3135. ASSERT_EQ("coder", res->body);
  3136. }
  3137. TEST_F(ServerTest, PostMethod2) {
  3138. auto res = cli_.Get("/person/john2");
  3139. ASSERT_TRUE(res);
  3140. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3141. Params params;
  3142. params.emplace("name", "john2");
  3143. params.emplace("note", "coder");
  3144. res = cli_.Post("/person", params);
  3145. ASSERT_TRUE(res);
  3146. ASSERT_EQ(StatusCode::OK_200, res->status);
  3147. res = cli_.Get("/person/john2");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3151. ASSERT_EQ("coder", res->body);
  3152. }
  3153. TEST_F(ServerTest, PutMethod3) {
  3154. auto res = cli_.Get("/person/john3");
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3157. Params params;
  3158. params.emplace("name", "john3");
  3159. params.emplace("note", "coder");
  3160. res = cli_.Put("/person", params);
  3161. ASSERT_TRUE(res);
  3162. ASSERT_EQ(StatusCode::OK_200, res->status);
  3163. res = cli_.Get("/person/john3");
  3164. ASSERT_TRUE(res);
  3165. ASSERT_EQ(StatusCode::OK_200, res->status);
  3166. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. ASSERT_EQ("coder", res->body);
  3168. }
  3169. TEST_F(ServerTest, DeleteMethod1) {
  3170. auto res = cli_.Get("/person/john4");
  3171. ASSERT_TRUE(res);
  3172. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3173. Params params;
  3174. params.emplace("name", "john4");
  3175. params.emplace("note", "coder");
  3176. res = cli_.Post("/person", params);
  3177. ASSERT_TRUE(res);
  3178. ASSERT_EQ(StatusCode::OK_200, res->status);
  3179. res = cli_.Get("/person/john4");
  3180. ASSERT_TRUE(res);
  3181. ASSERT_EQ(StatusCode::OK_200, res->status);
  3182. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3183. ASSERT_EQ("coder", res->body);
  3184. Params delete_params;
  3185. delete_params.emplace("name", "john4");
  3186. res = cli_.Delete("/person", delete_params);
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::OK_200, res->status);
  3189. ASSERT_EQ("DELETED", res->body);
  3190. res = cli_.Get("/person/john4");
  3191. ASSERT_TRUE(res);
  3192. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3193. }
  3194. TEST_F(ServerTest, DeleteMethod2) {
  3195. auto res = cli_.Get("/person/john5");
  3196. ASSERT_TRUE(res);
  3197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3198. Params params;
  3199. params.emplace("name", "john5");
  3200. params.emplace("note", "developer");
  3201. res = cli_.Post("/person", params);
  3202. ASSERT_TRUE(res);
  3203. ASSERT_EQ(StatusCode::OK_200, res->status);
  3204. res = cli_.Get("/person/john5");
  3205. ASSERT_TRUE(res);
  3206. ASSERT_EQ(StatusCode::OK_200, res->status);
  3207. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3208. ASSERT_EQ("developer", res->body);
  3209. Params delete_params;
  3210. delete_params.emplace("name", "john5");
  3211. Headers headers;
  3212. headers.emplace("Custom-Header", "test-value");
  3213. res = cli_.Delete("/person", headers, delete_params);
  3214. ASSERT_TRUE(res);
  3215. ASSERT_EQ(StatusCode::OK_200, res->status);
  3216. ASSERT_EQ("DELETED", res->body);
  3217. res = cli_.Get("/person/john5");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3220. }
  3221. TEST_F(ServerTest, DeleteMethod3) {
  3222. auto res = cli_.Get("/person/john6");
  3223. ASSERT_TRUE(res);
  3224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3225. Params params;
  3226. params.emplace("name", "john6");
  3227. params.emplace("note", "tester");
  3228. res = cli_.Post("/person", params);
  3229. ASSERT_TRUE(res);
  3230. ASSERT_EQ(StatusCode::OK_200, res->status);
  3231. res = cli_.Get("/person/john6");
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3235. ASSERT_EQ("tester", res->body);
  3236. Params delete_params;
  3237. delete_params.emplace("name", "john6");
  3238. Headers headers;
  3239. headers.emplace("Custom-Header", "test-value");
  3240. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. ASSERT_EQ("DELETED", res->body);
  3244. res = cli_.Get("/person/john6");
  3245. ASSERT_TRUE(res);
  3246. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3247. }
  3248. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3249. Params params;
  3250. params.emplace("json", JSON_DATA);
  3251. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::OK_200, res->status);
  3254. ASSERT_EQ(JSON_DATA, res->body);
  3255. }
  3256. TEST_F(ServerTest, PostEmptyContent) {
  3257. auto res = cli_.Post("/empty", "", "text/plain");
  3258. ASSERT_TRUE(res);
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. ASSERT_EQ("empty", res->body);
  3261. }
  3262. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3263. auto res = cli_.Post("/empty-no-content-type");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::OK_200, res->status);
  3266. ASSERT_EQ("empty-no-content-type", res->body);
  3267. }
  3268. TEST_F(ServerTest, PostPathOnly) {
  3269. auto res = cli_.Post("/path-only");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. ASSERT_EQ("path-only", res->body);
  3273. }
  3274. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3275. auto res = cli_.Post("/path-headers-only",
  3276. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3277. ASSERT_TRUE(res);
  3278. ASSERT_EQ(StatusCode::OK_200, res->status);
  3279. ASSERT_EQ("path-headers-only", res->body);
  3280. }
  3281. TEST_F(ServerTest, PostLarge) {
  3282. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::OK_200, res->status);
  3285. EXPECT_EQ(LARGE_DATA, res->body);
  3286. }
  3287. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3288. auto res = cli_.Put("/empty-no-content-type");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::OK_200, res->status);
  3291. ASSERT_EQ("empty-no-content-type", res->body);
  3292. }
  3293. TEST_F(ServerTest, GetMethodDir) {
  3294. auto res = cli_.Get("/dir/");
  3295. ASSERT_TRUE(res);
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3298. auto body = R"(<html>
  3299. <head>
  3300. </head>
  3301. <body>
  3302. <a href="/dir/test.html">Test</a>
  3303. <a href="/hi">hi</a>
  3304. </body>
  3305. </html>
  3306. )";
  3307. EXPECT_EQ(body, res->body);
  3308. }
  3309. TEST_F(ServerTest, GetMethodDirTest) {
  3310. auto res = cli_.Get("/dir/test.html");
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(StatusCode::OK_200, res->status);
  3313. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3314. EXPECT_EQ("test.html", res->body);
  3315. }
  3316. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3317. auto res = cli_.Get("/dir/../dir/test.html");
  3318. ASSERT_TRUE(res);
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3321. EXPECT_EQ("test.html", res->body);
  3322. }
  3323. TEST_F(ServerTest, GetMethodInvalidPath) {
  3324. auto res = cli_.Get("/dir/../test.html");
  3325. ASSERT_TRUE(res);
  3326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3327. }
  3328. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3329. auto res = cli_.Get("/../www/dir/test.html");
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3332. }
  3333. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3334. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3335. ASSERT_TRUE(res);
  3336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3337. }
  3338. TEST_F(ServerTest, GetMethodDirMountTest) {
  3339. auto res = cli_.Get("/mount/dir/test.html");
  3340. ASSERT_TRUE(res);
  3341. EXPECT_EQ(StatusCode::OK_200, res->status);
  3342. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3343. EXPECT_EQ("test.html", res->body);
  3344. }
  3345. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3346. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::OK_200, res->status);
  3349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3350. EXPECT_EQ("test.html", res->body);
  3351. }
  3352. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3353. auto res = cli_.Get("/mount/dir/../test.html");
  3354. ASSERT_TRUE(res);
  3355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3358. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3359. ASSERT_TRUE(res);
  3360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3361. }
  3362. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3363. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3364. ASSERT_TRUE(res);
  3365. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3366. }
  3367. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3368. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3369. ASSERT_TRUE(res);
  3370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3371. }
  3372. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3373. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3376. }
  3377. TEST_F(ServerTest, PostMethod303) {
  3378. auto res = cli_.Post("/1", "body", "text/plain");
  3379. ASSERT_TRUE(res);
  3380. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3381. EXPECT_EQ("/2", res->get_header_value("Location"));
  3382. }
  3383. TEST_F(ServerTest, PostMethod303Redirect) {
  3384. cli_.set_follow_location(true);
  3385. auto res = cli_.Post("/1", "body", "text/plain");
  3386. ASSERT_TRUE(res);
  3387. EXPECT_EQ(StatusCode::OK_200, res->status);
  3388. EXPECT_EQ("redirected.", res->body);
  3389. EXPECT_EQ("/2", res->location);
  3390. }
  3391. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3392. auto res = cli_.Get("/dir/test.abcde");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ(StatusCode::OK_200, res->status);
  3395. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3396. EXPECT_EQ("abcde", res->body);
  3397. }
  3398. TEST_F(ServerTest, StaticFileRange) {
  3399. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3400. ASSERT_TRUE(res);
  3401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3402. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3403. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3404. EXPECT_EQ(true, res->has_header("Content-Range"));
  3405. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3406. EXPECT_EQ(std::string("cd"), res->body);
  3407. }
  3408. TEST_F(ServerTest, StaticFileRanges) {
  3409. auto res =
  3410. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3413. EXPECT_TRUE(
  3414. res->get_header_value("Content-Type")
  3415. .find(
  3416. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3417. 0);
  3418. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3419. }
  3420. TEST_F(ServerTest, StaticFileRangeHead) {
  3421. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3422. ASSERT_TRUE(res);
  3423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3424. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3425. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3426. EXPECT_EQ(true, res->has_header("Content-Range"));
  3427. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3428. }
  3429. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3430. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3435. EXPECT_EQ(true, res->has_header("Content-Range"));
  3436. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3437. res->get_header_value("Content-Range"));
  3438. EXPECT_EQ("LAST\n", res->body);
  3439. }
  3440. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3441. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3446. EXPECT_EQ(true, res->has_header("Content-Range"));
  3447. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3448. }
  3449. TEST_F(ServerTest, StaticFileBigFile) {
  3450. auto res = cli_.Get("/dir/1MB.txt");
  3451. ASSERT_TRUE(res);
  3452. EXPECT_EQ(StatusCode::OK_200, res->status);
  3453. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3454. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3455. }
  3456. TEST_F(ServerTest, InvalidBaseDirMount) {
  3457. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3458. }
  3459. TEST_F(ServerTest, Binary) {
  3460. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3461. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3462. "application/octet-stream");
  3463. ASSERT_TRUE(res);
  3464. ASSERT_EQ(StatusCode::OK_200, res->status);
  3465. ASSERT_EQ(4U, res->body.size());
  3466. res = cli_.Put("/binary", binary.data(), binary.size(),
  3467. "application/octet-stream");
  3468. ASSERT_TRUE(res);
  3469. ASSERT_EQ(StatusCode::OK_200, res->status);
  3470. ASSERT_EQ(4U, res->body.size());
  3471. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3472. "application/octet-stream");
  3473. ASSERT_TRUE(res);
  3474. ASSERT_EQ(StatusCode::OK_200, res->status);
  3475. ASSERT_EQ(4U, res->body.size());
  3476. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3477. "application/octet-stream");
  3478. ASSERT_TRUE(res);
  3479. ASSERT_EQ(StatusCode::OK_200, res->status);
  3480. ASSERT_EQ(4U, res->body.size());
  3481. }
  3482. TEST_F(ServerTest, BinaryString) {
  3483. auto binary = std::string("\x00\x01\x02\x03", 4);
  3484. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3485. ASSERT_TRUE(res);
  3486. ASSERT_EQ(StatusCode::OK_200, res->status);
  3487. ASSERT_EQ(4U, res->body.size());
  3488. res = cli_.Put("/binary", binary, "application/octet-stream");
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. ASSERT_EQ(4U, res->body.size());
  3492. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ(4U, res->body.size());
  3496. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::OK_200, res->status);
  3499. ASSERT_EQ(4U, res->body.size());
  3500. }
  3501. TEST_F(ServerTest, EmptyRequest) {
  3502. auto res = cli_.Get("");
  3503. ASSERT_TRUE(!res);
  3504. EXPECT_EQ(Error::Connection, res.error());
  3505. }
  3506. TEST_F(ServerTest, LongRequest) {
  3507. std::string request;
  3508. for (size_t i = 0; i < 545; i++) {
  3509. request += "/TooLongRequest";
  3510. }
  3511. request += "OK";
  3512. auto res = cli_.Get(request.c_str());
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3515. }
  3516. TEST_F(ServerTest, TooLongRequest) {
  3517. std::string request;
  3518. for (size_t i = 0; i < 546; i++) {
  3519. request += "/TooLongRequest";
  3520. }
  3521. request += "_NG";
  3522. auto res = cli_.Get(request.c_str());
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3525. }
  3526. TEST_F(ServerTest, AlmostTooLongRequest) {
  3527. // test for #2046 - URI length check shouldn't include other content on req
  3528. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3529. // leading /, space, HTTP/1.1)
  3530. std::string request =
  3531. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3532. auto res = cli_.Get(request.c_str());
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3535. }
  3536. TEST_F(ServerTest, LongHeader) {
  3537. Request req;
  3538. req.method = "GET";
  3539. req.path = "/hi";
  3540. std::string host_and_port;
  3541. host_and_port += HOST;
  3542. host_and_port += ":";
  3543. host_and_port += std::to_string(PORT);
  3544. req.headers.emplace("Host", host_and_port.c_str());
  3545. req.headers.emplace("Accept", "*/*");
  3546. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3547. req.headers.emplace(
  3548. "Header-Name",
  3549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3577. "@@@@@@@@@@@@@@@@");
  3578. auto res = std::make_shared<Response>();
  3579. auto error = Error::Success;
  3580. auto ret = cli_.send(req, *res, error);
  3581. ASSERT_TRUE(ret);
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. }
  3584. TEST_F(ServerTest, LongQueryValue) {
  3585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3588. }
  3589. TEST_F(ServerTest, TooLongQueryValue) {
  3590. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3591. ASSERT_FALSE(res);
  3592. EXPECT_EQ(Error::Read, res.error());
  3593. }
  3594. TEST_F(ServerTest, TooLongHeader) {
  3595. Request req;
  3596. req.method = "GET";
  3597. req.path = "/hi";
  3598. std::string host_and_port;
  3599. host_and_port += HOST;
  3600. host_and_port += ":";
  3601. host_and_port += std::to_string(PORT);
  3602. req.headers.emplace("Host", host_and_port.c_str());
  3603. req.headers.emplace("Accept", "*/*");
  3604. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3605. req.headers.emplace(
  3606. "Header-Name",
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3635. "@@@@@@@@@@@@@@@@@");
  3636. auto res = std::make_shared<Response>();
  3637. auto error = Error::Success;
  3638. auto ret = cli_.send(req, *res, error);
  3639. ASSERT_TRUE(ret);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. }
  3642. TEST_F(ServerTest, HeaderCountAtLimit) {
  3643. // Test with headers just under the 100 limit
  3644. httplib::Headers headers;
  3645. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3646. // This should keep us just under the 100 header limit
  3647. for (int i = 0; i < 95; i++) {
  3648. std::string name = "X-Test-Header-" + std::to_string(i);
  3649. std::string value = "value" + std::to_string(i);
  3650. headers.emplace(name, value);
  3651. }
  3652. // This should work fine as we're under the limit
  3653. auto res = cli_.Get("/hi", headers);
  3654. EXPECT_TRUE(res);
  3655. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3656. }
  3657. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3658. // Test with many headers to exceed the 100 limit
  3659. httplib::Headers headers;
  3660. // Add 150 headers to definitely exceed the 100 limit
  3661. for (int i = 0; i < 150; i++) {
  3662. std::string name = "X-Test-Header-" + std::to_string(i);
  3663. std::string value = "value" + std::to_string(i);
  3664. headers.emplace(name, value);
  3665. }
  3666. // This should fail due to exceeding header count limit
  3667. auto res = cli_.Get("/hi", headers);
  3668. // The request should either fail or return 400 Bad Request
  3669. if (res) {
  3670. // If we get a response, it should be 400 Bad Request
  3671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3672. } else {
  3673. // Or the request should fail entirely
  3674. EXPECT_FALSE(res);
  3675. }
  3676. }
  3677. TEST_F(ServerTest, PercentEncoding) {
  3678. auto res = cli_.Get("/e%6edwith%");
  3679. ASSERT_TRUE(res);
  3680. EXPECT_EQ(StatusCode::OK_200, res->status);
  3681. }
  3682. TEST_F(ServerTest, PercentEncodingUnicode) {
  3683. auto res = cli_.Get("/e%u006edwith%");
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::OK_200, res->status);
  3686. }
  3687. TEST_F(ServerTest, InvalidPercentEncoding) {
  3688. auto res = cli_.Get("/%endwith%");
  3689. ASSERT_TRUE(res);
  3690. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3691. }
  3692. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3693. auto res = cli_.Get("/%uendwith%");
  3694. ASSERT_TRUE(res);
  3695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3696. }
  3697. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3698. auto res = cli_.Get("/hello?aaa=bbb%");
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3701. }
  3702. TEST_F(ServerTest, PlusSignEncoding) {
  3703. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3704. ASSERT_TRUE(res);
  3705. EXPECT_EQ(StatusCode::OK_200, res->status);
  3706. EXPECT_EQ("a +b", res->body);
  3707. }
  3708. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3709. // This test simulates a potential DoS attack using many headers
  3710. // to verify our security fix prevents memory exhaustion
  3711. httplib::Headers attack_headers;
  3712. // Attempt to add many headers like an attacker would (200 headers to far
  3713. // exceed limit)
  3714. for (int i = 0; i < 200; i++) {
  3715. std::string name = "X-Attack-Header-" + std::to_string(i);
  3716. std::string value = "attack_payload_" + std::to_string(i);
  3717. attack_headers.emplace(name, value);
  3718. }
  3719. // Try to POST with excessive headers
  3720. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3721. // Should either fail or return 400 Bad Request due to security limit
  3722. if (res) {
  3723. // If we get a response, it should be 400 Bad Request
  3724. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3725. } else {
  3726. // Request failed, which is the expected behavior for DoS protection
  3727. EXPECT_FALSE(res);
  3728. }
  3729. }
  3730. TEST_F(ServerTest, MultipartFormData) {
  3731. UploadFormDataItems items = {
  3732. {"text1", "text default", "", ""},
  3733. {"text2", "aωb", "", ""},
  3734. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3735. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3736. {"file3", "", "", "application/octet-stream"},
  3737. {"file4", "", "", " application/json tmp-string "}};
  3738. auto res = cli_.Post("/multipart", items);
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3743. UploadFormDataItems items = {
  3744. {"text", "default text", "", ""},
  3745. {"multi_text1", "aaaaa", "", ""},
  3746. {"multi_text1", "bbbbb", "", ""},
  3747. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3748. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3749. "application/json"},
  3750. };
  3751. auto res = cli_.Post("/multipart/multi_file_values", items);
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::OK_200, res->status);
  3754. }
  3755. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3756. auto res = cli_.Get("/hi");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3760. EXPECT_EQ("Hello World!", res->body);
  3761. }
  3762. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3763. Request req;
  3764. req.method = "POST";
  3765. req.path = "/chunked";
  3766. std::string host_and_port;
  3767. host_and_port += HOST;
  3768. host_and_port += ":";
  3769. host_and_port += std::to_string(PORT);
  3770. req.headers.emplace("Host", host_and_port.c_str());
  3771. req.headers.emplace("Accept", "*/*");
  3772. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3773. req.headers.emplace("Content-Type", "text/plain");
  3774. req.headers.emplace("Content-Length", "0");
  3775. req.headers.emplace(
  3776. "Transfer-Encoding",
  3777. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3778. // Client does not chunk, so make a chunked body manually.
  3779. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3780. auto res = std::make_shared<Response>();
  3781. auto error = Error::Success;
  3782. auto ret = cli_.send(req, *res, error);
  3783. ASSERT_TRUE(ret);
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. }
  3786. TEST_F(ServerTest, GetStreamed2) {
  3787. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3790. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3791. EXPECT_EQ(true, res->has_header("Content-Range"));
  3792. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3793. EXPECT_EQ(std::string("ab"), res->body);
  3794. }
  3795. TEST_F(ServerTest, GetStreamed) {
  3796. auto res = cli_.Get("/streamed");
  3797. ASSERT_TRUE(res);
  3798. EXPECT_EQ(StatusCode::OK_200, res->status);
  3799. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3800. EXPECT_EQ(std::string("aaabbb"), res->body);
  3801. }
  3802. TEST_F(ServerTest, GetStreamedWithRange1) {
  3803. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3804. ASSERT_TRUE(res);
  3805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3806. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3809. EXPECT_EQ(std::string("def"), res->body);
  3810. }
  3811. TEST_F(ServerTest, GetStreamedWithRange2) {
  3812. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3815. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3816. EXPECT_EQ(true, res->has_header("Content-Range"));
  3817. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3818. EXPECT_EQ(std::string("bcdefg"), res->body);
  3819. }
  3820. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3821. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3824. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3825. EXPECT_EQ(true, res->has_header("Content-Range"));
  3826. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3827. EXPECT_EQ(std::string("efg"), res->body);
  3828. }
  3829. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3830. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3833. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3834. EXPECT_EQ(false, res->has_header("Content-Range"));
  3835. EXPECT_EQ(0U, res->body.size());
  3836. }
  3837. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3838. auto res = cli_.Get("/streamed-with-range",
  3839. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3840. "92233720368547758079223372036854775807"}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3843. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3844. EXPECT_EQ(false, res->has_header("Content-Range"));
  3845. EXPECT_EQ(0U, res->body.size());
  3846. }
  3847. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3848. auto res = cli_.Get(
  3849. "/with-range",
  3850. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3851. {"Accept-Encoding", ""}});
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3854. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3855. EXPECT_EQ(true, res->has_header("Content-Range"));
  3856. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3857. EXPECT_EQ(std::string("abcdefg"), res->body);
  3858. }
  3859. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3860. auto res = cli_.Get("/with-range", {
  3861. {"Range", "bytes=0-"},
  3862. {"Accept-Encoding", ""},
  3863. });
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3866. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3867. EXPECT_EQ(true, res->has_header("Content-Range"));
  3868. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3869. EXPECT_EQ(std::string("abcdefg"), res->body);
  3870. }
  3871. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3872. auto res =
  3873. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3876. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(false, res->has_header("Content-Range"));
  3878. EXPECT_EQ(267U, res->body.size());
  3879. // Check that both range contents are present
  3880. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3881. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3882. // Check that Content-Range headers are present for both ranges
  3883. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3884. std::string::npos);
  3885. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3886. std::string::npos);
  3887. }
  3888. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3889. Ranges ranges;
  3890. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3891. ranges.emplace_back(0, -1);
  3892. }
  3893. auto res =
  3894. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3895. ASSERT_TRUE(res);
  3896. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3897. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3898. EXPECT_EQ(false, res->has_header("Content-Range"));
  3899. EXPECT_EQ(0U, res->body.size());
  3900. }
  3901. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3902. auto res =
  3903. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3906. EXPECT_EQ(5U, res->body.size());
  3907. // Check that overlapping ranges are coalesced into a single range
  3908. EXPECT_EQ("bcdef", res->body);
  3909. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3910. // Should be single range, not multipart
  3911. EXPECT_TRUE(res->has_header("Content-Range"));
  3912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3913. }
  3914. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3915. auto res =
  3916. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3919. EXPECT_EQ(268U, res->body.size());
  3920. // Check that both range contents are present
  3921. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3922. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3923. // Check that Content-Range headers are present for both ranges
  3924. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3925. std::string::npos);
  3926. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3927. std::string::npos);
  3928. }
  3929. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3930. auto res =
  3931. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3934. EXPECT_EQ(269U, res->body.size());
  3935. // Check that both duplicate range contents are present
  3936. size_t first_abc = res->body.find("abc\r\n");
  3937. EXPECT_TRUE(first_abc != std::string::npos);
  3938. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3939. EXPECT_TRUE(second_abc != std::string::npos);
  3940. // Check that Content-Range headers are present for both ranges
  3941. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3942. EXPECT_TRUE(first_range != std::string::npos);
  3943. size_t second_range =
  3944. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3945. EXPECT_TRUE(second_range != std::string::npos);
  3946. }
  3947. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3948. auto res = cli_.Get("/streamed-with-range?error",
  3949. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3952. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3953. EXPECT_EQ(false, res->has_header("Content-Range"));
  3954. EXPECT_EQ(0U, res->body.size());
  3955. }
  3956. TEST_F(ServerTest, GetStreamedEndless) {
  3957. uint64_t offset = 0;
  3958. auto res = cli_.Get("/streamed-cancel",
  3959. [&](const char * /*data*/, uint64_t data_length) {
  3960. if (offset < 100) {
  3961. offset += data_length;
  3962. return true;
  3963. }
  3964. return false;
  3965. });
  3966. ASSERT_TRUE(!res);
  3967. EXPECT_EQ(Error::Canceled, res.error());
  3968. }
  3969. TEST_F(ServerTest, ClientStop) {
  3970. std::atomic_size_t count{4};
  3971. std::vector<std::thread> threads;
  3972. for (auto i = count.load(); i != 0; --i) {
  3973. threads.emplace_back([&]() {
  3974. auto res = cli_.Get("/streamed-cancel",
  3975. [&](const char *, uint64_t) { return true; });
  3976. --count;
  3977. ASSERT_TRUE(!res);
  3978. EXPECT_TRUE(res.error() == Error::Canceled ||
  3979. res.error() == Error::Read || res.error() == Error::Write);
  3980. });
  3981. }
  3982. std::this_thread::sleep_for(std::chrono::seconds(2));
  3983. while (count != 0) {
  3984. cli_.stop();
  3985. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3986. }
  3987. for (auto &t : threads) {
  3988. t.join();
  3989. }
  3990. }
  3991. TEST_F(ServerTest, GetWithRange1) {
  3992. auto res = cli_.Get("/with-range", {
  3993. make_range_header({{3, 5}}),
  3994. {"Accept-Encoding", ""},
  3995. });
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3998. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3999. EXPECT_EQ(true, res->has_header("Content-Range"));
  4000. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4001. EXPECT_EQ(std::string("def"), res->body);
  4002. }
  4003. TEST_F(ServerTest, GetWithRange2) {
  4004. auto res = cli_.Get("/with-range", {
  4005. make_range_header({{1, -1}}),
  4006. {"Accept-Encoding", ""},
  4007. });
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4010. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4011. EXPECT_EQ(true, res->has_header("Content-Range"));
  4012. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4013. EXPECT_EQ(std::string("bcdefg"), res->body);
  4014. }
  4015. TEST_F(ServerTest, GetWithRange3) {
  4016. auto res = cli_.Get("/with-range", {
  4017. make_range_header({{0, 0}}),
  4018. {"Accept-Encoding", ""},
  4019. });
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4022. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4023. EXPECT_EQ(true, res->has_header("Content-Range"));
  4024. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4025. EXPECT_EQ(std::string("a"), res->body);
  4026. }
  4027. TEST_F(ServerTest, GetWithRange4) {
  4028. auto res = cli_.Get("/with-range", {
  4029. make_range_header({{-1, 2}}),
  4030. {"Accept-Encoding", ""},
  4031. });
  4032. ASSERT_TRUE(res);
  4033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4034. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4035. EXPECT_EQ(true, res->has_header("Content-Range"));
  4036. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4037. EXPECT_EQ(std::string("fg"), res->body);
  4038. }
  4039. TEST_F(ServerTest, GetWithRange5) {
  4040. auto res = cli_.Get("/with-range", {
  4041. make_range_header({{0, 5}}),
  4042. {"Accept-Encoding", ""},
  4043. });
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4046. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(true, res->has_header("Content-Range"));
  4048. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4049. EXPECT_EQ(std::string("abcdef"), res->body);
  4050. }
  4051. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4052. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4055. }
  4056. TEST_F(ServerTest, GetWithRangeMultipart) {
  4057. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4060. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ(false, res->has_header("Content-Range"));
  4062. EXPECT_EQ(267U, res->body.size());
  4063. }
  4064. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4065. auto res =
  4066. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4069. }
  4070. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4071. auto res = cli_.Get("/with-range-customized-response",
  4072. {{make_range_header({{1, 2}})}});
  4073. ASSERT_TRUE(res);
  4074. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4075. EXPECT_EQ(true, res->has_header("Content-Length"));
  4076. EXPECT_EQ(false, res->has_header("Content-Range"));
  4077. EXPECT_EQ(JSON_DATA, res->body);
  4078. }
  4079. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4080. auto res = cli_.Get("/with-range-customized-response",
  4081. {{make_range_header({{1, 2}, {4, 5}})}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4084. EXPECT_EQ(true, res->has_header("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(JSON_DATA, res->body);
  4087. }
  4088. TEST_F(ServerTest, Issue1772) {
  4089. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4092. }
  4093. TEST_F(ServerTest, Issue609) {
  4094. auto res = cli_.Delete("/issue609");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. EXPECT_EQ(std::string("ok"), res->body);
  4098. }
  4099. TEST_F(ServerTest, GetStreamedChunked) {
  4100. auto res = cli_.Get("/streamed-chunked");
  4101. ASSERT_TRUE(res);
  4102. EXPECT_EQ(StatusCode::OK_200, res->status);
  4103. EXPECT_EQ(std::string("123456789"), res->body);
  4104. }
  4105. TEST_F(ServerTest, GetStreamedChunked2) {
  4106. auto res = cli_.Get("/streamed-chunked2");
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::OK_200, res->status);
  4109. EXPECT_EQ(std::string("123456789"), res->body);
  4110. }
  4111. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4112. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::OK_200, res->status);
  4115. EXPECT_EQ(std::string("123456789"), res->body);
  4116. EXPECT_TRUE(res->has_header("Trailer"));
  4117. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4118. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4119. // Trailers are now stored separately from headers (security fix)
  4120. EXPECT_EQ(2U, res->trailers.size());
  4121. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4122. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4123. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4124. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4125. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4126. // Verify trailers are NOT in headers (security verification)
  4127. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4128. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4129. }
  4130. TEST_F(ServerTest, LargeChunkedPost) {
  4131. Request req;
  4132. req.method = "POST";
  4133. req.path = "/large-chunked";
  4134. std::string host_and_port;
  4135. host_and_port += HOST;
  4136. host_and_port += ":";
  4137. host_and_port += std::to_string(PORT);
  4138. req.headers.emplace("Host", host_and_port.c_str());
  4139. req.headers.emplace("Accept", "*/*");
  4140. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4141. req.headers.emplace("Content-Type", "text/plain");
  4142. req.headers.emplace("Content-Length", "0");
  4143. req.headers.emplace("Transfer-Encoding", "chunked");
  4144. std::string long_string(30 * 1024u, 'a');
  4145. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4146. // Attempt to make a large enough post to exceed OS buffers, to test that
  4147. // the server handles short reads if the full chunk data isn't available.
  4148. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4149. auto res = std::make_shared<Response>();
  4150. auto error = Error::Success;
  4151. auto ret = cli_.send(req, *res, error);
  4152. ASSERT_TRUE(ret);
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. }
  4155. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4156. auto res = cli_.Get("/remote_addr");
  4157. ASSERT_TRUE(res);
  4158. EXPECT_EQ(StatusCode::OK_200, res->status);
  4159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4160. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4161. }
  4162. TEST_F(ServerTest, GetMethodLocalAddr) {
  4163. auto res = cli_.Get("/local_addr");
  4164. ASSERT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::OK_200, res->status);
  4166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4167. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4168. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4169. }
  4170. TEST_F(ServerTest, HTTPResponseSplitting) {
  4171. auto res = cli_.Get("/http_response_splitting");
  4172. ASSERT_TRUE(res);
  4173. EXPECT_EQ(StatusCode::OK_200, res->status);
  4174. }
  4175. TEST_F(ServerTest, SlowRequest) {
  4176. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4177. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4178. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4179. }
  4180. #if 0
  4181. TEST_F(ServerTest, SlowPost) {
  4182. char buffer[64 * 1024];
  4183. memset(buffer, 0x42, sizeof(buffer));
  4184. auto res = cli_.Post(
  4185. "/slowpost", 64 * 1024 * 1024,
  4186. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4187. auto ret = sink.write(buffer, sizeof(buffer));
  4188. EXPECT_TRUE(ret);
  4189. return true;
  4190. },
  4191. "text/plain");
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. }
  4195. TEST_F(ServerTest, SlowPostFail) {
  4196. char buffer[64 * 1024];
  4197. memset(buffer, 0x42, sizeof(buffer));
  4198. cli_.set_write_timeout(std::chrono::seconds(0));
  4199. auto res = cli_.Post(
  4200. "/slowpost", 64 * 1024 * 1024,
  4201. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4202. sink.write(buffer, sizeof(buffer));
  4203. return true;
  4204. },
  4205. "text/plain");
  4206. ASSERT_TRUE(!res);
  4207. EXPECT_EQ(Error::Write, res.error());
  4208. }
  4209. #endif
  4210. TEST_F(ServerTest, Put) {
  4211. auto res = cli_.Put("/put", "PUT", "text/plain");
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. EXPECT_EQ("PUT", res->body);
  4215. }
  4216. TEST_F(ServerTest, PutWithContentProvider) {
  4217. auto res = cli_.Put(
  4218. "/put", 3,
  4219. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4220. sink.os << "PUT";
  4221. return true;
  4222. },
  4223. "text/plain");
  4224. ASSERT_TRUE(res);
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. EXPECT_EQ("PUT", res->body);
  4227. }
  4228. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4229. auto res = cli_.Post(
  4230. "/post", 42,
  4231. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4232. return false;
  4233. },
  4234. "text/plain");
  4235. ASSERT_TRUE(!res);
  4236. EXPECT_EQ(Error::Canceled, res.error());
  4237. }
  4238. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4239. auto res = cli_.Put(
  4240. "/put",
  4241. [](size_t /*offset*/, DataSink &sink) {
  4242. sink.os << "PUT";
  4243. sink.done();
  4244. return true;
  4245. },
  4246. "text/plain");
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::OK_200, res->status);
  4249. EXPECT_EQ("PUT", res->body);
  4250. }
  4251. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4252. auto res = cli_.Post(
  4253. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4254. "text/plain");
  4255. ASSERT_TRUE(!res);
  4256. EXPECT_EQ(Error::Canceled, res.error());
  4257. }
  4258. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4259. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4260. cli_.set_compress(true);
  4261. auto res = cli_.Put(
  4262. "/put", 3,
  4263. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4264. sink.os << "PUT";
  4265. return true;
  4266. },
  4267. "text/plain");
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::OK_200, res->status);
  4270. EXPECT_EQ("PUT", res->body);
  4271. }
  4272. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4273. cli_.set_compress(true);
  4274. auto res = cli_.Post(
  4275. "/post", 42,
  4276. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4277. return false;
  4278. },
  4279. "text/plain");
  4280. ASSERT_TRUE(!res);
  4281. EXPECT_EQ(Error::Canceled, res.error());
  4282. }
  4283. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4284. cli_.set_compress(true);
  4285. auto res = cli_.Put(
  4286. "/put",
  4287. [](size_t /*offset*/, DataSink &sink) {
  4288. sink.os << "PUT";
  4289. sink.done();
  4290. return true;
  4291. },
  4292. "text/plain");
  4293. ASSERT_TRUE(res);
  4294. EXPECT_EQ(StatusCode::OK_200, res->status);
  4295. EXPECT_EQ("PUT", res->body);
  4296. }
  4297. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4298. cli_.set_compress(true);
  4299. auto res = cli_.Post(
  4300. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4301. "text/plain");
  4302. ASSERT_TRUE(!res);
  4303. EXPECT_EQ(Error::Canceled, res.error());
  4304. }
  4305. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4306. cli_.set_compress(true);
  4307. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ(LARGE_DATA, res->body);
  4311. }
  4312. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4314. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4315. Client cli(s.c_str());
  4316. cli.enable_server_certificate_verification(false);
  4317. #else
  4318. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4319. Client cli(s.c_str());
  4320. #endif
  4321. cli.set_compress(true);
  4322. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ(LARGE_DATA, res->body);
  4326. // The compressed size should be less than a 10th of the original. May vary
  4327. // depending on the zlib library.
  4328. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4329. static_cast<uint64_t>(10 * 1024 * 1024));
  4330. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4331. }
  4332. TEST_F(ServerTest, PutContentWithDeflate) {
  4333. cli_.set_compress(false);
  4334. Headers headers;
  4335. headers.emplace("Content-Encoding", "deflate");
  4336. // PUT in deflate format:
  4337. auto res = cli_.Put("/put", headers,
  4338. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4339. ASSERT_TRUE(res);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. EXPECT_EQ("PUT", res->body);
  4342. }
  4343. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4344. Headers headers;
  4345. headers.emplace("Accept-Encoding", "gzip, deflate");
  4346. auto res = cli_.Get("/streamed-chunked", headers);
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. EXPECT_EQ(std::string("123456789"), res->body);
  4350. }
  4351. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4352. Headers headers;
  4353. headers.emplace("Accept-Encoding", "gzip, deflate");
  4354. auto res = cli_.Get("/streamed-chunked2", headers);
  4355. ASSERT_TRUE(res);
  4356. EXPECT_EQ(StatusCode::OK_200, res->status);
  4357. EXPECT_EQ(std::string("123456789"), res->body);
  4358. }
  4359. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4360. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4361. ASSERT_TRUE(res);
  4362. EXPECT_EQ(StatusCode::OK_200, res->status);
  4363. }
  4364. TEST(GzipDecompressor, ChunkedDecompression) {
  4365. std::string data;
  4366. for (size_t i = 0; i < 32 * 1024; ++i) {
  4367. data.push_back(static_cast<char>('a' + i % 26));
  4368. }
  4369. std::string compressed_data;
  4370. {
  4371. httplib::detail::gzip_compressor compressor;
  4372. bool result = compressor.compress(
  4373. data.data(), data.size(),
  4374. /*last=*/true,
  4375. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4376. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4377. compressed_data_size);
  4378. return true;
  4379. });
  4380. ASSERT_TRUE(result);
  4381. }
  4382. std::string decompressed_data;
  4383. {
  4384. httplib::detail::gzip_decompressor decompressor;
  4385. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4386. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4387. size_t chunk_size = 130;
  4388. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4389. chunk_begin += chunk_size) {
  4390. size_t current_chunk_size =
  4391. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4392. bool result = decompressor.decompress(
  4393. compressed_data.data() + chunk_begin, current_chunk_size,
  4394. [&](const char *decompressed_data_chunk,
  4395. size_t decompressed_data_chunk_size) {
  4396. decompressed_data.insert(decompressed_data.size(),
  4397. decompressed_data_chunk,
  4398. decompressed_data_chunk_size);
  4399. return true;
  4400. });
  4401. ASSERT_TRUE(result);
  4402. }
  4403. }
  4404. ASSERT_EQ(data, decompressed_data);
  4405. }
  4406. TEST(GzipDecompressor, DeflateDecompression) {
  4407. std::string original_text = "Raw deflate without gzip";
  4408. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4409. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4410. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4411. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4412. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4413. std::string decompressed_data;
  4414. {
  4415. httplib::detail::gzip_decompressor decompressor;
  4416. bool result = decompressor.decompress(
  4417. compressed_data.data(), compressed_data.size(),
  4418. [&](const char *decompressed_data_chunk,
  4419. size_t decompressed_data_chunk_size) {
  4420. decompressed_data.insert(decompressed_data.size(),
  4421. decompressed_data_chunk,
  4422. decompressed_data_chunk_size);
  4423. return true;
  4424. });
  4425. ASSERT_TRUE(result);
  4426. }
  4427. ASSERT_EQ(original_text, decompressed_data);
  4428. }
  4429. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4430. std::string original_text = "Raw deflate without gzip";
  4431. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4432. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4433. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4434. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4435. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4436. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4437. std::string decompressed_data;
  4438. {
  4439. httplib::detail::gzip_decompressor decompressor;
  4440. bool result = decompressor.decompress(
  4441. compressed_data.data(), compressed_data.size(),
  4442. [&](const char *decompressed_data_chunk,
  4443. size_t decompressed_data_chunk_size) {
  4444. decompressed_data.insert(decompressed_data.size(),
  4445. decompressed_data_chunk,
  4446. decompressed_data_chunk_size);
  4447. return true;
  4448. });
  4449. ASSERT_TRUE(result);
  4450. }
  4451. ASSERT_EQ(original_text, decompressed_data);
  4452. }
  4453. #ifdef _WIN32
  4454. TEST(GzipDecompressor, LargeRandomData) {
  4455. // prepare large random data that is difficult to be compressed and is
  4456. // expected to have large size even when compressed
  4457. std::random_device seed_gen;
  4458. std::mt19937 random(seed_gen());
  4459. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4460. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4461. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4462. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4463. // compress data over 4GiB
  4464. std::string compressed_data;
  4465. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4466. httplib::detail::gzip_compressor compressor;
  4467. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4468. data.size() * sizeof(std::uint32_t), true,
  4469. [&](const char *data, size_t size) {
  4470. compressed_data.insert(
  4471. compressed_data.size(), data, size);
  4472. return true;
  4473. });
  4474. ASSERT_TRUE(result);
  4475. // FIXME: compressed data size is expected to be greater than 4GiB,
  4476. // but there is no guarantee
  4477. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4478. // decompress data over 4GiB
  4479. std::string decompressed_data;
  4480. decompressed_data.reserve(data_size);
  4481. httplib::detail::gzip_decompressor decompressor;
  4482. result = decompressor.decompress(
  4483. compressed_data.data(), compressed_data.size(),
  4484. [&](const char *data, size_t size) {
  4485. decompressed_data.insert(decompressed_data.size(), data, size);
  4486. return true;
  4487. });
  4488. ASSERT_TRUE(result);
  4489. // compare
  4490. ASSERT_EQ(data_size, decompressed_data.size());
  4491. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4492. 0);
  4493. }
  4494. #endif
  4495. #endif
  4496. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4497. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4498. Headers headers;
  4499. headers.emplace("Accept-Encoding", "br");
  4500. auto res = cli_.Get("/streamed-chunked", headers);
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ(std::string("123456789"), res->body);
  4504. }
  4505. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4506. Headers headers;
  4507. headers.emplace("Accept-Encoding", "br");
  4508. auto res = cli_.Get("/streamed-chunked2", headers);
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ(std::string("123456789"), res->body);
  4512. }
  4513. #endif
  4514. TEST_F(ServerTest, Patch) {
  4515. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4516. ASSERT_TRUE(res);
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. EXPECT_EQ("PATCH", res->body);
  4519. }
  4520. TEST_F(ServerTest, Delete) {
  4521. auto res = cli_.Delete("/delete");
  4522. ASSERT_TRUE(res);
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("DELETE", res->body);
  4525. }
  4526. TEST_F(ServerTest, DeleteContentReceiver) {
  4527. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4528. ASSERT_TRUE(res);
  4529. EXPECT_EQ(StatusCode::OK_200, res->status);
  4530. EXPECT_EQ("content", res->body);
  4531. }
  4532. TEST_F(ServerTest, Options) {
  4533. auto res = cli_.Options("*");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4537. EXPECT_TRUE(res->body.empty());
  4538. }
  4539. TEST_F(ServerTest, URL) {
  4540. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(StatusCode::OK_200, res->status);
  4543. }
  4544. TEST_F(ServerTest, ArrayParam) {
  4545. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. }
  4549. TEST_F(ServerTest, NoMultipleHeaders) {
  4550. Headers headers = {{"Content-Length", "5"}};
  4551. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4552. "text/plain");
  4553. ASSERT_TRUE(res);
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. }
  4556. TEST_F(ServerTest, PostContentReceiver) {
  4557. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4558. ASSERT_TRUE(res);
  4559. ASSERT_EQ(StatusCode::OK_200, res->status);
  4560. ASSERT_EQ("content", res->body);
  4561. }
  4562. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4563. UploadFormDataItems items = {
  4564. {"text1", "text default", "", ""},
  4565. {"text2", "aωb", "", ""},
  4566. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4567. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4568. {"file3", "", "", "application/octet-stream"},
  4569. };
  4570. auto res = cli_.Post("/content_receiver", items);
  4571. ASSERT_TRUE(res);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. }
  4574. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4575. UploadFormDataItems items = {
  4576. {"text1", "text default", "", ""},
  4577. {"text2", "aωb", "", ""},
  4578. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4579. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4580. {"file3", "", "", "application/octet-stream"},
  4581. };
  4582. auto boundary = std::string("+++++");
  4583. std::string body;
  4584. for (const auto &item : items) {
  4585. body += "--" + boundary + "\r\n";
  4586. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4587. if (!item.filename.empty()) {
  4588. body += "; filename=\"" + item.filename + "\"";
  4589. }
  4590. body += "\r\n";
  4591. if (!item.content_type.empty()) {
  4592. body += "Content-Type: " + item.content_type + "\r\n";
  4593. }
  4594. body += "\r\n";
  4595. body += item.content + "\r\n";
  4596. }
  4597. body += "--" + boundary + "--\r\n";
  4598. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4599. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. TEST_F(ServerTest, PostContentReceiverGzip) {
  4604. cli_.set_compress(true);
  4605. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4606. ASSERT_TRUE(res);
  4607. ASSERT_EQ(StatusCode::OK_200, res->status);
  4608. ASSERT_EQ("content", res->body);
  4609. }
  4610. TEST_F(ServerTest, PutContentReceiver) {
  4611. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4612. ASSERT_TRUE(res);
  4613. ASSERT_EQ(StatusCode::OK_200, res->status);
  4614. ASSERT_EQ("content", res->body);
  4615. }
  4616. TEST_F(ServerTest, PatchContentReceiver) {
  4617. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4618. ASSERT_TRUE(res);
  4619. ASSERT_EQ(StatusCode::OK_200, res->status);
  4620. ASSERT_EQ("content", res->body);
  4621. }
  4622. template <typename ClientType>
  4623. void TestWithHeadersAndContentReceiver(
  4624. ClientType &cli,
  4625. std::function<Result(ClientType &, const std::string &, const Headers &,
  4626. const std::string &, const std::string &,
  4627. ContentReceiver, DownloadProgress)>
  4628. request_func) {
  4629. Headers headers;
  4630. headers.emplace("X-Custom-Header", "test-value");
  4631. std::string received_body;
  4632. auto res = request_func(
  4633. cli, "/content_receiver", headers, "content", "application/json",
  4634. [&](const char *data, size_t data_length) {
  4635. received_body.append(data, data_length);
  4636. return true;
  4637. },
  4638. nullptr);
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ("content", received_body);
  4642. }
  4643. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4645. using ClientT = SSLClient;
  4646. #else
  4647. using ClientT = Client;
  4648. #endif
  4649. TestWithHeadersAndContentReceiver<ClientT>(
  4650. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4651. const std::string &body, const std::string &content_type,
  4652. ContentReceiver receiver, DownloadProgress progress) {
  4653. return cli.Post(path, headers, body, content_type, receiver, progress);
  4654. });
  4655. }
  4656. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4657. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4658. using ClientT = SSLClient;
  4659. #else
  4660. using ClientT = Client;
  4661. #endif
  4662. TestWithHeadersAndContentReceiver<ClientT>(
  4663. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4664. const std::string &body, const std::string &content_type,
  4665. ContentReceiver receiver, DownloadProgress progress) {
  4666. return cli.Put(path, headers, body, content_type, receiver, progress);
  4667. });
  4668. }
  4669. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4670. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4671. using ClientT = SSLClient;
  4672. #else
  4673. using ClientT = Client;
  4674. #endif
  4675. TestWithHeadersAndContentReceiver<ClientT>(
  4676. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4677. const std::string &body, const std::string &content_type,
  4678. ContentReceiver receiver, DownloadProgress progress) {
  4679. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4680. });
  4681. }
  4682. template <typename ClientType>
  4683. void TestWithHeadersAndContentReceiverWithProgress(
  4684. ClientType &cli,
  4685. std::function<Result(ClientType &, const std::string &, const Headers &,
  4686. const std::string &, const std::string &,
  4687. ContentReceiver, DownloadProgress)>
  4688. request_func) {
  4689. Headers headers;
  4690. headers.emplace("X-Test-Header", "progress-test");
  4691. std::string received_body;
  4692. auto progress_called = false;
  4693. auto res = request_func(
  4694. cli, "/content_receiver", headers, "content", "text/plain",
  4695. [&](const char *data, size_t data_length) {
  4696. received_body.append(data, data_length);
  4697. return true;
  4698. },
  4699. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4700. progress_called = true;
  4701. return true;
  4702. });
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ("content", received_body);
  4706. EXPECT_TRUE(progress_called);
  4707. }
  4708. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4709. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4710. using ClientT = SSLClient;
  4711. #else
  4712. using ClientT = Client;
  4713. #endif
  4714. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4715. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4716. const std::string &body, const std::string &content_type,
  4717. ContentReceiver receiver, DownloadProgress progress) {
  4718. return cli.Post(path, headers, body, content_type, receiver, progress);
  4719. });
  4720. }
  4721. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4722. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4723. using ClientT = SSLClient;
  4724. #else
  4725. using ClientT = Client;
  4726. #endif
  4727. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4728. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4729. const std::string &body, const std::string &content_type,
  4730. ContentReceiver receiver, DownloadProgress progress) {
  4731. return cli.Put(path, headers, body, content_type, receiver, progress);
  4732. });
  4733. }
  4734. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4735. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4736. using ClientT = SSLClient;
  4737. #else
  4738. using ClientT = Client;
  4739. #endif
  4740. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4741. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4742. const std::string &body, const std::string &content_type,
  4743. ContentReceiver receiver, DownloadProgress progress) {
  4744. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4745. });
  4746. }
  4747. template <typename ClientType>
  4748. void TestWithHeadersAndContentReceiverError(
  4749. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4750. const Headers &, const std::string &,
  4751. const std::string &, ContentReceiver)>
  4752. request_func) {
  4753. Headers headers;
  4754. headers.emplace("X-Error-Test", "true");
  4755. std::string received_body;
  4756. auto receiver_failed = false;
  4757. auto res =
  4758. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4759. [&](const char *data, size_t data_length) {
  4760. received_body.append(data, data_length);
  4761. receiver_failed = true;
  4762. return false;
  4763. });
  4764. ASSERT_FALSE(res);
  4765. EXPECT_TRUE(receiver_failed);
  4766. }
  4767. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4769. using ClientT = SSLClient;
  4770. #else
  4771. using ClientT = Client;
  4772. #endif
  4773. TestWithHeadersAndContentReceiverError<ClientT>(
  4774. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4775. const std::string &body, const std::string &content_type,
  4776. ContentReceiver receiver) {
  4777. return cli.Post(path, headers, body, content_type, receiver);
  4778. });
  4779. }
  4780. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4781. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4782. using ClientT = SSLClient;
  4783. #else
  4784. using ClientT = Client;
  4785. #endif
  4786. TestWithHeadersAndContentReceiverError<ClientT>(
  4787. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4788. const std::string &body, const std::string &content_type,
  4789. ContentReceiver receiver) {
  4790. return cli.Put(path, headers, body, content_type, receiver);
  4791. });
  4792. }
  4793. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4794. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4795. using ClientT = SSLClient;
  4796. #else
  4797. using ClientT = Client;
  4798. #endif
  4799. TestWithHeadersAndContentReceiverError<ClientT>(
  4800. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4801. const std::string &body, const std::string &content_type,
  4802. ContentReceiver receiver) {
  4803. return cli.Patch(path, headers, body, content_type, receiver);
  4804. });
  4805. }
  4806. TEST_F(ServerTest, PostQueryStringAndBody) {
  4807. auto res =
  4808. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4809. ASSERT_TRUE(res);
  4810. ASSERT_EQ(StatusCode::OK_200, res->status);
  4811. }
  4812. TEST_F(ServerTest, HTTP2Magic) {
  4813. Request req;
  4814. req.method = "PRI";
  4815. req.path = "*";
  4816. req.body = "SM";
  4817. auto res = std::make_shared<Response>();
  4818. auto error = Error::Success;
  4819. auto ret = cli_.send(req, *res, error);
  4820. ASSERT_TRUE(ret);
  4821. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4822. }
  4823. TEST_F(ServerTest, KeepAlive) {
  4824. auto res = cli_.Get("/hi");
  4825. ASSERT_TRUE(res);
  4826. EXPECT_EQ(StatusCode::OK_200, res->status);
  4827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4828. EXPECT_EQ("Hello World!", res->body);
  4829. res = cli_.Get("/hi");
  4830. ASSERT_TRUE(res);
  4831. EXPECT_EQ(StatusCode::OK_200, res->status);
  4832. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4833. EXPECT_EQ("Hello World!", res->body);
  4834. res = cli_.Get("/hi");
  4835. ASSERT_TRUE(res);
  4836. EXPECT_EQ(StatusCode::OK_200, res->status);
  4837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4838. EXPECT_EQ("Hello World!", res->body);
  4839. res = cli_.Get("/not-exist");
  4840. ASSERT_TRUE(res);
  4841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4842. res = cli_.Post("/empty", "", "text/plain");
  4843. ASSERT_TRUE(res);
  4844. EXPECT_EQ(StatusCode::OK_200, res->status);
  4845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4846. EXPECT_EQ("empty", res->body);
  4847. EXPECT_EQ("close", res->get_header_value("Connection"));
  4848. res = cli_.Post(
  4849. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4850. "text/plain");
  4851. ASSERT_TRUE(res);
  4852. EXPECT_EQ(StatusCode::OK_200, res->status);
  4853. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4854. EXPECT_EQ("empty", res->body);
  4855. cli_.set_keep_alive(false);
  4856. res = cli_.Get("/last-request");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. EXPECT_EQ("close", res->get_header_value("Connection"));
  4860. }
  4861. TEST_F(ServerTest, TooManyRedirect) {
  4862. cli_.set_follow_location(true);
  4863. auto res = cli_.Get("/redirect/0");
  4864. ASSERT_TRUE(!res);
  4865. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4866. }
  4867. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4868. TEST_F(ServerTest, Gzip) {
  4869. Headers headers;
  4870. headers.emplace("Accept-Encoding", "gzip, deflate");
  4871. auto res = cli_.Get("/compress", headers);
  4872. ASSERT_TRUE(res);
  4873. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4874. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4875. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4876. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4877. "7890123456789012345678901234567890",
  4878. res->body);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. }
  4881. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4882. Headers headers;
  4883. headers.emplace("Accept-Encoding", "");
  4884. auto res = cli_.Get("/compress", headers);
  4885. ASSERT_TRUE(res);
  4886. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4889. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4890. "7890123456789012345678901234567890",
  4891. res->body);
  4892. EXPECT_EQ(StatusCode::OK_200, res->status);
  4893. }
  4894. TEST_F(ServerTest, GzipWithContentReceiver) {
  4895. Headers headers;
  4896. headers.emplace("Accept-Encoding", "gzip, deflate");
  4897. std::string body;
  4898. auto res = cli_.Get("/compress", headers,
  4899. [&](const char *data, uint64_t data_length) {
  4900. EXPECT_EQ(100U, data_length);
  4901. body.append(data, data_length);
  4902. return true;
  4903. });
  4904. ASSERT_TRUE(res);
  4905. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4907. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4908. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4909. "7890123456789012345678901234567890",
  4910. body);
  4911. EXPECT_EQ(StatusCode::OK_200, res->status);
  4912. }
  4913. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4914. Headers headers;
  4915. headers.emplace("Accept-Encoding", "gzip, deflate");
  4916. cli_.set_decompress(false);
  4917. auto res = cli_.Get("/compress", headers);
  4918. ASSERT_TRUE(res);
  4919. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4921. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4922. EXPECT_EQ(33U, res->body.size());
  4923. EXPECT_EQ(StatusCode::OK_200, res->status);
  4924. }
  4925. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4926. Headers headers;
  4927. headers.emplace("Accept-Encoding", "");
  4928. std::string body;
  4929. auto res = cli_.Get("/compress", headers,
  4930. [&](const char *data, uint64_t data_length) {
  4931. EXPECT_EQ(100U, data_length);
  4932. body.append(data, data_length);
  4933. return true;
  4934. });
  4935. ASSERT_TRUE(res);
  4936. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4938. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4940. "7890123456789012345678901234567890",
  4941. body);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. }
  4944. TEST_F(ServerTest, NoGzip) {
  4945. Headers headers;
  4946. headers.emplace("Accept-Encoding", "gzip, deflate");
  4947. auto res = cli_.Get("/nocompress", headers);
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4950. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4951. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4953. "7890123456789012345678901234567890",
  4954. res->body);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. }
  4957. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "gzip, deflate");
  4960. std::string body;
  4961. auto res = cli_.Get("/nocompress", headers,
  4962. [&](const char *data, uint64_t data_length) {
  4963. EXPECT_EQ(100U, data_length);
  4964. body.append(data, data_length);
  4965. return true;
  4966. });
  4967. ASSERT_TRUE(res);
  4968. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4969. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4970. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4971. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4972. "7890123456789012345678901234567890",
  4973. body);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. }
  4976. TEST_F(ServerTest, MultipartFormDataGzip) {
  4977. UploadFormDataItems items = {
  4978. {"key1", "test", "", ""},
  4979. {"key2", "--abcdefg123", "", ""},
  4980. };
  4981. cli_.set_compress(true);
  4982. auto res = cli_.Post("/compress-multipart", items);
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. }
  4986. #endif
  4987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4988. TEST_F(ServerTest, Brotli) {
  4989. Headers headers;
  4990. headers.emplace("Accept-Encoding", "br");
  4991. auto res = cli_.Get("/compress", headers);
  4992. ASSERT_TRUE(res);
  4993. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4995. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4996. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4997. "7890123456789012345678901234567890",
  4998. res->body);
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. }
  5001. #endif
  5002. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5003. TEST_F(ServerTest, Zstd) {
  5004. Headers headers;
  5005. headers.emplace("Accept-Encoding", "zstd");
  5006. auto res = cli_.Get("/compress", headers);
  5007. ASSERT_TRUE(res);
  5008. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5010. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5011. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5012. "7890123456789012345678901234567890",
  5013. res->body);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. }
  5016. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5017. Headers headers;
  5018. headers.emplace("Accept-Encoding", "");
  5019. auto res = cli_.Get("/compress", headers);
  5020. ASSERT_TRUE(res);
  5021. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5023. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5025. "7890123456789012345678901234567890",
  5026. res->body);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. }
  5029. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5030. Headers headers;
  5031. headers.emplace("Accept-Encoding", "zstd");
  5032. std::string body;
  5033. auto res = cli_.Get("/compress", headers,
  5034. [&](const char *data, uint64_t data_length) {
  5035. EXPECT_EQ(100U, data_length);
  5036. body.append(data, data_length);
  5037. return true;
  5038. });
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5042. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5044. "7890123456789012345678901234567890",
  5045. body);
  5046. EXPECT_EQ(StatusCode::OK_200, res->status);
  5047. }
  5048. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5049. Headers headers;
  5050. headers.emplace("Accept-Encoding", "zstd");
  5051. cli_.set_decompress(false);
  5052. auto res = cli_.Get("/compress", headers);
  5053. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5054. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5055. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5056. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5057. ASSERT_TRUE(res);
  5058. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5060. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5061. EXPECT_EQ(StatusCode::OK_200, res->status);
  5062. ASSERT_EQ(26U, res->body.size());
  5063. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5064. 0);
  5065. }
  5066. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5067. Headers headers;
  5068. headers.emplace("Accept-Encoding", "");
  5069. std::string body;
  5070. auto res = cli_.Get("/compress", headers,
  5071. [&](const char *data, uint64_t data_length) {
  5072. EXPECT_EQ(100U, data_length);
  5073. body.append(data, data_length);
  5074. return true;
  5075. });
  5076. ASSERT_TRUE(res);
  5077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5081. "7890123456789012345678901234567890",
  5082. body);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, NoZstd) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "zstd");
  5088. auto res = cli_.Get("/nocompress", headers);
  5089. ASSERT_TRUE(res);
  5090. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5091. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5092. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5094. "7890123456789012345678901234567890",
  5095. res->body);
  5096. EXPECT_EQ(StatusCode::OK_200, res->status);
  5097. }
  5098. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5099. Headers headers;
  5100. headers.emplace("Accept-Encoding", "zstd");
  5101. std::string body;
  5102. auto res = cli_.Get("/nocompress", headers,
  5103. [&](const char *data, uint64_t data_length) {
  5104. EXPECT_EQ(100U, data_length);
  5105. body.append(data, data_length);
  5106. return true;
  5107. });
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5110. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5111. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5112. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5113. "7890123456789012345678901234567890",
  5114. body);
  5115. EXPECT_EQ(StatusCode::OK_200, res->status);
  5116. }
  5117. // TODO: How to enable zstd ??
  5118. TEST_F(ServerTest, MultipartFormDataZstd) {
  5119. UploadFormDataItems items = {
  5120. {"key1", "test", "", ""},
  5121. {"key2", "--abcdefg123", "", ""},
  5122. };
  5123. Headers headers;
  5124. headers.emplace("Accept-Encoding", "zstd");
  5125. cli_.set_compress(true);
  5126. auto res = cli_.Post("/compress-multipart", headers, items);
  5127. ASSERT_TRUE(res);
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. }
  5130. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5131. Headers headers;
  5132. headers.emplace("Accept-Encoding", "zstd");
  5133. cli_.set_compress(true);
  5134. auto res = cli_.Put(
  5135. "/put", headers, 3,
  5136. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5137. sink.os << "PUT";
  5138. return true;
  5139. },
  5140. "text/plain");
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("PUT", res->body);
  5144. }
  5145. // Pre-compression logging tests
  5146. TEST_F(ServerTest, PreCompressionLogging) {
  5147. // Test data for compression (matches the actual /compress endpoint content)
  5148. const std::string test_content =
  5149. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5150. "3456789012345678901234567890";
  5151. // Variables to capture logging data
  5152. std::string pre_compression_body;
  5153. std::string pre_compression_content_type;
  5154. std::string pre_compression_content_encoding;
  5155. std::string post_compression_body;
  5156. std::string post_compression_content_type;
  5157. std::string post_compression_content_encoding;
  5158. // Set up pre-compression logger
  5159. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5160. const Response &res) {
  5161. pre_compression_body = res.body;
  5162. pre_compression_content_type = res.get_header_value("Content-Type");
  5163. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5164. });
  5165. // Set up post-compression logger
  5166. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5167. post_compression_body = res.body;
  5168. post_compression_content_type = res.get_header_value("Content-Type");
  5169. post_compression_content_encoding =
  5170. res.get_header_value("Content-Encoding");
  5171. });
  5172. // Test with gzip compression
  5173. Headers headers;
  5174. headers.emplace("Accept-Encoding", "gzip");
  5175. auto res = cli_.Get("/compress", headers);
  5176. // Verify response was compressed
  5177. ASSERT_TRUE(res);
  5178. EXPECT_EQ(StatusCode::OK_200, res->status);
  5179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5180. // Verify pre-compression logger captured uncompressed content
  5181. EXPECT_EQ(test_content, pre_compression_body);
  5182. EXPECT_EQ("text/plain", pre_compression_content_type);
  5183. EXPECT_TRUE(pre_compression_content_encoding
  5184. .empty()); // No encoding header before compression
  5185. // Verify post-compression logger captured compressed content
  5186. EXPECT_NE(test_content,
  5187. post_compression_body); // Should be different after compression
  5188. EXPECT_EQ("text/plain", post_compression_content_type);
  5189. EXPECT_EQ("gzip", post_compression_content_encoding);
  5190. // Verify compressed content is smaller
  5191. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5192. }
  5193. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5194. const std::string test_content =
  5195. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5196. "3456789012345678901234567890";
  5197. std::string pre_compression_body;
  5198. std::string post_compression_body;
  5199. svr_.set_pre_compression_logger(
  5200. [&](const Request & /*req*/, const Response &res) {
  5201. pre_compression_body = res.body;
  5202. });
  5203. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5204. post_compression_body = res.body;
  5205. });
  5206. Headers headers;
  5207. headers.emplace("Accept-Encoding", "br");
  5208. auto res = cli_.Get("/compress", headers);
  5209. ASSERT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5212. // Verify pre-compression content is uncompressed
  5213. EXPECT_EQ(test_content, pre_compression_body);
  5214. // Verify post-compression content is compressed
  5215. EXPECT_NE(test_content, post_compression_body);
  5216. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5217. }
  5218. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5219. const std::string test_content =
  5220. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5221. "3456789012345678901234567890";
  5222. std::string pre_compression_body;
  5223. std::string post_compression_body;
  5224. svr_.set_pre_compression_logger(
  5225. [&](const Request & /*req*/, const Response &res) {
  5226. pre_compression_body = res.body;
  5227. });
  5228. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5229. post_compression_body = res.body;
  5230. });
  5231. // Request without compression (use /nocompress endpoint)
  5232. Headers headers;
  5233. auto res = cli_.Get("/nocompress", headers);
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5237. // Pre-compression logger should not be called when no compression is applied
  5238. EXPECT_TRUE(
  5239. pre_compression_body.empty()); // Pre-compression logger not called
  5240. EXPECT_EQ(
  5241. test_content,
  5242. post_compression_body); // Post-compression logger captures final content
  5243. }
  5244. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5245. const std::string test_content =
  5246. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5247. "3456789012345678901234567890";
  5248. std::string pre_compression_body;
  5249. bool pre_logger_called = false;
  5250. // Set only pre-compression logger
  5251. svr_.set_pre_compression_logger(
  5252. [&](const Request & /*req*/, const Response &res) {
  5253. pre_compression_body = res.body;
  5254. pre_logger_called = true;
  5255. });
  5256. Headers headers;
  5257. headers.emplace("Accept-Encoding", "gzip");
  5258. auto res = cli_.Get("/compress", headers);
  5259. ASSERT_TRUE(res);
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5262. // Verify pre-compression logger was called
  5263. EXPECT_TRUE(pre_logger_called);
  5264. EXPECT_EQ(test_content, pre_compression_body);
  5265. }
  5266. TEST(ZstdDecompressor, ChunkedDecompression) {
  5267. std::string data;
  5268. for (size_t i = 0; i < 32 * 1024; ++i) {
  5269. data.push_back(static_cast<char>('a' + i % 26));
  5270. }
  5271. std::string compressed_data;
  5272. {
  5273. httplib::detail::zstd_compressor compressor;
  5274. bool result = compressor.compress(
  5275. data.data(), data.size(),
  5276. /*last=*/true,
  5277. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5278. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5279. compressed_data_size);
  5280. return true;
  5281. });
  5282. ASSERT_TRUE(result);
  5283. }
  5284. std::string decompressed_data;
  5285. {
  5286. httplib::detail::zstd_decompressor decompressor;
  5287. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5288. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5289. size_t chunk_size = 130;
  5290. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5291. chunk_begin += chunk_size) {
  5292. size_t current_chunk_size =
  5293. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5294. bool result = decompressor.decompress(
  5295. compressed_data.data() + chunk_begin, current_chunk_size,
  5296. [&](const char *decompressed_data_chunk,
  5297. size_t decompressed_data_chunk_size) {
  5298. decompressed_data.insert(decompressed_data.size(),
  5299. decompressed_data_chunk,
  5300. decompressed_data_chunk_size);
  5301. return true;
  5302. });
  5303. ASSERT_TRUE(result);
  5304. }
  5305. }
  5306. ASSERT_EQ(data, decompressed_data);
  5307. }
  5308. TEST(ZstdDecompressor, Decompress) {
  5309. std::string original_text = "Compressed with ZSTD";
  5310. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5311. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5312. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5313. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5314. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5315. std::string decompressed_data;
  5316. {
  5317. httplib::detail::zstd_decompressor decompressor;
  5318. bool result = decompressor.decompress(
  5319. compressed_data.data(), compressed_data.size(),
  5320. [&](const char *decompressed_data_chunk,
  5321. size_t decompressed_data_chunk_size) {
  5322. decompressed_data.insert(decompressed_data.size(),
  5323. decompressed_data_chunk,
  5324. decompressed_data_chunk_size);
  5325. return true;
  5326. });
  5327. ASSERT_TRUE(result);
  5328. }
  5329. ASSERT_EQ(original_text, decompressed_data);
  5330. }
  5331. #endif
  5332. // Sends a raw request to a server listening at HOST:PORT.
  5333. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5334. std::string *resp = nullptr) {
  5335. auto error = Error::Success;
  5336. auto client_sock = detail::create_client_socket(
  5337. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5338. /*connection_timeout_sec=*/5, 0,
  5339. /*read_timeout_sec=*/5, 0,
  5340. /*write_timeout_sec=*/5, 0, std::string(), error);
  5341. if (client_sock == INVALID_SOCKET) { return false; }
  5342. auto ret = detail::process_client_socket(
  5343. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5344. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5345. if (req.size() !=
  5346. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5347. return false;
  5348. }
  5349. char buf[512];
  5350. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5351. while (line_reader.getline()) {
  5352. if (resp) { *resp += line_reader.ptr(); }
  5353. }
  5354. return true;
  5355. });
  5356. detail::close_socket(client_sock);
  5357. return ret;
  5358. }
  5359. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5360. Server svr;
  5361. std::string header_value;
  5362. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5363. header_value = req.get_header_value("foo");
  5364. res.set_content("ok", "text/plain");
  5365. });
  5366. thread t = thread([&] { svr.listen(HOST, PORT); });
  5367. auto se = detail::scope_exit([&] {
  5368. svr.stop();
  5369. t.join();
  5370. ASSERT_FALSE(svr.is_running());
  5371. });
  5372. svr.wait_until_ready();
  5373. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5374. // like characters are not treated the same - use vertical tab and escape.
  5375. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5376. "foo: \t \v bar \x1B\t \r\n"
  5377. "Connection: close\r\n"
  5378. "\r\n";
  5379. std::string res;
  5380. ASSERT_TRUE(send_request(5, req, &res));
  5381. EXPECT_EQ(header_value, "");
  5382. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5383. }
  5384. // Sends a raw request and verifies that there isn't a crash or exception.
  5385. static void test_raw_request(const std::string &req,
  5386. std::string *out = nullptr) {
  5387. Server svr;
  5388. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5389. res.set_content("ok", "text/plain");
  5390. });
  5391. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5392. res.set_content("ok", "text/plain");
  5393. });
  5394. svr.Get("/header_field_value_check",
  5395. [&](const Request & /*req*/, Response &res) {
  5396. res.set_content("ok", "text/plain");
  5397. });
  5398. // Server read timeout must be longer than the client read timeout for the
  5399. // bug to reproduce, probably to force the server to process a request
  5400. // without a trailing blank line.
  5401. const time_t client_read_timeout_sec = 1;
  5402. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5403. bool listen_thread_ok = false;
  5404. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5405. auto se = detail::scope_exit([&] {
  5406. svr.stop();
  5407. t.join();
  5408. ASSERT_FALSE(svr.is_running());
  5409. EXPECT_TRUE(listen_thread_ok);
  5410. });
  5411. svr.wait_until_ready();
  5412. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5413. }
  5414. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5415. // A certain header line causes an exception if the header property is parsed
  5416. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5417. test_raw_request(
  5418. "GET /hi HTTP/1.1\r\n"
  5419. " : "
  5420. " "
  5421. " ");
  5422. }
  5423. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5424. // A certain header line causes an exception if the header property *name* is
  5425. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5426. // greedy matcher and requires backtracking when there are a lot of ":"
  5427. // characters.
  5428. // This occurs with libc++ but not libstdc++.
  5429. test_raw_request(
  5430. "GET /hi HTTP/1.1\r\n"
  5431. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5432. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5433. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5434. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5435. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5436. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5437. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5438. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5439. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5440. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5441. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5442. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5443. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5444. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5445. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5446. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5447. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5448. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5449. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5450. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5451. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5452. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5453. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5454. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5455. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5456. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5457. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5458. "&&&%%%");
  5459. }
  5460. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5461. // Make sure this doesn't crash the server.
  5462. // In a previous version of the header line regex, the "\r" rendered the line
  5463. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5464. // a new position where the leading white space ended and the field value
  5465. // began.
  5466. // The crash occurs with libc++ but not libstdc++.
  5467. test_raw_request("GET /hi HTTP/1.1\r\n"
  5468. "a:" +
  5469. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5470. "\r\n"
  5471. "\r\n");
  5472. }
  5473. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5474. std::string out;
  5475. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5476. "Content-Type: text/plain\r\n"
  5477. "Transfer-Encoding: chunked\r\n"
  5478. "\r\n"
  5479. "nothex\r\n",
  5480. &out);
  5481. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5482. }
  5483. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5484. std::string out;
  5485. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5486. "Content-Type: text/plain\r\n"
  5487. "Transfer-Encoding: chunked\r\n"
  5488. "\r\n"
  5489. "3\r\n"
  5490. "xyz\r\n"
  5491. "NaN\r\n",
  5492. &out);
  5493. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5494. }
  5495. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5496. std::string out;
  5497. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5498. "Content-Type: text/plain\r\n"
  5499. "Transfer-Encoding: chunked\r\n"
  5500. "\r\n"
  5501. // Length is too large for 64 bits.
  5502. "1ffffffffffffffff\r\n"
  5503. "xyz\r\n",
  5504. &out);
  5505. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5506. }
  5507. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5508. test_raw_request("GET /hi HTTP/1.1\r\n"
  5509. "Content-Type: text/plain\r\n\r");
  5510. }
  5511. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5512. std::string out;
  5513. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5514. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5515. }
  5516. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5517. std::string out;
  5518. std::string request(
  5519. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5520. test_raw_request(request, &out);
  5521. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5522. }
  5523. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5524. std::string out;
  5525. std::string request(
  5526. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5527. test_raw_request(request, &out);
  5528. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5529. }
  5530. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5531. std::string out;
  5532. std::string request(
  5533. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5534. test_raw_request(request, &out);
  5535. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5536. }
  5537. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5538. std::string out;
  5539. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5540. "Test: \r\n\r\n",
  5541. &out);
  5542. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5543. }
  5544. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5545. Server svr;
  5546. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5547. res.set_header("Cache-Control", "no-cache");
  5548. res.set_chunked_content_provider(
  5549. "text/event-stream", [](size_t offset, DataSink &sink) {
  5550. std::string s = "data:";
  5551. s += std::to_string(offset);
  5552. s += "\n\n";
  5553. auto ret = sink.write(s.data(), s.size());
  5554. EXPECT_TRUE(ret);
  5555. std::this_thread::sleep_for(std::chrono::seconds(1));
  5556. return true;
  5557. });
  5558. });
  5559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5560. svr.wait_until_ready();
  5561. Client client(HOST, PORT);
  5562. const Headers headers = {{"Accept", "text/event-stream"}};
  5563. auto get_thread = std::thread([&client, &headers]() {
  5564. auto res = client.Get(
  5565. "/events", headers,
  5566. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5567. });
  5568. auto se = detail::scope_exit([&] {
  5569. svr.stop();
  5570. get_thread.join();
  5571. listen_thread.join();
  5572. ASSERT_FALSE(svr.is_running());
  5573. });
  5574. // Give GET time to get a few messages.
  5575. std::this_thread::sleep_for(std::chrono::seconds(2));
  5576. }
  5577. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5578. httplib::Server svr;
  5579. svr.Post("/hi",
  5580. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5581. res.status = StatusCode::OK_200;
  5582. });
  5583. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5584. svr.wait_until_ready();
  5585. Client cli(HOST, PORT);
  5586. auto res = cli.Post("/hi", "data", "text/plain");
  5587. ASSERT_TRUE(res);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. svr.stop();
  5590. thread.join();
  5591. ASSERT_FALSE(svr.is_running());
  5592. res = cli.Post("/hi", "data", "text/plain");
  5593. ASSERT_FALSE(res);
  5594. }
  5595. TEST(ServerStopTest, ListenFailure) {
  5596. Server svr;
  5597. auto t = thread([&]() {
  5598. auto ret = svr.listen("????", PORT);
  5599. EXPECT_FALSE(ret);
  5600. });
  5601. svr.wait_until_ready();
  5602. svr.stop();
  5603. t.join();
  5604. }
  5605. TEST(ServerStopTest, Decommision) {
  5606. Server svr;
  5607. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5608. for (int i = 0; i < 4; i++) {
  5609. auto is_even = !(i % 2);
  5610. std::thread t{[&] {
  5611. try {
  5612. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5613. if (is_even) {
  5614. throw std::runtime_error("Some thing that happens to go wrong.");
  5615. }
  5616. svr.listen(HOST, PORT);
  5617. } catch (...) { svr.decommission(); }
  5618. }};
  5619. svr.wait_until_ready();
  5620. // Server is up
  5621. {
  5622. Client cli(HOST, PORT);
  5623. auto res = cli.Get("/hi");
  5624. if (is_even) {
  5625. EXPECT_FALSE(res);
  5626. } else {
  5627. EXPECT_TRUE(res);
  5628. EXPECT_EQ("hi...", res->body);
  5629. }
  5630. }
  5631. svr.stop();
  5632. t.join();
  5633. // Server is down...
  5634. {
  5635. Client cli(HOST, PORT);
  5636. auto res = cli.Get("/hi");
  5637. EXPECT_FALSE(res);
  5638. }
  5639. }
  5640. }
  5641. // Helper function for string body upload progress tests
  5642. template <typename SetupHandler, typename ClientCall>
  5643. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5644. ClientCall &&client_call,
  5645. const string &body) {
  5646. Server svr;
  5647. setup_handler(svr);
  5648. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5649. auto se = detail::scope_exit([&] {
  5650. svr.stop();
  5651. t.join();
  5652. });
  5653. svr.wait_until_ready();
  5654. Client cli(HOST, PORT);
  5655. vector<uint64_t> progress_values;
  5656. bool progress_called = false;
  5657. auto res =
  5658. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5659. progress_values.push_back(current);
  5660. progress_called = true;
  5661. return true;
  5662. });
  5663. ASSERT_TRUE(res);
  5664. EXPECT_EQ(200, res->status);
  5665. EXPECT_TRUE(progress_called);
  5666. }
  5667. TEST(UploadProgressTest, PostStringBodyBasic) {
  5668. TestStringBodyUploadProgress(
  5669. [](Server &svr) {
  5670. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5671. res.set_content("received", "text/plain");
  5672. });
  5673. },
  5674. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5675. return cli.Post("/test", body, "text/plain", progress_callback);
  5676. },
  5677. "test data for upload progress");
  5678. }
  5679. TEST(UploadProgressTest, PutStringBodyBasic) {
  5680. TestStringBodyUploadProgress(
  5681. [](Server &svr) {
  5682. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5683. res.set_content("put received", "text/plain");
  5684. });
  5685. },
  5686. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5687. return cli.Put("/test", body, "text/plain", progress_callback);
  5688. },
  5689. "put test data for upload progress");
  5690. }
  5691. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5692. TestStringBodyUploadProgress(
  5693. [](Server &svr) {
  5694. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5695. res.set_content("patch received", "text/plain");
  5696. });
  5697. },
  5698. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5699. return cli.Patch("/test", body, "text/plain", progress_callback);
  5700. },
  5701. "patch test data for upload progress");
  5702. }
  5703. // Helper function for content provider upload progress tests
  5704. template <typename SetupHandler, typename ClientCall>
  5705. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5706. ClientCall &&client_call) {
  5707. Server svr;
  5708. setup_handler(svr);
  5709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5710. auto se = detail::scope_exit([&] {
  5711. svr.stop();
  5712. t.join();
  5713. });
  5714. svr.wait_until_ready();
  5715. Client cli(HOST, PORT);
  5716. vector<uint64_t> progress_values;
  5717. auto res =
  5718. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5719. progress_values.push_back(current);
  5720. return true;
  5721. });
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(200, res->status);
  5724. EXPECT_FALSE(progress_values.empty());
  5725. }
  5726. TEST(UploadProgressTest, PostContentProviderProgress) {
  5727. TestContentProviderUploadProgress(
  5728. [](Server &svr) {
  5729. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5730. res.set_content("provider received", "text/plain");
  5731. });
  5732. },
  5733. [](Client &cli, UploadProgress progress_callback) {
  5734. return cli.Post(
  5735. "/test", 10,
  5736. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5737. sink.os << "test data";
  5738. return true;
  5739. },
  5740. "text/plain", progress_callback);
  5741. });
  5742. }
  5743. // Helper function for multipart upload progress tests
  5744. template <typename SetupHandler, typename ClientCall>
  5745. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5746. ClientCall &&client_call,
  5747. const string &endpoint) {
  5748. Server svr;
  5749. setup_handler(svr);
  5750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5751. auto se = detail::scope_exit([&] {
  5752. svr.stop();
  5753. t.join();
  5754. });
  5755. svr.wait_until_ready();
  5756. Client cli(HOST, PORT);
  5757. vector<uint64_t> progress_values;
  5758. UploadFormDataItems items = {
  5759. {"field1", "value1", "", ""},
  5760. {"field2", "longer value for progress tracking test", "", ""},
  5761. {"file1", "file content data for upload progress", "test.txt",
  5762. "text/plain"}};
  5763. auto res = client_call(cli, endpoint, items,
  5764. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5765. progress_values.push_back(current);
  5766. return true;
  5767. });
  5768. ASSERT_TRUE(res);
  5769. EXPECT_EQ(200, res->status);
  5770. EXPECT_FALSE(progress_values.empty());
  5771. }
  5772. TEST(UploadProgressTest, PostMultipartProgress) {
  5773. TestMultipartUploadProgress(
  5774. [](Server &svr) {
  5775. svr.Post("/multipart", [](const Request &req, Response &res) {
  5776. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5777. res.set_content("multipart received", "text/plain");
  5778. });
  5779. },
  5780. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5781. UploadProgress progress_callback) {
  5782. return cli.Post(endpoint, items, progress_callback);
  5783. },
  5784. "/multipart");
  5785. }
  5786. // Helper function for basic download progress tests
  5787. template <typename SetupHandler, typename ClientCall>
  5788. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5789. ClientCall &&client_call, const string &endpoint,
  5790. size_t expected_content_size) {
  5791. Server svr;
  5792. setup_handler(svr);
  5793. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5794. auto se = detail::scope_exit([&] {
  5795. svr.stop();
  5796. t.join();
  5797. });
  5798. svr.wait_until_ready();
  5799. Client cli(HOST, PORT);
  5800. vector<uint64_t> progress_values;
  5801. auto res = client_call(cli, endpoint,
  5802. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5803. progress_values.push_back(current);
  5804. return true;
  5805. });
  5806. ASSERT_TRUE(res);
  5807. EXPECT_EQ(200, res->status);
  5808. EXPECT_FALSE(progress_values.empty());
  5809. EXPECT_EQ(expected_content_size, res->body.size());
  5810. }
  5811. TEST(DownloadProgressTest, GetBasic) {
  5812. TestBasicDownloadProgress(
  5813. [](Server &svr) {
  5814. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5815. string content(1000, 'D');
  5816. res.set_content(content, "text/plain");
  5817. });
  5818. },
  5819. [](Client &cli, const string &endpoint,
  5820. DownloadProgress progress_callback) {
  5821. return cli.Get(endpoint, progress_callback);
  5822. },
  5823. "/download", 1000u);
  5824. }
  5825. // Helper function for content receiver download progress tests
  5826. template <typename SetupHandler, typename ClientCall>
  5827. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5828. ClientCall &&client_call,
  5829. const string &endpoint,
  5830. size_t expected_content_size) {
  5831. Server svr;
  5832. setup_handler(svr);
  5833. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5834. auto se = detail::scope_exit([&] {
  5835. svr.stop();
  5836. t.join();
  5837. });
  5838. svr.wait_until_ready();
  5839. Client cli(HOST, PORT);
  5840. vector<uint64_t> progress_values;
  5841. string received_body;
  5842. auto res = client_call(
  5843. cli, endpoint,
  5844. [&](const char *data, size_t data_length) -> bool {
  5845. received_body.append(data, data_length);
  5846. return true;
  5847. },
  5848. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5849. progress_values.push_back(current);
  5850. return true;
  5851. });
  5852. ASSERT_TRUE(res);
  5853. EXPECT_EQ(200, res->status);
  5854. EXPECT_FALSE(progress_values.empty());
  5855. EXPECT_EQ(expected_content_size, received_body.size());
  5856. EXPECT_TRUE(res->body.empty());
  5857. }
  5858. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5859. TestContentReceiverDownloadProgress(
  5860. [](Server &svr) {
  5861. svr.Get("/download-receiver",
  5862. [](const Request & /*req*/, Response &res) {
  5863. string content(2000, 'R');
  5864. res.set_content(content, "text/plain");
  5865. });
  5866. },
  5867. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5868. DownloadProgress progress_callback) {
  5869. return cli.Get(endpoint, content_receiver, progress_callback);
  5870. },
  5871. "/download-receiver", 2000u);
  5872. }
  5873. TEST(StreamingTest, NoContentLengthStreaming) {
  5874. Server svr;
  5875. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5876. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5877. if (offset < 6) {
  5878. sink.os << (offset < 3 ? "a" : "b");
  5879. } else {
  5880. sink.done();
  5881. }
  5882. return true;
  5883. });
  5884. });
  5885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5886. auto listen_se = detail::scope_exit([&] {
  5887. svr.stop();
  5888. listen_thread.join();
  5889. ASSERT_FALSE(svr.is_running());
  5890. });
  5891. svr.wait_until_ready();
  5892. Client client(HOST, PORT);
  5893. auto get_thread = std::thread([&client]() {
  5894. std::string s;
  5895. auto res =
  5896. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5897. s += std::string(data, len);
  5898. return true;
  5899. });
  5900. ASSERT_TRUE(res);
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. EXPECT_EQ("aaabbb", s);
  5903. });
  5904. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5905. // Give GET time to get a few messages.
  5906. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5907. }
  5908. TEST(MountTest, Unmount) {
  5909. Server svr;
  5910. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5911. auto se = detail::scope_exit([&] {
  5912. svr.stop();
  5913. listen_thread.join();
  5914. ASSERT_FALSE(svr.is_running());
  5915. });
  5916. svr.wait_until_ready();
  5917. Client cli("localhost", PORT);
  5918. svr.set_mount_point("/mount2", "./www2");
  5919. auto res = cli.Get("/");
  5920. ASSERT_TRUE(res);
  5921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5922. res = cli.Get("/mount2/dir/test.html");
  5923. ASSERT_TRUE(res);
  5924. EXPECT_EQ(StatusCode::OK_200, res->status);
  5925. svr.set_mount_point("/", "./www");
  5926. res = cli.Get("/dir/");
  5927. ASSERT_TRUE(res);
  5928. EXPECT_EQ(StatusCode::OK_200, res->status);
  5929. svr.remove_mount_point("/");
  5930. res = cli.Get("/dir/");
  5931. ASSERT_TRUE(res);
  5932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5933. svr.remove_mount_point("/mount2");
  5934. res = cli.Get("/mount2/dir/test.html");
  5935. ASSERT_TRUE(res);
  5936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5937. }
  5938. TEST(MountTest, Redicect) {
  5939. Server svr;
  5940. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5941. auto se = detail::scope_exit([&] {
  5942. svr.stop();
  5943. listen_thread.join();
  5944. ASSERT_FALSE(svr.is_running());
  5945. });
  5946. svr.set_mount_point("/", "./www");
  5947. svr.wait_until_ready();
  5948. Client cli("localhost", PORT);
  5949. auto res = cli.Get("/dir/");
  5950. ASSERT_TRUE(res);
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. res = cli.Get("/dir");
  5953. ASSERT_TRUE(res);
  5954. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5955. res = cli.Get("/file");
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. res = cli.Get("/file/");
  5959. ASSERT_TRUE(res);
  5960. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5961. cli.set_follow_location(true);
  5962. res = cli.Get("/dir");
  5963. ASSERT_TRUE(res);
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. }
  5966. TEST(MountTest, MultibytesPathName) {
  5967. Server svr;
  5968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5969. auto se = detail::scope_exit([&] {
  5970. svr.stop();
  5971. listen_thread.join();
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.set_mount_point("/", "./www");
  5975. svr.wait_until_ready();
  5976. Client cli("localhost", PORT);
  5977. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5978. ASSERT_TRUE(res);
  5979. EXPECT_EQ(StatusCode::OK_200, res->status);
  5980. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5981. }
  5982. TEST(KeepAliveTest, ReadTimeout) {
  5983. Server svr;
  5984. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5985. std::this_thread::sleep_for(std::chrono::seconds(2));
  5986. res.set_content("a", "text/plain");
  5987. });
  5988. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5989. res.set_content("b", "text/plain");
  5990. });
  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. cli.set_keep_alive(true);
  6000. cli.set_read_timeout(std::chrono::seconds(1));
  6001. auto resa = cli.Get("/a");
  6002. ASSERT_FALSE(resa);
  6003. EXPECT_EQ(Error::Read, resa.error());
  6004. auto resb = cli.Get("/b");
  6005. ASSERT_TRUE(resb);
  6006. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6007. EXPECT_EQ("b", resb->body);
  6008. }
  6009. TEST(KeepAliveTest, MaxCount) {
  6010. size_t keep_alive_max_count = 3;
  6011. Server svr;
  6012. svr.set_keep_alive_max_count(keep_alive_max_count);
  6013. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6014. res.set_content("Hello World!", "text/plain");
  6015. });
  6016. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6017. auto se = detail::scope_exit([&] {
  6018. svr.stop();
  6019. listen_thread.join();
  6020. ASSERT_FALSE(svr.is_running());
  6021. });
  6022. svr.wait_until_ready();
  6023. Client cli(HOST, PORT);
  6024. cli.set_keep_alive(true);
  6025. for (size_t i = 0; i < 5; i++) {
  6026. auto result = cli.Get("/hi");
  6027. ASSERT_TRUE(result);
  6028. EXPECT_EQ(StatusCode::OK_200, result->status);
  6029. if (i == keep_alive_max_count - 1) {
  6030. EXPECT_EQ("close", result->get_header_value("Connection"));
  6031. } else {
  6032. EXPECT_FALSE(result->has_header("Connection"));
  6033. }
  6034. }
  6035. }
  6036. TEST(KeepAliveTest, Issue1041) {
  6037. Server svr;
  6038. svr.set_keep_alive_timeout(3);
  6039. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6040. res.set_content("Hello World!", "text/plain");
  6041. });
  6042. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6043. auto se = detail::scope_exit([&] {
  6044. svr.stop();
  6045. listen_thread.join();
  6046. ASSERT_FALSE(svr.is_running());
  6047. });
  6048. svr.wait_until_ready();
  6049. Client cli(HOST, PORT);
  6050. cli.set_keep_alive(true);
  6051. auto result = cli.Get("/hi");
  6052. ASSERT_TRUE(result);
  6053. EXPECT_EQ(StatusCode::OK_200, result->status);
  6054. std::this_thread::sleep_for(std::chrono::seconds(5));
  6055. result = cli.Get("/hi");
  6056. ASSERT_TRUE(result);
  6057. EXPECT_EQ(StatusCode::OK_200, result->status);
  6058. }
  6059. TEST(KeepAliveTest, Issue1959) {
  6060. Server svr;
  6061. svr.set_keep_alive_timeout(5);
  6062. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6063. res.set_content("a", "text/plain");
  6064. });
  6065. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6066. auto se = detail::scope_exit([&] {
  6067. if (!svr.is_running()) return;
  6068. svr.stop();
  6069. listen_thread.join();
  6070. ASSERT_FALSE(svr.is_running());
  6071. });
  6072. svr.wait_until_ready();
  6073. Client cli("localhost", PORT);
  6074. cli.set_keep_alive(true);
  6075. using namespace std::chrono;
  6076. auto start = steady_clock::now();
  6077. cli.Get("/a");
  6078. svr.stop();
  6079. listen_thread.join();
  6080. auto end = steady_clock::now();
  6081. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6082. EXPECT_LT(elapsed, 5000);
  6083. }
  6084. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6085. TEST(KeepAliveTest, SSLClientReconnection) {
  6086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6087. ASSERT_TRUE(svr.is_valid());
  6088. svr.set_keep_alive_timeout(1);
  6089. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6090. res.set_content("Hello World!", "text/plain");
  6091. });
  6092. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6093. auto se = detail::scope_exit([&] {
  6094. svr.stop();
  6095. listen_thread.join();
  6096. ASSERT_FALSE(svr.is_running());
  6097. });
  6098. svr.wait_until_ready();
  6099. SSLClient cli(HOST, PORT);
  6100. cli.enable_server_certificate_verification(false);
  6101. cli.set_keep_alive(true);
  6102. auto result = cli.Get("/hi");
  6103. ASSERT_TRUE(result);
  6104. EXPECT_EQ(StatusCode::OK_200, result->status);
  6105. result = cli.Get("/hi");
  6106. ASSERT_TRUE(result);
  6107. EXPECT_EQ(StatusCode::OK_200, result->status);
  6108. std::this_thread::sleep_for(std::chrono::seconds(2));
  6109. // Recoonect
  6110. result = cli.Get("/hi");
  6111. ASSERT_TRUE(result);
  6112. EXPECT_EQ(StatusCode::OK_200, result->status);
  6113. result = cli.Get("/hi");
  6114. ASSERT_TRUE(result);
  6115. EXPECT_EQ(StatusCode::OK_200, result->status);
  6116. }
  6117. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6119. ASSERT_TRUE(svr.is_valid());
  6120. svr.set_keep_alive_timeout(1);
  6121. std::string content = "reconnect";
  6122. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6123. res.set_content("Hello World!", "text/plain");
  6124. });
  6125. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6126. auto se = detail::scope_exit([&] {
  6127. svr.stop();
  6128. listen_thread.join();
  6129. ASSERT_FALSE(svr.is_running());
  6130. });
  6131. svr.wait_until_ready();
  6132. SSLClient cli(HOST, PORT);
  6133. cli.enable_server_certificate_verification(false);
  6134. cli.set_keep_alive(true);
  6135. auto result = cli.Post(
  6136. "/hi", content.size(),
  6137. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6138. sink.write(content.c_str(), content.size());
  6139. return true;
  6140. },
  6141. "text/plain");
  6142. ASSERT_TRUE(result);
  6143. EXPECT_EQ(200, result->status);
  6144. std::this_thread::sleep_for(std::chrono::seconds(2));
  6145. // Recoonect
  6146. result = cli.Post(
  6147. "/hi", content.size(),
  6148. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6149. sink.write(content.c_str(), content.size());
  6150. return true;
  6151. },
  6152. "text/plain");
  6153. ASSERT_TRUE(result);
  6154. EXPECT_EQ(200, result->status);
  6155. result = cli.Post(
  6156. "/hi", content.size(),
  6157. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6158. sink.write(content.c_str(), content.size());
  6159. return true;
  6160. },
  6161. "text/plain");
  6162. ASSERT_TRUE(result);
  6163. EXPECT_EQ(200, result->status);
  6164. }
  6165. #endif
  6166. TEST(ClientProblemDetectionTest, ContentProvider) {
  6167. Server svr;
  6168. size_t content_length = 1024 * 1024;
  6169. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6170. res.set_content_provider(
  6171. content_length, "text/plain",
  6172. [&](size_t offset, size_t length, DataSink &sink) {
  6173. auto out_len = std::min(length, static_cast<size_t>(1024));
  6174. std::string out(out_len, '@');
  6175. sink.write(out.data(), out_len);
  6176. return offset < 4096;
  6177. },
  6178. [](bool success) { ASSERT_FALSE(success); });
  6179. });
  6180. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6181. res.set_content_provider(
  6182. 0, "text/plain",
  6183. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6184. EXPECT_TRUE(false);
  6185. return true;
  6186. },
  6187. [](bool success) { ASSERT_FALSE(success); });
  6188. });
  6189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6190. auto se = detail::scope_exit([&] {
  6191. svr.stop();
  6192. listen_thread.join();
  6193. ASSERT_FALSE(svr.is_running());
  6194. });
  6195. svr.wait_until_ready();
  6196. Client cli("localhost", PORT);
  6197. {
  6198. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6199. size_t /*data_length*/) { return false; });
  6200. ASSERT_FALSE(res);
  6201. }
  6202. {
  6203. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6204. size_t /*data_length*/) { return false; });
  6205. ASSERT_TRUE(res);
  6206. }
  6207. }
  6208. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6209. Server svr;
  6210. svr.set_error_handler([](Request const &, Response &res) -> void {
  6211. res.set_chunked_content_provider(
  6212. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6213. sink.os << "hello";
  6214. sink.os << "world";
  6215. sink.done();
  6216. return true;
  6217. });
  6218. });
  6219. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.wait_until_ready();
  6226. Client cli("localhost", PORT);
  6227. auto res = cli.Get("/");
  6228. ASSERT_TRUE(res);
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. EXPECT_EQ("helloworld", res->body);
  6231. }
  6232. TEST(LongPollingTest, ClientCloseDetection) {
  6233. Server svr;
  6234. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6235. res.set_chunked_content_provider(
  6236. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6237. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6238. sink.os << "hello";
  6239. auto count = 10;
  6240. while (count > 0 && sink.is_writable()) {
  6241. this_thread::sleep_for(chrono::milliseconds(10));
  6242. count--;
  6243. }
  6244. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6245. return true;
  6246. });
  6247. });
  6248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6249. auto se = detail::scope_exit([&] {
  6250. svr.stop();
  6251. listen_thread.join();
  6252. ASSERT_FALSE(svr.is_running());
  6253. });
  6254. svr.wait_until_ready();
  6255. Client cli("localhost", PORT);
  6256. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6257. EXPECT_EQ("hello", string(data, data_length));
  6258. return false; // close the socket immediately.
  6259. });
  6260. ASSERT_FALSE(res);
  6261. }
  6262. TEST(GetWithParametersTest, GetWithParameters) {
  6263. Server svr;
  6264. svr.Get("/", [&](const Request &req, Response &) {
  6265. EXPECT_EQ("world", req.get_param_value("hello"));
  6266. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6267. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6268. });
  6269. svr.Get("/params", [&](const Request &req, Response &) {
  6270. EXPECT_EQ("world", req.get_param_value("hello"));
  6271. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6272. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6273. });
  6274. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6275. EXPECT_EQ("resource-id", req.matches[1]);
  6276. EXPECT_EQ("foo", req.get_param_value("param1"));
  6277. EXPECT_EQ("bar", req.get_param_value("param2"));
  6278. });
  6279. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6280. EXPECT_EQ("user-id", req.path_params.at("id"));
  6281. EXPECT_EQ("foo", req.get_param_value("param1"));
  6282. EXPECT_EQ("bar", req.get_param_value("param2"));
  6283. });
  6284. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6285. auto se = detail::scope_exit([&] {
  6286. svr.stop();
  6287. listen_thread.join();
  6288. ASSERT_FALSE(svr.is_running());
  6289. });
  6290. svr.wait_until_ready();
  6291. {
  6292. Client cli(HOST, PORT);
  6293. Params params;
  6294. params.emplace("hello", "world");
  6295. params.emplace("hello2", "world2");
  6296. params.emplace("hello3", "world3");
  6297. auto res = cli.Get("/", params, Headers{});
  6298. ASSERT_TRUE(res);
  6299. EXPECT_EQ(StatusCode::OK_200, res->status);
  6300. }
  6301. {
  6302. Client cli(HOST, PORT);
  6303. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6304. ASSERT_TRUE(res);
  6305. EXPECT_EQ(StatusCode::OK_200, res->status);
  6306. }
  6307. {
  6308. Client cli(HOST, PORT);
  6309. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6310. ASSERT_TRUE(res);
  6311. EXPECT_EQ(StatusCode::OK_200, res->status);
  6312. }
  6313. {
  6314. Client cli(HOST, PORT);
  6315. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6316. ASSERT_TRUE(res);
  6317. EXPECT_EQ(StatusCode::OK_200, res->status);
  6318. }
  6319. }
  6320. TEST(GetWithParametersTest, GetWithParameters2) {
  6321. Server svr;
  6322. svr.Get("/", [&](const Request &req, Response &res) {
  6323. auto text = req.get_param_value("hello");
  6324. res.set_content(text, "text/plain");
  6325. });
  6326. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6327. auto se = detail::scope_exit([&] {
  6328. svr.stop();
  6329. listen_thread.join();
  6330. ASSERT_FALSE(svr.is_running());
  6331. });
  6332. svr.wait_until_ready();
  6333. Client cli("localhost", PORT);
  6334. Params params;
  6335. params.emplace("hello", "world");
  6336. std::string body;
  6337. auto res = cli.Get("/", params, Headers{},
  6338. [&](const char *data, size_t data_length) {
  6339. body.append(data, data_length);
  6340. return true;
  6341. });
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_EQ("world", body);
  6345. }
  6346. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6347. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6348. auto host = "httpbin.org";
  6349. auto path = std::string{"/range/32"};
  6350. #else
  6351. auto host = "nghttp2.org";
  6352. auto path = std::string{"/httpbin/range/32"};
  6353. #endif
  6354. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6355. SSLClient cli(host);
  6356. #else
  6357. Client cli(host);
  6358. #endif
  6359. cli.set_default_headers({make_range_header({{1, 10}})});
  6360. cli.set_connection_timeout(5);
  6361. {
  6362. auto res = cli.Get(path);
  6363. ASSERT_TRUE(res);
  6364. EXPECT_EQ("bcdefghijk", res->body);
  6365. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6366. }
  6367. {
  6368. auto res = cli.Get(path);
  6369. ASSERT_TRUE(res);
  6370. EXPECT_EQ("bcdefghijk", res->body);
  6371. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6372. }
  6373. }
  6374. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6375. Server svr;
  6376. svr.set_default_headers({{"Hello", "World"}});
  6377. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6378. res.set_content("ok", "text/plain");
  6379. });
  6380. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6381. auto se = detail::scope_exit([&] {
  6382. svr.stop();
  6383. listen_thread.join();
  6384. ASSERT_FALSE(svr.is_running());
  6385. });
  6386. svr.wait_until_ready();
  6387. Client cli("localhost", PORT);
  6388. auto res = cli.Get("/");
  6389. ASSERT_TRUE(res);
  6390. EXPECT_EQ(StatusCode::OK_200, res->status);
  6391. EXPECT_EQ("ok", res->body);
  6392. EXPECT_EQ("World", res->get_header_value("Hello"));
  6393. }
  6394. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6395. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6397. ASSERT_TRUE(svr.is_valid());
  6398. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6399. std::this_thread::sleep_for(std::chrono::seconds(2));
  6400. res.set_content("a", "text/plain");
  6401. });
  6402. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6403. res.set_content("b", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. SSLClient cli("localhost", PORT);
  6413. cli.enable_server_certificate_verification(false);
  6414. cli.set_keep_alive(true);
  6415. cli.set_read_timeout(std::chrono::seconds(1));
  6416. auto resa = cli.Get("/a");
  6417. ASSERT_TRUE(!resa);
  6418. EXPECT_EQ(Error::Read, resa.error());
  6419. auto resb = cli.Get("/b");
  6420. ASSERT_TRUE(resb);
  6421. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6422. EXPECT_EQ("b", resb->body);
  6423. }
  6424. #endif
  6425. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6426. protected:
  6427. ServerTestWithAI_PASSIVE()
  6428. : cli_(HOST, PORT)
  6429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6430. ,
  6431. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6432. #endif
  6433. {
  6434. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6435. cli_.enable_server_certificate_verification(false);
  6436. #endif
  6437. }
  6438. virtual void SetUp() {
  6439. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6440. res.set_content("Hello World!", "text/plain");
  6441. });
  6442. t_ = thread(
  6443. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6444. svr_.wait_until_ready();
  6445. }
  6446. virtual void TearDown() {
  6447. svr_.stop();
  6448. t_.join();
  6449. }
  6450. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6451. SSLClient cli_;
  6452. SSLServer svr_;
  6453. #else
  6454. Client cli_;
  6455. Server svr_;
  6456. #endif
  6457. thread t_;
  6458. };
  6459. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6460. auto res = cli_.Get("/hi");
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6464. EXPECT_EQ("Hello World!", res->body);
  6465. }
  6466. class ServerUpDownTest : public ::testing::Test {
  6467. protected:
  6468. ServerUpDownTest() : cli_(HOST, PORT) {}
  6469. virtual void SetUp() {
  6470. t_ = thread([&]() {
  6471. svr_.bind_to_any_port(HOST);
  6472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6473. ASSERT_TRUE(svr_.listen_after_bind());
  6474. });
  6475. svr_.wait_until_ready();
  6476. }
  6477. virtual void TearDown() {
  6478. svr_.stop();
  6479. t_.join();
  6480. }
  6481. Client cli_;
  6482. Server svr_;
  6483. thread t_;
  6484. };
  6485. TEST_F(ServerUpDownTest, QuickStartStop) {
  6486. // Should not crash, especially when run with
  6487. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6488. }
  6489. class PayloadMaxLengthTest : public ::testing::Test {
  6490. protected:
  6491. PayloadMaxLengthTest()
  6492. : cli_(HOST, PORT)
  6493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6494. ,
  6495. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6496. #endif
  6497. {
  6498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6499. cli_.enable_server_certificate_verification(false);
  6500. #endif
  6501. }
  6502. virtual void SetUp() {
  6503. svr_.set_payload_max_length(8);
  6504. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6505. res.set_content("test", "text/plain");
  6506. });
  6507. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6508. svr_.wait_until_ready();
  6509. }
  6510. virtual void TearDown() {
  6511. svr_.stop();
  6512. t_.join();
  6513. }
  6514. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6515. SSLClient cli_;
  6516. SSLServer svr_;
  6517. #else
  6518. Client cli_;
  6519. Server svr_;
  6520. #endif
  6521. thread t_;
  6522. };
  6523. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6524. auto res = cli_.Post("/test", "123456789", "text/plain");
  6525. ASSERT_TRUE(res);
  6526. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6527. res = cli_.Post("/test", "12345678", "text/plain");
  6528. ASSERT_TRUE(res);
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. }
  6531. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6532. // Test chunked encoding with payload exceeding the 8-byte limit
  6533. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6534. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6535. ASSERT_TRUE(res);
  6536. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6537. }
  6538. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6539. // Test chunked encoding with payload within the 8-byte limit
  6540. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6541. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6542. ASSERT_TRUE(res);
  6543. EXPECT_EQ(StatusCode::OK_200, res->status);
  6544. }
  6545. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6546. // Test using send_request to send chunked data exceeding payload limit
  6547. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6548. "Host: " +
  6549. std::string(HOST) + ":" + std::to_string(PORT) +
  6550. "\r\n"
  6551. "Transfer-Encoding: chunked\r\n"
  6552. "Connection: close\r\n"
  6553. "\r\n"
  6554. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6555. "0123456789\r\n"
  6556. "0\r\n" // End chunk
  6557. "\r\n";
  6558. std::string response;
  6559. bool result = send_request(1, chunked_request, &response);
  6560. if (!result) {
  6561. // If send_request fails, it might be because the server closed the
  6562. // connection due to payload limit enforcement, which is acceptable
  6563. SUCCEED()
  6564. << "Server rejected oversized chunked request (connection closed)";
  6565. } else {
  6566. // If we got a response, check if it's an error response or connection was
  6567. // closed early Short response length indicates connection was closed due to
  6568. // payload limit
  6569. if (response.length() <= 10) {
  6570. SUCCEED() << "Server closed connection for oversized chunked request";
  6571. } else {
  6572. // Check for error status codes
  6573. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6574. response.find("Payload Too Large") != std::string::npos ||
  6575. response.find("400") != std::string::npos);
  6576. }
  6577. }
  6578. }
  6579. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6580. // Test request without Content-Length header exceeding payload limit
  6581. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6582. "Host: " +
  6583. std::string(HOST) + ":" +
  6584. std::to_string(PORT) +
  6585. "\r\n"
  6586. "Connection: close\r\n"
  6587. "\r\n";
  6588. // Add payload exceeding the 8-byte limit
  6589. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6590. request_without_content_length += large_payload;
  6591. std::string response;
  6592. bool result = send_request(1, request_without_content_length, &response);
  6593. if (!result) {
  6594. // If send_request fails, server likely closed connection due to payload
  6595. // limit
  6596. SUCCEED() << "Server rejected oversized request without Content-Length "
  6597. "(connection closed)";
  6598. } else {
  6599. // Check if server responded with error or closed connection early
  6600. if (response.length() <= 10) {
  6601. SUCCEED() << "Server closed connection for oversized request without "
  6602. "Content-Length";
  6603. } else {
  6604. // Check for error status codes
  6605. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6606. response.find("Payload Too Large") != std::string::npos ||
  6607. response.find("400") != std::string::npos);
  6608. }
  6609. }
  6610. }
  6611. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6612. // Test request without Content-Length header within payload limit
  6613. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6614. "Host: " +
  6615. std::string(HOST) + ":" +
  6616. std::to_string(PORT) +
  6617. "\r\n"
  6618. "Connection: close\r\n"
  6619. "\r\n";
  6620. // Add payload within the 8-byte limit
  6621. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6622. request_without_content_length += small_payload;
  6623. std::string response;
  6624. bool result = send_request(1, request_without_content_length, &response);
  6625. // For requests without Content-Length, the server may have different behavior
  6626. // The key is that it should not reject due to payload limit for small
  6627. // payloads
  6628. if (result) {
  6629. // Check for any HTTP response (success or error, but not connection closed)
  6630. if (response.length() > 10) {
  6631. SUCCEED()
  6632. << "Server processed request without Content-Length within limit";
  6633. } else {
  6634. // Short response might indicate connection closed, which is acceptable
  6635. SUCCEED() << "Server closed connection for request without "
  6636. "Content-Length (acceptable behavior)";
  6637. }
  6638. } else {
  6639. // Connection failure might be due to protocol requirements
  6640. SUCCEED() << "Connection issue with request without Content-Length "
  6641. "(environment-specific)";
  6642. }
  6643. }
  6644. class LargePayloadMaxLengthTest : public ::testing::Test {
  6645. protected:
  6646. LargePayloadMaxLengthTest()
  6647. : cli_(HOST, PORT)
  6648. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6649. ,
  6650. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6651. #endif
  6652. {
  6653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6654. cli_.enable_server_certificate_verification(false);
  6655. #endif
  6656. }
  6657. virtual void SetUp() {
  6658. // Set 10MB payload limit
  6659. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6660. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6661. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6662. res.set_content("Large payload test", "text/plain");
  6663. });
  6664. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6665. svr_.wait_until_ready();
  6666. }
  6667. virtual void TearDown() {
  6668. svr_.stop();
  6669. t_.join();
  6670. }
  6671. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6672. SSLClient cli_;
  6673. SSLServer svr_;
  6674. #else
  6675. Client cli_;
  6676. Server svr_;
  6677. #endif
  6678. thread t_;
  6679. };
  6680. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6681. // Test chunked encoding with payload within 10MB limit
  6682. std::string medium_payload(5 * 1024 * 1024,
  6683. 'A'); // 5MB payload, within 10MB limit
  6684. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6685. ASSERT_TRUE(res);
  6686. EXPECT_EQ(StatusCode::OK_200, res->status);
  6687. }
  6688. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6689. // Test chunked encoding with payload exceeding 10MB limit
  6690. std::string large_payload(12 * 1024 * 1024,
  6691. 'B'); // 12MB payload, exceeds 10MB limit
  6692. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6693. ASSERT_TRUE(res);
  6694. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6695. }
  6696. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6697. // Test request without Content-Length header within 10MB 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 1MB payload (within 10MB limit)
  6706. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6707. request_without_content_length += medium_payload;
  6708. std::string response;
  6709. bool result = send_request(5, request_without_content_length, &response);
  6710. if (result) {
  6711. // Should get a proper HTTP response for payloads within limit
  6712. if (response.length() > 10) {
  6713. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6714. "10MB limit";
  6715. } else {
  6716. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6717. "Content-Length)";
  6718. }
  6719. } else {
  6720. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6721. }
  6722. }
  6723. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6724. // Test request without Content-Length header exceeding 10MB limit
  6725. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6726. "Host: " +
  6727. std::string(HOST) + ":" +
  6728. std::to_string(PORT) +
  6729. "\r\n"
  6730. "Connection: close\r\n"
  6731. "\r\n";
  6732. // Add 12MB payload (exceeds 10MB limit)
  6733. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6734. request_without_content_length += large_payload;
  6735. std::string response;
  6736. bool result = send_request(10, request_without_content_length, &response);
  6737. if (!result) {
  6738. // Server should close connection due to payload limit
  6739. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6740. "(connection closed)";
  6741. } else {
  6742. // Check for error response
  6743. if (response.length() <= 10) {
  6744. SUCCEED()
  6745. << "Server closed connection for 12MB request exceeding 10MB limit";
  6746. } else {
  6747. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6748. response.find("Payload Too Large") != std::string::npos ||
  6749. response.find("400") != std::string::npos);
  6750. }
  6751. }
  6752. }
  6753. TEST(HostAndPortPropertiesTest, NoSSL) {
  6754. httplib::Client cli("www.google.com", 1234);
  6755. ASSERT_EQ("www.google.com", cli.host());
  6756. ASSERT_EQ(1234, cli.port());
  6757. }
  6758. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6759. httplib::Client cli("www.google.com:1234");
  6760. ASSERT_EQ("www.google.com", cli.host());
  6761. ASSERT_EQ(1234, cli.port());
  6762. }
  6763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6764. TEST(HostAndPortPropertiesTest, SSL) {
  6765. httplib::SSLClient cli("www.google.com");
  6766. ASSERT_EQ("www.google.com", cli.host());
  6767. ASSERT_EQ(443, cli.port());
  6768. }
  6769. #endif
  6770. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6771. TEST(SSLClientTest, UpdateCAStore) {
  6772. httplib::SSLClient httplib_client("www.google.com");
  6773. auto ca_store_1 = X509_STORE_new();
  6774. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6775. nullptr);
  6776. httplib_client.set_ca_cert_store(ca_store_1);
  6777. auto ca_store_2 = X509_STORE_new();
  6778. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6779. nullptr);
  6780. httplib_client.set_ca_cert_store(ca_store_2);
  6781. }
  6782. TEST(SSLClientTest, ServerNameIndication_Online) {
  6783. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6784. auto host = "httpbin.org";
  6785. auto path = std::string{"/get"};
  6786. #else
  6787. auto host = "nghttp2.org";
  6788. auto path = std::string{"/httpbin/get"};
  6789. #endif
  6790. SSLClient cli(host, 443);
  6791. auto res = cli.Get(path);
  6792. ASSERT_TRUE(res);
  6793. ASSERT_EQ(StatusCode::OK_200, res->status);
  6794. }
  6795. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6796. // Use a site that will cause SSL verification failure due to self-signed cert
  6797. SSLClient cli("self-signed.badssl.com", 443);
  6798. cli.enable_server_certificate_verification(true);
  6799. auto res = cli.Get("/");
  6800. ASSERT_TRUE(!res);
  6801. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6802. // For SSL server verification errors, ssl_error should be 0, only
  6803. // ssl_openssl_error should be set
  6804. EXPECT_EQ(0, res.ssl_error());
  6805. // Verify OpenSSL error is captured for SSLServerVerification
  6806. // This occurs when SSL_get_verify_result() returns a verification failure
  6807. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6808. res.ssl_openssl_error());
  6809. }
  6810. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6811. // Use a site where hostname doesn't match the certificate
  6812. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6813. SSLClient cli("wrong.host.badssl.com", 443);
  6814. cli.enable_server_certificate_verification(true);
  6815. cli.enable_server_hostname_verification(true);
  6816. auto res = cli.Get("/");
  6817. ASSERT_TRUE(!res);
  6818. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6819. // For SSL hostname verification errors, ssl_error should be 0, only
  6820. // ssl_openssl_error should be set
  6821. EXPECT_EQ(0, res.ssl_error());
  6822. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6823. // This occurs when verify_host() fails due to hostname mismatch
  6824. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6825. res.ssl_openssl_error());
  6826. }
  6827. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6828. Client cli("https://google.com");
  6829. auto res = cli.Get("/");
  6830. ASSERT_TRUE(res);
  6831. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6832. }
  6833. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6834. SSLClient cli("google.com");
  6835. cli.set_ca_cert_path(CA_CERT_FILE);
  6836. auto res = cli.Get("/");
  6837. ASSERT_TRUE(res);
  6838. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6839. }
  6840. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6841. SSLClient cli("google.com");
  6842. cli.enable_server_certificate_verification(true);
  6843. cli.set_ca_cert_path("hello");
  6844. auto res = cli.Get("/");
  6845. ASSERT_TRUE(!res);
  6846. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6847. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6848. // should be set
  6849. EXPECT_EQ(0, res.ssl_error());
  6850. // Verify OpenSSL error is captured for SSLLoadingCerts
  6851. // This error occurs when SSL_CTX_load_verify_locations() fails
  6852. // > openssl errstr 0x80000002
  6853. // error:80000002:system library::No such file or directory
  6854. // > openssl errstr 0xA000126
  6855. // error:0A000126:SSL routines::unexpected eof while reading
  6856. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6857. res.ssl_openssl_error() == 0xA000126);
  6858. }
  6859. TEST(SSLClientTest, ServerCertificateVerification4) {
  6860. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6861. ASSERT_TRUE(svr.is_valid());
  6862. svr.Get("/test", [&](const Request &, Response &res) {
  6863. res.set_content("test", "text/plain");
  6864. svr.stop();
  6865. ASSERT_TRUE(true);
  6866. });
  6867. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6868. auto se = detail::scope_exit([&] {
  6869. t.join();
  6870. ASSERT_FALSE(svr.is_running());
  6871. });
  6872. svr.wait_until_ready();
  6873. SSLClient cli("127.0.0.1", PORT);
  6874. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6875. cli.enable_server_certificate_verification(true);
  6876. cli.set_connection_timeout(30);
  6877. auto res = cli.Get("/test");
  6878. ASSERT_TRUE(res);
  6879. ASSERT_EQ(StatusCode::OK_200, res->status);
  6880. }
  6881. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6882. std::string cert;
  6883. read_file(CA_CERT_FILE, cert);
  6884. SSLClient cli("google.com");
  6885. cli.load_ca_cert_store(cert.data(), cert.size());
  6886. const auto res = cli.Get("/");
  6887. ASSERT_TRUE(res);
  6888. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6889. }
  6890. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6891. // clang-format off
  6892. static constexpr char cert[] =
  6893. "GlobalSign Root CA\n"
  6894. "==================\n"
  6895. "-----BEGIN CERTIFICATE-----\n"
  6896. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6897. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6898. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6899. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6900. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6901. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6902. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6903. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6904. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6905. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6906. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6907. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6908. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6909. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6910. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6911. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6912. "-----END CERTIFICATE-----\n";
  6913. // clang-format on
  6914. SSLClient cli("google.com");
  6915. cli.load_ca_cert_store(cert, sizeof(cert));
  6916. const auto res = cli.Get("/");
  6917. ASSERT_TRUE(res);
  6918. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6919. }
  6920. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6921. SSLClient cli("www.youtube.com");
  6922. cli.set_ca_cert_path(CA_CERT_FILE);
  6923. cli.enable_server_certificate_verification(true);
  6924. cli.set_follow_location(true);
  6925. auto res = cli.Get("/");
  6926. ASSERT_TRUE(res);
  6927. ASSERT_EQ(StatusCode::OK_200, res->status);
  6928. }
  6929. TEST(SSLClientTest, Issue2004_Online) {
  6930. Client client("https://google.com");
  6931. client.set_follow_location(true);
  6932. auto res = client.Get("/");
  6933. ASSERT_TRUE(res);
  6934. ASSERT_EQ(StatusCode::OK_200, res->status);
  6935. auto body = res->body;
  6936. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6937. }
  6938. #if 0
  6939. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6940. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6941. ASSERT_TRUE(cli != nullptr);
  6942. cli->set_address_family(AF_INET6);
  6943. cli->set_interface("en0");
  6944. auto res = cli->Get("/get");
  6945. ASSERT_TRUE(res);
  6946. ASSERT_EQ(StatusCode::OK_200, res->status);
  6947. }
  6948. #endif
  6949. void ClientCertPresent(
  6950. const std::string &client_cert_file,
  6951. const std::string &client_private_key_file,
  6952. const std::string &client_encrypted_private_key_pass = std::string()) {
  6953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6954. CLIENT_CA_CERT_DIR);
  6955. ASSERT_TRUE(svr.is_valid());
  6956. svr.Get("/test", [&](const Request &req, Response &res) {
  6957. res.set_content("test", "text/plain");
  6958. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6959. ASSERT_TRUE(peer_cert != nullptr);
  6960. auto subject_name = X509_get_subject_name(peer_cert);
  6961. ASSERT_TRUE(subject_name != nullptr);
  6962. std::string common_name;
  6963. {
  6964. char name[BUFSIZ];
  6965. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6966. name, sizeof(name));
  6967. common_name.assign(name, static_cast<size_t>(name_len));
  6968. }
  6969. EXPECT_EQ("Common Name", common_name);
  6970. X509_free(peer_cert);
  6971. });
  6972. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6973. auto se = detail::scope_exit([&] {
  6974. svr.stop();
  6975. t.join();
  6976. ASSERT_FALSE(svr.is_running());
  6977. });
  6978. svr.wait_until_ready();
  6979. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6980. client_encrypted_private_key_pass);
  6981. cli.enable_server_certificate_verification(false);
  6982. cli.set_connection_timeout(30);
  6983. auto res = cli.Get("/test");
  6984. ASSERT_TRUE(res);
  6985. ASSERT_EQ(StatusCode::OK_200, res->status);
  6986. }
  6987. TEST(SSLClientServerTest, ClientCertPresent) {
  6988. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6989. }
  6990. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6991. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6992. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6993. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6994. }
  6995. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6996. void MemoryClientCertPresent(
  6997. const std::string &client_cert_file,
  6998. const std::string &client_private_key_file,
  6999. const std::string &client_encrypted_private_key_pass = std::string()) {
  7000. auto f = fopen(SERVER_CERT_FILE, "r+");
  7001. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7002. fclose(f);
  7003. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7004. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7005. fclose(f);
  7006. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7007. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7008. auto client_ca_cert_store = X509_STORE_new();
  7009. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7010. X509_free(client_cert);
  7011. fclose(f);
  7012. f = fopen(client_cert_file.c_str(), "r+");
  7013. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7014. fclose(f);
  7015. f = fopen(client_private_key_file.c_str(), "r+");
  7016. auto client_private_key = PEM_read_PrivateKey(
  7017. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7018. fclose(f);
  7019. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7020. ASSERT_TRUE(svr.is_valid());
  7021. svr.Get("/test", [&](const Request &req, Response &res) {
  7022. res.set_content("test", "text/plain");
  7023. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7024. ASSERT_TRUE(peer_cert != nullptr);
  7025. auto subject_name = X509_get_subject_name(peer_cert);
  7026. ASSERT_TRUE(subject_name != nullptr);
  7027. std::string common_name;
  7028. {
  7029. char name[BUFSIZ];
  7030. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7031. name, sizeof(name));
  7032. common_name.assign(name, static_cast<size_t>(name_len));
  7033. }
  7034. EXPECT_EQ("Common Name", common_name);
  7035. X509_free(peer_cert);
  7036. });
  7037. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7038. auto se = detail::scope_exit([&] {
  7039. svr.stop();
  7040. t.join();
  7041. ASSERT_FALSE(svr.is_running());
  7042. });
  7043. svr.wait_until_ready();
  7044. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7045. client_encrypted_private_key_pass);
  7046. cli.enable_server_certificate_verification(false);
  7047. cli.set_connection_timeout(30);
  7048. auto res = cli.Get("/test");
  7049. ASSERT_TRUE(res);
  7050. ASSERT_EQ(StatusCode::OK_200, res->status);
  7051. X509_free(server_cert);
  7052. EVP_PKEY_free(server_private_key);
  7053. X509_free(client_cert);
  7054. EVP_PKEY_free(client_private_key);
  7055. }
  7056. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7057. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7058. }
  7059. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7060. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7061. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7062. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7063. }
  7064. #endif
  7065. TEST(SSLClientServerTest, ClientCertMissing) {
  7066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7067. CLIENT_CA_CERT_DIR);
  7068. ASSERT_TRUE(svr.is_valid());
  7069. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7070. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7071. auto se = detail::scope_exit([&] {
  7072. svr.stop();
  7073. t.join();
  7074. ASSERT_FALSE(svr.is_running());
  7075. });
  7076. svr.wait_until_ready();
  7077. SSLClient cli(HOST, PORT);
  7078. cli.set_connection_timeout(30);
  7079. auto res = cli.Get("/test");
  7080. ASSERT_TRUE(!res);
  7081. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7082. // For SSL server verification errors, ssl_error should be 0, only
  7083. // ssl_openssl_error should be set
  7084. EXPECT_EQ(0, res.ssl_error());
  7085. // Verify OpenSSL error is captured for SSLServerVerification
  7086. // Note: This test may have different error codes depending on the exact
  7087. // verification failure
  7088. EXPECT_NE(0UL, res.ssl_openssl_error());
  7089. }
  7090. TEST(SSLClientServerTest, TrustDirOptional) {
  7091. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7092. ASSERT_TRUE(svr.is_valid());
  7093. svr.Get("/test", [&](const Request &, Response &res) {
  7094. res.set_content("test", "text/plain");
  7095. });
  7096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7097. auto se = detail::scope_exit([&] {
  7098. svr.stop();
  7099. t.join();
  7100. ASSERT_FALSE(svr.is_running());
  7101. });
  7102. svr.wait_until_ready();
  7103. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7104. cli.enable_server_certificate_verification(false);
  7105. cli.set_connection_timeout(30);
  7106. auto res = cli.Get("/test");
  7107. ASSERT_TRUE(res);
  7108. ASSERT_EQ(StatusCode::OK_200, res->status);
  7109. }
  7110. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7111. class NoListenSSLServer : public SSLServer {
  7112. public:
  7113. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7114. const char *client_ca_cert_file_path,
  7115. const char *client_ca_cert_dir_path = nullptr)
  7116. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7117. client_ca_cert_dir_path),
  7118. stop_(false) {}
  7119. std::atomic_bool stop_;
  7120. private:
  7121. bool process_and_close_socket(socket_t /*sock*/) override {
  7122. // Don't create SSL context
  7123. while (!stop_.load()) {
  7124. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7125. }
  7126. return true;
  7127. }
  7128. };
  7129. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7130. CLIENT_CA_CERT_FILE);
  7131. ASSERT_TRUE(svr.is_valid());
  7132. svr.Get("/test", [&](const Request &, Response &res) {
  7133. res.set_content("test", "text/plain");
  7134. });
  7135. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7136. auto se = detail::scope_exit([&] {
  7137. svr.stop_ = true;
  7138. svr.stop();
  7139. t.join();
  7140. ASSERT_FALSE(svr.is_running());
  7141. });
  7142. svr.wait_until_ready();
  7143. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7144. cli.enable_server_certificate_verification(false);
  7145. cli.set_connection_timeout(1);
  7146. auto res = cli.Get("/test");
  7147. ASSERT_TRUE(!res);
  7148. EXPECT_EQ(Error::SSLConnection, res.error());
  7149. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7150. }
  7151. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7152. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7153. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7154. SSL_CTX_set_options(&ssl_ctx,
  7155. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7156. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7157. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7158. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7159. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7160. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7161. "ECDHE-DSS-AES128-SHA256:"
  7162. "ECDHE-RSA-AES256-SHA256:"
  7163. "ECDHE-DSS-AES256-SHA256:";
  7164. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7165. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7166. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7167. SSL_FILETYPE_PEM) != 1) {
  7168. return false;
  7169. }
  7170. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7171. CLIENT_CA_CERT_DIR);
  7172. SSL_CTX_set_verify(
  7173. &ssl_ctx,
  7174. SSL_VERIFY_PEER |
  7175. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7176. nullptr);
  7177. return true;
  7178. };
  7179. SSLServer svr(setup_ssl_ctx_callback);
  7180. ASSERT_TRUE(svr.is_valid());
  7181. svr.Get("/test", [&](const Request &req, Response &res) {
  7182. res.set_content("test", "text/plain");
  7183. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7184. ASSERT_TRUE(peer_cert != nullptr);
  7185. auto subject_name = X509_get_subject_name(peer_cert);
  7186. ASSERT_TRUE(subject_name != nullptr);
  7187. std::string common_name;
  7188. {
  7189. char name[BUFSIZ];
  7190. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7191. name, sizeof(name));
  7192. common_name.assign(name, static_cast<size_t>(name_len));
  7193. }
  7194. EXPECT_EQ("Common Name", common_name);
  7195. X509_free(peer_cert);
  7196. });
  7197. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7198. auto se = detail::scope_exit([&] {
  7199. svr.stop();
  7200. t.join();
  7201. ASSERT_FALSE(svr.is_running());
  7202. });
  7203. svr.wait_until_ready();
  7204. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  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. }
  7211. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7212. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7213. // prepare large data
  7214. std::random_device seed_gen;
  7215. std::mt19937 random(seed_gen());
  7216. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7217. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7218. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7219. // server
  7220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7221. ASSERT_TRUE(svr.is_valid());
  7222. svr.Post("/binary", [&](const Request &req, Response &res) {
  7223. EXPECT_EQ(large_size_byte, req.body.size());
  7224. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7225. res.set_content(req.body, "application/octet-stream");
  7226. });
  7227. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7228. auto se = detail::scope_exit([&] {
  7229. svr.stop();
  7230. listen_thread.join();
  7231. ASSERT_FALSE(svr.is_running());
  7232. });
  7233. svr.wait_until_ready();
  7234. // client POST
  7235. SSLClient cli("localhost", PORT);
  7236. cli.enable_server_certificate_verification(false);
  7237. cli.set_read_timeout(std::chrono::seconds(100));
  7238. cli.set_write_timeout(std::chrono::seconds(100));
  7239. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7240. large_size_byte, "application/octet-stream");
  7241. // compare
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(large_size_byte, res->body.size());
  7244. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7245. }
  7246. #endif
  7247. #ifdef _WIN32
  7248. TEST(CleanupTest, WSACleanup) {
  7249. int ret = WSACleanup();
  7250. ASSERT_EQ(0, ret);
  7251. }
  7252. #endif
  7253. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7254. TEST(NoSSLSupport, SimpleInterface) {
  7255. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7256. }
  7257. #endif
  7258. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7259. TEST(InvalidScheme, SimpleInterface) {
  7260. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7261. }
  7262. #endif
  7263. TEST(NoScheme, SimpleInterface) {
  7264. Client cli("yahoo.com:80");
  7265. ASSERT_TRUE(cli.is_valid());
  7266. }
  7267. TEST(SendAPI, SimpleInterface_Online) {
  7268. Client cli("http://yahoo.com");
  7269. Request req;
  7270. req.method = "GET";
  7271. req.path = "/";
  7272. auto res = cli.send(req);
  7273. ASSERT_TRUE(res);
  7274. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7275. }
  7276. TEST(SendAPI, WithParamsInRequest) {
  7277. Server svr;
  7278. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7279. EXPECT_TRUE(req.has_param("test"));
  7280. EXPECT_EQ("test_value", req.get_param_value("test"));
  7281. });
  7282. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7283. auto se = detail::scope_exit([&] {
  7284. svr.stop();
  7285. t.join();
  7286. ASSERT_FALSE(svr.is_running());
  7287. });
  7288. svr.wait_until_ready();
  7289. Client cli(HOST, PORT);
  7290. {
  7291. Request req;
  7292. req.method = "GET";
  7293. req.path = "/";
  7294. req.params.emplace("test", "test_value");
  7295. auto res = cli.send(req);
  7296. ASSERT_TRUE(res);
  7297. }
  7298. {
  7299. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7300. ASSERT_TRUE(res);
  7301. }
  7302. }
  7303. TEST(ClientImplMethods, GetSocketTest) {
  7304. httplib::Server svr;
  7305. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7306. res.status = StatusCode::OK_200;
  7307. });
  7308. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7309. auto se = detail::scope_exit([&] {
  7310. svr.stop();
  7311. thread.join();
  7312. ASSERT_FALSE(svr.is_running());
  7313. });
  7314. svr.wait_until_ready();
  7315. {
  7316. httplib::Client cli("http://127.0.0.1:3333");
  7317. cli.set_keep_alive(true);
  7318. // Use the behavior of cpp-httplib of opening the connection
  7319. // only when the first request happens. If that changes,
  7320. // this test would be obsolete.
  7321. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7322. // This also implicitly tests the server. But other tests would fail much
  7323. // earlier than this one to be considered.
  7324. auto res = cli.Get("/");
  7325. ASSERT_TRUE(res);
  7326. EXPECT_EQ(StatusCode::OK_200, res->status);
  7327. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7328. }
  7329. }
  7330. // Disabled due to out-of-memory problem on GitHub Actions
  7331. #ifdef _WIN64
  7332. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7333. // allocate content size larger than 2GB in memory
  7334. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7335. char *content = (char *)malloc(content_size);
  7336. ASSERT_TRUE(content);
  7337. Server svr;
  7338. svr.Get("/foo",
  7339. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7340. res.set_content(content, content_size, "application/octet-stream");
  7341. });
  7342. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7343. auto se = detail::scope_exit([&] {
  7344. svr.stop();
  7345. listen_thread.join();
  7346. if (content) free(content);
  7347. ASSERT_FALSE(svr.is_running());
  7348. });
  7349. svr.wait_until_ready();
  7350. Client cli(HOST, PORT);
  7351. auto res = cli.Get("/foo");
  7352. ASSERT_TRUE(res);
  7353. EXPECT_EQ(StatusCode::OK_200, res->status);
  7354. EXPECT_EQ(content_size, res->body.length());
  7355. }
  7356. #endif
  7357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7358. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7359. Client cli("http://yahoo.com");
  7360. auto res = cli.Get("/");
  7361. ASSERT_TRUE(res);
  7362. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7363. cli.set_follow_location(true);
  7364. res = cli.Get("/");
  7365. ASSERT_TRUE(res);
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7368. }
  7369. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7370. Client cli("https://yahoo.com");
  7371. auto res = cli.Get("/");
  7372. ASSERT_TRUE(res);
  7373. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7374. cli.set_follow_location(true);
  7375. res = cli.Get("/");
  7376. ASSERT_TRUE(res);
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7379. }
  7380. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7381. Client cli("https://yahoo.com");
  7382. auto res = cli.Get("/");
  7383. ASSERT_TRUE(res);
  7384. ASSERT_FALSE(!res);
  7385. ASSERT_TRUE(res);
  7386. ASSERT_FALSE(res == nullptr);
  7387. ASSERT_TRUE(res != nullptr);
  7388. EXPECT_EQ(Error::Success, res.error());
  7389. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7390. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7391. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7392. cli.set_follow_location(true);
  7393. res = cli.Get("/");
  7394. ASSERT_TRUE(res);
  7395. EXPECT_EQ(Error::Success, res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7397. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7400. }
  7401. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7402. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7403. Client cli("https://cdnjs.cloudflare.com");
  7404. auto res =
  7405. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7406. ASSERT_TRUE(res);
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ(287630U, res->body.size());
  7409. EXPECT_EQ("application/javascript; charset=utf-8",
  7410. res->get_header_value("Content-Type"));
  7411. }
  7412. #endif
  7413. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7414. #undef REDIR_HOST // Silence compiler warning
  7415. #define REDIR_HOST "https://httpbingo.org"
  7416. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7417. Client cli(REDIR_HOST);
  7418. cli.set_follow_location(true);
  7419. auto res =
  7420. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7421. ASSERT_TRUE(res);
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. }
  7424. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7425. Client cli(REDIR_HOST);
  7426. cli.set_follow_location(true);
  7427. Params params;
  7428. params.emplace("url", "http://example.com");
  7429. params.emplace("status_code", "302");
  7430. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7431. ASSERT_TRUE(res);
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. }
  7434. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7435. Client cli(REDIR_HOST);
  7436. cli.set_follow_location(true);
  7437. Params params;
  7438. params.emplace("url", "http://example.com");
  7439. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7440. ASSERT_TRUE(res);
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. }
  7443. TEST(HttpToHttpsRedirectTest, CertFile) {
  7444. Server svr;
  7445. ASSERT_TRUE(svr.is_valid());
  7446. svr.Get("/index", [&](const Request &, Response &res) {
  7447. res.set_redirect("https://127.0.0.1:1235/index");
  7448. svr.stop();
  7449. });
  7450. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7451. ASSERT_TRUE(ssl_svr.is_valid());
  7452. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7453. res.set_content("test", "text/plain");
  7454. ssl_svr.stop();
  7455. });
  7456. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7457. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7458. auto se = detail::scope_exit([&] {
  7459. t2.join();
  7460. t.join();
  7461. ASSERT_FALSE(svr.is_running());
  7462. });
  7463. svr.wait_until_ready();
  7464. ssl_svr.wait_until_ready();
  7465. Client cli("127.0.0.1", PORT);
  7466. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7467. cli.enable_server_certificate_verification(true);
  7468. cli.set_follow_location(true);
  7469. cli.set_connection_timeout(30);
  7470. auto res = cli.Get("/index");
  7471. ASSERT_TRUE(res);
  7472. ASSERT_EQ(StatusCode::OK_200, res->status);
  7473. }
  7474. TEST(MultipartFormDataTest, LargeData) {
  7475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7476. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7477. const ContentReader &content_reader) {
  7478. if (req.is_multipart_form_data()) {
  7479. std::vector<FormData> items;
  7480. content_reader(
  7481. [&](const FormData &file) {
  7482. items.push_back(file);
  7483. return true;
  7484. },
  7485. [&](const char *data, size_t data_length) {
  7486. items.back().content.append(data, data_length);
  7487. return true;
  7488. });
  7489. EXPECT_TRUE(std::string(items[0].name) == "document");
  7490. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7491. EXPECT_TRUE(items[0].filename == "2MB_data");
  7492. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7493. EXPECT_TRUE(items[1].name == "hello");
  7494. EXPECT_TRUE(items[1].content == "world");
  7495. EXPECT_TRUE(items[1].filename == "");
  7496. EXPECT_TRUE(items[1].content_type == "");
  7497. } else {
  7498. std::string body;
  7499. content_reader([&](const char *data, size_t data_length) {
  7500. body.append(data, data_length);
  7501. return true;
  7502. });
  7503. }
  7504. });
  7505. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7506. auto se = detail::scope_exit([&] {
  7507. svr.stop();
  7508. t.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.wait_until_ready();
  7512. {
  7513. std::string data(1024 * 1024 * 2, '.');
  7514. std::stringstream buffer;
  7515. buffer << data;
  7516. Client cli("https://localhost:8080");
  7517. cli.enable_server_certificate_verification(false);
  7518. UploadFormDataItems items{
  7519. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7520. {"hello", "world", "", ""},
  7521. };
  7522. auto res = cli.Post("/post", items);
  7523. ASSERT_TRUE(res);
  7524. ASSERT_EQ(StatusCode::OK_200, res->status);
  7525. }
  7526. }
  7527. TEST(MultipartFormDataTest, DataProviderItems) {
  7528. std::random_device seed_gen;
  7529. std::mt19937 random(seed_gen());
  7530. std::string rand1;
  7531. rand1.resize(1000);
  7532. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7533. std::string rand2;
  7534. rand2.resize(3000);
  7535. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7537. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7538. const ContentReader &content_reader) {
  7539. ASSERT_FALSE(req.is_multipart_form_data());
  7540. std::string body;
  7541. content_reader([&](const char *data, size_t data_length) {
  7542. body.append(data, data_length);
  7543. return true;
  7544. });
  7545. EXPECT_EQ(body, "");
  7546. });
  7547. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7548. const ContentReader &content_reader) {
  7549. ASSERT_TRUE(req.is_multipart_form_data());
  7550. std::vector<FormData> items;
  7551. content_reader(
  7552. [&](const FormData &file) {
  7553. items.push_back(file);
  7554. return true;
  7555. },
  7556. [&](const char *data, size_t data_length) {
  7557. items.back().content.append(data, data_length);
  7558. return true;
  7559. });
  7560. ASSERT_TRUE(items.size() == 2);
  7561. EXPECT_EQ(std::string(items[0].name), "name1");
  7562. EXPECT_EQ(items[0].content, "Testing123");
  7563. EXPECT_EQ(items[0].filename, "filename1");
  7564. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7565. EXPECT_EQ(items[1].name, "name2");
  7566. EXPECT_EQ(items[1].content, "Testing456");
  7567. EXPECT_EQ(items[1].filename, "");
  7568. EXPECT_EQ(items[1].content_type, "");
  7569. });
  7570. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7571. const ContentReader &content_reader) {
  7572. ASSERT_TRUE(req.is_multipart_form_data());
  7573. std::vector<FormData> items;
  7574. content_reader(
  7575. [&](const FormData &file) {
  7576. items.push_back(file);
  7577. return true;
  7578. },
  7579. [&](const char *data, size_t data_length) {
  7580. items.back().content.append(data, data_length);
  7581. return true;
  7582. });
  7583. ASSERT_TRUE(items.size() == 2);
  7584. EXPECT_EQ(items[0].name, "name3");
  7585. EXPECT_EQ(items[0].content, rand1);
  7586. EXPECT_EQ(items[0].filename, "filename3");
  7587. EXPECT_EQ(items[0].content_type, "");
  7588. EXPECT_EQ(items[1].name, "name4");
  7589. EXPECT_EQ(items[1].content, rand2);
  7590. EXPECT_EQ(items[1].filename, "filename4");
  7591. EXPECT_EQ(items[1].content_type, "");
  7592. });
  7593. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7594. const ContentReader &content_reader) {
  7595. ASSERT_TRUE(req.is_multipart_form_data());
  7596. std::vector<FormData> items;
  7597. content_reader(
  7598. [&](const FormData &file) {
  7599. items.push_back(file);
  7600. return true;
  7601. },
  7602. [&](const char *data, size_t data_length) {
  7603. items.back().content.append(data, data_length);
  7604. return true;
  7605. });
  7606. ASSERT_TRUE(items.size() == 4);
  7607. EXPECT_EQ(std::string(items[0].name), "name1");
  7608. EXPECT_EQ(items[0].content, "Testing123");
  7609. EXPECT_EQ(items[0].filename, "filename1");
  7610. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7611. EXPECT_EQ(items[1].name, "name2");
  7612. EXPECT_EQ(items[1].content, "Testing456");
  7613. EXPECT_EQ(items[1].filename, "");
  7614. EXPECT_EQ(items[1].content_type, "");
  7615. EXPECT_EQ(items[2].name, "name3");
  7616. EXPECT_EQ(items[2].content, rand1);
  7617. EXPECT_EQ(items[2].filename, "filename3");
  7618. EXPECT_EQ(items[2].content_type, "");
  7619. EXPECT_EQ(items[3].name, "name4");
  7620. EXPECT_EQ(items[3].content, rand2);
  7621. EXPECT_EQ(items[3].filename, "filename4");
  7622. EXPECT_EQ(items[3].content_type, "");
  7623. });
  7624. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7625. auto se = detail::scope_exit([&] {
  7626. svr.stop();
  7627. t.join();
  7628. ASSERT_FALSE(svr.is_running());
  7629. });
  7630. svr.wait_until_ready();
  7631. {
  7632. Client cli("https://localhost:8080");
  7633. cli.enable_server_certificate_verification(false);
  7634. UploadFormDataItems items{
  7635. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7636. {"name2", "Testing456", "", ""}, // not a file
  7637. };
  7638. {
  7639. auto res = cli.Post("/post-none", {}, {}, {});
  7640. ASSERT_TRUE(res);
  7641. ASSERT_EQ(StatusCode::OK_200, res->status);
  7642. }
  7643. FormDataProviderItems providers;
  7644. {
  7645. auto res =
  7646. cli.Post("/post-items", {}, items, providers); // empty providers
  7647. ASSERT_TRUE(res);
  7648. ASSERT_EQ(StatusCode::OK_200, res->status);
  7649. }
  7650. providers.push_back({"name3",
  7651. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7652. // test the offset is given correctly at each step
  7653. if (!offset)
  7654. sink.os.write(rand1.data(), 30);
  7655. else if (offset == 30)
  7656. sink.os.write(rand1.data() + 30, 300);
  7657. else if (offset == 330)
  7658. sink.os.write(rand1.data() + 330, 670);
  7659. else if (offset == rand1.size())
  7660. sink.done();
  7661. return true;
  7662. },
  7663. "filename3",
  7664. {}});
  7665. providers.push_back({"name4",
  7666. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7667. // test the offset is given correctly at each step
  7668. if (!offset)
  7669. sink.os.write(rand2.data(), 2000);
  7670. else if (offset == 2000)
  7671. sink.os.write(rand2.data() + 2000, 1);
  7672. else if (offset == 2001)
  7673. sink.os.write(rand2.data() + 2001, 999);
  7674. else if (offset == rand2.size())
  7675. sink.done();
  7676. return true;
  7677. },
  7678. "filename4",
  7679. {}});
  7680. {
  7681. auto res = cli.Post("/post-providers", {}, {}, providers);
  7682. ASSERT_TRUE(res);
  7683. ASSERT_EQ(StatusCode::OK_200, res->status);
  7684. }
  7685. {
  7686. auto res = cli.Post("/post-both", {}, items, providers);
  7687. ASSERT_TRUE(res);
  7688. ASSERT_EQ(StatusCode::OK_200, res->status);
  7689. }
  7690. }
  7691. }
  7692. TEST(MultipartFormDataTest, BadHeader) {
  7693. Server svr;
  7694. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7695. res.set_content("ok", "text/plain");
  7696. });
  7697. thread t = thread([&] { svr.listen(HOST, PORT); });
  7698. auto se = detail::scope_exit([&] {
  7699. svr.stop();
  7700. t.join();
  7701. ASSERT_FALSE(svr.is_running());
  7702. });
  7703. svr.wait_until_ready();
  7704. const std::string body =
  7705. "This is the preamble. It is to be ignored, though it\r\n"
  7706. "is a handy place for composition agents to include an\r\n"
  7707. "explanatory note to non-MIME conformant readers.\r\n"
  7708. "\r\n"
  7709. "\r\n"
  7710. "--simple boundary\r\n"
  7711. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7712. ": BAD...\r\n"
  7713. "\r\n"
  7714. "value1\r\n"
  7715. "--simple boundary\r\n"
  7716. "Content-Disposition: form-data; name=\"field2\"; "
  7717. "filename=\"example.txt\"\r\n"
  7718. "\r\n"
  7719. "value2\r\n"
  7720. "--simple boundary--\r\n"
  7721. "This is the epilogue. It is also to be ignored.\r\n";
  7722. std::string content_type =
  7723. R"(multipart/form-data; boundary="simple boundary")";
  7724. Client cli(HOST, PORT);
  7725. auto res = cli.Post("/post", body, content_type.c_str());
  7726. ASSERT_TRUE(res);
  7727. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7728. }
  7729. TEST(MultipartFormDataTest, WithPreamble) {
  7730. Server svr;
  7731. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7732. res.set_content("ok", "text/plain");
  7733. });
  7734. thread t = thread([&] { svr.listen(HOST, PORT); });
  7735. auto se = detail::scope_exit([&] {
  7736. svr.stop();
  7737. t.join();
  7738. ASSERT_FALSE(svr.is_running());
  7739. });
  7740. svr.wait_until_ready();
  7741. const std::string body =
  7742. "This is the preamble. It is to be ignored, though it\r\n"
  7743. "is a handy place for composition agents to include an\r\n"
  7744. "explanatory note to non-MIME conformant readers.\r\n"
  7745. "\r\n"
  7746. "\r\n"
  7747. "--simple boundary\r\n"
  7748. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7749. "\r\n"
  7750. "value1\r\n"
  7751. "--simple boundary\r\n"
  7752. "Content-Disposition: form-data; name=\"field2\"; "
  7753. "filename=\"example.txt\"\r\n"
  7754. "\r\n"
  7755. "value2\r\n"
  7756. "--simple boundary--\r\n"
  7757. "This is the epilogue. It is also to be ignored.\r\n";
  7758. std::string content_type =
  7759. R"(multipart/form-data; boundary="simple boundary")";
  7760. Client cli(HOST, PORT);
  7761. auto res = cli.Post("/post", body, content_type.c_str());
  7762. ASSERT_TRUE(res);
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. }
  7765. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7767. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7768. const ContentReader &content_reader) {
  7769. if (req.is_multipart_form_data()) {
  7770. std::vector<FormData> items;
  7771. content_reader(
  7772. [&](const FormData &file) {
  7773. items.push_back(file);
  7774. return true;
  7775. },
  7776. [&](const char *data, size_t data_length) {
  7777. items.back().content.append(data, data_length);
  7778. return true;
  7779. });
  7780. EXPECT_TRUE(std::string(items[0].name) == "document");
  7781. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7782. EXPECT_TRUE(items[0].filename == "2MB_data");
  7783. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7784. EXPECT_TRUE(items[1].name == "hello");
  7785. EXPECT_TRUE(items[1].content == "world");
  7786. EXPECT_TRUE(items[1].filename == "");
  7787. EXPECT_TRUE(items[1].content_type == "");
  7788. } else {
  7789. std::string body;
  7790. content_reader([&](const char *data, size_t data_length) {
  7791. body.append(data, data_length);
  7792. return true;
  7793. });
  7794. }
  7795. });
  7796. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7797. auto se = detail::scope_exit([&] {
  7798. svr.stop();
  7799. t.join();
  7800. ASSERT_FALSE(svr.is_running());
  7801. });
  7802. svr.wait_until_ready();
  7803. {
  7804. std::string data(1024 * 1024 * 2, '.');
  7805. std::stringstream buffer;
  7806. buffer << data;
  7807. Client cli("https://localhost:8080");
  7808. cli.enable_server_certificate_verification(false);
  7809. UploadFormDataItems items{
  7810. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7811. {"hello", "world", "", ""},
  7812. };
  7813. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7814. ASSERT_TRUE(res);
  7815. ASSERT_EQ(StatusCode::OK_200, res->status);
  7816. }
  7817. }
  7818. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7819. std::string data(1024 * 1024 * 2, '&');
  7820. std::stringstream buffer;
  7821. buffer << data;
  7822. Client cli("https://localhost:8080");
  7823. UploadFormDataItems items{
  7824. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7825. {"hello", "world", "", ""},
  7826. };
  7827. for (const char &c : " \t\r\n") {
  7828. auto res =
  7829. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7830. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7831. ASSERT_FALSE(res);
  7832. }
  7833. }
  7834. TEST(MultipartFormDataTest, PutFormData) {
  7835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7836. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7837. const ContentReader &content_reader) {
  7838. if (req.is_multipart_form_data()) {
  7839. std::vector<FormData> items;
  7840. content_reader(
  7841. [&](const FormData &file) {
  7842. items.push_back(file);
  7843. return true;
  7844. },
  7845. [&](const char *data, size_t data_length) {
  7846. items.back().content.append(data, data_length);
  7847. return true;
  7848. });
  7849. EXPECT_TRUE(std::string(items[0].name) == "document");
  7850. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7851. EXPECT_TRUE(items[0].filename == "2MB_data");
  7852. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7853. EXPECT_TRUE(items[1].name == "hello");
  7854. EXPECT_TRUE(items[1].content == "world");
  7855. EXPECT_TRUE(items[1].filename == "");
  7856. EXPECT_TRUE(items[1].content_type == "");
  7857. } else {
  7858. std::string body;
  7859. content_reader([&](const char *data, size_t data_length) {
  7860. body.append(data, data_length);
  7861. return true;
  7862. });
  7863. }
  7864. });
  7865. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7866. auto se = detail::scope_exit([&] {
  7867. svr.stop();
  7868. t.join();
  7869. ASSERT_FALSE(svr.is_running());
  7870. });
  7871. svr.wait_until_ready();
  7872. {
  7873. std::string data(1024 * 1024 * 2, '&');
  7874. std::stringstream buffer;
  7875. buffer << data;
  7876. Client cli("https://localhost:8080");
  7877. cli.enable_server_certificate_verification(false);
  7878. UploadFormDataItems items{
  7879. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7880. {"hello", "world", "", ""},
  7881. };
  7882. auto res = cli.Put("/put", items);
  7883. ASSERT_TRUE(res);
  7884. ASSERT_EQ(StatusCode::OK_200, res->status);
  7885. }
  7886. }
  7887. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7889. svr.Put("/put_customboundary",
  7890. [&](const Request &req, const Response & /*res*/,
  7891. const ContentReader &content_reader) {
  7892. if (req.is_multipart_form_data()) {
  7893. std::vector<FormData> items;
  7894. content_reader(
  7895. [&](const FormData &file) {
  7896. items.push_back(file);
  7897. return true;
  7898. },
  7899. [&](const char *data, size_t data_length) {
  7900. items.back().content.append(data, data_length);
  7901. return true;
  7902. });
  7903. EXPECT_TRUE(std::string(items[0].name) == "document");
  7904. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7905. EXPECT_TRUE(items[0].filename == "2MB_data");
  7906. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7907. EXPECT_TRUE(items[1].name == "hello");
  7908. EXPECT_TRUE(items[1].content == "world");
  7909. EXPECT_TRUE(items[1].filename == "");
  7910. EXPECT_TRUE(items[1].content_type == "");
  7911. } else {
  7912. std::string body;
  7913. content_reader([&](const char *data, size_t data_length) {
  7914. body.append(data, data_length);
  7915. return true;
  7916. });
  7917. }
  7918. });
  7919. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. t.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. {
  7927. std::string data(1024 * 1024 * 2, '&');
  7928. std::stringstream buffer;
  7929. buffer << data;
  7930. Client cli("https://localhost:8080");
  7931. cli.enable_server_certificate_verification(false);
  7932. UploadFormDataItems items{
  7933. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7934. {"hello", "world", "", ""},
  7935. };
  7936. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7937. ASSERT_TRUE(res);
  7938. ASSERT_EQ(StatusCode::OK_200, res->status);
  7939. }
  7940. }
  7941. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7942. std::string data(1024 * 1024 * 2, '&');
  7943. std::stringstream buffer;
  7944. buffer << data;
  7945. Client cli("https://localhost:8080");
  7946. cli.enable_server_certificate_verification(false);
  7947. UploadFormDataItems items{
  7948. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7949. {"hello", "world", "", ""},
  7950. };
  7951. for (const char &c : " \t\r\n") {
  7952. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7953. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7954. ASSERT_FALSE(res);
  7955. }
  7956. }
  7957. TEST(MultipartFormDataTest, AlternateFilename) {
  7958. auto handled = false;
  7959. Server svr;
  7960. svr.Post("/test", [&](const Request &req, Response &res) {
  7961. ASSERT_EQ(2u, req.form.files.size());
  7962. ASSERT_EQ(1u, req.form.fields.size());
  7963. // Test files
  7964. const auto &file1 = req.form.get_file("file1");
  7965. ASSERT_EQ("file1", file1.name);
  7966. ASSERT_EQ("A.txt", file1.filename);
  7967. ASSERT_EQ("text/plain", file1.content_type);
  7968. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  7969. const auto &file2 = req.form.get_file("file2");
  7970. ASSERT_EQ("file2", file2.name);
  7971. ASSERT_EQ("a.html", file2.filename);
  7972. ASSERT_EQ("text/html", file2.content_type);
  7973. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7974. file2.content);
  7975. // Test text field
  7976. const auto &text = req.form.get_field("text");
  7977. ASSERT_EQ("text default", text);
  7978. res.set_content("ok", "text/plain");
  7979. handled = true;
  7980. });
  7981. thread t = thread([&] { svr.listen(HOST, PORT); });
  7982. auto se = detail::scope_exit([&] {
  7983. svr.stop();
  7984. t.join();
  7985. ASSERT_FALSE(svr.is_running());
  7986. ASSERT_TRUE(handled);
  7987. });
  7988. svr.wait_until_ready();
  7989. auto req = "POST /test HTTP/1.1\r\n"
  7990. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7991. "Content-Length: 399\r\n"
  7992. "\r\n"
  7993. "----------\r\n"
  7994. "Content-Disposition: form-data; name=\"text\"\r\n"
  7995. "\r\n"
  7996. "text default\r\n"
  7997. "----------\r\n"
  7998. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7999. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8000. "Content-Type: text/plain\r\n"
  8001. "\r\n"
  8002. "Content of a.txt.\r\n"
  8003. "\r\n"
  8004. "----------\r\n"
  8005. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8006. "\"a.html\"\r\n"
  8007. "Content-Type: text/html\r\n"
  8008. "\r\n"
  8009. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8010. "\r\n"
  8011. "------------\r\n";
  8012. ASSERT_TRUE(send_request(1, req));
  8013. }
  8014. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8015. auto handled = false;
  8016. Server svr;
  8017. svr.Post("/test", [&](const Request &req, Response &) {
  8018. ASSERT_EQ(2u, req.form.fields.size());
  8019. const auto &text1 = req.form.get_field("text1");
  8020. ASSERT_EQ("text1", text1);
  8021. const auto &text2 = req.form.get_field("text2");
  8022. ASSERT_EQ("text2", text2);
  8023. handled = true;
  8024. });
  8025. thread t = thread([&] { svr.listen(HOST, PORT); });
  8026. auto se = detail::scope_exit([&] {
  8027. svr.stop();
  8028. t.join();
  8029. ASSERT_FALSE(svr.is_running());
  8030. ASSERT_TRUE(handled);
  8031. });
  8032. svr.wait_until_ready();
  8033. auto req = "POST /test HTTP/1.1\r\n"
  8034. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8035. "Content-Length: 146\r\n"
  8036. "\r\n----------\r\n"
  8037. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8038. "\r\n"
  8039. "text1"
  8040. "\r\n----------\r\n"
  8041. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8042. "\r\n"
  8043. "text2"
  8044. "\r\n------------";
  8045. std::string response;
  8046. ASSERT_TRUE(send_request(1, req, &response));
  8047. ASSERT_EQ("200", response.substr(9, 3));
  8048. }
  8049. TEST(MultipartFormDataTest, ContentLength) {
  8050. auto handled = false;
  8051. Server svr;
  8052. svr.Post("/test", [&](const Request &req, Response &) {
  8053. ASSERT_EQ(2u, req.form.fields.size());
  8054. const auto &text1 = req.form.get_field("text1");
  8055. ASSERT_EQ("text1", text1);
  8056. const auto &text2 = req.form.get_field("text2");
  8057. ASSERT_EQ("text2", text2);
  8058. handled = true;
  8059. });
  8060. thread t = thread([&] { svr.listen(HOST, PORT); });
  8061. auto se = detail::scope_exit([&] {
  8062. svr.stop();
  8063. t.join();
  8064. ASSERT_FALSE(svr.is_running());
  8065. ASSERT_TRUE(handled);
  8066. });
  8067. svr.wait_until_ready();
  8068. auto req = "POST /test HTTP/1.1\r\n"
  8069. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8070. "Content-Length: 167\r\n"
  8071. "\r\n----------\r\n"
  8072. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8073. "Content-Length: 5\r\n"
  8074. "\r\n"
  8075. "text1"
  8076. "\r\n----------\r\n"
  8077. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8078. "\r\n"
  8079. "text2"
  8080. "\r\n------------\r\n";
  8081. std::string response;
  8082. ASSERT_TRUE(send_request(1, req, &response));
  8083. ASSERT_EQ("200", response.substr(9, 3));
  8084. }
  8085. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8086. auto handled = false;
  8087. Server svr;
  8088. svr.Post("/test", [&](const Request &req, Response &) {
  8089. ASSERT_EQ(2u, req.form.fields.size());
  8090. const auto &text1 = req.form.get_field("text1");
  8091. ASSERT_EQ("text1", text1);
  8092. // TODO: Add header access for text fields if needed
  8093. const auto &text2 = req.form.get_field("text2");
  8094. ASSERT_EQ("text2", text2);
  8095. // TODO: Header access for text fields needs to be implemented
  8096. // auto &headers = it->second.headers;
  8097. // ASSERT_EQ(3U, headers.size());
  8098. // auto custom_header = headers.find("x-whatever");
  8099. // ASSERT_TRUE(custom_header != headers.end());
  8100. // ASSERT_NE("customvalue", custom_header->second);
  8101. // ASSERT_EQ("CustomValue", custom_header->second);
  8102. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8103. handled = true;
  8104. });
  8105. thread t = thread([&] { svr.listen(HOST, PORT); });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. t.join();
  8109. ASSERT_FALSE(svr.is_running());
  8110. ASSERT_TRUE(handled);
  8111. });
  8112. svr.wait_until_ready();
  8113. auto req = "POST /test HTTP/1.1\r\n"
  8114. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8115. "Content-Length: 232\r\n"
  8116. "\r\n----------\r\n"
  8117. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8118. "Content-Length: 5\r\n"
  8119. "X-Test: 1\r\n"
  8120. "\r\n"
  8121. "text1"
  8122. "\r\n----------\r\n"
  8123. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8124. "Content-Type: text/plain\r\n"
  8125. "X-Whatever: CustomValue\r\n"
  8126. "\r\n"
  8127. "text2"
  8128. "\r\n------------\r\n"
  8129. "That should be disregarded. Not even read";
  8130. std::string response;
  8131. ASSERT_TRUE(send_request(1, req, &response));
  8132. ASSERT_EQ("200", response.substr(9, 3));
  8133. }
  8134. #endif
  8135. TEST(MultipartFormDataTest, LargeHeader) {
  8136. auto handled = false;
  8137. Server svr;
  8138. svr.Post("/test", [&](const Request &req, Response &) {
  8139. ASSERT_EQ(1u, req.form.fields.size());
  8140. const auto &text = req.form.get_field("name1");
  8141. ASSERT_EQ("text1", text);
  8142. handled = true;
  8143. });
  8144. thread t = thread([&] { svr.listen(HOST, PORT); });
  8145. auto se = detail::scope_exit([&] {
  8146. svr.stop();
  8147. t.join();
  8148. ASSERT_FALSE(svr.is_running());
  8149. ASSERT_TRUE(handled);
  8150. });
  8151. svr.wait_until_ready();
  8152. auto boundary = std::string("cpp-httplib-multipart-data");
  8153. std::string content = "--" + boundary +
  8154. "\r\n"
  8155. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8156. "\r\n"
  8157. "text1\r\n"
  8158. "--" +
  8159. boundary + "--\r\n";
  8160. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8161. "Content-Type: multipart/form-data;boundary=" +
  8162. boundary +
  8163. "\r\n"
  8164. "Content-Length: " +
  8165. std::to_string(content.size()) +
  8166. "\r\n"
  8167. "Dummy-Header: ";
  8168. std::string header_suffix = "\r\n"
  8169. "\r\n";
  8170. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8171. size_t header_dummy_size =
  8172. read_buff_size -
  8173. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8174. auto header_dummy = std::string(header_dummy_size, '@');
  8175. auto req = header_prefix + header_dummy + header_suffix + content;
  8176. std::string response;
  8177. ASSERT_TRUE(send_request(1, req, &response));
  8178. ASSERT_EQ("200", response.substr(9, 3));
  8179. }
  8180. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8181. static constexpr unsigned int number_of_tasks{1000000};
  8182. std::atomic_uint count{0};
  8183. std::unique_ptr<TaskQueue> task_queue{
  8184. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8185. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8186. auto queued = task_queue->enqueue(
  8187. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8188. EXPECT_TRUE(queued);
  8189. }
  8190. EXPECT_NO_THROW(task_queue->shutdown());
  8191. EXPECT_EQ(number_of_tasks, count.load());
  8192. }
  8193. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8194. static constexpr unsigned int number_of_tasks{1000000};
  8195. static constexpr unsigned int qlimit{2};
  8196. unsigned int queued_count{0};
  8197. std::atomic_uint count{0};
  8198. std::unique_ptr<TaskQueue> task_queue{
  8199. new ThreadPool{/*num_threads=*/1, qlimit}};
  8200. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8201. if (task_queue->enqueue(
  8202. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8203. queued_count++;
  8204. }
  8205. }
  8206. EXPECT_NO_THROW(task_queue->shutdown());
  8207. EXPECT_EQ(queued_count, count.load());
  8208. EXPECT_TRUE(queued_count <= number_of_tasks);
  8209. EXPECT_TRUE(queued_count >= qlimit);
  8210. }
  8211. TEST(TaskQueueTest, MaxQueuedRequests) {
  8212. static constexpr unsigned int qlimit{3};
  8213. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8214. std::condition_variable sem_cv;
  8215. std::mutex sem_mtx;
  8216. int credits = 0;
  8217. bool queued;
  8218. /* Fill up the queue with tasks that will block until we give them credits to
  8219. * complete. */
  8220. for (unsigned int n = 0; n <= qlimit;) {
  8221. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8222. std::unique_lock<std::mutex> lock(sem_mtx);
  8223. while (credits <= 0) {
  8224. sem_cv.wait(lock);
  8225. }
  8226. /* Consume the credit and signal the test code if they are all gone. */
  8227. if (--credits == 0) { sem_cv.notify_one(); }
  8228. });
  8229. if (n < qlimit) {
  8230. /* The first qlimit enqueues must succeed. */
  8231. EXPECT_TRUE(queued);
  8232. } else {
  8233. /* The last one will succeed only when the worker thread
  8234. * starts and dequeues the first blocking task. Although
  8235. * not necessary for the correctness of this test, we sleep for
  8236. * a short while to avoid busy waiting. */
  8237. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8238. }
  8239. if (queued) { n++; }
  8240. }
  8241. /* Further enqueues must fail since the queue is full. */
  8242. for (auto i = 0; i < 4; i++) {
  8243. queued = task_queue->enqueue([] {});
  8244. EXPECT_FALSE(queued);
  8245. }
  8246. /* Give the credits to allow the previous tasks to complete. */
  8247. {
  8248. std::unique_lock<std::mutex> lock(sem_mtx);
  8249. credits += qlimit + 1;
  8250. }
  8251. sem_cv.notify_all();
  8252. /* Wait for all the credits to be consumed. */
  8253. {
  8254. std::unique_lock<std::mutex> lock(sem_mtx);
  8255. while (credits > 0) {
  8256. sem_cv.wait(lock);
  8257. }
  8258. }
  8259. /* Check that we are able again to enqueue at least qlimit tasks. */
  8260. for (unsigned int i = 0; i < qlimit; i++) {
  8261. queued = task_queue->enqueue([] {});
  8262. EXPECT_TRUE(queued);
  8263. }
  8264. EXPECT_NO_THROW(task_queue->shutdown());
  8265. }
  8266. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8267. Server svr;
  8268. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8269. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8270. });
  8271. svr.Get("/hello", [](const Request &req, Response &res) {
  8272. res.set_content(req.get_param_value("key"), "text/plain");
  8273. });
  8274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8275. auto se = detail::scope_exit([&] {
  8276. svr.stop();
  8277. thread.join();
  8278. ASSERT_FALSE(svr.is_running());
  8279. });
  8280. svr.wait_until_ready();
  8281. {
  8282. Client cli(HOST, PORT);
  8283. cli.set_follow_location(true);
  8284. auto res = cli.Get("/");
  8285. ASSERT_TRUE(res);
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_EQ("val&key2=val2", res->body);
  8288. }
  8289. }
  8290. TEST(VulnerabilityTest, CRLFInjection) {
  8291. Server svr;
  8292. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8293. res.set_content("Hello 1", "text/plain");
  8294. });
  8295. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8296. res.set_content("Hello 2", "text/plain");
  8297. });
  8298. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8299. res.set_content("Hello 3", "text/plain");
  8300. });
  8301. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8302. res.set_content("Hello 4", "text/plain");
  8303. });
  8304. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8305. for (const auto &x : req.headers) {
  8306. auto key = x.first;
  8307. EXPECT_STRNE("evil", key.c_str());
  8308. }
  8309. });
  8310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8311. auto se = detail::scope_exit([&] {
  8312. svr.stop();
  8313. thread.join();
  8314. ASSERT_FALSE(svr.is_running());
  8315. });
  8316. svr.wait_until_ready();
  8317. {
  8318. Client cli(HOST, PORT);
  8319. cli.Post("/test1", "A=B",
  8320. "application/x-www-form-urlencoded\r\nevil: hello1");
  8321. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8322. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8323. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8324. }
  8325. }
  8326. TEST(PathParamsTest, StaticMatch) {
  8327. const auto pattern = "/users/all";
  8328. detail::PathParamsMatcher matcher(pattern);
  8329. Request request;
  8330. request.path = "/users/all";
  8331. ASSERT_TRUE(matcher.match(request));
  8332. std::unordered_map<std::string, std::string> expected_params = {};
  8333. EXPECT_EQ(request.path_params, expected_params);
  8334. }
  8335. TEST(PathParamsTest, StaticMismatch) {
  8336. const auto pattern = "/users/all";
  8337. detail::PathParamsMatcher matcher(pattern);
  8338. Request request;
  8339. request.path = "/users/1";
  8340. ASSERT_FALSE(matcher.match(request));
  8341. }
  8342. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8343. const auto pattern = "/users/:id/subscriptions";
  8344. detail::PathParamsMatcher matcher(pattern);
  8345. Request request;
  8346. request.path = "/users/42/subscriptions";
  8347. ASSERT_TRUE(matcher.match(request));
  8348. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8349. EXPECT_EQ(request.path_params, expected_params);
  8350. }
  8351. TEST(PathParamsTest, SingleParamInTheEnd) {
  8352. const auto pattern = "/users/:id";
  8353. detail::PathParamsMatcher matcher(pattern);
  8354. Request request;
  8355. request.path = "/users/24";
  8356. ASSERT_TRUE(matcher.match(request));
  8357. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8358. EXPECT_EQ(request.path_params, expected_params);
  8359. }
  8360. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8361. const auto pattern = "/users/:id/";
  8362. detail::PathParamsMatcher matcher(pattern);
  8363. Request request;
  8364. request.path = "/users/42/";
  8365. ASSERT_TRUE(matcher.match(request));
  8366. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8367. EXPECT_EQ(request.path_params, expected_params);
  8368. }
  8369. TEST(PathParamsTest, EmptyParam) {
  8370. const auto pattern = "/users/:id/";
  8371. detail::PathParamsMatcher matcher(pattern);
  8372. Request request;
  8373. request.path = "/users//";
  8374. ASSERT_TRUE(matcher.match(request));
  8375. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8376. EXPECT_EQ(request.path_params, expected_params);
  8377. }
  8378. TEST(PathParamsTest, FragmentMismatch) {
  8379. const auto pattern = "/users/:id/";
  8380. detail::PathParamsMatcher matcher(pattern);
  8381. Request request;
  8382. request.path = "/admins/24/";
  8383. ASSERT_FALSE(matcher.match(request));
  8384. }
  8385. TEST(PathParamsTest, ExtraFragments) {
  8386. const auto pattern = "/users/:id";
  8387. detail::PathParamsMatcher matcher(pattern);
  8388. Request request;
  8389. request.path = "/users/42/subscriptions";
  8390. ASSERT_FALSE(matcher.match(request));
  8391. }
  8392. TEST(PathParamsTest, MissingTrailingParam) {
  8393. const auto pattern = "/users/:id";
  8394. detail::PathParamsMatcher matcher(pattern);
  8395. Request request;
  8396. request.path = "/users";
  8397. ASSERT_FALSE(matcher.match(request));
  8398. }
  8399. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8400. const auto pattern = "/users/:id/subscriptions";
  8401. detail::PathParamsMatcher matcher(pattern);
  8402. Request request;
  8403. request.path = "/users/subscriptions";
  8404. ASSERT_FALSE(matcher.match(request));
  8405. }
  8406. TEST(PathParamsTest, MultipleParams) {
  8407. const auto pattern = "/users/:userid/subscriptions/:subid";
  8408. detail::PathParamsMatcher matcher(pattern);
  8409. Request request;
  8410. request.path = "/users/42/subscriptions/2";
  8411. ASSERT_TRUE(matcher.match(request));
  8412. std::unordered_map<std::string, std::string> expected_params = {
  8413. {"userid", "42"}, {"subid", "2"}};
  8414. EXPECT_EQ(request.path_params, expected_params);
  8415. }
  8416. TEST(PathParamsTest, SequenceOfParams) {
  8417. const auto pattern = "/values/:x/:y/:z";
  8418. detail::PathParamsMatcher matcher(pattern);
  8419. Request request;
  8420. request.path = "/values/1/2/3";
  8421. ASSERT_TRUE(matcher.match(request));
  8422. std::unordered_map<std::string, std::string> expected_params = {
  8423. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8424. EXPECT_EQ(request.path_params, expected_params);
  8425. }
  8426. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8427. const auto pattern = "/prefix:suffix";
  8428. detail::PathParamsMatcher matcher(pattern);
  8429. Request request;
  8430. request.path = "/prefix:suffix";
  8431. ASSERT_TRUE(matcher.match(request));
  8432. const std::unordered_map<std::string, std::string> expected_params = {};
  8433. EXPECT_EQ(request.path_params, expected_params);
  8434. }
  8435. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8436. // If ipv6 regex working, regex match codepath is taken.
  8437. // else port will default to 80 in Client impl
  8438. int clientImplMagicPort = 80;
  8439. int port = 4321;
  8440. // above ports must be different to avoid false negative
  8441. EXPECT_NE(clientImplMagicPort, port);
  8442. std::string ipV6TestURL = "http://[ff06::c3]";
  8443. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8444. CLIENT_PRIVATE_KEY_FILE);
  8445. EXPECT_EQ(cli.port(), port);
  8446. }
  8447. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8448. auto file_path = "./www/dir/index.html";
  8449. auto dir_path = "./www/dir";
  8450. detail::FileStat stat_file(file_path);
  8451. EXPECT_TRUE(stat_file.is_file());
  8452. EXPECT_FALSE(stat_file.is_dir());
  8453. detail::FileStat stat_dir(dir_path);
  8454. EXPECT_FALSE(stat_dir.is_file());
  8455. EXPECT_TRUE(stat_dir.is_dir());
  8456. }
  8457. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8458. Server svr;
  8459. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8460. EXPECT_EQ(res.status, 400);
  8461. });
  8462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8463. auto se = detail::scope_exit([&] {
  8464. svr.stop();
  8465. thread.join();
  8466. ASSERT_FALSE(svr.is_running());
  8467. });
  8468. svr.wait_until_ready();
  8469. Client cli(HOST, PORT);
  8470. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8471. }
  8472. TEST(InvalidHeaderCharsTest, is_field_name) {
  8473. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8474. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8475. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8476. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8477. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8478. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8479. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8480. EXPECT_FALSE(detail::fields::is_field_name(""));
  8481. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8482. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8483. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8484. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8485. }
  8486. TEST(InvalidHeaderCharsTest, is_field_value) {
  8487. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8488. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8489. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8490. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8491. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8492. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8493. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8494. EXPECT_TRUE(detail::fields::is_field_value(""));
  8495. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8496. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8497. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8498. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8499. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8500. }
  8501. TEST(InvalidHeaderCharsTest, OnServer) {
  8502. Server svr;
  8503. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8504. std::string header = "Not Set";
  8505. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8506. res.set_header(header, "value");
  8507. res.set_content("Page Content Page Content", "text/plain");
  8508. });
  8509. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8510. std::string header = "Not Set";
  8511. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8512. res.set_header("X-Test", header);
  8513. res.set_content("Page Content Page Content", "text/plain");
  8514. });
  8515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8516. auto se = detail::scope_exit([&] {
  8517. svr.stop();
  8518. thread.join();
  8519. ASSERT_FALSE(svr.is_running());
  8520. });
  8521. svr.wait_until_ready();
  8522. Client cli(HOST, PORT);
  8523. {
  8524. auto res = cli.Get(
  8525. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8526. ASSERT_TRUE(res);
  8527. EXPECT_EQ("Page Content Page Content", res->body);
  8528. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8529. }
  8530. {
  8531. auto res = cli.Get(
  8532. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8533. ASSERT_TRUE(res);
  8534. EXPECT_EQ("Page Content Page Content", res->body);
  8535. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8536. }
  8537. }
  8538. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8539. auto handled = false;
  8540. Server svr;
  8541. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8542. thread t = thread([&] { svr.listen(HOST, PORT); });
  8543. auto se = detail::scope_exit([&] {
  8544. svr.stop();
  8545. t.join();
  8546. ASSERT_FALSE(svr.is_running());
  8547. ASSERT_FALSE(handled);
  8548. });
  8549. svr.wait_until_ready();
  8550. auto req = "POST /test HTTP/1.1\r\n"
  8551. "Content-Length: x\r\n"
  8552. "\r\n";
  8553. std::string response;
  8554. ASSERT_TRUE(send_request(1, req, &response));
  8555. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8556. response.substr(0, response.find("\r\n")));
  8557. }
  8558. #ifndef _WIN32
  8559. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8560. static constexpr char reject[] = "Unauthorized";
  8561. static constexpr char accept[] = "Upload accepted";
  8562. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8563. Server svr;
  8564. svr.set_expect_100_continue_handler(
  8565. [](const Request & /*req*/, Response &res) {
  8566. res.status = StatusCode::Unauthorized_401;
  8567. res.set_content(reject, "text/plain");
  8568. return res.status;
  8569. });
  8570. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8571. res.set_content(accept, "text/plain");
  8572. });
  8573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8574. auto se = detail::scope_exit([&] {
  8575. svr.stop();
  8576. thread.join();
  8577. ASSERT_FALSE(svr.is_running());
  8578. });
  8579. svr.wait_until_ready();
  8580. {
  8581. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8582. curl_easy_init(), &curl_easy_cleanup};
  8583. ASSERT_NE(curl, nullptr);
  8584. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8585. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8586. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8587. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8588. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8589. &curl_slist_free_all};
  8590. ASSERT_NE(list, nullptr);
  8591. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8592. struct read_data {
  8593. size_t read_size;
  8594. size_t total_size;
  8595. } data = {0, total_size};
  8596. using read_callback_t =
  8597. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8598. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8599. void *userdata) -> size_t {
  8600. read_data *data = (read_data *)userdata;
  8601. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8602. std::fill_n(ptr, size * nmemb, 'A');
  8603. data->read_size += size * nmemb;
  8604. return size * nmemb;
  8605. };
  8606. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8607. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8608. std::vector<char> buffer;
  8609. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8610. using write_callback_t =
  8611. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8612. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8613. void *userdata) -> size_t {
  8614. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8615. buffer->reserve(buffer->size() + size * nmemb + 1);
  8616. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8617. return size * nmemb;
  8618. };
  8619. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8620. {
  8621. const auto res = curl_easy_perform(curl.get());
  8622. ASSERT_EQ(res, CURLE_OK);
  8623. }
  8624. {
  8625. auto response_code = long{};
  8626. const auto res =
  8627. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8628. ASSERT_EQ(res, CURLE_OK);
  8629. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8630. }
  8631. {
  8632. auto dl = curl_off_t{};
  8633. const auto res =
  8634. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8635. ASSERT_EQ(res, CURLE_OK);
  8636. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8637. }
  8638. {
  8639. buffer.push_back('\0');
  8640. ASSERT_STRCASEEQ(buffer.data(), reject);
  8641. }
  8642. }
  8643. }
  8644. #endif
  8645. template <typename S, typename C>
  8646. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8647. svr.Get("/stream", [&](const Request &, Response &res) {
  8648. auto data = new std::string("01234567890123456789");
  8649. res.set_content_provider(
  8650. data->size(), "text/plain",
  8651. [&, data](size_t offset, size_t length, DataSink &sink) {
  8652. const size_t DATA_CHUNK_SIZE = 4;
  8653. const auto &d = *data;
  8654. std::this_thread::sleep_for(std::chrono::seconds(1));
  8655. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8656. return true;
  8657. },
  8658. [data](bool success) {
  8659. EXPECT_FALSE(success);
  8660. delete data;
  8661. });
  8662. });
  8663. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8664. auto i = new size_t(0);
  8665. res.set_content_provider(
  8666. "text/plain",
  8667. [i](size_t, DataSink &sink) {
  8668. if (*i < 5) {
  8669. std::this_thread::sleep_for(std::chrono::seconds(1));
  8670. sink.write("abcd", 4);
  8671. (*i)++;
  8672. } else {
  8673. sink.done();
  8674. }
  8675. return true;
  8676. },
  8677. [i](bool success) {
  8678. EXPECT_FALSE(success);
  8679. delete i;
  8680. });
  8681. });
  8682. svr.Get("/chunked", [&](const Request &, Response &res) {
  8683. auto i = new size_t(0);
  8684. res.set_chunked_content_provider(
  8685. "text/plain",
  8686. [i](size_t, DataSink &sink) {
  8687. if (*i < 5) {
  8688. std::this_thread::sleep_for(std::chrono::seconds(1));
  8689. sink.os << "abcd";
  8690. (*i)++;
  8691. } else {
  8692. sink.done();
  8693. }
  8694. return true;
  8695. },
  8696. [i](bool success) {
  8697. EXPECT_FALSE(success);
  8698. delete i;
  8699. });
  8700. });
  8701. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8702. auto se = detail::scope_exit([&] {
  8703. svr.stop();
  8704. listen_thread.join();
  8705. ASSERT_FALSE(svr.is_running());
  8706. });
  8707. svr.wait_until_ready();
  8708. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8709. {
  8710. auto start = std::chrono::steady_clock::now();
  8711. auto res = cli.Get("/stream");
  8712. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8713. std::chrono::steady_clock::now() - start)
  8714. .count();
  8715. ASSERT_FALSE(res);
  8716. EXPECT_EQ(Error::Read, res.error());
  8717. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8718. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8719. }
  8720. {
  8721. auto start = std::chrono::steady_clock::now();
  8722. auto res = cli.Get("/stream_without_length");
  8723. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8724. std::chrono::steady_clock::now() - start)
  8725. .count();
  8726. ASSERT_FALSE(res);
  8727. EXPECT_EQ(Error::Read, res.error());
  8728. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8729. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8730. }
  8731. {
  8732. auto start = std::chrono::steady_clock::now();
  8733. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8734. EXPECT_EQ("abcd", string(data, data_length));
  8735. return true;
  8736. });
  8737. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8738. std::chrono::steady_clock::now() - start)
  8739. .count();
  8740. ASSERT_FALSE(res);
  8741. EXPECT_EQ(Error::Read, res.error());
  8742. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8743. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8744. }
  8745. }
  8746. TEST(MaxTimeoutTest, ContentStream) {
  8747. time_t timeout = 2000;
  8748. time_t threshold = 200;
  8749. Server svr;
  8750. Client cli("localhost", PORT);
  8751. max_timeout_test(svr, cli, timeout, threshold);
  8752. }
  8753. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8754. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8755. time_t timeout = 2000;
  8756. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8758. SSLClient cli("localhost", PORT);
  8759. cli.enable_server_certificate_verification(false);
  8760. max_timeout_test(svr, cli, timeout, threshold);
  8761. }
  8762. #endif
  8763. class EventDispatcher {
  8764. public:
  8765. EventDispatcher() {}
  8766. void wait_event(DataSink *sink) {
  8767. unique_lock<mutex> lk(m_);
  8768. int id = id_;
  8769. cv_.wait(lk, [&] { return cid_ == id; });
  8770. sink->write(message_.data(), message_.size());
  8771. }
  8772. void send_event(const string &message) {
  8773. lock_guard<mutex> lk(m_);
  8774. cid_ = id_++;
  8775. message_ = message;
  8776. cv_.notify_all();
  8777. }
  8778. private:
  8779. mutex m_;
  8780. condition_variable cv_;
  8781. atomic_int id_{0};
  8782. atomic_int cid_{-1};
  8783. string message_;
  8784. };
  8785. TEST(ClientInThreadTest, Issue2068) {
  8786. EventDispatcher ed;
  8787. Server svr;
  8788. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8789. res.set_chunked_content_provider("text/event-stream",
  8790. [&](size_t /*offset*/, DataSink &sink) {
  8791. ed.wait_event(&sink);
  8792. return true;
  8793. });
  8794. });
  8795. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8796. svr.wait_until_ready();
  8797. thread event_thread([&] {
  8798. int id = 0;
  8799. while (svr.is_running()) {
  8800. this_thread::sleep_for(chrono::milliseconds(500));
  8801. std::stringstream ss;
  8802. ss << "data: " << id << "\n\n";
  8803. ed.send_event(ss.str());
  8804. id++;
  8805. }
  8806. });
  8807. auto se = detail::scope_exit([&] {
  8808. svr.stop();
  8809. listen_thread.join();
  8810. event_thread.join();
  8811. ASSERT_FALSE(svr.is_running());
  8812. });
  8813. {
  8814. auto client = detail::make_unique<Client>(HOST, PORT);
  8815. client->set_read_timeout(std::chrono::minutes(10));
  8816. std::atomic<bool> stop{false};
  8817. std::thread t([&] {
  8818. client->Get("/event1",
  8819. [&](const char *, size_t) -> bool { return !stop; });
  8820. });
  8821. std::this_thread::sleep_for(std::chrono::seconds(2));
  8822. stop = true;
  8823. client->stop();
  8824. client.reset();
  8825. t.join();
  8826. }
  8827. }
  8828. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8829. Server svr;
  8830. svr.Get("/", [](const Request &req, Response &res) {
  8831. EXPECT_EQ(2U, req.trailers.size());
  8832. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8833. // Denied
  8834. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8835. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8836. // Accepted
  8837. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8838. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  8839. EXPECT_TRUE(req.has_trailer("X-World"));
  8840. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  8841. res.set_content("ok", "text/plain");
  8842. });
  8843. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8844. auto se = detail::scope_exit([&] {
  8845. svr.stop();
  8846. t.join();
  8847. ASSERT_FALSE(svr.is_running());
  8848. });
  8849. svr.wait_until_ready();
  8850. const std::string req = "GET / HTTP/1.1\r\n"
  8851. "Transfer-Encoding: chunked\r\n"
  8852. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  8853. "\r\n"
  8854. "0\r\n"
  8855. "Content-Length: 10\r\n"
  8856. "Host: internal.local\r\n"
  8857. "Content-Type: malicious/content\r\n"
  8858. "Cookie: any\r\n"
  8859. "Set-Cookie: any\r\n"
  8860. "X-Forwarded-For: attacker.com\r\n"
  8861. "X-Real-Ip: 1.1.1.1\r\n"
  8862. "X-Hello: hello\r\n"
  8863. "X-World: world\r\n"
  8864. "\r\n";
  8865. std::string res;
  8866. ASSERT_TRUE(send_request(1, req, &res));
  8867. }