test.cc 314 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295
  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. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodePathTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_path(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodePathTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_path("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  252. string unescapedCharacters = "-_.!~*'()";
  253. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  254. }
  255. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  256. string reservedCharacters = ";,/?:@&=+$";
  257. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  258. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  259. }
  260. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  261. string chineseCharacters = u8"中国語";
  262. string russianCharacters = u8"дом";
  263. string brazilianCharacters = u8"óculos";
  264. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  265. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  266. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  267. "%D0%B4%D0%BE%D0%BC");
  268. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  269. }
  270. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  271. // Issue #2082 use case: encoding path component with ampersand
  272. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  273. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  274. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  275. }
  276. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  277. string unescapedCharacters = "-_.!~*'()";
  278. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  279. }
  280. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  281. string reservedCharacters = ";,/?:@&=+$#";
  282. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  283. }
  284. TEST(EncodeUriTest, TestUTF8Characters) {
  285. string chineseCharacters = u8"中国語";
  286. string russianCharacters = u8"дом";
  287. string brazilianCharacters = u8"óculos";
  288. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  289. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  290. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  291. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  292. }
  293. TEST(EncodeUriTest, TestCompleteUri) {
  294. string uri =
  295. "https://example.com/path/to/resource?query=value&param=test#fragment";
  296. EXPECT_EQ(
  297. httplib::encode_uri(uri),
  298. "https://example.com/path/to/resource?query=value&param=test#fragment");
  299. }
  300. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  301. string uri =
  302. "https://example.com/path with spaces/file name.html?q=hello world";
  303. EXPECT_EQ(httplib::encode_uri(uri),
  304. "https://example.com/path%20with%20spaces/"
  305. "file%20name.html?q=hello%20world");
  306. }
  307. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  308. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  309. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  310. }
  311. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  312. string unescapedCharacters = "-_.!~*'()";
  313. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  314. }
  315. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  316. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  317. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  318. string encodedBrazilian = "%C3%B3culos";
  319. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  320. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  321. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  322. }
  323. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  324. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  325. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  326. "Piri Tommy Villiers - on & on");
  327. }
  328. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  329. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  330. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  331. }
  332. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  333. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  334. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  335. }
  336. TEST(DecodeUriTest, TestUTF8Characters) {
  337. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  338. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  339. string encodedBrazilian = "%C3%B3culos";
  340. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  341. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  342. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  343. }
  344. TEST(DecodeUriTest, TestCompleteUri) {
  345. string encodedUri = "https://example.com/path%20with%20spaces/"
  346. "file%20name.html?q=hello%20world";
  347. EXPECT_EQ(
  348. httplib::decode_uri(encodedUri),
  349. "https://example.com/path with spaces/file name.html?q=hello world");
  350. }
  351. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  352. string original =
  353. "https://example.com/path with spaces/file name.html?q=hello world";
  354. string encoded = httplib::encode_uri(original);
  355. string decoded = httplib::decode_uri(encoded);
  356. EXPECT_EQ(decoded, original);
  357. }
  358. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  359. string original = "Piri Tommy Villiers - on & on";
  360. string encoded = httplib::encode_uri_component(original);
  361. string decoded = httplib::decode_uri_component(encoded);
  362. EXPECT_EQ(decoded, original);
  363. }
  364. TEST(TrimTests, TrimStringTests) {
  365. EXPECT_EQ("abc", detail::trim_copy("abc"));
  366. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  367. EXPECT_TRUE(detail::trim_copy("").empty());
  368. }
  369. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  370. // Simple case without quality values
  371. std::vector<std::string> result1;
  372. EXPECT_TRUE(detail::parse_accept_header(
  373. "text/html,application/json,text/plain", result1));
  374. EXPECT_EQ(result1.size(), 3U);
  375. EXPECT_EQ(result1[0], "text/html");
  376. EXPECT_EQ(result1[1], "application/json");
  377. EXPECT_EQ(result1[2], "text/plain");
  378. // With quality values
  379. std::vector<std::string> result2;
  380. EXPECT_TRUE(detail::parse_accept_header(
  381. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  382. EXPECT_EQ(result2.size(), 3U);
  383. EXPECT_EQ(result2[0], "application/json"); // highest q value
  384. EXPECT_EQ(result2[1], "text/html");
  385. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  386. }
  387. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  388. // Mixed with and without quality values
  389. std::vector<std::string> result;
  390. EXPECT_TRUE(detail::parse_accept_header(
  391. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  392. EXPECT_EQ(result.size(), 3U);
  393. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  394. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  395. EXPECT_EQ(result[2], "application/json"); // q=0.5
  396. }
  397. TEST(ParseAcceptHeaderTest, EdgeCases) {
  398. // Empty header
  399. std::vector<std::string> empty_result;
  400. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  401. EXPECT_TRUE(empty_result.empty());
  402. // Single type
  403. std::vector<std::string> single_result;
  404. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  405. EXPECT_EQ(single_result.size(), 1U);
  406. EXPECT_EQ(single_result[0], "application/json");
  407. // Wildcard types
  408. std::vector<std::string> wildcard_result;
  409. EXPECT_TRUE(detail::parse_accept_header(
  410. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  411. EXPECT_EQ(wildcard_result.size(), 3U);
  412. EXPECT_EQ(wildcard_result[0], "application/json");
  413. EXPECT_EQ(wildcard_result[1], "text/*");
  414. EXPECT_EQ(wildcard_result[2], "*/*");
  415. }
  416. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  417. // Common browser Accept header
  418. std::vector<std::string> browser_result;
  419. EXPECT_TRUE(
  420. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  421. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  422. browser_result));
  423. EXPECT_EQ(browser_result.size(), 6U);
  424. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  425. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  426. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  427. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  428. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  429. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  430. // API client header
  431. std::vector<std::string> api_result;
  432. EXPECT_TRUE(detail::parse_accept_header(
  433. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  434. api_result));
  435. EXPECT_EQ(api_result.size(), 3U);
  436. EXPECT_EQ(api_result[0], "application/json");
  437. EXPECT_EQ(api_result[1], "application/xml");
  438. EXPECT_EQ(api_result[2], "text/plain");
  439. }
  440. TEST(ParseAcceptHeaderTest, SpecialCases) {
  441. // Quality value with 3 decimal places
  442. std::vector<std::string> decimal_result;
  443. EXPECT_TRUE(detail::parse_accept_header(
  444. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  445. EXPECT_EQ(decimal_result.size(), 2U);
  446. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  447. EXPECT_EQ(decimal_result[1], "text/html");
  448. // Zero quality (should still be included but with lowest priority)
  449. std::vector<std::string> zero_q_result;
  450. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  451. zero_q_result));
  452. EXPECT_EQ(zero_q_result.size(), 2U);
  453. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  454. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  455. // No spaces around commas
  456. std::vector<std::string> no_space_result;
  457. EXPECT_TRUE(detail::parse_accept_header(
  458. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  459. no_space_result));
  460. EXPECT_EQ(no_space_result.size(), 3U);
  461. EXPECT_EQ(no_space_result[0], "text/html");
  462. EXPECT_EQ(no_space_result[1], "application/json");
  463. EXPECT_EQ(no_space_result[2], "text/plain");
  464. }
  465. TEST(ParseAcceptHeaderTest, InvalidCases) {
  466. std::vector<std::string> result;
  467. // Invalid quality value (> 1.0)
  468. EXPECT_FALSE(
  469. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  470. // Invalid quality value (< 0.0)
  471. EXPECT_FALSE(
  472. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  473. // Invalid quality value (not a number)
  474. EXPECT_FALSE(detail::parse_accept_header(
  475. "text/html;q=invalid,application/json", result));
  476. // Empty quality value
  477. EXPECT_FALSE(
  478. detail::parse_accept_header("text/html;q=,application/json", result));
  479. // Invalid media type format (no slash and not wildcard)
  480. EXPECT_FALSE(
  481. detail::parse_accept_header("invalidtype,application/json", result));
  482. // Empty media type
  483. result.clear();
  484. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  485. // Only commas
  486. result.clear();
  487. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  488. // Valid cases should still work
  489. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  490. EXPECT_EQ(result.size(), 1U);
  491. EXPECT_EQ(result[0], "*/*");
  492. EXPECT_TRUE(detail::parse_accept_header("*", result));
  493. EXPECT_EQ(result.size(), 1U);
  494. EXPECT_EQ(result[0], "*");
  495. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  496. EXPECT_EQ(result.size(), 1U);
  497. EXPECT_EQ(result[0], "text/*");
  498. }
  499. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  500. Server svr;
  501. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  502. EXPECT_EQ(req.accept_content_types.size(), 3U);
  503. EXPECT_EQ(req.accept_content_types[0], "application/json");
  504. EXPECT_EQ(req.accept_content_types[1], "text/html");
  505. EXPECT_EQ(req.accept_content_types[2], "*/*");
  506. res.set_content("ok", "text/plain");
  507. });
  508. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  509. EXPECT_TRUE(false);
  510. res.set_content("bad request", "text/plain");
  511. });
  512. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  513. auto se = detail::scope_exit([&] {
  514. svr.stop();
  515. listen_thread.join();
  516. ASSERT_FALSE(svr.is_running());
  517. });
  518. svr.wait_until_ready();
  519. Client cli("localhost", PORT);
  520. {
  521. auto res =
  522. cli.Get("/accept_ok",
  523. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  524. ASSERT_TRUE(res);
  525. EXPECT_EQ(StatusCode::OK_200, res->status);
  526. }
  527. {
  528. auto res = cli.Get("/accept_bad_request",
  529. {{"Accept", "text/html;q=abc,application/json"}});
  530. ASSERT_TRUE(res);
  531. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  532. }
  533. }
  534. TEST(DivideTest, DivideStringTests) {
  535. auto divide = [](const std::string &str, char d) {
  536. std::string lhs;
  537. std::string rhs;
  538. detail::divide(str, d,
  539. [&](const char *lhs_data, std::size_t lhs_size,
  540. const char *rhs_data, std::size_t rhs_size) {
  541. lhs.assign(lhs_data, lhs_size);
  542. rhs.assign(rhs_data, rhs_size);
  543. });
  544. return std::make_pair(std::move(lhs), std::move(rhs));
  545. };
  546. {
  547. const auto res = divide("", '=');
  548. EXPECT_EQ(res.first, "");
  549. EXPECT_EQ(res.second, "");
  550. }
  551. {
  552. const auto res = divide("=", '=');
  553. EXPECT_EQ(res.first, "");
  554. EXPECT_EQ(res.second, "");
  555. }
  556. {
  557. const auto res = divide(" ", '=');
  558. EXPECT_EQ(res.first, " ");
  559. EXPECT_EQ(res.second, "");
  560. }
  561. {
  562. const auto res = divide("a", '=');
  563. EXPECT_EQ(res.first, "a");
  564. EXPECT_EQ(res.second, "");
  565. }
  566. {
  567. const auto res = divide("a=", '=');
  568. EXPECT_EQ(res.first, "a");
  569. EXPECT_EQ(res.second, "");
  570. }
  571. {
  572. const auto res = divide("=b", '=');
  573. EXPECT_EQ(res.first, "");
  574. EXPECT_EQ(res.second, "b");
  575. }
  576. {
  577. const auto res = divide("a=b", '=');
  578. EXPECT_EQ(res.first, "a");
  579. EXPECT_EQ(res.second, "b");
  580. }
  581. {
  582. const auto res = divide("a=b=", '=');
  583. EXPECT_EQ(res.first, "a");
  584. EXPECT_EQ(res.second, "b=");
  585. }
  586. {
  587. const auto res = divide("a=b=c", '=');
  588. EXPECT_EQ(res.first, "a");
  589. EXPECT_EQ(res.second, "b=c");
  590. }
  591. }
  592. TEST(SplitTest, ParseQueryString) {
  593. string s = "key1=val1&key2=val2&key3=val3";
  594. Params dic;
  595. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  596. [&](const char *b, const char *e) {
  597. string key, val;
  598. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  599. if (key.empty()) {
  600. key.assign(b2, e2);
  601. } else {
  602. val.assign(b2, e2);
  603. }
  604. });
  605. dic.emplace(key, val);
  606. });
  607. EXPECT_EQ("val1", dic.find("key1")->second);
  608. EXPECT_EQ("val2", dic.find("key2")->second);
  609. EXPECT_EQ("val3", dic.find("key3")->second);
  610. }
  611. TEST(SplitTest, ParseInvalidQueryTests) {
  612. {
  613. string s = " ";
  614. Params dict;
  615. detail::parse_query_text(s, dict);
  616. EXPECT_TRUE(dict.empty());
  617. }
  618. {
  619. string s = " = =";
  620. Params dict;
  621. detail::parse_query_text(s, dict);
  622. EXPECT_TRUE(dict.empty());
  623. }
  624. }
  625. TEST(ParseQueryTest, ParseQueryString) {
  626. {
  627. std::string s = "key1=val1&key2=val2&key3=val3";
  628. Params dic;
  629. detail::parse_query_text(s, dic);
  630. EXPECT_EQ("val1", dic.find("key1")->second);
  631. EXPECT_EQ("val2", dic.find("key2")->second);
  632. EXPECT_EQ("val3", dic.find("key3")->second);
  633. }
  634. {
  635. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  636. Params dic;
  637. detail::parse_query_text(s, dic);
  638. EXPECT_EQ("", dic.find("key1")->second);
  639. EXPECT_EQ("val1", dic.find("key2")->second);
  640. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  641. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  642. }
  643. }
  644. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  645. Params dic;
  646. EXPECT_EQ(detail::params_to_query_str(dic), "");
  647. dic.emplace("key1", "val1");
  648. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  649. dic.emplace("key2", "val2");
  650. dic.emplace("key3", "val3");
  651. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  652. }
  653. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  654. string content_type = "multipart/form-data; boundary=something";
  655. string boundary;
  656. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  657. EXPECT_TRUE(ret);
  658. EXPECT_EQ(boundary, "something");
  659. }
  660. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  661. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  662. string boundary;
  663. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  664. EXPECT_TRUE(ret);
  665. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  666. }
  667. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  668. string content_type =
  669. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  670. string boundary;
  671. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  672. EXPECT_TRUE(ret);
  673. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  674. }
  675. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  676. string content_type =
  677. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  678. string boundary;
  679. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  680. EXPECT_TRUE(ret);
  681. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  682. }
  683. TEST(GetHeaderValueTest, DefaultValue) {
  684. Headers headers = {{"Dummy", "Dummy"}};
  685. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  686. EXPECT_STREQ("text/plain", val);
  687. }
  688. TEST(GetHeaderValueTest, DefaultValueInt) {
  689. Headers headers = {{"Dummy", "Dummy"}};
  690. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  691. EXPECT_EQ(100ull, val);
  692. }
  693. TEST(GetHeaderValueTest, RegularValue) {
  694. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  695. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  696. EXPECT_STREQ("text/html", val);
  697. }
  698. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  699. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  700. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  701. EXPECT_STREQ("text/html", val);
  702. }
  703. TEST(GetHeaderValueTest, SetContent) {
  704. Response res;
  705. res.set_content("html", "text/html");
  706. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  707. res.set_content("text", "text/plain");
  708. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  709. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  710. }
  711. TEST(GetHeaderValueTest, RegularValueInt) {
  712. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  713. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  714. EXPECT_EQ(100ull, val);
  715. }
  716. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  717. Headers headers = {{"Content-Length", "x"}};
  718. auto is_invalid_value = false;
  719. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  720. is_invalid_value);
  721. EXPECT_EQ(0ull, val);
  722. EXPECT_TRUE(is_invalid_value);
  723. }
  724. TEST(GetHeaderValueTest, Range) {
  725. {
  726. Headers headers = {make_range_header({{1, -1}})};
  727. auto val = detail::get_header_value(headers, "Range", 0, 0);
  728. EXPECT_STREQ("bytes=1-", val);
  729. }
  730. {
  731. Headers headers = {make_range_header({{-1, 1}})};
  732. auto val = detail::get_header_value(headers, "Range", 0, 0);
  733. EXPECT_STREQ("bytes=-1", val);
  734. }
  735. {
  736. Headers headers = {make_range_header({{1, 10}})};
  737. auto val = detail::get_header_value(headers, "Range", 0, 0);
  738. EXPECT_STREQ("bytes=1-10", val);
  739. }
  740. {
  741. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  742. auto val = detail::get_header_value(headers, "Range", 0, 0);
  743. EXPECT_STREQ("bytes=1-10, 100-", val);
  744. }
  745. {
  746. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  747. auto val = detail::get_header_value(headers, "Range", 0, 0);
  748. EXPECT_STREQ("bytes=1-10, 100-200", val);
  749. }
  750. {
  751. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  752. auto val = detail::get_header_value(headers, "Range", 0, 0);
  753. EXPECT_STREQ("bytes=0-0, -1", val);
  754. }
  755. }
  756. TEST(ParseHeaderValueTest, Range) {
  757. {
  758. Ranges ranges;
  759. auto ret = detail::parse_range_header("bytes=1-", ranges);
  760. EXPECT_TRUE(ret);
  761. EXPECT_EQ(1u, ranges.size());
  762. EXPECT_EQ(1u, ranges[0].first);
  763. EXPECT_EQ(-1, ranges[0].second);
  764. }
  765. {
  766. Ranges ranges;
  767. auto ret = detail::parse_range_header("bytes=-1", ranges);
  768. EXPECT_TRUE(ret);
  769. EXPECT_EQ(1u, ranges.size());
  770. EXPECT_EQ(-1, ranges[0].first);
  771. EXPECT_EQ(1u, ranges[0].second);
  772. }
  773. {
  774. Ranges ranges;
  775. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(1u, ranges.size());
  778. EXPECT_EQ(1u, ranges[0].first);
  779. EXPECT_EQ(10u, ranges[0].second);
  780. }
  781. {
  782. Ranges ranges;
  783. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  784. EXPECT_FALSE(ret);
  785. }
  786. {
  787. Ranges ranges;
  788. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  789. EXPECT_TRUE(ret);
  790. EXPECT_EQ(2u, ranges.size());
  791. EXPECT_EQ(1u, ranges[0].first);
  792. EXPECT_EQ(10u, ranges[0].second);
  793. EXPECT_EQ(100u, ranges[1].first);
  794. EXPECT_EQ(-1, ranges[1].second);
  795. }
  796. {
  797. Ranges ranges;
  798. auto ret =
  799. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(3u, ranges.size());
  802. EXPECT_EQ(1u, ranges[0].first);
  803. EXPECT_EQ(10u, ranges[0].second);
  804. EXPECT_EQ(100u, ranges[1].first);
  805. EXPECT_EQ(200u, ranges[1].second);
  806. EXPECT_EQ(300u, ranges[2].first);
  807. EXPECT_EQ(400u, ranges[2].second);
  808. }
  809. {
  810. Ranges ranges;
  811. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  812. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  813. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  819. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  820. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", 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_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  824. EXPECT_TRUE(ranges.empty());
  825. }
  826. }
  827. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  828. Request req;
  829. req.set_header("Accept-Encoding", "gzip");
  830. Response res;
  831. res.set_header("Content-Type", "text/plain");
  832. auto ret = detail::encoding_type(req, res);
  833. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  834. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  835. #else
  836. EXPECT_TRUE(ret == detail::EncodingType::None);
  837. #endif
  838. }
  839. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  840. Request req;
  841. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  842. Response res;
  843. res.set_header("Content-Type", "text/plain");
  844. auto ret = detail::encoding_type(req, res);
  845. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  846. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  847. #elif CPPHTTPLIB_ZLIB_SUPPORT
  848. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  849. #elif CPPHTTPLIB_ZSTD_SUPPORT
  850. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  851. #else
  852. EXPECT_TRUE(ret == detail::EncodingType::None);
  853. #endif
  854. }
  855. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  856. Request req;
  857. req.set_header("Accept-Encoding",
  858. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  859. Response res;
  860. res.set_header("Content-Type", "text/plain");
  861. auto ret = detail::encoding_type(req, res);
  862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  863. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  864. #elif CPPHTTPLIB_ZLIB_SUPPORT
  865. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  866. #elif CPPHTTPLIB_ZSTD_SUPPORT
  867. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  868. #else
  869. EXPECT_TRUE(ret == detail::EncodingType::None);
  870. #endif
  871. }
  872. TEST(BufferStreamTest, read) {
  873. detail::BufferStream strm1;
  874. Stream &strm = strm1;
  875. EXPECT_EQ(5, strm.write("hello"));
  876. char buf[512];
  877. EXPECT_EQ(2, strm.read(buf, 2));
  878. EXPECT_EQ('h', buf[0]);
  879. EXPECT_EQ('e', buf[1]);
  880. EXPECT_EQ(2, strm.read(buf, 2));
  881. EXPECT_EQ('l', buf[0]);
  882. EXPECT_EQ('l', buf[1]);
  883. EXPECT_EQ(1, strm.read(buf, 1));
  884. EXPECT_EQ('o', buf[0]);
  885. EXPECT_EQ(0, strm.read(buf, 1));
  886. }
  887. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  888. auto host = "www.httpwatch.com";
  889. auto ip = hosted_at(host);
  890. EXPECT_EQ("23.96.13.243", ip);
  891. std::vector<std::string> addrs;
  892. hosted_at(host, addrs);
  893. EXPECT_EQ(1u, addrs.size());
  894. }
  895. #if 0 // It depends on each test environment...
  896. TEST(HostnameToIPConversionTest, YouTube_Online) {
  897. auto host = "www.youtube.com";
  898. std::vector<std::string> addrs;
  899. hosted_at(host, addrs);
  900. EXPECT_EQ(20u, addrs.size());
  901. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  902. EXPECT_TRUE(it != addrs.end());
  903. }
  904. #endif
  905. class ChunkedEncodingTest : public ::testing::Test {
  906. protected:
  907. ChunkedEncodingTest()
  908. : cli_(HOST, PORT)
  909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  910. ,
  911. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  912. #endif
  913. {
  914. cli_.set_connection_timeout(2);
  915. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  916. cli_.enable_server_certificate_verification(false);
  917. #endif
  918. }
  919. virtual void SetUp() {
  920. read_file("./image.jpg", image_data_);
  921. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  922. res.set_content("Hello World!", "text/plain");
  923. });
  924. svr_.Get(
  925. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  926. res.set_chunked_content_provider(
  927. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  928. size_t remaining = image_data_.size() - offset;
  929. if (remaining == 0) {
  930. sink.done();
  931. } else {
  932. constexpr size_t CHUNK_SIZE = 1024;
  933. size_t send_size = std::min(CHUNK_SIZE, remaining);
  934. sink.write(&image_data_[offset], send_size);
  935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  936. }
  937. return true;
  938. });
  939. });
  940. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  941. svr_.wait_until_ready();
  942. }
  943. virtual void TearDown() {
  944. svr_.stop();
  945. if (!request_threads_.empty()) {
  946. std::this_thread::sleep_for(std::chrono::seconds(1));
  947. for (auto &t : request_threads_) {
  948. t.join();
  949. }
  950. }
  951. t_.join();
  952. }
  953. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  954. SSLClient cli_;
  955. SSLServer svr_;
  956. #else
  957. Client cli_;
  958. Server svr_;
  959. #endif
  960. thread t_;
  961. std::vector<thread> request_threads_;
  962. std::string image_data_;
  963. };
  964. TEST_F(ChunkedEncodingTest, NormalGet) {
  965. auto res = cli_.Get("/chunked");
  966. ASSERT_TRUE(res);
  967. std::string out;
  968. read_file("./image.jpg", out);
  969. EXPECT_EQ(StatusCode::OK_200, res->status);
  970. EXPECT_EQ(out, res->body);
  971. }
  972. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  973. std::string body;
  974. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  975. body.append(data, data_length);
  976. return true;
  977. });
  978. ASSERT_TRUE(res);
  979. std::string out;
  980. read_file("./image.jpg", out);
  981. EXPECT_EQ(StatusCode::OK_200, res->status);
  982. EXPECT_EQ(out, body);
  983. }
  984. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  985. std::string body;
  986. auto res = cli_.Get(
  987. "/chunked",
  988. [&](const Response &response) {
  989. EXPECT_EQ(StatusCode::OK_200, response.status);
  990. return true;
  991. },
  992. [&](const char *data, size_t data_length) {
  993. body.append(data, data_length);
  994. return true;
  995. });
  996. ASSERT_TRUE(res);
  997. std::string out;
  998. read_file("./image.jpg", out);
  999. EXPECT_EQ(StatusCode::OK_200, res->status);
  1000. EXPECT_EQ(out, body);
  1001. }
  1002. TEST(RangeTest, FromHTTPBin_Online) {
  1003. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1004. auto host = "httpbin.org";
  1005. auto path = std::string{"/range/32"};
  1006. #else
  1007. auto host = "nghttp2.org";
  1008. auto path = std::string{"/httpbin/range/32"};
  1009. #endif
  1010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1011. auto port = 443;
  1012. SSLClient cli(host, port);
  1013. #else
  1014. auto port = 80;
  1015. Client cli(host, port);
  1016. #endif
  1017. cli.set_connection_timeout(5);
  1018. {
  1019. auto res = cli.Get(path);
  1020. ASSERT_TRUE(res);
  1021. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1022. EXPECT_EQ(StatusCode::OK_200, res->status);
  1023. }
  1024. {
  1025. Headers headers = {make_range_header({{1, -1}})};
  1026. auto res = cli.Get(path, headers);
  1027. ASSERT_TRUE(res);
  1028. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1030. }
  1031. {
  1032. Headers headers = {make_range_header({{1, 10}})};
  1033. auto res = cli.Get(path, headers);
  1034. ASSERT_TRUE(res);
  1035. EXPECT_EQ("bcdefghijk", res->body);
  1036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1037. }
  1038. {
  1039. Headers headers = {make_range_header({{0, 31}})};
  1040. auto res = cli.Get(path, headers);
  1041. ASSERT_TRUE(res);
  1042. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1043. EXPECT_EQ(StatusCode::OK_200, res->status);
  1044. }
  1045. {
  1046. Headers headers = {make_range_header({{0, -1}})};
  1047. auto res = cli.Get(path, headers);
  1048. ASSERT_TRUE(res);
  1049. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1050. EXPECT_EQ(StatusCode::OK_200, res->status);
  1051. }
  1052. {
  1053. Headers headers = {make_range_header({{0, 32}})};
  1054. auto res = cli.Get(path, headers);
  1055. ASSERT_TRUE(res);
  1056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1057. }
  1058. }
  1059. TEST(ConnectionErrorTest, InvalidHost) {
  1060. auto host = "-abcde.com";
  1061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1062. auto port = 443;
  1063. SSLClient cli(host, port);
  1064. #else
  1065. auto port = 80;
  1066. Client cli(host, port);
  1067. #endif
  1068. cli.set_connection_timeout(std::chrono::seconds(2));
  1069. auto res = cli.Get("/");
  1070. ASSERT_TRUE(!res);
  1071. EXPECT_EQ(Error::Connection, res.error());
  1072. }
  1073. TEST(ConnectionErrorTest, InvalidHost2) {
  1074. auto host = "httpbin.org/";
  1075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1076. SSLClient cli(host);
  1077. #else
  1078. Client cli(host);
  1079. #endif
  1080. cli.set_connection_timeout(std::chrono::seconds(2));
  1081. auto res = cli.Get("/");
  1082. ASSERT_TRUE(!res);
  1083. EXPECT_EQ(Error::Connection, res.error());
  1084. }
  1085. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1086. auto host = "httpbin.org/";
  1087. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1088. SSLClient cli(host);
  1089. #else
  1090. Client cli(host);
  1091. #endif
  1092. cli.set_connection_timeout(std::chrono::seconds(2));
  1093. auto res = cli.Get("/");
  1094. ASSERT_TRUE(!res);
  1095. stringstream s;
  1096. s << "error code: " << res.error();
  1097. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1098. }
  1099. TEST(ConnectionErrorTest, InvalidPort) {
  1100. auto host = "localhost";
  1101. auto port = 44380;
  1102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1103. SSLClient cli(host, port);
  1104. #else
  1105. Client cli(host, port);
  1106. #endif
  1107. cli.set_connection_timeout(std::chrono::seconds(2));
  1108. auto res = cli.Get("/");
  1109. ASSERT_TRUE(!res);
  1110. EXPECT_TRUE(Error::Connection == res.error() ||
  1111. Error::ConnectionTimeout == res.error());
  1112. }
  1113. TEST(ConnectionErrorTest, Timeout_Online) {
  1114. auto host = "google.com";
  1115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1116. auto port = 44380;
  1117. SSLClient cli(host, port);
  1118. #else
  1119. auto port = 8080;
  1120. Client cli(host, port);
  1121. #endif
  1122. cli.set_connection_timeout(std::chrono::seconds(2));
  1123. // only probe one address type so that the error reason
  1124. // correlates to the timed-out IPv4, not the unsupported
  1125. // IPv6 connection attempt
  1126. cli.set_address_family(AF_INET);
  1127. auto res = cli.Get("/");
  1128. ASSERT_TRUE(!res);
  1129. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1130. }
  1131. TEST(CancelTest, NoCancel_Online) {
  1132. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1133. auto host = "httpbin.org";
  1134. auto path = std::string{"/range/32"};
  1135. #else
  1136. auto host = "nghttp2.org";
  1137. auto path = std::string{"/httpbin/range/32"};
  1138. #endif
  1139. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1140. auto port = 443;
  1141. SSLClient cli(host, port);
  1142. #else
  1143. auto port = 80;
  1144. Client cli(host, port);
  1145. #endif
  1146. cli.set_connection_timeout(std::chrono::seconds(5));
  1147. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1148. ASSERT_TRUE(res);
  1149. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. }
  1152. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1153. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1154. auto host = "httpbin.org";
  1155. auto path = std::string{"/range/32"};
  1156. #else
  1157. auto host = "nghttp2.org";
  1158. auto path = std::string{"/httpbin/range/32"};
  1159. #endif
  1160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1161. auto port = 443;
  1162. SSLClient cli(host, port);
  1163. #else
  1164. auto port = 80;
  1165. Client cli(host, port);
  1166. #endif
  1167. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1168. cli.set_connection_timeout(std::chrono::seconds(5));
  1169. ASSERT_TRUE(!res);
  1170. EXPECT_EQ(Error::Canceled, res.error());
  1171. }
  1172. TEST(CancelTest, WithCancelLargePayload_Online) {
  1173. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1174. auto host = "httpbin.org";
  1175. auto path = std::string{"/range/65536"};
  1176. #else
  1177. auto host = "nghttp2.org";
  1178. auto path = std::string{"/httpbin/range/65536"};
  1179. #endif
  1180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1181. auto port = 443;
  1182. SSLClient cli(host, port);
  1183. #else
  1184. auto port = 80;
  1185. Client cli(host, port);
  1186. #endif
  1187. cli.set_connection_timeout(std::chrono::seconds(5));
  1188. uint32_t count = 0;
  1189. auto res =
  1190. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1191. ASSERT_TRUE(!res);
  1192. EXPECT_EQ(Error::Canceled, res.error());
  1193. }
  1194. TEST(CancelTest, NoCancelPost) {
  1195. Server svr;
  1196. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1197. res.set_content("Hello World!", "text/plain");
  1198. });
  1199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1200. auto se = detail::scope_exit([&] {
  1201. svr.stop();
  1202. thread.join();
  1203. ASSERT_FALSE(svr.is_running());
  1204. });
  1205. svr.wait_until_ready();
  1206. Client cli(HOST, PORT);
  1207. cli.set_connection_timeout(std::chrono::seconds(5));
  1208. auto res =
  1209. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1210. "application/json", [](uint64_t, uint64_t) { return true; });
  1211. ASSERT_TRUE(res);
  1212. EXPECT_EQ("Hello World!", res->body);
  1213. EXPECT_EQ(StatusCode::OK_200, res->status);
  1214. }
  1215. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1216. Server svr;
  1217. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1218. res.set_content("Hello World!", "text/plain");
  1219. });
  1220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1221. auto se = detail::scope_exit([&] {
  1222. svr.stop();
  1223. thread.join();
  1224. ASSERT_FALSE(svr.is_running());
  1225. });
  1226. svr.wait_until_ready();
  1227. Client cli(HOST, PORT);
  1228. cli.set_connection_timeout(std::chrono::seconds(5));
  1229. auto res =
  1230. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1231. "application/json", [](uint64_t, uint64_t) { return false; });
  1232. ASSERT_TRUE(!res);
  1233. EXPECT_EQ(Error::Canceled, res.error());
  1234. }
  1235. TEST(CancelTest, WithCancelLargePayloadPost) {
  1236. Server svr;
  1237. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1238. res.set_content(LARGE_DATA, "text/plain");
  1239. });
  1240. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. thread.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. Client cli(HOST, PORT);
  1248. cli.set_connection_timeout(std::chrono::seconds(5));
  1249. auto res =
  1250. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1251. "application/json", [](uint64_t, uint64_t) { return false; });
  1252. ASSERT_TRUE(!res);
  1253. EXPECT_EQ(Error::Canceled, res.error());
  1254. }
  1255. TEST(CancelTest, NoCancelPut) {
  1256. Server svr;
  1257. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1258. res.set_content("Hello World!", "text/plain");
  1259. });
  1260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1261. auto se = detail::scope_exit([&] {
  1262. svr.stop();
  1263. thread.join();
  1264. ASSERT_FALSE(svr.is_running());
  1265. });
  1266. svr.wait_until_ready();
  1267. Client cli(HOST, PORT);
  1268. cli.set_connection_timeout(std::chrono::seconds(5));
  1269. auto res =
  1270. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1271. "application/json", [](uint64_t, uint64_t) { return true; });
  1272. ASSERT_TRUE(res);
  1273. EXPECT_EQ("Hello World!", res->body);
  1274. EXPECT_EQ(StatusCode::OK_200, res->status);
  1275. }
  1276. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1277. Server svr;
  1278. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1279. res.set_content("Hello World!", "text/plain");
  1280. });
  1281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1282. auto se = detail::scope_exit([&] {
  1283. svr.stop();
  1284. thread.join();
  1285. ASSERT_FALSE(svr.is_running());
  1286. });
  1287. svr.wait_until_ready();
  1288. Client cli(HOST, PORT);
  1289. cli.set_connection_timeout(std::chrono::seconds(5));
  1290. auto res =
  1291. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1292. "application/json", [](uint64_t, uint64_t) { return false; });
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_EQ(Error::Canceled, res.error());
  1295. }
  1296. TEST(CancelTest, WithCancelLargePayloadPut) {
  1297. Server svr;
  1298. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1299. res.set_content(LARGE_DATA, "text/plain");
  1300. });
  1301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1302. auto se = detail::scope_exit([&] {
  1303. svr.stop();
  1304. thread.join();
  1305. ASSERT_FALSE(svr.is_running());
  1306. });
  1307. svr.wait_until_ready();
  1308. Client cli(HOST, PORT);
  1309. cli.set_connection_timeout(std::chrono::seconds(5));
  1310. auto res =
  1311. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1312. "application/json", [](uint64_t, uint64_t) { return false; });
  1313. ASSERT_TRUE(!res);
  1314. EXPECT_EQ(Error::Canceled, res.error());
  1315. }
  1316. TEST(CancelTest, NoCancelPatch) {
  1317. Server svr;
  1318. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return true; });
  1333. ASSERT_TRUE(res);
  1334. EXPECT_EQ("Hello World!", res->body);
  1335. EXPECT_EQ(StatusCode::OK_200, res->status);
  1336. }
  1337. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1338. Server svr;
  1339. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1340. res.set_content("Hello World!", "text/plain");
  1341. });
  1342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1343. auto se = detail::scope_exit([&] {
  1344. svr.stop();
  1345. thread.join();
  1346. ASSERT_FALSE(svr.is_running());
  1347. });
  1348. svr.wait_until_ready();
  1349. Client cli(HOST, PORT);
  1350. cli.set_connection_timeout(std::chrono::seconds(5));
  1351. auto res =
  1352. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1353. "application/json", [](uint64_t, uint64_t) { return false; });
  1354. ASSERT_TRUE(!res);
  1355. EXPECT_EQ(Error::Canceled, res.error());
  1356. }
  1357. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1358. Server svr;
  1359. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1360. res.set_content(LARGE_DATA, "text/plain");
  1361. });
  1362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1363. auto se = detail::scope_exit([&] {
  1364. svr.stop();
  1365. thread.join();
  1366. ASSERT_FALSE(svr.is_running());
  1367. });
  1368. svr.wait_until_ready();
  1369. Client cli(HOST, PORT);
  1370. cli.set_connection_timeout(std::chrono::seconds(5));
  1371. auto res =
  1372. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1373. "application/json", [](uint64_t, uint64_t) { return false; });
  1374. ASSERT_TRUE(!res);
  1375. EXPECT_EQ(Error::Canceled, res.error());
  1376. }
  1377. TEST(CancelTest, NoCancelDelete) {
  1378. Server svr;
  1379. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return true; });
  1394. ASSERT_TRUE(res);
  1395. EXPECT_EQ("Hello World!", res->body);
  1396. EXPECT_EQ(StatusCode::OK_200, res->status);
  1397. }
  1398. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1399. Server svr;
  1400. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1401. res.set_content("Hello World!", "text/plain");
  1402. });
  1403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. thread.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. Client cli(HOST, PORT);
  1411. cli.set_connection_timeout(std::chrono::seconds(5));
  1412. auto res =
  1413. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1414. "application/json", [](uint64_t, uint64_t) { return false; });
  1415. ASSERT_TRUE(!res);
  1416. EXPECT_EQ(Error::Canceled, res.error());
  1417. }
  1418. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1419. Server svr;
  1420. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1421. res.set_content(LARGE_DATA, "text/plain");
  1422. });
  1423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1424. auto se = detail::scope_exit([&] {
  1425. svr.stop();
  1426. thread.join();
  1427. ASSERT_FALSE(svr.is_running());
  1428. });
  1429. svr.wait_until_ready();
  1430. Client cli(HOST, PORT);
  1431. cli.set_connection_timeout(std::chrono::seconds(5));
  1432. auto res =
  1433. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1434. "application/json", [](uint64_t, uint64_t) { return false; });
  1435. ASSERT_TRUE(!res);
  1436. EXPECT_EQ(Error::Canceled, res.error());
  1437. }
  1438. static std::string remove_whitespace(const std::string &input) {
  1439. std::string output;
  1440. output.reserve(input.size());
  1441. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1442. [](unsigned char c) { return !std::isspace(c); });
  1443. return output;
  1444. }
  1445. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1446. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1447. auto host = "httpbin.org";
  1448. auto path = std::string{"/basic-auth/hello/world"};
  1449. #else
  1450. auto host = "nghttp2.org";
  1451. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1452. #endif
  1453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1454. auto port = 443;
  1455. SSLClient cli(host, port);
  1456. #else
  1457. auto port = 80;
  1458. Client cli(host, port);
  1459. #endif
  1460. {
  1461. auto res = cli.Get(path);
  1462. ASSERT_TRUE(res);
  1463. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1464. }
  1465. {
  1466. auto res =
  1467. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1468. ASSERT_TRUE(res);
  1469. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1470. remove_whitespace(res->body));
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. {
  1474. cli.set_basic_auth("hello", "world");
  1475. auto res = cli.Get(path);
  1476. ASSERT_TRUE(res);
  1477. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1478. remove_whitespace(res->body));
  1479. EXPECT_EQ(StatusCode::OK_200, res->status);
  1480. }
  1481. {
  1482. cli.set_basic_auth("hello", "bad");
  1483. auto res = cli.Get(path);
  1484. ASSERT_TRUE(res);
  1485. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1486. }
  1487. {
  1488. cli.set_basic_auth("bad", "world");
  1489. auto res = cli.Get(path);
  1490. ASSERT_TRUE(res);
  1491. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1492. }
  1493. }
  1494. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1495. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1496. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1497. auto host = "httpbin.org";
  1498. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1499. auto paths = std::vector<std::string>{
  1500. "/digest-auth/auth/hello/world/MD5",
  1501. "/digest-auth/auth/hello/world/SHA-256",
  1502. "/digest-auth/auth/hello/world/SHA-512",
  1503. "/digest-auth/auth-int/hello/world/MD5",
  1504. };
  1505. #else
  1506. auto host = "nghttp2.org";
  1507. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1508. auto paths = std::vector<std::string>{
  1509. "/httpbin/digest-auth/auth/hello/world/MD5",
  1510. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1511. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1512. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1513. };
  1514. #endif
  1515. auto port = 443;
  1516. SSLClient cli(host, port);
  1517. {
  1518. auto res = cli.Get(unauth_path);
  1519. ASSERT_TRUE(res);
  1520. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1521. }
  1522. {
  1523. cli.set_digest_auth("hello", "world");
  1524. for (const auto &path : paths) {
  1525. auto res = cli.Get(path.c_str());
  1526. ASSERT_TRUE(res);
  1527. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1528. remove_whitespace(res->body));
  1529. EXPECT_EQ(StatusCode::OK_200, res->status);
  1530. }
  1531. cli.set_digest_auth("hello", "bad");
  1532. for (const auto &path : paths) {
  1533. auto res = cli.Get(path.c_str());
  1534. ASSERT_TRUE(res);
  1535. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1536. }
  1537. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1538. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1539. // cli.set_digest_auth("bad", "world");
  1540. // for (const auto& path : paths) {
  1541. // auto res = cli.Get(path.c_str());
  1542. // ASSERT_TRUE(res);
  1543. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1544. // }
  1545. }
  1546. }
  1547. #endif
  1548. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1549. auto host = "google.com";
  1550. auto another_host = "example.com";
  1551. auto wrong_ip = "0.0.0.0";
  1552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1553. SSLClient cli(host);
  1554. #else
  1555. Client cli(host);
  1556. #endif
  1557. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1558. auto res = cli.Get("/");
  1559. ASSERT_TRUE(res);
  1560. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1561. }
  1562. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1563. auto host = "google.com";
  1564. auto wrong_ip = "0.0.0.0";
  1565. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1566. SSLClient cli(host);
  1567. #else
  1568. Client cli(host);
  1569. #endif
  1570. cli.set_hostname_addr_map({{host, wrong_ip}});
  1571. auto res = cli.Get("/");
  1572. ASSERT_TRUE(!res);
  1573. EXPECT_EQ(Error::Connection, res.error());
  1574. }
  1575. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1576. auto host = "nghttp2.org";
  1577. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1578. SSLClient cli(host);
  1579. #else
  1580. Client cli(host);
  1581. #endif
  1582. cli.set_follow_location(true);
  1583. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ(StatusCode::OK_200, res->status);
  1586. }
  1587. TEST(RedirectTest, Redirect_Online) {
  1588. auto host = "nghttp2.org";
  1589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1590. SSLClient cli(host);
  1591. #else
  1592. Client cli(host);
  1593. #endif
  1594. cli.set_follow_location(true);
  1595. auto res = cli.Get("/httpbin/redirect/3");
  1596. ASSERT_TRUE(res);
  1597. EXPECT_EQ(StatusCode::OK_200, res->status);
  1598. }
  1599. TEST(RelativeRedirectTest, Redirect_Online) {
  1600. auto host = "nghttp2.org";
  1601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1602. SSLClient cli(host);
  1603. #else
  1604. Client cli(host);
  1605. #endif
  1606. cli.set_follow_location(true);
  1607. auto res = cli.Get("/httpbin/relative-redirect/3");
  1608. ASSERT_TRUE(res);
  1609. EXPECT_EQ(StatusCode::OK_200, res->status);
  1610. }
  1611. TEST(TooManyRedirectTest, Redirect_Online) {
  1612. auto host = "nghttp2.org";
  1613. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1614. SSLClient cli(host);
  1615. #else
  1616. Client cli(host);
  1617. #endif
  1618. cli.set_follow_location(true);
  1619. auto res = cli.Get("/httpbin/redirect/21");
  1620. ASSERT_TRUE(!res);
  1621. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1622. }
  1623. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1624. TEST(YahooRedirectTest, Redirect_Online) {
  1625. Client cli("yahoo.com");
  1626. auto res = cli.Get("/");
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1629. cli.set_follow_location(true);
  1630. res = cli.Get("/");
  1631. ASSERT_TRUE(res);
  1632. EXPECT_EQ(StatusCode::OK_200, res->status);
  1633. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1634. }
  1635. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1636. #define REDIR_HOST "httpbingo.org"
  1637. #define REDIR_PATH "/redirect-to"
  1638. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1639. SSLClient cli(REDIR_HOST);
  1640. cli.set_follow_location(true);
  1641. auto res =
  1642. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ(StatusCode::OK_200, res->status);
  1645. }
  1646. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1647. SSLClient cli(REDIR_HOST);
  1648. cli.set_follow_location(true);
  1649. Params params;
  1650. params.emplace("url", "http://example.com");
  1651. params.emplace("status_code", "302");
  1652. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1653. ASSERT_TRUE(res);
  1654. EXPECT_EQ(StatusCode::OK_200, res->status);
  1655. }
  1656. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1657. SSLClient cli(REDIR_HOST);
  1658. cli.set_follow_location(true);
  1659. Params params;
  1660. params.emplace("url", "http://example.com");
  1661. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1662. ASSERT_TRUE(res);
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. TEST(UrlWithSpace, Redirect_Online) {
  1666. SSLClient cli("edge.forgecdn.net");
  1667. cli.set_follow_location(true);
  1668. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1669. ASSERT_TRUE(res);
  1670. EXPECT_EQ(StatusCode::OK_200, res->status);
  1671. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1672. }
  1673. #endif
  1674. #if !defined(_WIN32) && !defined(_WIN64)
  1675. TEST(ReceiveSignals, Signal) {
  1676. auto setupSignalHandlers = []() {
  1677. struct sigaction act;
  1678. sigemptyset(&act.sa_mask);
  1679. act.sa_flags = SA_SIGINFO;
  1680. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1681. switch (sig) {
  1682. case SIGINT:
  1683. default: break;
  1684. }
  1685. };
  1686. ::sigaction(SIGINT, &act, nullptr);
  1687. };
  1688. Server svr;
  1689. int port = 0;
  1690. auto thread = std::thread([&]() {
  1691. setupSignalHandlers();
  1692. port = svr.bind_to_any_port("localhost");
  1693. svr.listen_after_bind();
  1694. });
  1695. auto se = detail::scope_exit([&] {
  1696. svr.stop();
  1697. thread.join();
  1698. ASSERT_FALSE(svr.is_running());
  1699. });
  1700. svr.wait_until_ready();
  1701. ASSERT_TRUE(svr.is_running());
  1702. pthread_kill(thread.native_handle(), SIGINT);
  1703. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1704. ASSERT_TRUE(svr.is_running());
  1705. }
  1706. #endif
  1707. TEST(RedirectToDifferentPort, Redirect) {
  1708. Server svr1;
  1709. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1710. res.set_content("Hello World!", "text/plain");
  1711. });
  1712. int svr1_port = 0;
  1713. auto thread1 = std::thread([&]() {
  1714. svr1_port = svr1.bind_to_any_port("localhost");
  1715. svr1.listen_after_bind();
  1716. });
  1717. Server svr2;
  1718. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1719. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1720. });
  1721. int svr2_port = 0;
  1722. auto thread2 = std::thread([&]() {
  1723. svr2_port = svr2.bind_to_any_port("localhost");
  1724. svr2.listen_after_bind();
  1725. });
  1726. auto se = detail::scope_exit([&] {
  1727. svr2.stop();
  1728. thread2.join();
  1729. svr1.stop();
  1730. thread1.join();
  1731. ASSERT_FALSE(svr2.is_running());
  1732. ASSERT_FALSE(svr1.is_running());
  1733. });
  1734. svr1.wait_until_ready();
  1735. svr2.wait_until_ready();
  1736. Client cli("localhost", svr2_port);
  1737. cli.set_follow_location(true);
  1738. auto res = cli.Get("/2");
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_EQ("Hello World!", res->body);
  1742. }
  1743. TEST(RedirectFromPageWithContent, Redirect) {
  1744. Server svr;
  1745. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1746. res.set_content("___", "text/plain");
  1747. res.set_redirect("/2");
  1748. });
  1749. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1750. res.set_content("Hello World!", "text/plain");
  1751. });
  1752. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1753. auto se = detail::scope_exit([&] {
  1754. svr.stop();
  1755. th.join();
  1756. ASSERT_FALSE(svr.is_running());
  1757. });
  1758. svr.wait_until_ready();
  1759. {
  1760. Client cli("localhost", PORT);
  1761. cli.set_follow_location(true);
  1762. std::string body;
  1763. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1764. body.append(data, data_length);
  1765. return true;
  1766. });
  1767. ASSERT_TRUE(res);
  1768. EXPECT_EQ(StatusCode::OK_200, res->status);
  1769. EXPECT_EQ("Hello World!", body);
  1770. }
  1771. {
  1772. Client cli("localhost", PORT);
  1773. std::string body;
  1774. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1775. body.append(data, data_length);
  1776. return true;
  1777. });
  1778. ASSERT_TRUE(res);
  1779. EXPECT_EQ(StatusCode::Found_302, res->status);
  1780. EXPECT_EQ("___", body);
  1781. }
  1782. }
  1783. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1784. Server svr;
  1785. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1786. res.set_content("___", "text/plain");
  1787. // res.set_redirect("/2");
  1788. res.set_redirect("http://[::1]:1234/2");
  1789. });
  1790. svr.Get("/2", [&](const Request &req, Response &res) {
  1791. auto host_header = req.headers.find("Host");
  1792. ASSERT_TRUE(host_header != req.headers.end());
  1793. EXPECT_EQ("[::1]:1234", host_header->second);
  1794. res.set_content("Hello World!", "text/plain");
  1795. });
  1796. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1797. auto se = detail::scope_exit([&] {
  1798. svr.stop();
  1799. th.join();
  1800. ASSERT_FALSE(svr.is_running());
  1801. });
  1802. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1803. // actually starts anything, so the condition !svr.is_running() will
  1804. // always remain true, and the loop never stops.
  1805. // This basically counts how many milliseconds have passed since the
  1806. // call to svr.listen(), and if after 5 seconds nothing started yet
  1807. // aborts the test.
  1808. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1809. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1810. ASSERT_LT(milliseconds, 5000U);
  1811. }
  1812. {
  1813. Client cli("http://[::1]:1234");
  1814. cli.set_follow_location(true);
  1815. std::string body;
  1816. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1817. body.append(data, data_length);
  1818. return true;
  1819. });
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::OK_200, res->status);
  1822. EXPECT_EQ("Hello World!", body);
  1823. }
  1824. {
  1825. Client cli("http://[::1]:1234");
  1826. std::string body;
  1827. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1828. body.append(data, data_length);
  1829. return true;
  1830. });
  1831. ASSERT_TRUE(res);
  1832. EXPECT_EQ(StatusCode::Found_302, res->status);
  1833. EXPECT_EQ("___", body);
  1834. }
  1835. }
  1836. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1837. Server svr;
  1838. svr.Get("/foo", [](const Request &req, Response &res) {
  1839. auto a = req.params.find("a");
  1840. if (a != req.params.end()) {
  1841. res.set_content((*a).second, "text/plain");
  1842. res.status = StatusCode::OK_200;
  1843. } else {
  1844. res.status = StatusCode::BadRequest_400;
  1845. }
  1846. });
  1847. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1848. auto se = detail::scope_exit([&] {
  1849. svr.stop();
  1850. thread.join();
  1851. ASSERT_FALSE(svr.is_running());
  1852. });
  1853. svr.wait_until_ready();
  1854. {
  1855. Client cli(HOST, PORT);
  1856. cli.set_path_encode(false);
  1857. auto res = cli.Get("/foo?a=explicitly+encoded");
  1858. ASSERT_TRUE(res);
  1859. EXPECT_EQ(StatusCode::OK_200, res->status);
  1860. // This expects it back with a space, as the `+` won't have been
  1861. // url-encoded, and server-side the params get decoded turning `+`
  1862. // into spaces.
  1863. EXPECT_EQ("explicitly encoded", res->body);
  1864. }
  1865. }
  1866. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1867. Server svr;
  1868. svr.Get("/", [](const Request &req, Response &) {
  1869. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1870. });
  1871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1872. auto se = detail::scope_exit([&] {
  1873. svr.stop();
  1874. thread.join();
  1875. ASSERT_FALSE(svr.is_running());
  1876. });
  1877. svr.wait_until_ready();
  1878. {
  1879. Client cli(HOST, PORT);
  1880. cli.set_path_encode(false);
  1881. auto res = cli.Get("/?something=%0A");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(StatusCode::OK_200, res->status);
  1884. }
  1885. }
  1886. TEST(BindServerTest, DISABLED_BindDualStack) {
  1887. Server svr;
  1888. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1892. auto se = detail::scope_exit([&] {
  1893. svr.stop();
  1894. thread.join();
  1895. ASSERT_FALSE(svr.is_running());
  1896. });
  1897. svr.wait_until_ready();
  1898. {
  1899. Client cli("127.0.0.1", PORT);
  1900. auto res = cli.Get("/1");
  1901. ASSERT_TRUE(res);
  1902. EXPECT_EQ(StatusCode::OK_200, res->status);
  1903. EXPECT_EQ("Hello World!", res->body);
  1904. }
  1905. {
  1906. Client cli("::1", PORT);
  1907. auto res = cli.Get("/1");
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(StatusCode::OK_200, res->status);
  1910. EXPECT_EQ("Hello World!", res->body);
  1911. }
  1912. }
  1913. TEST(BindServerTest, BindAndListenSeparately) {
  1914. Server svr;
  1915. int port = svr.bind_to_any_port("0.0.0.0");
  1916. ASSERT_TRUE(svr.is_valid());
  1917. ASSERT_TRUE(port > 0);
  1918. svr.stop();
  1919. }
  1920. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1921. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1923. CLIENT_CA_CERT_DIR);
  1924. int port = svr.bind_to_any_port("0.0.0.0");
  1925. ASSERT_TRUE(svr.is_valid());
  1926. ASSERT_TRUE(port > 0);
  1927. svr.stop();
  1928. }
  1929. #endif
  1930. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1931. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1932. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1933. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1934. int port = svr.bind_to_any_port("0.0.0.0");
  1935. ASSERT_TRUE(svr.is_valid());
  1936. ASSERT_TRUE(port > 0);
  1937. svr.stop();
  1938. }
  1939. #endif
  1940. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1941. X509 *readCertificate(const std::string &strFileName) {
  1942. std::ifstream inStream(strFileName);
  1943. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1944. std::istreambuf_iterator<char>());
  1945. if (strCertPEM.empty()) return (nullptr);
  1946. BIO *pbCert = BIO_new(BIO_s_mem());
  1947. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1948. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1949. BIO_free(pbCert);
  1950. return (pCert);
  1951. }
  1952. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1953. std::ifstream inStream(strFileName);
  1954. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1955. std::istreambuf_iterator<char>());
  1956. if (strPrivateKeyPEM.empty()) return (nullptr);
  1957. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1958. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1959. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1960. BIO_free(pbPrivKey);
  1961. return (pPrivateKey);
  1962. }
  1963. TEST(BindServerTest, UpdateCerts) {
  1964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1965. int port = svr.bind_to_any_port("0.0.0.0");
  1966. ASSERT_TRUE(svr.is_valid());
  1967. ASSERT_TRUE(port > 0);
  1968. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1969. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1970. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1971. ASSERT_TRUE(cert != nullptr);
  1972. ASSERT_TRUE(ca_cert != nullptr);
  1973. ASSERT_TRUE(key != nullptr);
  1974. X509_STORE *cert_store = X509_STORE_new();
  1975. X509_STORE_add_cert(cert_store, ca_cert);
  1976. svr.update_certs(cert, key, cert_store);
  1977. ASSERT_TRUE(svr.is_valid());
  1978. svr.stop();
  1979. X509_free(cert);
  1980. X509_free(ca_cert);
  1981. EVP_PKEY_free(key);
  1982. }
  1983. #endif
  1984. TEST(ErrorHandlerTest, ContentLength) {
  1985. Server svr;
  1986. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1987. res.status = StatusCode::OK_200;
  1988. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1989. "text/html"); // <= Content-Length still 13
  1990. });
  1991. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1992. res.set_content("Hello World!\n", "text/plain");
  1993. res.status = 524;
  1994. });
  1995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1996. auto se = detail::scope_exit([&] {
  1997. svr.stop();
  1998. thread.join();
  1999. ASSERT_FALSE(svr.is_running());
  2000. });
  2001. svr.wait_until_ready();
  2002. {
  2003. Client cli(HOST, PORT);
  2004. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2005. ASSERT_TRUE(res);
  2006. EXPECT_EQ(StatusCode::OK_200, res->status);
  2007. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2008. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2009. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2010. }
  2011. }
  2012. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2013. TEST(ExceptionTest, WithoutExceptionHandler) {
  2014. Server svr;
  2015. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2016. throw std::runtime_error("exception...");
  2017. });
  2018. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2019. throw std::runtime_error("exception\r\n...");
  2020. });
  2021. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2022. auto se = detail::scope_exit([&] {
  2023. svr.stop();
  2024. listen_thread.join();
  2025. ASSERT_FALSE(svr.is_running());
  2026. });
  2027. svr.wait_until_ready();
  2028. Client cli("localhost", PORT);
  2029. {
  2030. auto res = cli.Get("/exception");
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2033. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2034. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2035. }
  2036. {
  2037. auto res = cli.Get("/unknown");
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2040. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2041. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2042. }
  2043. }
  2044. TEST(ExceptionTest, WithExceptionHandler) {
  2045. Server svr;
  2046. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2047. std::exception_ptr ep) {
  2048. EXPECT_FALSE(ep == nullptr);
  2049. try {
  2050. std::rethrow_exception(ep);
  2051. } catch (std::exception &e) {
  2052. EXPECT_EQ("abc", std::string(e.what()));
  2053. } catch (...) {}
  2054. res.status = StatusCode::InternalServerError_500;
  2055. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2056. "text/html"); // <= Content-Length still 13 at this point
  2057. });
  2058. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2059. res.set_content("Hello World!\n", "text/plain");
  2060. throw std::runtime_error("abc");
  2061. });
  2062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2063. auto se = detail::scope_exit([&] {
  2064. svr.stop();
  2065. thread.join();
  2066. ASSERT_FALSE(svr.is_running());
  2067. });
  2068. svr.wait_until_ready();
  2069. for (size_t i = 0; i < 10; i++) {
  2070. Client cli(HOST, PORT);
  2071. for (size_t j = 0; j < 100; j++) {
  2072. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2073. ASSERT_TRUE(res);
  2074. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2075. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2076. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2077. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2078. }
  2079. cli.set_keep_alive(true);
  2080. for (size_t j = 0; j < 100; j++) {
  2081. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2082. ASSERT_TRUE(res);
  2083. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2085. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2086. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2087. }
  2088. }
  2089. }
  2090. TEST(ExceptionTest, AndErrorHandler) {
  2091. Server svr;
  2092. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2093. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2094. });
  2095. svr.set_exception_handler(
  2096. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2097. EXPECT_FALSE(ep == nullptr);
  2098. try {
  2099. std::rethrow_exception(ep);
  2100. } catch (std::exception &e) {
  2101. res.set_content(e.what(), "text/html");
  2102. } catch (...) {}
  2103. res.status = StatusCode::InternalServerError_500;
  2104. });
  2105. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2106. throw std::runtime_error("EXCEPTION");
  2107. });
  2108. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2109. res.set_content("ERROR", "text/html");
  2110. res.status = StatusCode::InternalServerError_500;
  2111. });
  2112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2113. auto se = detail::scope_exit([&] {
  2114. svr.stop();
  2115. thread.join();
  2116. ASSERT_FALSE(svr.is_running());
  2117. });
  2118. svr.wait_until_ready();
  2119. Client cli(HOST, PORT);
  2120. {
  2121. auto res = cli.Get("/exception");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2124. EXPECT_EQ("EXCEPTION", res->body);
  2125. }
  2126. {
  2127. auto res = cli.Get("/error");
  2128. ASSERT_TRUE(res);
  2129. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2130. EXPECT_EQ("ERROR", res->body);
  2131. }
  2132. {
  2133. auto res = cli.Get("/invalid");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2136. EXPECT_EQ("NOT_FOUND", res->body);
  2137. }
  2138. }
  2139. #endif
  2140. TEST(NoContentTest, ContentLength) {
  2141. Server svr;
  2142. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2143. res.status = StatusCode::NoContent_204;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. {
  2153. Client cli(HOST, PORT);
  2154. auto res = cli.Get("/hi");
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2157. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2158. }
  2159. }
  2160. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2161. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2163. ASSERT_TRUE(svr.is_valid());
  2164. #else
  2165. Server svr;
  2166. #endif
  2167. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2168. if (req.path == "/routing_handler") {
  2169. res.set_header("PRE_ROUTING", "on");
  2170. res.set_content("Routing Handler", "text/plain");
  2171. return httplib::Server::HandlerResponse::Handled;
  2172. }
  2173. return httplib::Server::HandlerResponse::Unhandled;
  2174. });
  2175. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2176. res.set_content("Error", "text/html");
  2177. });
  2178. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2179. if (req.path == "/routing_handler") {
  2180. res.set_header("POST_ROUTING", "on");
  2181. }
  2182. });
  2183. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!\n", "text/plain");
  2185. });
  2186. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2187. auto se = detail::scope_exit([&] {
  2188. svr.stop();
  2189. thread.join();
  2190. ASSERT_FALSE(svr.is_running());
  2191. });
  2192. svr.wait_until_ready();
  2193. {
  2194. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2195. SSLClient cli(HOST, PORT);
  2196. cli.enable_server_certificate_verification(false);
  2197. #else
  2198. Client cli(HOST, PORT);
  2199. #endif
  2200. auto res = cli.Get("/routing_handler");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Routing Handler", res->body);
  2204. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2205. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2206. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2207. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2208. }
  2209. {
  2210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2211. SSLClient cli(HOST, PORT);
  2212. cli.enable_server_certificate_verification(false);
  2213. #else
  2214. Client cli(HOST, PORT);
  2215. #endif
  2216. auto res = cli.Get("/hi");
  2217. ASSERT_TRUE(res);
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. EXPECT_EQ("Hello World!\n", res->body);
  2220. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2221. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2222. }
  2223. {
  2224. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2225. SSLClient cli(HOST, PORT);
  2226. cli.enable_server_certificate_verification(false);
  2227. #else
  2228. Client cli(HOST, PORT);
  2229. #endif
  2230. auto res = cli.Get("/aaa");
  2231. ASSERT_TRUE(res);
  2232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2233. EXPECT_EQ("Error", res->body);
  2234. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2235. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2236. }
  2237. }
  2238. TEST(RequestHandlerTest, PreRequestHandler) {
  2239. auto route_path = "/user/:user";
  2240. Server svr;
  2241. svr.Get("/hi", [](const Request &, Response &res) {
  2242. res.set_content("hi", "text/plain");
  2243. });
  2244. svr.Get(route_path, [](const Request &req, Response &res) {
  2245. res.set_content(req.path_params.at("user"), "text/plain");
  2246. });
  2247. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2248. if (req.matched_route == route_path) {
  2249. auto user = req.path_params.at("user");
  2250. if (user != "john") {
  2251. res.status = StatusCode::Forbidden_403;
  2252. res.set_content("error", "text/html");
  2253. return Server::HandlerResponse::Handled;
  2254. }
  2255. }
  2256. return Server::HandlerResponse::Unhandled;
  2257. });
  2258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2259. auto se = detail::scope_exit([&] {
  2260. svr.stop();
  2261. thread.join();
  2262. ASSERT_FALSE(svr.is_running());
  2263. });
  2264. svr.wait_until_ready();
  2265. Client cli(HOST, PORT);
  2266. {
  2267. auto res = cli.Get("/hi");
  2268. ASSERT_TRUE(res);
  2269. EXPECT_EQ(StatusCode::OK_200, res->status);
  2270. EXPECT_EQ("hi", res->body);
  2271. }
  2272. {
  2273. auto res = cli.Get("/user/john");
  2274. ASSERT_TRUE(res);
  2275. EXPECT_EQ(StatusCode::OK_200, res->status);
  2276. EXPECT_EQ("john", res->body);
  2277. }
  2278. {
  2279. auto res = cli.Get("/user/invalid-user");
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2282. EXPECT_EQ("error", res->body);
  2283. }
  2284. }
  2285. TEST(InvalidFormatTest, StatusCode) {
  2286. Server svr;
  2287. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2288. res.set_content("Hello World!\n", "text/plain");
  2289. res.status = 9999; // Status should be a three-digit code...
  2290. });
  2291. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. {
  2299. Client cli(HOST, PORT);
  2300. auto res = cli.Get("/hi");
  2301. ASSERT_FALSE(res);
  2302. }
  2303. }
  2304. TEST(URLFragmentTest, WithFragment) {
  2305. Server svr;
  2306. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2307. EXPECT_TRUE(req.target == "/hi");
  2308. });
  2309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2310. auto se = detail::scope_exit([&] {
  2311. svr.stop();
  2312. thread.join();
  2313. ASSERT_FALSE(svr.is_running());
  2314. });
  2315. svr.wait_until_ready();
  2316. {
  2317. Client cli(HOST, PORT);
  2318. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2319. EXPECT_TRUE(res);
  2320. EXPECT_EQ(StatusCode::OK_200, res->status);
  2321. res = cli.Get("/hi%23key1=val1=key2=val2");
  2322. EXPECT_TRUE(res);
  2323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2324. }
  2325. }
  2326. TEST(HeaderWriter, SetHeaderWriter) {
  2327. Server svr;
  2328. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2329. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2330. return detail::write_headers(strm, hdrs);
  2331. });
  2332. svr.Get("/hi", [](const Request &req, Response &res) {
  2333. auto it = req.headers.find("CustomClientHeader");
  2334. EXPECT_TRUE(it != req.headers.end());
  2335. EXPECT_EQ(it->second, "CustomClientValue");
  2336. res.set_content("Hello World!\n", "text/plain");
  2337. });
  2338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2339. auto se = detail::scope_exit([&] {
  2340. svr.stop();
  2341. thread.join();
  2342. ASSERT_FALSE(svr.is_running());
  2343. });
  2344. svr.wait_until_ready();
  2345. {
  2346. Client cli(HOST, PORT);
  2347. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2348. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2349. return detail::write_headers(strm, hdrs);
  2350. });
  2351. auto res = cli.Get("/hi");
  2352. EXPECT_TRUE(res);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. auto it = res->headers.find("CustomServerHeader");
  2355. EXPECT_TRUE(it != res->headers.end());
  2356. EXPECT_EQ(it->second, "CustomServerValue");
  2357. }
  2358. }
  2359. class ServerTest : public ::testing::Test {
  2360. protected:
  2361. ServerTest()
  2362. : cli_(HOST, PORT)
  2363. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2364. ,
  2365. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2366. #endif
  2367. {
  2368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2369. cli_.enable_server_certificate_verification(false);
  2370. #endif
  2371. }
  2372. virtual void SetUp() {
  2373. svr_.set_mount_point("/", "./www");
  2374. svr_.set_mount_point("/mount", "./www2");
  2375. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2376. svr_.Get("/hi",
  2377. [&](const Request & /*req*/, Response &res) {
  2378. res.set_content("Hello World!", "text/plain");
  2379. })
  2380. .Get("/file_content",
  2381. [&](const Request & /*req*/, Response &res) {
  2382. res.set_file_content("./www/dir/test.html");
  2383. })
  2384. .Get("/file_content_with_content_type",
  2385. [&](const Request & /*req*/, Response &res) {
  2386. res.set_file_content("./www/file", "text/plain");
  2387. })
  2388. .Get("/invalid_file_content",
  2389. [&](const Request & /*req*/, Response &res) {
  2390. res.set_file_content("./www/dir/invalid_file_path");
  2391. })
  2392. .Get("/http_response_splitting",
  2393. [&](const Request & /*req*/, Response &res) {
  2394. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2395. EXPECT_EQ(0U, res.headers.size());
  2396. EXPECT_FALSE(res.has_header("a"));
  2397. res.set_header("a", "1\nSet-Cookie: a=1");
  2398. EXPECT_EQ(0U, res.headers.size());
  2399. EXPECT_FALSE(res.has_header("a"));
  2400. res.set_header("a", "1\rSet-Cookie: a=1");
  2401. EXPECT_EQ(0U, res.headers.size());
  2402. EXPECT_FALSE(res.has_header("a"));
  2403. res.set_header("a\r\nb", "0");
  2404. EXPECT_EQ(0U, res.headers.size());
  2405. EXPECT_FALSE(res.has_header("a"));
  2406. res.set_header("a\rb", "0");
  2407. EXPECT_EQ(0U, res.headers.size());
  2408. EXPECT_FALSE(res.has_header("a"));
  2409. res.set_header("a\nb", "0");
  2410. EXPECT_EQ(0U, res.headers.size());
  2411. EXPECT_FALSE(res.has_header("a"));
  2412. res.set_redirect("1\r\nSet-Cookie: a=1");
  2413. EXPECT_EQ(0U, res.headers.size());
  2414. EXPECT_FALSE(res.has_header("Location"));
  2415. })
  2416. .Get("/slow",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. std::this_thread::sleep_for(std::chrono::seconds(2));
  2419. res.set_content("slow", "text/plain");
  2420. })
  2421. #if 0
  2422. .Post("/slowpost",
  2423. [&](const Request & /*req*/, Response &res) {
  2424. std::this_thread::sleep_for(std::chrono::seconds(2));
  2425. res.set_content("slow", "text/plain");
  2426. })
  2427. #endif
  2428. .Get("/remote_addr",
  2429. [&](const Request &req, Response &res) {
  2430. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2431. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2432. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2433. EXPECT_EQ(req.remote_port,
  2434. std::stoi(req.get_header_value("REMOTE_PORT")));
  2435. res.set_content(remote_addr.c_str(), "text/plain");
  2436. })
  2437. .Get("/local_addr",
  2438. [&](const Request &req, Response &res) {
  2439. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2440. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2441. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2442. auto local_port = req.get_header_value("LOCAL_PORT");
  2443. EXPECT_EQ(req.local_addr, local_addr);
  2444. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2445. res.set_content(local_addr.append(":").append(local_port),
  2446. "text/plain");
  2447. })
  2448. .Get("/endwith%",
  2449. [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. })
  2452. .Get("/a\\+\\+b",
  2453. [&](const Request &req, Response &res) {
  2454. ASSERT_TRUE(req.has_param("a +b"));
  2455. auto val = req.get_param_value("a +b");
  2456. res.set_content(val, "text/plain");
  2457. })
  2458. .Get("/", [&](const Request & /*req*/,
  2459. Response &res) { res.set_redirect("/hi"); })
  2460. .Post("/1",
  2461. [](const Request & /*req*/, Response &res) {
  2462. res.set_redirect("/2", StatusCode::SeeOther_303);
  2463. })
  2464. .Get("/2",
  2465. [](const Request & /*req*/, Response &res) {
  2466. res.set_content("redirected.", "text/plain");
  2467. res.status = StatusCode::OK_200;
  2468. })
  2469. .Post("/person",
  2470. [&](const Request &req, Response &res) {
  2471. if (req.has_param("name") && req.has_param("note")) {
  2472. persons_[req.get_param_value("name")] =
  2473. req.get_param_value("note");
  2474. } else {
  2475. res.status = StatusCode::BadRequest_400;
  2476. }
  2477. })
  2478. .Put("/person",
  2479. [&](const Request &req, Response &res) {
  2480. if (req.has_param("name") && req.has_param("note")) {
  2481. persons_[req.get_param_value("name")] =
  2482. req.get_param_value("note");
  2483. } else {
  2484. res.status = StatusCode::BadRequest_400;
  2485. }
  2486. })
  2487. .Get("/person/(.*)",
  2488. [&](const Request &req, Response &res) {
  2489. string name = req.matches[1];
  2490. if (persons_.find(name) != persons_.end()) {
  2491. auto note = persons_[name];
  2492. res.set_content(note, "text/plain");
  2493. } else {
  2494. res.status = StatusCode::NotFound_404;
  2495. }
  2496. })
  2497. .Delete("/person",
  2498. [&](const Request &req, Response &res) {
  2499. if (req.has_param("name")) {
  2500. string name = req.get_param_value("name");
  2501. if (persons_.find(name) != persons_.end()) {
  2502. persons_.erase(name);
  2503. res.set_content("DELETED", "text/plain");
  2504. } else {
  2505. res.status = StatusCode::NotFound_404;
  2506. }
  2507. } else {
  2508. res.status = StatusCode::BadRequest_400;
  2509. }
  2510. })
  2511. .Post("/x-www-form-urlencoded-json",
  2512. [&](const Request &req, Response &res) {
  2513. auto json = req.get_param_value("json");
  2514. ASSERT_EQ(JSON_DATA, json);
  2515. res.set_content(json, "appliation/json");
  2516. res.status = StatusCode::OK_200;
  2517. })
  2518. .Get("/streamed-chunked",
  2519. [&](const Request & /*req*/, Response &res) {
  2520. res.set_chunked_content_provider(
  2521. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2522. sink.os << "123";
  2523. sink.os << "456";
  2524. sink.os << "789";
  2525. sink.done();
  2526. return true;
  2527. });
  2528. })
  2529. .Get("/streamed-chunked2",
  2530. [&](const Request & /*req*/, Response &res) {
  2531. auto i = new int(0);
  2532. res.set_chunked_content_provider(
  2533. "text/plain",
  2534. [i](size_t /*offset*/, DataSink &sink) {
  2535. switch (*i) {
  2536. case 0: sink.os << "123"; break;
  2537. case 1: sink.os << "456"; break;
  2538. case 2: sink.os << "789"; break;
  2539. case 3: sink.done(); break;
  2540. }
  2541. (*i)++;
  2542. return true;
  2543. },
  2544. [i](bool success) {
  2545. EXPECT_TRUE(success);
  2546. delete i;
  2547. });
  2548. })
  2549. .Get("/streamed-chunked-with-trailer",
  2550. [&](const Request & /*req*/, Response &res) {
  2551. auto i = new int(0);
  2552. res.set_header("Trailer", "Dummy1, Dummy2");
  2553. res.set_chunked_content_provider(
  2554. "text/plain",
  2555. [i](size_t /*offset*/, DataSink &sink) {
  2556. switch (*i) {
  2557. case 0: sink.os << "123"; break;
  2558. case 1: sink.os << "456"; break;
  2559. case 2: sink.os << "789"; break;
  2560. case 3: {
  2561. sink.done_with_trailer(
  2562. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2563. } break;
  2564. }
  2565. (*i)++;
  2566. return true;
  2567. },
  2568. [i](bool success) {
  2569. EXPECT_TRUE(success);
  2570. delete i;
  2571. });
  2572. })
  2573. .Get("/streamed",
  2574. [&](const Request & /*req*/, Response &res) {
  2575. res.set_content_provider(
  2576. 6, "text/plain",
  2577. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2578. sink.os << (offset < 3 ? "a" : "b");
  2579. return true;
  2580. });
  2581. })
  2582. .Get("/streamed-with-range",
  2583. [&](const Request &req, Response &res) {
  2584. auto data = new std::string("abcdefg");
  2585. res.set_content_provider(
  2586. data->size(), "text/plain",
  2587. [data](size_t offset, size_t length, DataSink &sink) {
  2588. size_t DATA_CHUNK_SIZE = 4;
  2589. const auto &d = *data;
  2590. auto out_len =
  2591. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2592. auto ret =
  2593. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2594. EXPECT_TRUE(ret);
  2595. return true;
  2596. },
  2597. [data, &req](bool success) {
  2598. EXPECT_EQ(success, !req.has_param("error"));
  2599. delete data;
  2600. });
  2601. })
  2602. .Get("/streamed-cancel",
  2603. [&](const Request & /*req*/, Response &res) {
  2604. res.set_content_provider(
  2605. size_t(-1), "text/plain",
  2606. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2607. sink.os << "data_chunk";
  2608. return true;
  2609. });
  2610. })
  2611. .Get("/regex-with-delimiter",
  2612. [&](const Request &req, Response & /*res*/) {
  2613. ASSERT_TRUE(req.has_param("key"));
  2614. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2615. })
  2616. .Get("/with-range",
  2617. [&](const Request & /*req*/, Response &res) {
  2618. res.set_content("abcdefg", "text/plain");
  2619. })
  2620. .Get("/with-range-customized-response",
  2621. [&](const Request & /*req*/, Response &res) {
  2622. res.status = StatusCode::BadRequest_400;
  2623. res.set_content(JSON_DATA, "application/json");
  2624. })
  2625. .Post("/chunked",
  2626. [&](const Request &req, Response & /*res*/) {
  2627. EXPECT_EQ(req.body, "dechunked post body");
  2628. })
  2629. .Post("/large-chunked",
  2630. [&](const Request &req, Response & /*res*/) {
  2631. std::string expected(6 * 30 * 1024u, 'a');
  2632. EXPECT_EQ(req.body, expected);
  2633. })
  2634. .Post("/multipart",
  2635. [&](const Request &req, Response & /*res*/) {
  2636. EXPECT_EQ(6u, req.files.size());
  2637. ASSERT_TRUE(!req.has_file("???"));
  2638. ASSERT_TRUE(req.body.empty());
  2639. {
  2640. const auto &file = req.get_file_value("text1");
  2641. EXPECT_TRUE(file.filename.empty());
  2642. EXPECT_EQ("text default", file.content);
  2643. }
  2644. {
  2645. const auto &file = req.get_file_value("text2");
  2646. EXPECT_TRUE(file.filename.empty());
  2647. EXPECT_EQ("aωb", file.content);
  2648. }
  2649. {
  2650. const auto &file = req.get_file_value("file1");
  2651. EXPECT_EQ("hello.txt", file.filename);
  2652. EXPECT_EQ("text/plain", file.content_type);
  2653. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2654. }
  2655. {
  2656. const auto &file = req.get_file_value("file3");
  2657. EXPECT_TRUE(file.filename.empty());
  2658. EXPECT_EQ("application/octet-stream", file.content_type);
  2659. EXPECT_EQ(0u, file.content.size());
  2660. }
  2661. {
  2662. const auto &file = req.get_file_value("file4");
  2663. EXPECT_TRUE(file.filename.empty());
  2664. EXPECT_EQ(0u, file.content.size());
  2665. EXPECT_EQ("application/json tmp-string", file.content_type);
  2666. }
  2667. })
  2668. .Post("/multipart/multi_file_values",
  2669. [&](const Request &req, Response & /*res*/) {
  2670. EXPECT_EQ(5u, req.files.size());
  2671. ASSERT_TRUE(!req.has_file("???"));
  2672. ASSERT_TRUE(req.body.empty());
  2673. {
  2674. const auto &text_value = req.get_file_values("text");
  2675. EXPECT_EQ(1u, text_value.size());
  2676. auto &text = text_value[0];
  2677. EXPECT_TRUE(text.filename.empty());
  2678. EXPECT_EQ("default text", text.content);
  2679. }
  2680. {
  2681. const auto &text1_values = req.get_file_values("multi_text1");
  2682. EXPECT_EQ(2u, text1_values.size());
  2683. EXPECT_EQ("aaaaa", text1_values[0].content);
  2684. EXPECT_EQ("bbbbb", text1_values[1].content);
  2685. }
  2686. {
  2687. const auto &file1_values = req.get_file_values("multi_file1");
  2688. EXPECT_EQ(2u, file1_values.size());
  2689. auto file1 = file1_values[0];
  2690. EXPECT_EQ(file1.filename, "hello.txt");
  2691. EXPECT_EQ(file1.content_type, "text/plain");
  2692. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2693. auto file2 = file1_values[1];
  2694. EXPECT_EQ(file2.filename, "world.json");
  2695. EXPECT_EQ(file2.content_type, "application/json");
  2696. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2697. }
  2698. })
  2699. .Post("/empty",
  2700. [&](const Request &req, Response &res) {
  2701. EXPECT_EQ(req.body, "");
  2702. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2703. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2704. res.set_content("empty", "text/plain");
  2705. })
  2706. .Post("/empty-no-content-type",
  2707. [&](const Request &req, Response &res) {
  2708. EXPECT_EQ(req.body, "");
  2709. EXPECT_FALSE(req.has_header("Content-Type"));
  2710. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2711. res.set_content("empty-no-content-type", "text/plain");
  2712. })
  2713. .Post("/path-only",
  2714. [&](const Request &req, Response &res) {
  2715. EXPECT_EQ(req.body, "");
  2716. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2717. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2718. res.set_content("path-only", "text/plain");
  2719. })
  2720. .Post("/path-headers-only",
  2721. [&](const Request &req, Response &res) {
  2722. EXPECT_EQ(req.body, "");
  2723. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2724. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2725. EXPECT_EQ("world", req.get_header_value("hello"));
  2726. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2727. res.set_content("path-headers-only", "text/plain");
  2728. })
  2729. .Post("/post-large",
  2730. [&](const Request &req, Response &res) {
  2731. EXPECT_EQ(req.body, LARGE_DATA);
  2732. res.set_content(req.body, "text/plain");
  2733. })
  2734. .Put("/empty-no-content-type",
  2735. [&](const Request &req, Response &res) {
  2736. EXPECT_EQ(req.body, "");
  2737. EXPECT_FALSE(req.has_header("Content-Type"));
  2738. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2739. res.set_content("empty-no-content-type", "text/plain");
  2740. })
  2741. .Put("/put",
  2742. [&](const Request &req, Response &res) {
  2743. EXPECT_EQ(req.body, "PUT");
  2744. res.set_content(req.body, "text/plain");
  2745. })
  2746. .Put("/put-large",
  2747. [&](const Request &req, Response &res) {
  2748. EXPECT_EQ(req.body, LARGE_DATA);
  2749. res.set_content(req.body, "text/plain");
  2750. })
  2751. .Patch("/patch",
  2752. [&](const Request &req, Response &res) {
  2753. EXPECT_EQ(req.body, "PATCH");
  2754. res.set_content(req.body, "text/plain");
  2755. })
  2756. .Delete("/delete",
  2757. [&](const Request & /*req*/, Response &res) {
  2758. res.set_content("DELETE", "text/plain");
  2759. })
  2760. .Delete("/delete-body",
  2761. [&](const Request &req, Response &res) {
  2762. EXPECT_EQ(req.body, "content");
  2763. res.set_content(req.body, "text/plain");
  2764. })
  2765. .Options(R"(\*)",
  2766. [&](const Request & /*req*/, Response &res) {
  2767. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2768. })
  2769. .Get("/request-target",
  2770. [&](const Request &req, Response & /*res*/) {
  2771. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2772. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2773. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2774. })
  2775. .Get("/long-query-value",
  2776. [&](const Request &req, Response & /*res*/) {
  2777. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2778. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2779. })
  2780. .Get("/too-long-query-value",
  2781. [&](const Request &req, Response & /*res*/) {
  2782. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2783. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2784. })
  2785. .Get("/array-param",
  2786. [&](const Request &req, Response & /*res*/) {
  2787. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2788. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2789. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2790. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2791. })
  2792. .Post("/validate-no-multiple-headers",
  2793. [&](const Request &req, Response & /*res*/) {
  2794. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2795. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2796. })
  2797. .Post("/content_receiver",
  2798. [&](const Request &req, Response &res,
  2799. const ContentReader &content_reader) {
  2800. if (req.is_multipart_form_data()) {
  2801. MultipartFormDataItems files;
  2802. content_reader(
  2803. [&](const MultipartFormData &file) {
  2804. files.push_back(file);
  2805. return true;
  2806. },
  2807. [&](const char *data, size_t data_length) {
  2808. files.back().content.append(data, data_length);
  2809. return true;
  2810. });
  2811. EXPECT_EQ(5u, files.size());
  2812. {
  2813. const auto &file = get_file_value(files, "text1");
  2814. EXPECT_TRUE(file.filename.empty());
  2815. EXPECT_EQ("text default", file.content);
  2816. }
  2817. {
  2818. const auto &file = get_file_value(files, "text2");
  2819. EXPECT_TRUE(file.filename.empty());
  2820. EXPECT_EQ("aωb", file.content);
  2821. }
  2822. {
  2823. const auto &file = get_file_value(files, "file1");
  2824. EXPECT_EQ("hello.txt", file.filename);
  2825. EXPECT_EQ("text/plain", file.content_type);
  2826. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2827. }
  2828. {
  2829. const auto &file = get_file_value(files, "file3");
  2830. EXPECT_TRUE(file.filename.empty());
  2831. EXPECT_EQ("application/octet-stream", file.content_type);
  2832. EXPECT_EQ(0u, file.content.size());
  2833. }
  2834. } else {
  2835. std::string body;
  2836. content_reader([&](const char *data, size_t data_length) {
  2837. EXPECT_EQ(7U, data_length);
  2838. body.append(data, data_length);
  2839. return true;
  2840. });
  2841. EXPECT_EQ(body, "content");
  2842. res.set_content(body, "text/plain");
  2843. }
  2844. })
  2845. .Put("/content_receiver",
  2846. [&](const Request & /*req*/, Response &res,
  2847. const ContentReader &content_reader) {
  2848. std::string body;
  2849. content_reader([&](const char *data, size_t data_length) {
  2850. body.append(data, data_length);
  2851. return true;
  2852. });
  2853. EXPECT_EQ(body, "content");
  2854. res.set_content(body, "text/plain");
  2855. })
  2856. .Patch("/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. .Post("/query-string-and-body",
  2868. [&](const Request &req, Response & /*res*/) {
  2869. ASSERT_TRUE(req.has_param("key"));
  2870. EXPECT_EQ(req.get_param_value("key"), "value");
  2871. EXPECT_EQ(req.body, "content");
  2872. })
  2873. .Get("/last-request",
  2874. [&](const Request &req, Response & /*res*/) {
  2875. EXPECT_EQ("close", req.get_header_value("Connection"));
  2876. })
  2877. .Get(R"(/redirect/(\d+))",
  2878. [&](const Request &req, Response &res) {
  2879. auto num = std::stoi(req.matches[1]) + 1;
  2880. std::string url = "/redirect/" + std::to_string(num);
  2881. res.set_redirect(url);
  2882. })
  2883. .Post("/binary",
  2884. [&](const Request &req, Response &res) {
  2885. EXPECT_EQ(4U, req.body.size());
  2886. EXPECT_EQ("application/octet-stream",
  2887. req.get_header_value("Content-Type"));
  2888. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2889. res.set_content(req.body, "application/octet-stream");
  2890. })
  2891. .Put("/binary",
  2892. [&](const Request &req, Response &res) {
  2893. EXPECT_EQ(4U, req.body.size());
  2894. EXPECT_EQ("application/octet-stream",
  2895. req.get_header_value("Content-Type"));
  2896. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2897. res.set_content(req.body, "application/octet-stream");
  2898. })
  2899. .Patch("/binary",
  2900. [&](const Request &req, Response &res) {
  2901. EXPECT_EQ(4U, req.body.size());
  2902. EXPECT_EQ("application/octet-stream",
  2903. req.get_header_value("Content-Type"));
  2904. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2905. res.set_content(req.body, "application/octet-stream");
  2906. })
  2907. .Delete("/binary",
  2908. [&](const Request &req, Response &res) {
  2909. EXPECT_EQ(4U, req.body.size());
  2910. EXPECT_EQ("application/octet-stream",
  2911. req.get_header_value("Content-Type"));
  2912. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2913. res.set_content(req.body, "application/octet-stream");
  2914. })
  2915. .Get("/issue1772",
  2916. [&](const Request & /*req*/, Response &res) {
  2917. res.status = 401;
  2918. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2919. })
  2920. .Delete("/issue609",
  2921. [](const httplib::Request &, httplib::Response &res,
  2922. const httplib::ContentReader &) {
  2923. res.set_content("ok", "text/plain");
  2924. })
  2925. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2926. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2927. .Get("/compress",
  2928. [&](const Request & /*req*/, Response &res) {
  2929. res.set_content(
  2930. "12345678901234567890123456789012345678901234567890123456789"
  2931. "01234567890123456789012345678901234567890",
  2932. "text/plain");
  2933. })
  2934. .Get("/nocompress",
  2935. [&](const Request & /*req*/, Response &res) {
  2936. res.set_content(
  2937. "12345678901234567890123456789012345678901234567890123456789"
  2938. "01234567890123456789012345678901234567890",
  2939. "application/octet-stream");
  2940. })
  2941. .Post("/compress-multipart",
  2942. [&](const Request &req, Response & /*res*/) {
  2943. EXPECT_EQ(2u, req.files.size());
  2944. ASSERT_TRUE(!req.has_file("???"));
  2945. {
  2946. const auto &file = req.get_file_value("key1");
  2947. EXPECT_TRUE(file.filename.empty());
  2948. EXPECT_EQ("test", file.content);
  2949. }
  2950. {
  2951. const auto &file = req.get_file_value("key2");
  2952. EXPECT_TRUE(file.filename.empty());
  2953. EXPECT_EQ("--abcdefg123", file.content);
  2954. }
  2955. })
  2956. #endif
  2957. ;
  2958. persons_["john"] = "programmer";
  2959. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2960. svr_.wait_until_ready();
  2961. }
  2962. virtual void TearDown() {
  2963. svr_.stop();
  2964. if (!request_threads_.empty()) {
  2965. std::this_thread::sleep_for(std::chrono::seconds(1));
  2966. for (auto &t : request_threads_) {
  2967. t.join();
  2968. }
  2969. }
  2970. t_.join();
  2971. }
  2972. map<string, string> persons_;
  2973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2974. SSLClient cli_;
  2975. SSLServer svr_;
  2976. #else
  2977. Client cli_;
  2978. Server svr_;
  2979. #endif
  2980. thread t_;
  2981. std::vector<thread> request_threads_;
  2982. };
  2983. TEST_F(ServerTest, GetMethod200) {
  2984. auto res = cli_.Get("/hi");
  2985. ASSERT_TRUE(res);
  2986. EXPECT_EQ("HTTP/1.1", res->version);
  2987. EXPECT_EQ(StatusCode::OK_200, res->status);
  2988. EXPECT_EQ("OK", res->reason);
  2989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2990. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2991. EXPECT_EQ("Hello World!", res->body);
  2992. }
  2993. void performance_test(const char *host) {
  2994. auto port = 1234;
  2995. Server svr;
  2996. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Benchmark Response", "text/plain");
  2998. });
  2999. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3000. auto se = detail::scope_exit([&] {
  3001. svr.stop();
  3002. listen_thread.join();
  3003. ASSERT_FALSE(svr.is_running());
  3004. });
  3005. svr.wait_until_ready();
  3006. Client cli(host, port);
  3007. auto start = std::chrono::high_resolution_clock::now();
  3008. auto res = cli.Get("/benchmark");
  3009. ASSERT_TRUE(res);
  3010. EXPECT_EQ(StatusCode::OK_200, res->status);
  3011. auto end = std::chrono::high_resolution_clock::now();
  3012. auto elapsed =
  3013. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3014. .count();
  3015. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3016. << "ms (Issue #1777)";
  3017. }
  3018. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3019. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3020. TEST_F(ServerTest, GetEmptyFile) {
  3021. auto res = cli_.Get("/empty_file");
  3022. ASSERT_TRUE(res);
  3023. EXPECT_EQ(StatusCode::OK_200, res->status);
  3024. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3025. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3026. EXPECT_EQ("", res->body);
  3027. }
  3028. TEST_F(ServerTest, GetFileContent) {
  3029. auto res = cli_.Get("/file_content");
  3030. ASSERT_TRUE(res);
  3031. EXPECT_EQ(StatusCode::OK_200, res->status);
  3032. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3033. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3034. EXPECT_EQ("test.html", res->body);
  3035. }
  3036. TEST_F(ServerTest, GetFileContentWithRange) {
  3037. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3038. ASSERT_TRUE(res);
  3039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3040. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3041. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3042. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3043. EXPECT_EQ("est", res->body);
  3044. }
  3045. TEST_F(ServerTest, GetFileContentWithContentType) {
  3046. auto res = cli_.Get("/file_content_with_content_type");
  3047. ASSERT_TRUE(res);
  3048. EXPECT_EQ(StatusCode::OK_200, res->status);
  3049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3050. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3051. EXPECT_EQ("file\n", res->body);
  3052. }
  3053. TEST_F(ServerTest, GetInvalidFileContent) {
  3054. auto res = cli_.Get("/invalid_file_content");
  3055. ASSERT_TRUE(res);
  3056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3057. }
  3058. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3059. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3060. ASSERT_TRUE(res);
  3061. EXPECT_EQ("HTTP/1.1", res->version);
  3062. EXPECT_EQ(StatusCode::OK_200, res->status);
  3063. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3064. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3065. EXPECT_EQ("Hello World!", res->body);
  3066. }
  3067. TEST_F(ServerTest, GetMethod302) {
  3068. auto res = cli_.Get("/");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ(StatusCode::Found_302, res->status);
  3071. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3072. }
  3073. TEST_F(ServerTest, GetMethod302Redirect) {
  3074. cli_.set_follow_location(true);
  3075. auto res = cli_.Get("/");
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_EQ("Hello World!", res->body);
  3079. EXPECT_EQ("/hi", res->location);
  3080. }
  3081. TEST_F(ServerTest, GetMethod404) {
  3082. auto res = cli_.Get("/invalid");
  3083. ASSERT_TRUE(res);
  3084. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3085. }
  3086. TEST_F(ServerTest, HeadMethod200) {
  3087. auto res = cli_.Head("/hi");
  3088. ASSERT_TRUE(res);
  3089. EXPECT_EQ(StatusCode::OK_200, res->status);
  3090. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3091. EXPECT_TRUE(res->body.empty());
  3092. }
  3093. TEST_F(ServerTest, HeadMethod200Static) {
  3094. auto res = cli_.Head("/mount/dir/index.html");
  3095. ASSERT_TRUE(res);
  3096. EXPECT_EQ(StatusCode::OK_200, res->status);
  3097. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3098. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3099. EXPECT_TRUE(res->body.empty());
  3100. }
  3101. TEST_F(ServerTest, HeadMethod404) {
  3102. auto res = cli_.Head("/invalid");
  3103. ASSERT_TRUE(res);
  3104. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3105. EXPECT_TRUE(res->body.empty());
  3106. }
  3107. TEST_F(ServerTest, GetMethodPersonJohn) {
  3108. auto res = cli_.Get("/person/john");
  3109. ASSERT_TRUE(res);
  3110. EXPECT_EQ(StatusCode::OK_200, res->status);
  3111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3112. EXPECT_EQ("programmer", res->body);
  3113. }
  3114. TEST_F(ServerTest, PostMethod1) {
  3115. auto res = cli_.Get("/person/john1");
  3116. ASSERT_TRUE(res);
  3117. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3118. res = cli_.Post("/person", "name=john1&note=coder",
  3119. "application/x-www-form-urlencoded");
  3120. ASSERT_TRUE(res);
  3121. ASSERT_EQ(StatusCode::OK_200, res->status);
  3122. res = cli_.Get("/person/john1");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(StatusCode::OK_200, res->status);
  3125. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3126. ASSERT_EQ("coder", res->body);
  3127. }
  3128. TEST_F(ServerTest, PostMethod2) {
  3129. auto res = cli_.Get("/person/john2");
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3132. Params params;
  3133. params.emplace("name", "john2");
  3134. params.emplace("note", "coder");
  3135. res = cli_.Post("/person", params);
  3136. ASSERT_TRUE(res);
  3137. ASSERT_EQ(StatusCode::OK_200, res->status);
  3138. res = cli_.Get("/person/john2");
  3139. ASSERT_TRUE(res);
  3140. ASSERT_EQ(StatusCode::OK_200, res->status);
  3141. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3142. ASSERT_EQ("coder", res->body);
  3143. }
  3144. TEST_F(ServerTest, PutMethod3) {
  3145. auto res = cli_.Get("/person/john3");
  3146. ASSERT_TRUE(res);
  3147. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3148. Params params;
  3149. params.emplace("name", "john3");
  3150. params.emplace("note", "coder");
  3151. res = cli_.Put("/person", params);
  3152. ASSERT_TRUE(res);
  3153. ASSERT_EQ(StatusCode::OK_200, res->status);
  3154. res = cli_.Get("/person/john3");
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::OK_200, res->status);
  3157. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3158. ASSERT_EQ("coder", res->body);
  3159. }
  3160. TEST_F(ServerTest, DeleteMethod1) {
  3161. auto res = cli_.Get("/person/john4");
  3162. ASSERT_TRUE(res);
  3163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3164. Params params;
  3165. params.emplace("name", "john4");
  3166. params.emplace("note", "coder");
  3167. res = cli_.Post("/person", params);
  3168. ASSERT_TRUE(res);
  3169. ASSERT_EQ(StatusCode::OK_200, res->status);
  3170. res = cli_.Get("/person/john4");
  3171. ASSERT_TRUE(res);
  3172. ASSERT_EQ(StatusCode::OK_200, res->status);
  3173. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3174. ASSERT_EQ("coder", res->body);
  3175. Params delete_params;
  3176. delete_params.emplace("name", "john4");
  3177. res = cli_.Delete("/person", delete_params);
  3178. ASSERT_TRUE(res);
  3179. ASSERT_EQ(StatusCode::OK_200, res->status);
  3180. ASSERT_EQ("DELETED", res->body);
  3181. res = cli_.Get("/person/john4");
  3182. ASSERT_TRUE(res);
  3183. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3184. }
  3185. TEST_F(ServerTest, DeleteMethod2) {
  3186. auto res = cli_.Get("/person/john5");
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3189. Params params;
  3190. params.emplace("name", "john5");
  3191. params.emplace("note", "developer");
  3192. res = cli_.Post("/person", params);
  3193. ASSERT_TRUE(res);
  3194. ASSERT_EQ(StatusCode::OK_200, res->status);
  3195. res = cli_.Get("/person/john5");
  3196. ASSERT_TRUE(res);
  3197. ASSERT_EQ(StatusCode::OK_200, res->status);
  3198. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3199. ASSERT_EQ("developer", res->body);
  3200. Params delete_params;
  3201. delete_params.emplace("name", "john5");
  3202. Headers headers;
  3203. headers.emplace("Custom-Header", "test-value");
  3204. res = cli_.Delete("/person", headers, delete_params);
  3205. ASSERT_TRUE(res);
  3206. ASSERT_EQ(StatusCode::OK_200, res->status);
  3207. ASSERT_EQ("DELETED", res->body);
  3208. res = cli_.Get("/person/john5");
  3209. ASSERT_TRUE(res);
  3210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3211. }
  3212. TEST_F(ServerTest, DeleteMethod3) {
  3213. auto res = cli_.Get("/person/john6");
  3214. ASSERT_TRUE(res);
  3215. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3216. Params params;
  3217. params.emplace("name", "john6");
  3218. params.emplace("note", "tester");
  3219. res = cli_.Post("/person", params);
  3220. ASSERT_TRUE(res);
  3221. ASSERT_EQ(StatusCode::OK_200, res->status);
  3222. res = cli_.Get("/person/john6");
  3223. ASSERT_TRUE(res);
  3224. ASSERT_EQ(StatusCode::OK_200, res->status);
  3225. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3226. ASSERT_EQ("tester", res->body);
  3227. Params delete_params;
  3228. delete_params.emplace("name", "john6");
  3229. Headers headers;
  3230. headers.emplace("Custom-Header", "test-value");
  3231. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. ASSERT_EQ("DELETED", res->body);
  3235. res = cli_.Get("/person/john6");
  3236. ASSERT_TRUE(res);
  3237. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3238. }
  3239. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3240. Params params;
  3241. params.emplace("json", JSON_DATA);
  3242. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ(JSON_DATA, res->body);
  3246. }
  3247. TEST_F(ServerTest, PostEmptyContent) {
  3248. auto res = cli_.Post("/empty", "", "text/plain");
  3249. ASSERT_TRUE(res);
  3250. ASSERT_EQ(StatusCode::OK_200, res->status);
  3251. ASSERT_EQ("empty", res->body);
  3252. }
  3253. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3254. auto res = cli_.Post("/empty-no-content-type");
  3255. ASSERT_TRUE(res);
  3256. ASSERT_EQ(StatusCode::OK_200, res->status);
  3257. ASSERT_EQ("empty-no-content-type", res->body);
  3258. }
  3259. TEST_F(ServerTest, PostPathOnly) {
  3260. auto res = cli_.Post("/path-only");
  3261. ASSERT_TRUE(res);
  3262. ASSERT_EQ(StatusCode::OK_200, res->status);
  3263. ASSERT_EQ("path-only", res->body);
  3264. }
  3265. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3266. auto res = cli_.Post("/path-headers-only",
  3267. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3268. ASSERT_TRUE(res);
  3269. ASSERT_EQ(StatusCode::OK_200, res->status);
  3270. ASSERT_EQ("path-headers-only", res->body);
  3271. }
  3272. TEST_F(ServerTest, PostLarge) {
  3273. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3274. ASSERT_TRUE(res);
  3275. ASSERT_EQ(StatusCode::OK_200, res->status);
  3276. EXPECT_EQ(LARGE_DATA, res->body);
  3277. }
  3278. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3279. auto res = cli_.Put("/empty-no-content-type");
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::OK_200, res->status);
  3282. ASSERT_EQ("empty-no-content-type", res->body);
  3283. }
  3284. TEST_F(ServerTest, GetMethodDir) {
  3285. auto res = cli_.Get("/dir/");
  3286. ASSERT_TRUE(res);
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3289. auto body = R"(<html>
  3290. <head>
  3291. </head>
  3292. <body>
  3293. <a href="/dir/test.html">Test</a>
  3294. <a href="/hi">hi</a>
  3295. </body>
  3296. </html>
  3297. )";
  3298. EXPECT_EQ(body, res->body);
  3299. }
  3300. TEST_F(ServerTest, GetMethodDirTest) {
  3301. auto res = cli_.Get("/dir/test.html");
  3302. ASSERT_TRUE(res);
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3305. EXPECT_EQ("test.html", res->body);
  3306. }
  3307. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3308. auto res = cli_.Get("/dir/../dir/test.html");
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3312. EXPECT_EQ("test.html", res->body);
  3313. }
  3314. TEST_F(ServerTest, GetMethodInvalidPath) {
  3315. auto res = cli_.Get("/dir/../test.html");
  3316. ASSERT_TRUE(res);
  3317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3318. }
  3319. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3320. auto res = cli_.Get("/../www/dir/test.html");
  3321. ASSERT_TRUE(res);
  3322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3323. }
  3324. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3325. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3326. ASSERT_TRUE(res);
  3327. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3328. }
  3329. TEST_F(ServerTest, GetMethodDirMountTest) {
  3330. auto res = cli_.Get("/mount/dir/test.html");
  3331. ASSERT_TRUE(res);
  3332. EXPECT_EQ(StatusCode::OK_200, res->status);
  3333. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3334. EXPECT_EQ("test.html", res->body);
  3335. }
  3336. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3337. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3338. ASSERT_TRUE(res);
  3339. EXPECT_EQ(StatusCode::OK_200, res->status);
  3340. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3341. EXPECT_EQ("test.html", res->body);
  3342. }
  3343. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3344. auto res = cli_.Get("/mount/dir/../test.html");
  3345. ASSERT_TRUE(res);
  3346. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3347. }
  3348. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3349. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3350. ASSERT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3352. }
  3353. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3354. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3355. ASSERT_TRUE(res);
  3356. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3357. }
  3358. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3359. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3360. ASSERT_TRUE(res);
  3361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3362. }
  3363. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3364. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3365. ASSERT_TRUE(res);
  3366. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3367. }
  3368. TEST_F(ServerTest, PostMethod303) {
  3369. auto res = cli_.Post("/1", "body", "text/plain");
  3370. ASSERT_TRUE(res);
  3371. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3372. EXPECT_EQ("/2", res->get_header_value("Location"));
  3373. }
  3374. TEST_F(ServerTest, PostMethod303Redirect) {
  3375. cli_.set_follow_location(true);
  3376. auto res = cli_.Post("/1", "body", "text/plain");
  3377. ASSERT_TRUE(res);
  3378. EXPECT_EQ(StatusCode::OK_200, res->status);
  3379. EXPECT_EQ("redirected.", res->body);
  3380. EXPECT_EQ("/2", res->location);
  3381. }
  3382. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3383. auto res = cli_.Get("/dir/test.abcde");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(StatusCode::OK_200, res->status);
  3386. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3387. EXPECT_EQ("abcde", res->body);
  3388. }
  3389. TEST_F(ServerTest, StaticFileRange) {
  3390. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3393. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3395. EXPECT_EQ(true, res->has_header("Content-Range"));
  3396. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3397. EXPECT_EQ(std::string("cd"), res->body);
  3398. }
  3399. TEST_F(ServerTest, StaticFileRanges) {
  3400. auto res =
  3401. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3404. EXPECT_TRUE(
  3405. res->get_header_value("Content-Type")
  3406. .find(
  3407. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3408. 0);
  3409. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3410. }
  3411. TEST_F(ServerTest, StaticFileRangeHead) {
  3412. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3415. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3416. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3417. EXPECT_EQ(true, res->has_header("Content-Range"));
  3418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3419. }
  3420. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3421. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3422. ASSERT_TRUE(res);
  3423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3425. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3426. EXPECT_EQ(true, res->has_header("Content-Range"));
  3427. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3428. res->get_header_value("Content-Range"));
  3429. EXPECT_EQ("LAST\n", res->body);
  3430. }
  3431. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3432. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3433. ASSERT_TRUE(res);
  3434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3436. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3437. EXPECT_EQ(true, res->has_header("Content-Range"));
  3438. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3439. }
  3440. TEST_F(ServerTest, StaticFileBigFile) {
  3441. auto res = cli_.Get("/dir/1MB.txt");
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3446. }
  3447. TEST_F(ServerTest, InvalidBaseDirMount) {
  3448. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3449. }
  3450. TEST_F(ServerTest, Binary) {
  3451. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3452. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3453. "application/octet-stream");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. ASSERT_EQ(4U, res->body.size());
  3457. res = cli_.Put("/binary", binary.data(), binary.size(),
  3458. "application/octet-stream");
  3459. ASSERT_TRUE(res);
  3460. ASSERT_EQ(StatusCode::OK_200, res->status);
  3461. ASSERT_EQ(4U, res->body.size());
  3462. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3463. "application/octet-stream");
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. ASSERT_EQ(4U, res->body.size());
  3467. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3468. "application/octet-stream");
  3469. ASSERT_TRUE(res);
  3470. ASSERT_EQ(StatusCode::OK_200, res->status);
  3471. ASSERT_EQ(4U, res->body.size());
  3472. }
  3473. TEST_F(ServerTest, BinaryString) {
  3474. auto binary = std::string("\x00\x01\x02\x03", 4);
  3475. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ(4U, res->body.size());
  3479. res = cli_.Put("/binary", binary, "application/octet-stream");
  3480. ASSERT_TRUE(res);
  3481. ASSERT_EQ(StatusCode::OK_200, res->status);
  3482. ASSERT_EQ(4U, res->body.size());
  3483. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3484. ASSERT_TRUE(res);
  3485. ASSERT_EQ(StatusCode::OK_200, res->status);
  3486. ASSERT_EQ(4U, res->body.size());
  3487. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3488. ASSERT_TRUE(res);
  3489. ASSERT_EQ(StatusCode::OK_200, res->status);
  3490. ASSERT_EQ(4U, res->body.size());
  3491. }
  3492. TEST_F(ServerTest, EmptyRequest) {
  3493. auto res = cli_.Get("");
  3494. ASSERT_TRUE(!res);
  3495. EXPECT_EQ(Error::Connection, res.error());
  3496. }
  3497. TEST_F(ServerTest, LongRequest) {
  3498. std::string request;
  3499. for (size_t i = 0; i < 545; i++) {
  3500. request += "/TooLongRequest";
  3501. }
  3502. request += "OK";
  3503. auto res = cli_.Get(request.c_str());
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3506. }
  3507. TEST_F(ServerTest, TooLongRequest) {
  3508. std::string request;
  3509. for (size_t i = 0; i < 546; i++) {
  3510. request += "/TooLongRequest";
  3511. }
  3512. request += "_NG";
  3513. auto res = cli_.Get(request.c_str());
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3516. }
  3517. TEST_F(ServerTest, AlmostTooLongRequest) {
  3518. // test for #2046 - URI length check shouldn't include other content on req
  3519. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3520. // leading /, space, HTTP/1.1)
  3521. std::string request =
  3522. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3523. auto res = cli_.Get(request.c_str());
  3524. ASSERT_TRUE(res);
  3525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3526. }
  3527. TEST_F(ServerTest, LongHeader) {
  3528. Request req;
  3529. req.method = "GET";
  3530. req.path = "/hi";
  3531. std::string host_and_port;
  3532. host_and_port += HOST;
  3533. host_and_port += ":";
  3534. host_and_port += std::to_string(PORT);
  3535. req.headers.emplace("Host", host_and_port.c_str());
  3536. req.headers.emplace("Accept", "*/*");
  3537. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3538. req.headers.emplace(
  3539. "Header-Name",
  3540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3541. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3568. "@@@@@@@@@@@@@@@@");
  3569. auto res = std::make_shared<Response>();
  3570. auto error = Error::Success;
  3571. auto ret = cli_.send(req, *res, error);
  3572. ASSERT_TRUE(ret);
  3573. EXPECT_EQ(StatusCode::OK_200, res->status);
  3574. }
  3575. TEST_F(ServerTest, LongQueryValue) {
  3576. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3579. }
  3580. TEST_F(ServerTest, TooLongQueryValue) {
  3581. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3582. ASSERT_FALSE(res);
  3583. EXPECT_EQ(Error::Read, res.error());
  3584. }
  3585. TEST_F(ServerTest, TooLongHeader) {
  3586. Request req;
  3587. req.method = "GET";
  3588. req.path = "/hi";
  3589. std::string host_and_port;
  3590. host_and_port += HOST;
  3591. host_and_port += ":";
  3592. host_and_port += std::to_string(PORT);
  3593. req.headers.emplace("Host", host_and_port.c_str());
  3594. req.headers.emplace("Accept", "*/*");
  3595. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3596. req.headers.emplace(
  3597. "Header-Name",
  3598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@");
  3627. auto res = std::make_shared<Response>();
  3628. auto error = Error::Success;
  3629. auto ret = cli_.send(req, *res, error);
  3630. ASSERT_TRUE(ret);
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. }
  3633. TEST_F(ServerTest, HeaderCountAtLimit) {
  3634. // Test with headers just under the 100 limit
  3635. httplib::Headers headers;
  3636. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3637. // This should keep us just under the 100 header limit
  3638. for (int i = 0; i < 95; i++) {
  3639. std::string name = "X-Test-Header-" + std::to_string(i);
  3640. std::string value = "value" + std::to_string(i);
  3641. headers.emplace(name, value);
  3642. }
  3643. // This should work fine as we're under the limit
  3644. auto res = cli_.Get("/hi", headers);
  3645. EXPECT_TRUE(res);
  3646. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3647. }
  3648. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3649. // Test with many headers to exceed the 100 limit
  3650. httplib::Headers headers;
  3651. // Add 150 headers to definitely exceed the 100 limit
  3652. for (int i = 0; i < 150; i++) {
  3653. std::string name = "X-Test-Header-" + std::to_string(i);
  3654. std::string value = "value" + std::to_string(i);
  3655. headers.emplace(name, value);
  3656. }
  3657. // This should fail due to exceeding header count limit
  3658. auto res = cli_.Get("/hi", headers);
  3659. // The request should either fail or return 400 Bad Request
  3660. if (res) {
  3661. // If we get a response, it should be 400 Bad Request
  3662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3663. } else {
  3664. // Or the request should fail entirely
  3665. EXPECT_FALSE(res);
  3666. }
  3667. }
  3668. TEST_F(ServerTest, PercentEncoding) {
  3669. auto res = cli_.Get("/e%6edwith%");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. }
  3673. TEST_F(ServerTest, PercentEncodingUnicode) {
  3674. auto res = cli_.Get("/e%u006edwith%");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::OK_200, res->status);
  3677. }
  3678. TEST_F(ServerTest, InvalidPercentEncoding) {
  3679. auto res = cli_.Get("/%endwith%");
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3682. }
  3683. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3684. auto res = cli_.Get("/%uendwith%");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3687. }
  3688. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3689. auto res = cli_.Get("/hello?aaa=bbb%");
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3692. }
  3693. TEST_F(ServerTest, PlusSignEncoding) {
  3694. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::OK_200, res->status);
  3697. EXPECT_EQ("a +b", res->body);
  3698. }
  3699. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3700. // This test simulates a potential DoS attack using many headers
  3701. // to verify our security fix prevents memory exhaustion
  3702. httplib::Headers attack_headers;
  3703. // Attempt to add many headers like an attacker would (200 headers to far
  3704. // exceed limit)
  3705. for (int i = 0; i < 200; i++) {
  3706. std::string name = "X-Attack-Header-" + std::to_string(i);
  3707. std::string value = "attack_payload_" + std::to_string(i);
  3708. attack_headers.emplace(name, value);
  3709. }
  3710. // Try to POST with excessive headers
  3711. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3712. // Should either fail or return 400 Bad Request due to security limit
  3713. if (res) {
  3714. // If we get a response, it should be 400 Bad Request
  3715. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3716. } else {
  3717. // Request failed, which is the expected behavior for DoS protection
  3718. EXPECT_FALSE(res);
  3719. }
  3720. }
  3721. TEST_F(ServerTest, MultipartFormData) {
  3722. MultipartFormDataItemsForClientInput items = {
  3723. {"text1", "text default", "", ""},
  3724. {"text2", "aωb", "", ""},
  3725. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3726. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3727. {"file3", "", "", "application/octet-stream"},
  3728. {"file4", "", "", " application/json tmp-string "}};
  3729. auto res = cli_.Post("/multipart", items);
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. }
  3733. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3734. MultipartFormDataItemsForClientInput items = {
  3735. {"text", "default text", "", ""},
  3736. {"multi_text1", "aaaaa", "", ""},
  3737. {"multi_text1", "bbbbb", "", ""},
  3738. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3739. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3740. "application/json"},
  3741. };
  3742. auto res = cli_.Post("/multipart/multi_file_values", items);
  3743. ASSERT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. }
  3746. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3747. auto res = cli_.Get("/hi");
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::OK_200, res->status);
  3750. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3751. EXPECT_EQ("Hello World!", res->body);
  3752. }
  3753. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3754. Request req;
  3755. req.method = "POST";
  3756. req.path = "/chunked";
  3757. std::string host_and_port;
  3758. host_and_port += HOST;
  3759. host_and_port += ":";
  3760. host_and_port += std::to_string(PORT);
  3761. req.headers.emplace("Host", host_and_port.c_str());
  3762. req.headers.emplace("Accept", "*/*");
  3763. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3764. req.headers.emplace("Content-Type", "text/plain");
  3765. req.headers.emplace("Content-Length", "0");
  3766. req.headers.emplace(
  3767. "Transfer-Encoding",
  3768. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3769. // Client does not chunk, so make a chunked body manually.
  3770. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3771. auto res = std::make_shared<Response>();
  3772. auto error = Error::Success;
  3773. auto ret = cli_.send(req, *res, error);
  3774. ASSERT_TRUE(ret);
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. }
  3777. TEST_F(ServerTest, GetStreamed2) {
  3778. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3781. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3782. EXPECT_EQ(true, res->has_header("Content-Range"));
  3783. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3784. EXPECT_EQ(std::string("ab"), res->body);
  3785. }
  3786. TEST_F(ServerTest, GetStreamed) {
  3787. auto res = cli_.Get("/streamed");
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::OK_200, res->status);
  3790. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3791. EXPECT_EQ(std::string("aaabbb"), res->body);
  3792. }
  3793. TEST_F(ServerTest, GetStreamedWithRange1) {
  3794. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3797. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3798. EXPECT_EQ(true, res->has_header("Content-Range"));
  3799. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3800. EXPECT_EQ(std::string("def"), res->body);
  3801. }
  3802. TEST_F(ServerTest, GetStreamedWithRange2) {
  3803. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3804. ASSERT_TRUE(res);
  3805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3806. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3809. EXPECT_EQ(std::string("bcdefg"), res->body);
  3810. }
  3811. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3812. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3815. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3816. EXPECT_EQ(true, res->has_header("Content-Range"));
  3817. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3818. EXPECT_EQ(std::string("efg"), res->body);
  3819. }
  3820. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3821. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3824. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3825. EXPECT_EQ(false, res->has_header("Content-Range"));
  3826. EXPECT_EQ(0U, res->body.size());
  3827. }
  3828. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3829. auto res = cli_.Get("/streamed-with-range",
  3830. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3831. "92233720368547758079223372036854775807"}});
  3832. ASSERT_TRUE(res);
  3833. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3834. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3835. EXPECT_EQ(false, res->has_header("Content-Range"));
  3836. EXPECT_EQ(0U, res->body.size());
  3837. }
  3838. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3839. auto res = cli_.Get(
  3840. "/with-range",
  3841. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3842. {"Accept-Encoding", ""}});
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3845. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3846. EXPECT_EQ(true, res->has_header("Content-Range"));
  3847. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3848. EXPECT_EQ(std::string("abcdefg"), res->body);
  3849. }
  3850. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3851. auto res = cli_.Get("/with-range", {
  3852. {"Range", "bytes=0-"},
  3853. {"Accept-Encoding", ""},
  3854. });
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3857. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3858. EXPECT_EQ(true, res->has_header("Content-Range"));
  3859. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3860. EXPECT_EQ(std::string("abcdefg"), res->body);
  3861. }
  3862. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3863. auto res =
  3864. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3865. ASSERT_TRUE(res);
  3866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3867. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3868. EXPECT_EQ(false, res->has_header("Content-Range"));
  3869. EXPECT_EQ(267U, res->body.size());
  3870. // Check that both range contents are present
  3871. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3872. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3873. // Check that Content-Range headers are present for both ranges
  3874. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3875. std::string::npos);
  3876. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3877. std::string::npos);
  3878. }
  3879. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3880. Ranges ranges;
  3881. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3882. ranges.emplace_back(0, -1);
  3883. }
  3884. auto res =
  3885. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3888. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(false, res->has_header("Content-Range"));
  3890. EXPECT_EQ(0U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3893. auto res =
  3894. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3895. ASSERT_TRUE(res);
  3896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3897. EXPECT_EQ(5U, res->body.size());
  3898. // Check that overlapping ranges are coalesced into a single range
  3899. EXPECT_EQ("bcdef", res->body);
  3900. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3901. // Should be single range, not multipart
  3902. EXPECT_TRUE(res->has_header("Content-Range"));
  3903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3904. }
  3905. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3906. auto res =
  3907. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3910. EXPECT_EQ(268U, res->body.size());
  3911. // Check that both range contents are present
  3912. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3913. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3914. // Check that Content-Range headers are present for both ranges
  3915. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3916. std::string::npos);
  3917. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3918. std::string::npos);
  3919. }
  3920. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3921. auto res =
  3922. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3925. EXPECT_EQ(269U, res->body.size());
  3926. // Check that both duplicate range contents are present
  3927. size_t first_abc = res->body.find("abc\r\n");
  3928. EXPECT_TRUE(first_abc != std::string::npos);
  3929. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3930. EXPECT_TRUE(second_abc != std::string::npos);
  3931. // Check that Content-Range headers are present for both ranges
  3932. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3933. EXPECT_TRUE(first_range != std::string::npos);
  3934. size_t second_range =
  3935. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3936. EXPECT_TRUE(second_range != std::string::npos);
  3937. }
  3938. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3939. auto res = cli_.Get("/streamed-with-range?error",
  3940. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3941. ASSERT_TRUE(res);
  3942. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3943. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3944. EXPECT_EQ(false, res->has_header("Content-Range"));
  3945. EXPECT_EQ(0U, res->body.size());
  3946. }
  3947. TEST_F(ServerTest, GetStreamedEndless) {
  3948. uint64_t offset = 0;
  3949. auto res = cli_.Get("/streamed-cancel",
  3950. [&](const char * /*data*/, uint64_t data_length) {
  3951. if (offset < 100) {
  3952. offset += data_length;
  3953. return true;
  3954. }
  3955. return false;
  3956. });
  3957. ASSERT_TRUE(!res);
  3958. EXPECT_EQ(Error::Canceled, res.error());
  3959. }
  3960. TEST_F(ServerTest, ClientStop) {
  3961. std::atomic_size_t count{4};
  3962. std::vector<std::thread> threads;
  3963. for (auto i = count.load(); i != 0; --i) {
  3964. threads.emplace_back([&]() {
  3965. auto res = cli_.Get("/streamed-cancel",
  3966. [&](const char *, uint64_t) { return true; });
  3967. --count;
  3968. ASSERT_TRUE(!res);
  3969. EXPECT_TRUE(res.error() == Error::Canceled ||
  3970. res.error() == Error::Read || res.error() == Error::Write);
  3971. });
  3972. }
  3973. std::this_thread::sleep_for(std::chrono::seconds(2));
  3974. while (count != 0) {
  3975. cli_.stop();
  3976. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3977. }
  3978. for (auto &t : threads) {
  3979. t.join();
  3980. }
  3981. }
  3982. TEST_F(ServerTest, GetWithRange1) {
  3983. auto res = cli_.Get("/with-range", {
  3984. make_range_header({{3, 5}}),
  3985. {"Accept-Encoding", ""},
  3986. });
  3987. ASSERT_TRUE(res);
  3988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3989. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3990. EXPECT_EQ(true, res->has_header("Content-Range"));
  3991. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3992. EXPECT_EQ(std::string("def"), res->body);
  3993. }
  3994. TEST_F(ServerTest, GetWithRange2) {
  3995. auto res = cli_.Get("/with-range", {
  3996. make_range_header({{1, -1}}),
  3997. {"Accept-Encoding", ""},
  3998. });
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4001. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4002. EXPECT_EQ(true, res->has_header("Content-Range"));
  4003. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4004. EXPECT_EQ(std::string("bcdefg"), res->body);
  4005. }
  4006. TEST_F(ServerTest, GetWithRange3) {
  4007. auto res = cli_.Get("/with-range", {
  4008. make_range_header({{0, 0}}),
  4009. {"Accept-Encoding", ""},
  4010. });
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4013. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4014. EXPECT_EQ(true, res->has_header("Content-Range"));
  4015. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4016. EXPECT_EQ(std::string("a"), res->body);
  4017. }
  4018. TEST_F(ServerTest, GetWithRange4) {
  4019. auto res = cli_.Get("/with-range", {
  4020. make_range_header({{-1, 2}}),
  4021. {"Accept-Encoding", ""},
  4022. });
  4023. ASSERT_TRUE(res);
  4024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4025. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4026. EXPECT_EQ(true, res->has_header("Content-Range"));
  4027. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4028. EXPECT_EQ(std::string("fg"), res->body);
  4029. }
  4030. TEST_F(ServerTest, GetWithRange5) {
  4031. auto res = cli_.Get("/with-range", {
  4032. make_range_header({{0, 5}}),
  4033. {"Accept-Encoding", ""},
  4034. });
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4038. EXPECT_EQ(true, res->has_header("Content-Range"));
  4039. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4040. EXPECT_EQ(std::string("abcdef"), res->body);
  4041. }
  4042. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4043. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4046. }
  4047. TEST_F(ServerTest, GetWithRangeMultipart) {
  4048. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4049. ASSERT_TRUE(res);
  4050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4051. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4052. EXPECT_EQ(false, res->has_header("Content-Range"));
  4053. EXPECT_EQ(267U, res->body.size());
  4054. }
  4055. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4056. auto res =
  4057. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4060. }
  4061. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4062. auto res = cli_.Get("/with-range-customized-response",
  4063. {{make_range_header({{1, 2}})}});
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4066. EXPECT_EQ(true, res->has_header("Content-Length"));
  4067. EXPECT_EQ(false, res->has_header("Content-Range"));
  4068. EXPECT_EQ(JSON_DATA, res->body);
  4069. }
  4070. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4071. auto res = cli_.Get("/with-range-customized-response",
  4072. {{make_range_header({{1, 2}, {4, 5}})}});
  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, Issue1772) {
  4080. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4083. }
  4084. TEST_F(ServerTest, Issue609) {
  4085. auto res = cli_.Delete("/issue609");
  4086. ASSERT_TRUE(res);
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. EXPECT_EQ(std::string("ok"), res->body);
  4089. }
  4090. TEST_F(ServerTest, GetStreamedChunked) {
  4091. auto res = cli_.Get("/streamed-chunked");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. EXPECT_EQ(std::string("123456789"), res->body);
  4095. }
  4096. TEST_F(ServerTest, GetStreamedChunked2) {
  4097. auto res = cli_.Get("/streamed-chunked2");
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ(std::string("123456789"), res->body);
  4101. }
  4102. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4103. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. EXPECT_EQ(std::string("123456789"), res->body);
  4107. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  4108. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  4109. }
  4110. TEST_F(ServerTest, LargeChunkedPost) {
  4111. Request req;
  4112. req.method = "POST";
  4113. req.path = "/large-chunked";
  4114. std::string host_and_port;
  4115. host_and_port += HOST;
  4116. host_and_port += ":";
  4117. host_and_port += std::to_string(PORT);
  4118. req.headers.emplace("Host", host_and_port.c_str());
  4119. req.headers.emplace("Accept", "*/*");
  4120. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4121. req.headers.emplace("Content-Type", "text/plain");
  4122. req.headers.emplace("Content-Length", "0");
  4123. req.headers.emplace("Transfer-Encoding", "chunked");
  4124. std::string long_string(30 * 1024u, 'a');
  4125. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4126. // Attempt to make a large enough post to exceed OS buffers, to test that
  4127. // the server handles short reads if the full chunk data isn't available.
  4128. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4129. auto res = std::make_shared<Response>();
  4130. auto error = Error::Success;
  4131. auto ret = cli_.send(req, *res, error);
  4132. ASSERT_TRUE(ret);
  4133. EXPECT_EQ(StatusCode::OK_200, res->status);
  4134. }
  4135. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4136. auto res = cli_.Get("/remote_addr");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::OK_200, res->status);
  4139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4140. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4141. }
  4142. TEST_F(ServerTest, GetMethodLocalAddr) {
  4143. auto res = cli_.Get("/local_addr");
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::OK_200, res->status);
  4146. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4147. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4148. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4149. }
  4150. TEST_F(ServerTest, HTTPResponseSplitting) {
  4151. auto res = cli_.Get("/http_response_splitting");
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. }
  4155. TEST_F(ServerTest, SlowRequest) {
  4156. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4157. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4158. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4159. }
  4160. #if 0
  4161. TEST_F(ServerTest, SlowPost) {
  4162. char buffer[64 * 1024];
  4163. memset(buffer, 0x42, sizeof(buffer));
  4164. auto res = cli_.Post(
  4165. "/slowpost", 64 * 1024 * 1024,
  4166. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4167. auto ret = sink.write(buffer, sizeof(buffer));
  4168. EXPECT_TRUE(ret);
  4169. return true;
  4170. },
  4171. "text/plain");
  4172. ASSERT_TRUE(res);
  4173. EXPECT_EQ(StatusCode::OK_200, res->status);
  4174. }
  4175. TEST_F(ServerTest, SlowPostFail) {
  4176. char buffer[64 * 1024];
  4177. memset(buffer, 0x42, sizeof(buffer));
  4178. cli_.set_write_timeout(std::chrono::seconds(0));
  4179. auto res = cli_.Post(
  4180. "/slowpost", 64 * 1024 * 1024,
  4181. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4182. sink.write(buffer, sizeof(buffer));
  4183. return true;
  4184. },
  4185. "text/plain");
  4186. ASSERT_TRUE(!res);
  4187. EXPECT_EQ(Error::Write, res.error());
  4188. }
  4189. #endif
  4190. TEST_F(ServerTest, Put) {
  4191. auto res = cli_.Put("/put", "PUT", "text/plain");
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ("PUT", res->body);
  4195. }
  4196. TEST_F(ServerTest, PutWithContentProvider) {
  4197. auto res = cli_.Put(
  4198. "/put", 3,
  4199. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4200. sink.os << "PUT";
  4201. return true;
  4202. },
  4203. "text/plain");
  4204. ASSERT_TRUE(res);
  4205. EXPECT_EQ(StatusCode::OK_200, res->status);
  4206. EXPECT_EQ("PUT", res->body);
  4207. }
  4208. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4209. auto res = cli_.Post(
  4210. "/post", 42,
  4211. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4212. return false;
  4213. },
  4214. "text/plain");
  4215. ASSERT_TRUE(!res);
  4216. EXPECT_EQ(Error::Canceled, res.error());
  4217. }
  4218. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4219. auto res = cli_.Put(
  4220. "/put",
  4221. [](size_t /*offset*/, DataSink &sink) {
  4222. sink.os << "PUT";
  4223. sink.done();
  4224. return true;
  4225. },
  4226. "text/plain");
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. EXPECT_EQ("PUT", res->body);
  4230. }
  4231. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4232. auto res = cli_.Post(
  4233. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4234. "text/plain");
  4235. ASSERT_TRUE(!res);
  4236. EXPECT_EQ(Error::Canceled, res.error());
  4237. }
  4238. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4239. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4240. cli_.set_compress(true);
  4241. auto res = cli_.Put(
  4242. "/put", 3,
  4243. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4244. sink.os << "PUT";
  4245. return true;
  4246. },
  4247. "text/plain");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("PUT", res->body);
  4251. }
  4252. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4253. cli_.set_compress(true);
  4254. auto res = cli_.Post(
  4255. "/post", 42,
  4256. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4257. return false;
  4258. },
  4259. "text/plain");
  4260. ASSERT_TRUE(!res);
  4261. EXPECT_EQ(Error::Canceled, res.error());
  4262. }
  4263. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4264. cli_.set_compress(true);
  4265. auto res = cli_.Put(
  4266. "/put",
  4267. [](size_t /*offset*/, DataSink &sink) {
  4268. sink.os << "PUT";
  4269. sink.done();
  4270. return true;
  4271. },
  4272. "text/plain");
  4273. ASSERT_TRUE(res);
  4274. EXPECT_EQ(StatusCode::OK_200, res->status);
  4275. EXPECT_EQ("PUT", res->body);
  4276. }
  4277. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4278. cli_.set_compress(true);
  4279. auto res = cli_.Post(
  4280. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4281. "text/plain");
  4282. ASSERT_TRUE(!res);
  4283. EXPECT_EQ(Error::Canceled, res.error());
  4284. }
  4285. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4286. cli_.set_compress(true);
  4287. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. EXPECT_EQ(LARGE_DATA, res->body);
  4291. }
  4292. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4293. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4294. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4295. Client cli(s.c_str());
  4296. cli.enable_server_certificate_verification(false);
  4297. #else
  4298. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4299. Client cli(s.c_str());
  4300. #endif
  4301. cli.set_compress(true);
  4302. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::OK_200, res->status);
  4305. EXPECT_EQ(LARGE_DATA, res->body);
  4306. // The compressed size should be less than a 10th of the original. May vary
  4307. // depending on the zlib library.
  4308. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4309. static_cast<uint64_t>(10 * 1024 * 1024));
  4310. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4311. }
  4312. TEST_F(ServerTest, PutContentWithDeflate) {
  4313. cli_.set_compress(false);
  4314. Headers headers;
  4315. headers.emplace("Content-Encoding", "deflate");
  4316. // PUT in deflate format:
  4317. auto res = cli_.Put("/put", headers,
  4318. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ("PUT", res->body);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4324. Headers headers;
  4325. headers.emplace("Accept-Encoding", "gzip, deflate");
  4326. auto res = cli_.Get("/streamed-chunked", headers);
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. EXPECT_EQ(std::string("123456789"), res->body);
  4330. }
  4331. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4332. Headers headers;
  4333. headers.emplace("Accept-Encoding", "gzip, deflate");
  4334. auto res = cli_.Get("/streamed-chunked2", headers);
  4335. ASSERT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ(std::string("123456789"), res->body);
  4338. }
  4339. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4340. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. }
  4344. TEST(GzipDecompressor, ChunkedDecompression) {
  4345. std::string data;
  4346. for (size_t i = 0; i < 32 * 1024; ++i) {
  4347. data.push_back(static_cast<char>('a' + i % 26));
  4348. }
  4349. std::string compressed_data;
  4350. {
  4351. httplib::detail::gzip_compressor compressor;
  4352. bool result = compressor.compress(
  4353. data.data(), data.size(),
  4354. /*last=*/true,
  4355. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4356. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4357. compressed_data_size);
  4358. return true;
  4359. });
  4360. ASSERT_TRUE(result);
  4361. }
  4362. std::string decompressed_data;
  4363. {
  4364. httplib::detail::gzip_decompressor decompressor;
  4365. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4366. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4367. size_t chunk_size = 130;
  4368. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4369. chunk_begin += chunk_size) {
  4370. size_t current_chunk_size =
  4371. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4372. bool result = decompressor.decompress(
  4373. compressed_data.data() + chunk_begin, current_chunk_size,
  4374. [&](const char *decompressed_data_chunk,
  4375. size_t decompressed_data_chunk_size) {
  4376. decompressed_data.insert(decompressed_data.size(),
  4377. decompressed_data_chunk,
  4378. decompressed_data_chunk_size);
  4379. return true;
  4380. });
  4381. ASSERT_TRUE(result);
  4382. }
  4383. }
  4384. ASSERT_EQ(data, decompressed_data);
  4385. }
  4386. TEST(GzipDecompressor, DeflateDecompression) {
  4387. std::string original_text = "Raw deflate without gzip";
  4388. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4389. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4390. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4391. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4392. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4393. std::string decompressed_data;
  4394. {
  4395. httplib::detail::gzip_decompressor decompressor;
  4396. bool result = decompressor.decompress(
  4397. compressed_data.data(), compressed_data.size(),
  4398. [&](const char *decompressed_data_chunk,
  4399. size_t decompressed_data_chunk_size) {
  4400. decompressed_data.insert(decompressed_data.size(),
  4401. decompressed_data_chunk,
  4402. decompressed_data_chunk_size);
  4403. return true;
  4404. });
  4405. ASSERT_TRUE(result);
  4406. }
  4407. ASSERT_EQ(original_text, decompressed_data);
  4408. }
  4409. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4410. std::string original_text = "Raw deflate without gzip";
  4411. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4412. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4413. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4414. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4415. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4416. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4417. std::string decompressed_data;
  4418. {
  4419. httplib::detail::gzip_decompressor decompressor;
  4420. bool result = decompressor.decompress(
  4421. compressed_data.data(), compressed_data.size(),
  4422. [&](const char *decompressed_data_chunk,
  4423. size_t decompressed_data_chunk_size) {
  4424. decompressed_data.insert(decompressed_data.size(),
  4425. decompressed_data_chunk,
  4426. decompressed_data_chunk_size);
  4427. return true;
  4428. });
  4429. ASSERT_TRUE(result);
  4430. }
  4431. ASSERT_EQ(original_text, decompressed_data);
  4432. }
  4433. #ifdef _WIN32
  4434. TEST(GzipDecompressor, LargeRandomData) {
  4435. // prepare large random data that is difficult to be compressed and is
  4436. // expected to have large size even when compressed
  4437. std::random_device seed_gen;
  4438. std::mt19937 random(seed_gen());
  4439. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4440. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4441. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4442. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4443. // compress data over 4GiB
  4444. std::string compressed_data;
  4445. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4446. httplib::detail::gzip_compressor compressor;
  4447. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4448. data.size() * sizeof(std::uint32_t), true,
  4449. [&](const char *data, size_t size) {
  4450. compressed_data.insert(
  4451. compressed_data.size(), data, size);
  4452. return true;
  4453. });
  4454. ASSERT_TRUE(result);
  4455. // FIXME: compressed data size is expected to be greater than 4GiB,
  4456. // but there is no guarantee
  4457. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4458. // decompress data over 4GiB
  4459. std::string decompressed_data;
  4460. decompressed_data.reserve(data_size);
  4461. httplib::detail::gzip_decompressor decompressor;
  4462. result = decompressor.decompress(
  4463. compressed_data.data(), compressed_data.size(),
  4464. [&](const char *data, size_t size) {
  4465. decompressed_data.insert(decompressed_data.size(), data, size);
  4466. return true;
  4467. });
  4468. ASSERT_TRUE(result);
  4469. // compare
  4470. ASSERT_EQ(data_size, decompressed_data.size());
  4471. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4472. 0);
  4473. }
  4474. #endif
  4475. #endif
  4476. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4477. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4478. Headers headers;
  4479. headers.emplace("Accept-Encoding", "br");
  4480. auto res = cli_.Get("/streamed-chunked", headers);
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ(std::string("123456789"), res->body);
  4484. }
  4485. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4486. Headers headers;
  4487. headers.emplace("Accept-Encoding", "br");
  4488. auto res = cli_.Get("/streamed-chunked2", headers);
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ(std::string("123456789"), res->body);
  4492. }
  4493. #endif
  4494. TEST_F(ServerTest, Patch) {
  4495. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4496. ASSERT_TRUE(res);
  4497. EXPECT_EQ(StatusCode::OK_200, res->status);
  4498. EXPECT_EQ("PATCH", res->body);
  4499. }
  4500. TEST_F(ServerTest, Delete) {
  4501. auto res = cli_.Delete("/delete");
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::OK_200, res->status);
  4504. EXPECT_EQ("DELETE", res->body);
  4505. }
  4506. TEST_F(ServerTest, DeleteContentReceiver) {
  4507. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::OK_200, res->status);
  4510. EXPECT_EQ("content", res->body);
  4511. }
  4512. TEST_F(ServerTest, Options) {
  4513. auto res = cli_.Options("*");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4517. EXPECT_TRUE(res->body.empty());
  4518. }
  4519. TEST_F(ServerTest, URL) {
  4520. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. }
  4524. TEST_F(ServerTest, ArrayParam) {
  4525. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. }
  4529. TEST_F(ServerTest, NoMultipleHeaders) {
  4530. Headers headers = {{"Content-Length", "5"}};
  4531. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4532. "text/plain");
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. }
  4536. TEST_F(ServerTest, PostContentReceiver) {
  4537. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4538. ASSERT_TRUE(res);
  4539. ASSERT_EQ(StatusCode::OK_200, res->status);
  4540. ASSERT_EQ("content", res->body);
  4541. }
  4542. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4543. MultipartFormDataItemsForClientInput items = {
  4544. {"text1", "text default", "", ""},
  4545. {"text2", "aωb", "", ""},
  4546. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4547. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4548. {"file3", "", "", "application/octet-stream"},
  4549. };
  4550. auto res = cli_.Post("/content_receiver", items);
  4551. ASSERT_TRUE(res);
  4552. EXPECT_EQ(StatusCode::OK_200, res->status);
  4553. }
  4554. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4555. MultipartFormDataItemsForClientInput items = {
  4556. {"text1", "text default", "", ""},
  4557. {"text2", "aωb", "", ""},
  4558. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4559. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4560. {"file3", "", "", "application/octet-stream"},
  4561. };
  4562. auto boundary = std::string("+++++");
  4563. std::string body;
  4564. for (const auto &item : items) {
  4565. body += "--" + boundary + "\r\n";
  4566. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4567. if (!item.filename.empty()) {
  4568. body += "; filename=\"" + item.filename + "\"";
  4569. }
  4570. body += "\r\n";
  4571. if (!item.content_type.empty()) {
  4572. body += "Content-Type: " + item.content_type + "\r\n";
  4573. }
  4574. body += "\r\n";
  4575. body += item.content + "\r\n";
  4576. }
  4577. body += "--" + boundary + "--\r\n";
  4578. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4579. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, PostContentReceiverGzip) {
  4584. cli_.set_compress(true);
  4585. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4586. ASSERT_TRUE(res);
  4587. ASSERT_EQ(StatusCode::OK_200, res->status);
  4588. ASSERT_EQ("content", res->body);
  4589. }
  4590. TEST_F(ServerTest, PutContentReceiver) {
  4591. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4592. ASSERT_TRUE(res);
  4593. ASSERT_EQ(StatusCode::OK_200, res->status);
  4594. ASSERT_EQ("content", res->body);
  4595. }
  4596. TEST_F(ServerTest, PatchContentReceiver) {
  4597. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4598. ASSERT_TRUE(res);
  4599. ASSERT_EQ(StatusCode::OK_200, res->status);
  4600. ASSERT_EQ("content", res->body);
  4601. }
  4602. template <typename ClientType>
  4603. void TestWithHeadersAndContentReceiver(
  4604. ClientType &cli,
  4605. std::function<Result(ClientType &, const std::string &, const Headers &,
  4606. const std::string &, const std::string &,
  4607. ContentReceiver, DownloadProgress)>
  4608. request_func) {
  4609. Headers headers;
  4610. headers.emplace("X-Custom-Header", "test-value");
  4611. std::string received_body;
  4612. auto res = request_func(
  4613. cli, "/content_receiver", headers, "content", "application/json",
  4614. [&](const char *data, size_t data_length) {
  4615. received_body.append(data, data_length);
  4616. return true;
  4617. },
  4618. nullptr);
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("content", received_body);
  4622. }
  4623. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4624. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4625. using ClientT = SSLClient;
  4626. #else
  4627. using ClientT = Client;
  4628. #endif
  4629. TestWithHeadersAndContentReceiver<ClientT>(
  4630. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4631. const std::string &body, const std::string &content_type,
  4632. ContentReceiver receiver, DownloadProgress progress) {
  4633. return cli.Post(path, headers, body, content_type, receiver, progress);
  4634. });
  4635. }
  4636. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4637. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4638. using ClientT = SSLClient;
  4639. #else
  4640. using ClientT = Client;
  4641. #endif
  4642. TestWithHeadersAndContentReceiver<ClientT>(
  4643. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4644. const std::string &body, const std::string &content_type,
  4645. ContentReceiver receiver, DownloadProgress progress) {
  4646. return cli.Put(path, headers, body, content_type, receiver, progress);
  4647. });
  4648. }
  4649. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4651. using ClientT = SSLClient;
  4652. #else
  4653. using ClientT = Client;
  4654. #endif
  4655. TestWithHeadersAndContentReceiver<ClientT>(
  4656. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4657. const std::string &body, const std::string &content_type,
  4658. ContentReceiver receiver, DownloadProgress progress) {
  4659. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4660. });
  4661. }
  4662. template <typename ClientType>
  4663. void TestWithHeadersAndContentReceiverWithProgress(
  4664. ClientType &cli,
  4665. std::function<Result(ClientType &, const std::string &, const Headers &,
  4666. const std::string &, const std::string &,
  4667. ContentReceiver, DownloadProgress)>
  4668. request_func) {
  4669. Headers headers;
  4670. headers.emplace("X-Test-Header", "progress-test");
  4671. std::string received_body;
  4672. auto progress_called = false;
  4673. auto res = request_func(
  4674. cli, "/content_receiver", headers, "content", "text/plain",
  4675. [&](const char *data, size_t data_length) {
  4676. received_body.append(data, data_length);
  4677. return true;
  4678. },
  4679. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4680. progress_called = true;
  4681. return true;
  4682. });
  4683. ASSERT_TRUE(res);
  4684. EXPECT_EQ(StatusCode::OK_200, res->status);
  4685. EXPECT_EQ("content", received_body);
  4686. EXPECT_TRUE(progress_called);
  4687. }
  4688. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4690. using ClientT = SSLClient;
  4691. #else
  4692. using ClientT = Client;
  4693. #endif
  4694. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4695. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4696. const std::string &body, const std::string &content_type,
  4697. ContentReceiver receiver, DownloadProgress progress) {
  4698. return cli.Post(path, headers, body, content_type, receiver, progress);
  4699. });
  4700. }
  4701. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4703. using ClientT = SSLClient;
  4704. #else
  4705. using ClientT = Client;
  4706. #endif
  4707. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4708. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4709. const std::string &body, const std::string &content_type,
  4710. ContentReceiver receiver, DownloadProgress progress) {
  4711. return cli.Put(path, headers, body, content_type, receiver, progress);
  4712. });
  4713. }
  4714. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4716. using ClientT = SSLClient;
  4717. #else
  4718. using ClientT = Client;
  4719. #endif
  4720. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4721. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4722. const std::string &body, const std::string &content_type,
  4723. ContentReceiver receiver, DownloadProgress progress) {
  4724. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4725. });
  4726. }
  4727. template <typename ClientType>
  4728. void TestWithHeadersAndContentReceiverError(
  4729. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4730. const Headers &, const std::string &,
  4731. const std::string &, ContentReceiver)>
  4732. request_func) {
  4733. Headers headers;
  4734. headers.emplace("X-Error-Test", "true");
  4735. std::string received_body;
  4736. auto receiver_failed = false;
  4737. auto res =
  4738. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4739. [&](const char *data, size_t data_length) {
  4740. received_body.append(data, data_length);
  4741. receiver_failed = true;
  4742. return false;
  4743. });
  4744. ASSERT_FALSE(res);
  4745. EXPECT_TRUE(receiver_failed);
  4746. }
  4747. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4748. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4749. using ClientT = SSLClient;
  4750. #else
  4751. using ClientT = Client;
  4752. #endif
  4753. TestWithHeadersAndContentReceiverError<ClientT>(
  4754. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4755. const std::string &body, const std::string &content_type,
  4756. ContentReceiver receiver) {
  4757. return cli.Post(path, headers, body, content_type, receiver);
  4758. });
  4759. }
  4760. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4762. using ClientT = SSLClient;
  4763. #else
  4764. using ClientT = Client;
  4765. #endif
  4766. TestWithHeadersAndContentReceiverError<ClientT>(
  4767. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4768. const std::string &body, const std::string &content_type,
  4769. ContentReceiver receiver) {
  4770. return cli.Put(path, headers, body, content_type, receiver);
  4771. });
  4772. }
  4773. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4774. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4775. using ClientT = SSLClient;
  4776. #else
  4777. using ClientT = Client;
  4778. #endif
  4779. TestWithHeadersAndContentReceiverError<ClientT>(
  4780. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4781. const std::string &body, const std::string &content_type,
  4782. ContentReceiver receiver) {
  4783. return cli.Patch(path, headers, body, content_type, receiver);
  4784. });
  4785. }
  4786. TEST_F(ServerTest, PostQueryStringAndBody) {
  4787. auto res =
  4788. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4789. ASSERT_TRUE(res);
  4790. ASSERT_EQ(StatusCode::OK_200, res->status);
  4791. }
  4792. TEST_F(ServerTest, HTTP2Magic) {
  4793. Request req;
  4794. req.method = "PRI";
  4795. req.path = "*";
  4796. req.body = "SM";
  4797. auto res = std::make_shared<Response>();
  4798. auto error = Error::Success;
  4799. auto ret = cli_.send(req, *res, error);
  4800. ASSERT_TRUE(ret);
  4801. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4802. }
  4803. TEST_F(ServerTest, KeepAlive) {
  4804. auto res = cli_.Get("/hi");
  4805. ASSERT_TRUE(res);
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4808. EXPECT_EQ("Hello World!", res->body);
  4809. res = cli_.Get("/hi");
  4810. ASSERT_TRUE(res);
  4811. EXPECT_EQ(StatusCode::OK_200, res->status);
  4812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4813. EXPECT_EQ("Hello World!", res->body);
  4814. res = cli_.Get("/hi");
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(StatusCode::OK_200, res->status);
  4817. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4818. EXPECT_EQ("Hello World!", res->body);
  4819. res = cli_.Get("/not-exist");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4822. res = cli_.Post("/empty", "", "text/plain");
  4823. ASSERT_TRUE(res);
  4824. EXPECT_EQ(StatusCode::OK_200, res->status);
  4825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4826. EXPECT_EQ("empty", res->body);
  4827. EXPECT_EQ("close", res->get_header_value("Connection"));
  4828. res = cli_.Post(
  4829. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4830. "text/plain");
  4831. ASSERT_TRUE(res);
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4834. EXPECT_EQ("empty", res->body);
  4835. cli_.set_keep_alive(false);
  4836. res = cli_.Get("/last-request");
  4837. ASSERT_TRUE(res);
  4838. EXPECT_EQ(StatusCode::OK_200, res->status);
  4839. EXPECT_EQ("close", res->get_header_value("Connection"));
  4840. }
  4841. TEST_F(ServerTest, TooManyRedirect) {
  4842. cli_.set_follow_location(true);
  4843. auto res = cli_.Get("/redirect/0");
  4844. ASSERT_TRUE(!res);
  4845. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4846. }
  4847. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4848. TEST_F(ServerTest, Gzip) {
  4849. Headers headers;
  4850. headers.emplace("Accept-Encoding", "gzip, deflate");
  4851. auto res = cli_.Get("/compress", headers);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4855. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4856. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4857. "7890123456789012345678901234567890",
  4858. res->body);
  4859. EXPECT_EQ(StatusCode::OK_200, res->status);
  4860. }
  4861. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4862. Headers headers;
  4863. headers.emplace("Accept-Encoding", "");
  4864. auto res = cli_.Get("/compress", headers);
  4865. ASSERT_TRUE(res);
  4866. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4867. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4868. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4869. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4870. "7890123456789012345678901234567890",
  4871. res->body);
  4872. EXPECT_EQ(StatusCode::OK_200, res->status);
  4873. }
  4874. TEST_F(ServerTest, GzipWithContentReceiver) {
  4875. Headers headers;
  4876. headers.emplace("Accept-Encoding", "gzip, deflate");
  4877. std::string body;
  4878. auto res = cli_.Get("/compress", headers,
  4879. [&](const char *data, uint64_t data_length) {
  4880. EXPECT_EQ(100U, data_length);
  4881. body.append(data, data_length);
  4882. return true;
  4883. });
  4884. ASSERT_TRUE(res);
  4885. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4887. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4888. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4889. "7890123456789012345678901234567890",
  4890. body);
  4891. EXPECT_EQ(StatusCode::OK_200, res->status);
  4892. }
  4893. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4894. Headers headers;
  4895. headers.emplace("Accept-Encoding", "gzip, deflate");
  4896. cli_.set_decompress(false);
  4897. auto res = cli_.Get("/compress", headers);
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4901. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4902. EXPECT_EQ(33U, res->body.size());
  4903. EXPECT_EQ(StatusCode::OK_200, res->status);
  4904. }
  4905. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4906. Headers headers;
  4907. headers.emplace("Accept-Encoding", "");
  4908. std::string body;
  4909. auto res = cli_.Get("/compress", headers,
  4910. [&](const char *data, uint64_t data_length) {
  4911. EXPECT_EQ(100U, data_length);
  4912. body.append(data, data_length);
  4913. return true;
  4914. });
  4915. ASSERT_TRUE(res);
  4916. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4917. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4918. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4919. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4920. "7890123456789012345678901234567890",
  4921. body);
  4922. EXPECT_EQ(StatusCode::OK_200, res->status);
  4923. }
  4924. TEST_F(ServerTest, NoGzip) {
  4925. Headers headers;
  4926. headers.emplace("Accept-Encoding", "gzip, deflate");
  4927. auto res = cli_.Get("/nocompress", headers);
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4930. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4933. "7890123456789012345678901234567890",
  4934. res->body);
  4935. EXPECT_EQ(StatusCode::OK_200, res->status);
  4936. }
  4937. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "gzip, deflate");
  4940. std::string body;
  4941. auto res = cli_.Get("/nocompress", headers,
  4942. [&](const char *data, uint64_t data_length) {
  4943. EXPECT_EQ(100U, data_length);
  4944. body.append(data, data_length);
  4945. return true;
  4946. });
  4947. ASSERT_TRUE(res);
  4948. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4949. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4950. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4951. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4952. "7890123456789012345678901234567890",
  4953. body);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. }
  4956. TEST_F(ServerTest, MultipartFormDataGzip) {
  4957. MultipartFormDataItemsForClientInput items = {
  4958. {"key1", "test", "", ""},
  4959. {"key2", "--abcdefg123", "", ""},
  4960. };
  4961. cli_.set_compress(true);
  4962. auto res = cli_.Post("/compress-multipart", items);
  4963. ASSERT_TRUE(res);
  4964. EXPECT_EQ(StatusCode::OK_200, res->status);
  4965. }
  4966. #endif
  4967. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4968. TEST_F(ServerTest, Brotli) {
  4969. Headers headers;
  4970. headers.emplace("Accept-Encoding", "br");
  4971. auto res = cli_.Get("/compress", headers);
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4974. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4975. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4976. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4977. "7890123456789012345678901234567890",
  4978. res->body);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. }
  4981. #endif
  4982. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4983. TEST_F(ServerTest, Zstd) {
  4984. Headers headers;
  4985. headers.emplace("Accept-Encoding", "zstd");
  4986. auto res = cli_.Get("/compress", headers);
  4987. ASSERT_TRUE(res);
  4988. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4990. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4992. "7890123456789012345678901234567890",
  4993. res->body);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4997. Headers headers;
  4998. headers.emplace("Accept-Encoding", "");
  4999. auto res = cli_.Get("/compress", headers);
  5000. ASSERT_TRUE(res);
  5001. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5003. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5004. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5005. "7890123456789012345678901234567890",
  5006. res->body);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. }
  5009. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5010. Headers headers;
  5011. headers.emplace("Accept-Encoding", "zstd");
  5012. std::string body;
  5013. auto res = cli_.Get("/compress", headers,
  5014. [&](const char *data, uint64_t data_length) {
  5015. EXPECT_EQ(100U, data_length);
  5016. body.append(data, data_length);
  5017. return true;
  5018. });
  5019. ASSERT_TRUE(res);
  5020. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5022. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5024. "7890123456789012345678901234567890",
  5025. body);
  5026. EXPECT_EQ(StatusCode::OK_200, res->status);
  5027. }
  5028. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5029. Headers headers;
  5030. headers.emplace("Accept-Encoding", "zstd");
  5031. cli_.set_decompress(false);
  5032. auto res = cli_.Get("/compress", headers);
  5033. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5034. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5035. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5036. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5037. ASSERT_TRUE(res);
  5038. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. ASSERT_EQ(26U, res->body.size());
  5043. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5044. 0);
  5045. }
  5046. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5047. Headers headers;
  5048. headers.emplace("Accept-Encoding", "");
  5049. std::string body;
  5050. auto res = cli_.Get("/compress", headers,
  5051. [&](const char *data, uint64_t data_length) {
  5052. EXPECT_EQ(100U, data_length);
  5053. body.append(data, data_length);
  5054. return true;
  5055. });
  5056. ASSERT_TRUE(res);
  5057. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5061. "7890123456789012345678901234567890",
  5062. body);
  5063. EXPECT_EQ(StatusCode::OK_200, res->status);
  5064. }
  5065. TEST_F(ServerTest, NoZstd) {
  5066. Headers headers;
  5067. headers.emplace("Accept-Encoding", "zstd");
  5068. auto res = cli_.Get("/nocompress", headers);
  5069. ASSERT_TRUE(res);
  5070. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5071. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5072. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5073. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5074. "7890123456789012345678901234567890",
  5075. res->body);
  5076. EXPECT_EQ(StatusCode::OK_200, res->status);
  5077. }
  5078. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5079. Headers headers;
  5080. headers.emplace("Accept-Encoding", "zstd");
  5081. std::string body;
  5082. auto res = cli_.Get("/nocompress", headers,
  5083. [&](const char *data, uint64_t data_length) {
  5084. EXPECT_EQ(100U, data_length);
  5085. body.append(data, data_length);
  5086. return true;
  5087. });
  5088. ASSERT_TRUE(res);
  5089. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5090. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5093. "7890123456789012345678901234567890",
  5094. body);
  5095. EXPECT_EQ(StatusCode::OK_200, res->status);
  5096. }
  5097. // TODO: How to enable zstd ??
  5098. TEST_F(ServerTest, MultipartFormDataZstd) {
  5099. MultipartFormDataItemsForClientInput items = {
  5100. {"key1", "test", "", ""},
  5101. {"key2", "--abcdefg123", "", ""},
  5102. };
  5103. Headers headers;
  5104. headers.emplace("Accept-Encoding", "zstd");
  5105. cli_.set_compress(true);
  5106. auto res = cli_.Post("/compress-multipart", headers, items);
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. }
  5110. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5111. Headers headers;
  5112. headers.emplace("Accept-Encoding", "zstd");
  5113. cli_.set_compress(true);
  5114. auto res = cli_.Put(
  5115. "/put", headers, 3,
  5116. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5117. sink.os << "PUT";
  5118. return true;
  5119. },
  5120. "text/plain");
  5121. ASSERT_TRUE(res);
  5122. EXPECT_EQ(StatusCode::OK_200, res->status);
  5123. EXPECT_EQ("PUT", res->body);
  5124. }
  5125. // Pre-compression logging tests
  5126. TEST_F(ServerTest, PreCompressionLogging) {
  5127. // Test data for compression (matches the actual /compress endpoint content)
  5128. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5129. // Variables to capture logging data
  5130. std::string pre_compression_body;
  5131. std::string pre_compression_content_type;
  5132. std::string pre_compression_content_encoding;
  5133. std::string post_compression_body;
  5134. std::string post_compression_content_type;
  5135. std::string post_compression_content_encoding;
  5136. // Set up pre-compression logger
  5137. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5138. pre_compression_body = res.body;
  5139. pre_compression_content_type = res.get_header_value("Content-Type");
  5140. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5141. });
  5142. // Set up post-compression logger
  5143. svr_.set_logger([&](const Request &req, const Response &res) {
  5144. post_compression_body = res.body;
  5145. post_compression_content_type = res.get_header_value("Content-Type");
  5146. post_compression_content_encoding = res.get_header_value("Content-Encoding");
  5147. });
  5148. // Test with gzip compression
  5149. Headers headers;
  5150. headers.emplace("Accept-Encoding", "gzip");
  5151. auto res = cli_.Get("/compress", headers);
  5152. // Verify response was compressed
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5156. // Verify pre-compression logger captured uncompressed content
  5157. EXPECT_EQ(test_content, pre_compression_body);
  5158. EXPECT_EQ("text/plain", pre_compression_content_type);
  5159. EXPECT_TRUE(pre_compression_content_encoding.empty()); // No encoding header before compression
  5160. // Verify post-compression logger captured compressed content
  5161. EXPECT_NE(test_content, post_compression_body); // Should be different after compression
  5162. EXPECT_EQ("text/plain", post_compression_content_type);
  5163. EXPECT_EQ("gzip", post_compression_content_encoding);
  5164. // Verify compressed content is smaller
  5165. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5166. }
  5167. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5168. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5169. std::string pre_compression_body;
  5170. std::string post_compression_body;
  5171. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5172. pre_compression_body = res.body;
  5173. });
  5174. svr_.set_logger([&](const Request &req, const Response &res) {
  5175. post_compression_body = res.body;
  5176. });
  5177. Headers headers;
  5178. headers.emplace("Accept-Encoding", "br");
  5179. auto res = cli_.Get("/compress", headers);
  5180. ASSERT_TRUE(res);
  5181. EXPECT_EQ(StatusCode::OK_200, res->status);
  5182. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5183. // Verify pre-compression content is uncompressed
  5184. EXPECT_EQ(test_content, pre_compression_body);
  5185. // Verify post-compression content is compressed
  5186. EXPECT_NE(test_content, post_compression_body);
  5187. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5188. }
  5189. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5190. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5191. std::string pre_compression_body;
  5192. std::string post_compression_body;
  5193. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5194. pre_compression_body = res.body;
  5195. });
  5196. svr_.set_logger([&](const Request &req, const Response &res) {
  5197. post_compression_body = res.body;
  5198. });
  5199. // Request without compression (use /nocompress endpoint)
  5200. Headers headers;
  5201. auto res = cli_.Get("/nocompress", headers);
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5205. // Pre-compression logger should not be called when no compression is applied
  5206. EXPECT_TRUE(pre_compression_body.empty()); // Pre-compression logger not called
  5207. EXPECT_EQ(test_content, post_compression_body); // Post-compression logger captures final content
  5208. }
  5209. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5210. const std::string test_content = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
  5211. std::string pre_compression_body;
  5212. bool pre_logger_called = false;
  5213. // Set only pre-compression logger
  5214. svr_.set_pre_compression_logger([&](const Request &req, const Response &res) {
  5215. pre_compression_body = res.body;
  5216. pre_logger_called = true;
  5217. });
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip");
  5220. auto res = cli_.Get("/compress", headers);
  5221. ASSERT_TRUE(res);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5224. // Verify pre-compression logger was called
  5225. EXPECT_TRUE(pre_logger_called);
  5226. EXPECT_EQ(test_content, pre_compression_body);
  5227. }
  5228. TEST(ZstdDecompressor, ChunkedDecompression) {
  5229. std::string data;
  5230. for (size_t i = 0; i < 32 * 1024; ++i) {
  5231. data.push_back(static_cast<char>('a' + i % 26));
  5232. }
  5233. std::string compressed_data;
  5234. {
  5235. httplib::detail::zstd_compressor compressor;
  5236. bool result = compressor.compress(
  5237. data.data(), data.size(),
  5238. /*last=*/true,
  5239. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5240. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5241. compressed_data_size);
  5242. return true;
  5243. });
  5244. ASSERT_TRUE(result);
  5245. }
  5246. std::string decompressed_data;
  5247. {
  5248. httplib::detail::zstd_decompressor decompressor;
  5249. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5250. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5251. size_t chunk_size = 130;
  5252. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5253. chunk_begin += chunk_size) {
  5254. size_t current_chunk_size =
  5255. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5256. bool result = decompressor.decompress(
  5257. compressed_data.data() + chunk_begin, current_chunk_size,
  5258. [&](const char *decompressed_data_chunk,
  5259. size_t decompressed_data_chunk_size) {
  5260. decompressed_data.insert(decompressed_data.size(),
  5261. decompressed_data_chunk,
  5262. decompressed_data_chunk_size);
  5263. return true;
  5264. });
  5265. ASSERT_TRUE(result);
  5266. }
  5267. }
  5268. ASSERT_EQ(data, decompressed_data);
  5269. }
  5270. TEST(ZstdDecompressor, Decompress) {
  5271. std::string original_text = "Compressed with ZSTD";
  5272. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5273. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5274. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5275. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5276. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5277. std::string decompressed_data;
  5278. {
  5279. httplib::detail::zstd_decompressor decompressor;
  5280. bool result = decompressor.decompress(
  5281. compressed_data.data(), compressed_data.size(),
  5282. [&](const char *decompressed_data_chunk,
  5283. size_t decompressed_data_chunk_size) {
  5284. decompressed_data.insert(decompressed_data.size(),
  5285. decompressed_data_chunk,
  5286. decompressed_data_chunk_size);
  5287. return true;
  5288. });
  5289. ASSERT_TRUE(result);
  5290. }
  5291. ASSERT_EQ(original_text, decompressed_data);
  5292. }
  5293. #endif
  5294. // Sends a raw request to a server listening at HOST:PORT.
  5295. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5296. std::string *resp = nullptr) {
  5297. auto error = Error::Success;
  5298. auto client_sock = detail::create_client_socket(
  5299. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5300. /*connection_timeout_sec=*/5, 0,
  5301. /*read_timeout_sec=*/5, 0,
  5302. /*write_timeout_sec=*/5, 0, std::string(), error);
  5303. if (client_sock == INVALID_SOCKET) { return false; }
  5304. auto ret = detail::process_client_socket(
  5305. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5306. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5307. if (req.size() !=
  5308. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5309. return false;
  5310. }
  5311. char buf[512];
  5312. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5313. while (line_reader.getline()) {
  5314. if (resp) { *resp += line_reader.ptr(); }
  5315. }
  5316. return true;
  5317. });
  5318. detail::close_socket(client_sock);
  5319. return ret;
  5320. }
  5321. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5322. Server svr;
  5323. std::string header_value;
  5324. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5325. header_value = req.get_header_value("foo");
  5326. res.set_content("ok", "text/plain");
  5327. });
  5328. thread t = thread([&] { svr.listen(HOST, PORT); });
  5329. auto se = detail::scope_exit([&] {
  5330. svr.stop();
  5331. t.join();
  5332. ASSERT_FALSE(svr.is_running());
  5333. });
  5334. svr.wait_until_ready();
  5335. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5336. // like characters are not treated the same - use vertical tab and escape.
  5337. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5338. "foo: \t \v bar \x1B\t \r\n"
  5339. "Connection: close\r\n"
  5340. "\r\n";
  5341. std::string res;
  5342. ASSERT_TRUE(send_request(5, req, &res));
  5343. EXPECT_EQ(header_value, "");
  5344. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5345. }
  5346. // Sends a raw request and verifies that there isn't a crash or exception.
  5347. static void test_raw_request(const std::string &req,
  5348. std::string *out = nullptr) {
  5349. Server svr;
  5350. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5351. res.set_content("ok", "text/plain");
  5352. });
  5353. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5354. res.set_content("ok", "text/plain");
  5355. });
  5356. svr.Get("/header_field_value_check",
  5357. [&](const Request & /*req*/, Response &res) {
  5358. res.set_content("ok", "text/plain");
  5359. });
  5360. // Server read timeout must be longer than the client read timeout for the
  5361. // bug to reproduce, probably to force the server to process a request
  5362. // without a trailing blank line.
  5363. const time_t client_read_timeout_sec = 1;
  5364. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5365. bool listen_thread_ok = false;
  5366. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5367. auto se = detail::scope_exit([&] {
  5368. svr.stop();
  5369. t.join();
  5370. ASSERT_FALSE(svr.is_running());
  5371. EXPECT_TRUE(listen_thread_ok);
  5372. });
  5373. svr.wait_until_ready();
  5374. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5375. }
  5376. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5377. // A certain header line causes an exception if the header property is parsed
  5378. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5379. test_raw_request(
  5380. "GET /hi HTTP/1.1\r\n"
  5381. " : "
  5382. " "
  5383. " ");
  5384. }
  5385. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5386. // A certain header line causes an exception if the header property *name* is
  5387. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5388. // greedy matcher and requires backtracking when there are a lot of ":"
  5389. // characters.
  5390. // This occurs with libc++ but not libstdc++.
  5391. test_raw_request(
  5392. "GET /hi HTTP/1.1\r\n"
  5393. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5394. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5395. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5396. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5397. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5398. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5399. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5400. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5401. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5402. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5403. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5404. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5405. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5406. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5407. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5408. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5409. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5410. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5411. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5412. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5413. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5414. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5415. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5416. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5417. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5418. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5419. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5420. "&&&%%%");
  5421. }
  5422. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5423. // Make sure this doesn't crash the server.
  5424. // In a previous version of the header line regex, the "\r" rendered the line
  5425. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5426. // a new position where the leading white space ended and the field value
  5427. // began.
  5428. // The crash occurs with libc++ but not libstdc++.
  5429. test_raw_request("GET /hi HTTP/1.1\r\n"
  5430. "a:" +
  5431. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5432. "\r\n"
  5433. "\r\n");
  5434. }
  5435. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5436. std::string out;
  5437. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5438. "Content-Type: text/plain\r\n"
  5439. "Transfer-Encoding: chunked\r\n"
  5440. "\r\n"
  5441. "nothex\r\n",
  5442. &out);
  5443. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5444. }
  5445. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5446. std::string out;
  5447. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5448. "Content-Type: text/plain\r\n"
  5449. "Transfer-Encoding: chunked\r\n"
  5450. "\r\n"
  5451. "3\r\n"
  5452. "xyz\r\n"
  5453. "NaN\r\n",
  5454. &out);
  5455. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5456. }
  5457. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5458. std::string out;
  5459. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5460. "Content-Type: text/plain\r\n"
  5461. "Transfer-Encoding: chunked\r\n"
  5462. "\r\n"
  5463. // Length is too large for 64 bits.
  5464. "1ffffffffffffffff\r\n"
  5465. "xyz\r\n",
  5466. &out);
  5467. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5468. }
  5469. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5470. test_raw_request("GET /hi HTTP/1.1\r\n"
  5471. "Content-Type: text/plain\r\n\r");
  5472. }
  5473. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5474. std::string out;
  5475. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5476. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5477. }
  5478. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5479. std::string out;
  5480. std::string request(
  5481. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5482. test_raw_request(request, &out);
  5483. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5484. }
  5485. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5486. std::string out;
  5487. std::string request(
  5488. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5489. test_raw_request(request, &out);
  5490. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5491. }
  5492. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5493. std::string out;
  5494. std::string request(
  5495. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5496. test_raw_request(request, &out);
  5497. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5498. }
  5499. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5500. std::string out;
  5501. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5502. "Test: \r\n\r\n",
  5503. &out);
  5504. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5505. }
  5506. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5507. Server svr;
  5508. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5509. res.set_header("Cache-Control", "no-cache");
  5510. res.set_chunked_content_provider(
  5511. "text/event-stream", [](size_t offset, DataSink &sink) {
  5512. std::string s = "data:";
  5513. s += std::to_string(offset);
  5514. s += "\n\n";
  5515. auto ret = sink.write(s.data(), s.size());
  5516. EXPECT_TRUE(ret);
  5517. std::this_thread::sleep_for(std::chrono::seconds(1));
  5518. return true;
  5519. });
  5520. });
  5521. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5522. svr.wait_until_ready();
  5523. Client client(HOST, PORT);
  5524. const Headers headers = {{"Accept", "text/event-stream"}};
  5525. auto get_thread = std::thread([&client, &headers]() {
  5526. auto res = client.Get(
  5527. "/events", headers,
  5528. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5529. });
  5530. auto se = detail::scope_exit([&] {
  5531. svr.stop();
  5532. get_thread.join();
  5533. listen_thread.join();
  5534. ASSERT_FALSE(svr.is_running());
  5535. });
  5536. // Give GET time to get a few messages.
  5537. std::this_thread::sleep_for(std::chrono::seconds(2));
  5538. }
  5539. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5540. httplib::Server svr;
  5541. svr.Post("/hi",
  5542. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5543. res.status = StatusCode::OK_200;
  5544. });
  5545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5546. svr.wait_until_ready();
  5547. Client cli(HOST, PORT);
  5548. auto res = cli.Post("/hi", "data", "text/plain");
  5549. ASSERT_TRUE(res);
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. svr.stop();
  5552. thread.join();
  5553. ASSERT_FALSE(svr.is_running());
  5554. res = cli.Post("/hi", "data", "text/plain");
  5555. ASSERT_FALSE(res);
  5556. }
  5557. TEST(ServerStopTest, ListenFailure) {
  5558. Server svr;
  5559. auto t = thread([&]() {
  5560. auto ret = svr.listen("????", PORT);
  5561. EXPECT_FALSE(ret);
  5562. });
  5563. svr.wait_until_ready();
  5564. svr.stop();
  5565. t.join();
  5566. }
  5567. TEST(ServerStopTest, Decommision) {
  5568. Server svr;
  5569. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5570. for (int i = 0; i < 4; i++) {
  5571. auto is_even = !(i % 2);
  5572. std::thread t{[&] {
  5573. try {
  5574. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5575. if (is_even) {
  5576. throw std::runtime_error("Some thing that happens to go wrong.");
  5577. }
  5578. svr.listen(HOST, PORT);
  5579. } catch (...) { svr.decommission(); }
  5580. }};
  5581. svr.wait_until_ready();
  5582. // Server is up
  5583. {
  5584. Client cli(HOST, PORT);
  5585. auto res = cli.Get("/hi");
  5586. if (is_even) {
  5587. EXPECT_FALSE(res);
  5588. } else {
  5589. EXPECT_TRUE(res);
  5590. EXPECT_EQ("hi...", res->body);
  5591. }
  5592. }
  5593. svr.stop();
  5594. t.join();
  5595. // Server is down...
  5596. {
  5597. Client cli(HOST, PORT);
  5598. auto res = cli.Get("/hi");
  5599. EXPECT_FALSE(res);
  5600. }
  5601. }
  5602. }
  5603. // Helper function for string body upload progress tests
  5604. template <typename SetupHandler, typename ClientCall>
  5605. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5606. ClientCall &&client_call,
  5607. const string &body) {
  5608. Server svr;
  5609. setup_handler(svr);
  5610. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5611. auto se = detail::scope_exit([&] {
  5612. svr.stop();
  5613. t.join();
  5614. });
  5615. svr.wait_until_ready();
  5616. Client cli(HOST, PORT);
  5617. vector<uint64_t> progress_values;
  5618. bool progress_called = false;
  5619. auto res =
  5620. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5621. progress_values.push_back(current);
  5622. progress_called = true;
  5623. return true;
  5624. });
  5625. ASSERT_TRUE(res);
  5626. EXPECT_EQ(200, res->status);
  5627. EXPECT_TRUE(progress_called);
  5628. }
  5629. TEST(UploadProgressTest, PostStringBodyBasic) {
  5630. TestStringBodyUploadProgress(
  5631. [](Server &svr) {
  5632. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5633. res.set_content("received", "text/plain");
  5634. });
  5635. },
  5636. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5637. return cli.Post("/test", body, "text/plain", progress_callback);
  5638. },
  5639. "test data for upload progress");
  5640. }
  5641. TEST(UploadProgressTest, PutStringBodyBasic) {
  5642. TestStringBodyUploadProgress(
  5643. [](Server &svr) {
  5644. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5645. res.set_content("put received", "text/plain");
  5646. });
  5647. },
  5648. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5649. return cli.Put("/test", body, "text/plain", progress_callback);
  5650. },
  5651. "put test data for upload progress");
  5652. }
  5653. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5654. TestStringBodyUploadProgress(
  5655. [](Server &svr) {
  5656. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5657. res.set_content("patch received", "text/plain");
  5658. });
  5659. },
  5660. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5661. return cli.Patch("/test", body, "text/plain", progress_callback);
  5662. },
  5663. "patch test data for upload progress");
  5664. }
  5665. // Helper function for content provider upload progress tests
  5666. template <typename SetupHandler, typename ClientCall>
  5667. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5668. ClientCall &&client_call) {
  5669. Server svr;
  5670. setup_handler(svr);
  5671. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5672. auto se = detail::scope_exit([&] {
  5673. svr.stop();
  5674. t.join();
  5675. });
  5676. svr.wait_until_ready();
  5677. Client cli(HOST, PORT);
  5678. vector<uint64_t> progress_values;
  5679. auto res =
  5680. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5681. progress_values.push_back(current);
  5682. return true;
  5683. });
  5684. ASSERT_TRUE(res);
  5685. EXPECT_EQ(200, res->status);
  5686. EXPECT_FALSE(progress_values.empty());
  5687. }
  5688. TEST(UploadProgressTest, PostContentProviderProgress) {
  5689. TestContentProviderUploadProgress(
  5690. [](Server &svr) {
  5691. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5692. res.set_content("provider received", "text/plain");
  5693. });
  5694. },
  5695. [](Client &cli, UploadProgress progress_callback) {
  5696. return cli.Post(
  5697. "/test", 10,
  5698. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5699. sink.os << "test data";
  5700. return true;
  5701. },
  5702. "text/plain", progress_callback);
  5703. });
  5704. }
  5705. // Helper function for multipart upload progress tests
  5706. template <typename SetupHandler, typename ClientCall>
  5707. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5708. ClientCall &&client_call,
  5709. const string &endpoint) {
  5710. Server svr;
  5711. setup_handler(svr);
  5712. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5713. auto se = detail::scope_exit([&] {
  5714. svr.stop();
  5715. t.join();
  5716. });
  5717. svr.wait_until_ready();
  5718. Client cli(HOST, PORT);
  5719. vector<uint64_t> progress_values;
  5720. MultipartFormDataItemsForClientInput items = {
  5721. {"field1", "value1", "", ""},
  5722. {"field2", "longer value for progress tracking test", "", ""},
  5723. {"file1", "file content data for upload progress", "test.txt",
  5724. "text/plain"}};
  5725. auto res = client_call(cli, endpoint, items,
  5726. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5727. progress_values.push_back(current);
  5728. return true;
  5729. });
  5730. ASSERT_TRUE(res);
  5731. EXPECT_EQ(200, res->status);
  5732. EXPECT_FALSE(progress_values.empty());
  5733. }
  5734. TEST(UploadProgressTest, PostMultipartProgress) {
  5735. TestMultipartUploadProgress(
  5736. [](Server &svr) {
  5737. svr.Post("/multipart", [](const Request &req, Response &res) {
  5738. EXPECT_FALSE(req.files.empty());
  5739. res.set_content("multipart received", "text/plain");
  5740. });
  5741. },
  5742. [](Client &cli, const string &endpoint,
  5743. const MultipartFormDataItemsForClientInput &items,
  5744. UploadProgress progress_callback) {
  5745. return cli.Post(endpoint, items, progress_callback);
  5746. },
  5747. "/multipart");
  5748. }
  5749. // Helper function for basic download progress tests
  5750. template <typename SetupHandler, typename ClientCall>
  5751. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5752. ClientCall &&client_call, const string &endpoint,
  5753. size_t expected_content_size) {
  5754. Server svr;
  5755. setup_handler(svr);
  5756. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5757. auto se = detail::scope_exit([&] {
  5758. svr.stop();
  5759. t.join();
  5760. });
  5761. svr.wait_until_ready();
  5762. Client cli(HOST, PORT);
  5763. vector<uint64_t> progress_values;
  5764. auto res = client_call(cli, endpoint,
  5765. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5766. progress_values.push_back(current);
  5767. return true;
  5768. });
  5769. ASSERT_TRUE(res);
  5770. EXPECT_EQ(200, res->status);
  5771. EXPECT_FALSE(progress_values.empty());
  5772. EXPECT_EQ(expected_content_size, res->body.size());
  5773. }
  5774. TEST(DownloadProgressTest, GetBasic) {
  5775. TestBasicDownloadProgress(
  5776. [](Server &svr) {
  5777. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5778. string content(1000, 'D');
  5779. res.set_content(content, "text/plain");
  5780. });
  5781. },
  5782. [](Client &cli, const string &endpoint,
  5783. DownloadProgress progress_callback) {
  5784. return cli.Get(endpoint, progress_callback);
  5785. },
  5786. "/download", 1000u);
  5787. }
  5788. // Helper function for content receiver download progress tests
  5789. template <typename SetupHandler, typename ClientCall>
  5790. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5791. ClientCall &&client_call,
  5792. const string &endpoint,
  5793. size_t expected_content_size) {
  5794. Server svr;
  5795. setup_handler(svr);
  5796. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5797. auto se = detail::scope_exit([&] {
  5798. svr.stop();
  5799. t.join();
  5800. });
  5801. svr.wait_until_ready();
  5802. Client cli(HOST, PORT);
  5803. vector<uint64_t> progress_values;
  5804. string received_body;
  5805. auto res = client_call(
  5806. cli, endpoint,
  5807. [&](const char *data, size_t data_length) -> bool {
  5808. received_body.append(data, data_length);
  5809. return true;
  5810. },
  5811. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5812. progress_values.push_back(current);
  5813. return true;
  5814. });
  5815. ASSERT_TRUE(res);
  5816. EXPECT_EQ(200, res->status);
  5817. EXPECT_FALSE(progress_values.empty());
  5818. EXPECT_EQ(expected_content_size, received_body.size());
  5819. EXPECT_TRUE(res->body.empty());
  5820. }
  5821. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5822. TestContentReceiverDownloadProgress(
  5823. [](Server &svr) {
  5824. svr.Get("/download-receiver",
  5825. [](const Request & /*req*/, Response &res) {
  5826. string content(2000, 'R');
  5827. res.set_content(content, "text/plain");
  5828. });
  5829. },
  5830. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5831. DownloadProgress progress_callback) {
  5832. return cli.Get(endpoint, content_receiver, progress_callback);
  5833. },
  5834. "/download-receiver", 2000u);
  5835. }
  5836. TEST(StreamingTest, NoContentLengthStreaming) {
  5837. Server svr;
  5838. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5839. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5840. if (offset < 6) {
  5841. sink.os << (offset < 3 ? "a" : "b");
  5842. } else {
  5843. sink.done();
  5844. }
  5845. return true;
  5846. });
  5847. });
  5848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5849. auto listen_se = detail::scope_exit([&] {
  5850. svr.stop();
  5851. listen_thread.join();
  5852. ASSERT_FALSE(svr.is_running());
  5853. });
  5854. svr.wait_until_ready();
  5855. Client client(HOST, PORT);
  5856. auto get_thread = std::thread([&client]() {
  5857. std::string s;
  5858. auto res =
  5859. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5860. s += std::string(data, len);
  5861. return true;
  5862. });
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. EXPECT_EQ("aaabbb", s);
  5866. });
  5867. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5868. // Give GET time to get a few messages.
  5869. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5870. }
  5871. TEST(MountTest, Unmount) {
  5872. Server svr;
  5873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5874. auto se = detail::scope_exit([&] {
  5875. svr.stop();
  5876. listen_thread.join();
  5877. ASSERT_FALSE(svr.is_running());
  5878. });
  5879. svr.wait_until_ready();
  5880. Client cli("localhost", PORT);
  5881. svr.set_mount_point("/mount2", "./www2");
  5882. auto res = cli.Get("/");
  5883. ASSERT_TRUE(res);
  5884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5885. res = cli.Get("/mount2/dir/test.html");
  5886. ASSERT_TRUE(res);
  5887. EXPECT_EQ(StatusCode::OK_200, res->status);
  5888. svr.set_mount_point("/", "./www");
  5889. res = cli.Get("/dir/");
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. svr.remove_mount_point("/");
  5893. res = cli.Get("/dir/");
  5894. ASSERT_TRUE(res);
  5895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5896. svr.remove_mount_point("/mount2");
  5897. res = cli.Get("/mount2/dir/test.html");
  5898. ASSERT_TRUE(res);
  5899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5900. }
  5901. TEST(MountTest, Redicect) {
  5902. Server svr;
  5903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5904. auto se = detail::scope_exit([&] {
  5905. svr.stop();
  5906. listen_thread.join();
  5907. ASSERT_FALSE(svr.is_running());
  5908. });
  5909. svr.set_mount_point("/", "./www");
  5910. svr.wait_until_ready();
  5911. Client cli("localhost", PORT);
  5912. auto res = cli.Get("/dir/");
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. res = cli.Get("/dir");
  5916. ASSERT_TRUE(res);
  5917. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5918. res = cli.Get("/file");
  5919. ASSERT_TRUE(res);
  5920. EXPECT_EQ(StatusCode::OK_200, res->status);
  5921. res = cli.Get("/file/");
  5922. ASSERT_TRUE(res);
  5923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5924. cli.set_follow_location(true);
  5925. res = cli.Get("/dir");
  5926. ASSERT_TRUE(res);
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. }
  5929. TEST(MountTest, MultibytesPathName) {
  5930. Server svr;
  5931. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5932. auto se = detail::scope_exit([&] {
  5933. svr.stop();
  5934. listen_thread.join();
  5935. ASSERT_FALSE(svr.is_running());
  5936. });
  5937. svr.set_mount_point("/", "./www");
  5938. svr.wait_until_ready();
  5939. Client cli("localhost", PORT);
  5940. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5941. ASSERT_TRUE(res);
  5942. EXPECT_EQ(StatusCode::OK_200, res->status);
  5943. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5944. }
  5945. TEST(KeepAliveTest, ReadTimeout) {
  5946. Server svr;
  5947. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5948. std::this_thread::sleep_for(std::chrono::seconds(2));
  5949. res.set_content("a", "text/plain");
  5950. });
  5951. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5952. res.set_content("b", "text/plain");
  5953. });
  5954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5955. auto se = detail::scope_exit([&] {
  5956. svr.stop();
  5957. listen_thread.join();
  5958. ASSERT_FALSE(svr.is_running());
  5959. });
  5960. svr.wait_until_ready();
  5961. Client cli("localhost", PORT);
  5962. cli.set_keep_alive(true);
  5963. cli.set_read_timeout(std::chrono::seconds(1));
  5964. auto resa = cli.Get("/a");
  5965. ASSERT_FALSE(resa);
  5966. EXPECT_EQ(Error::Read, resa.error());
  5967. auto resb = cli.Get("/b");
  5968. ASSERT_TRUE(resb);
  5969. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5970. EXPECT_EQ("b", resb->body);
  5971. }
  5972. TEST(KeepAliveTest, MaxCount) {
  5973. size_t keep_alive_max_count = 3;
  5974. Server svr;
  5975. svr.set_keep_alive_max_count(keep_alive_max_count);
  5976. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5977. res.set_content("Hello World!", "text/plain");
  5978. });
  5979. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5980. auto se = detail::scope_exit([&] {
  5981. svr.stop();
  5982. listen_thread.join();
  5983. ASSERT_FALSE(svr.is_running());
  5984. });
  5985. svr.wait_until_ready();
  5986. Client cli(HOST, PORT);
  5987. cli.set_keep_alive(true);
  5988. for (size_t i = 0; i < 5; i++) {
  5989. auto result = cli.Get("/hi");
  5990. ASSERT_TRUE(result);
  5991. EXPECT_EQ(StatusCode::OK_200, result->status);
  5992. if (i == keep_alive_max_count - 1) {
  5993. EXPECT_EQ("close", result->get_header_value("Connection"));
  5994. } else {
  5995. EXPECT_FALSE(result->has_header("Connection"));
  5996. }
  5997. }
  5998. }
  5999. TEST(KeepAliveTest, Issue1041) {
  6000. Server svr;
  6001. svr.set_keep_alive_timeout(3);
  6002. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6003. res.set_content("Hello World!", "text/plain");
  6004. });
  6005. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6006. auto se = detail::scope_exit([&] {
  6007. svr.stop();
  6008. listen_thread.join();
  6009. ASSERT_FALSE(svr.is_running());
  6010. });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. cli.set_keep_alive(true);
  6014. auto result = cli.Get("/hi");
  6015. ASSERT_TRUE(result);
  6016. EXPECT_EQ(StatusCode::OK_200, result->status);
  6017. std::this_thread::sleep_for(std::chrono::seconds(5));
  6018. result = cli.Get("/hi");
  6019. ASSERT_TRUE(result);
  6020. EXPECT_EQ(StatusCode::OK_200, result->status);
  6021. }
  6022. TEST(KeepAliveTest, Issue1959) {
  6023. Server svr;
  6024. svr.set_keep_alive_timeout(5);
  6025. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6026. res.set_content("a", "text/plain");
  6027. });
  6028. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6029. auto se = detail::scope_exit([&] {
  6030. if (!svr.is_running()) return;
  6031. svr.stop();
  6032. listen_thread.join();
  6033. ASSERT_FALSE(svr.is_running());
  6034. });
  6035. svr.wait_until_ready();
  6036. Client cli("localhost", PORT);
  6037. cli.set_keep_alive(true);
  6038. using namespace std::chrono;
  6039. auto start = steady_clock::now();
  6040. cli.Get("/a");
  6041. svr.stop();
  6042. listen_thread.join();
  6043. auto end = steady_clock::now();
  6044. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6045. EXPECT_LT(elapsed, 5000);
  6046. }
  6047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6048. TEST(KeepAliveTest, SSLClientReconnection) {
  6049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6050. ASSERT_TRUE(svr.is_valid());
  6051. svr.set_keep_alive_timeout(1);
  6052. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6053. res.set_content("Hello World!", "text/plain");
  6054. });
  6055. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6056. auto se = detail::scope_exit([&] {
  6057. svr.stop();
  6058. listen_thread.join();
  6059. ASSERT_FALSE(svr.is_running());
  6060. });
  6061. svr.wait_until_ready();
  6062. SSLClient cli(HOST, PORT);
  6063. cli.enable_server_certificate_verification(false);
  6064. cli.set_keep_alive(true);
  6065. auto result = cli.Get("/hi");
  6066. ASSERT_TRUE(result);
  6067. EXPECT_EQ(StatusCode::OK_200, result->status);
  6068. result = cli.Get("/hi");
  6069. ASSERT_TRUE(result);
  6070. EXPECT_EQ(StatusCode::OK_200, result->status);
  6071. std::this_thread::sleep_for(std::chrono::seconds(2));
  6072. // Recoonect
  6073. result = cli.Get("/hi");
  6074. ASSERT_TRUE(result);
  6075. EXPECT_EQ(StatusCode::OK_200, result->status);
  6076. result = cli.Get("/hi");
  6077. ASSERT_TRUE(result);
  6078. EXPECT_EQ(StatusCode::OK_200, result->status);
  6079. }
  6080. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6082. ASSERT_TRUE(svr.is_valid());
  6083. svr.set_keep_alive_timeout(1);
  6084. std::string content = "reconnect";
  6085. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6086. res.set_content("Hello World!", "text/plain");
  6087. });
  6088. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6089. auto se = detail::scope_exit([&] {
  6090. svr.stop();
  6091. listen_thread.join();
  6092. ASSERT_FALSE(svr.is_running());
  6093. });
  6094. svr.wait_until_ready();
  6095. SSLClient cli(HOST, PORT);
  6096. cli.enable_server_certificate_verification(false);
  6097. cli.set_keep_alive(true);
  6098. auto result = cli.Post(
  6099. "/hi", content.size(),
  6100. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6101. sink.write(content.c_str(), content.size());
  6102. return true;
  6103. },
  6104. "text/plain");
  6105. ASSERT_TRUE(result);
  6106. EXPECT_EQ(200, result->status);
  6107. std::this_thread::sleep_for(std::chrono::seconds(2));
  6108. // Recoonect
  6109. result = cli.Post(
  6110. "/hi", content.size(),
  6111. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6112. sink.write(content.c_str(), content.size());
  6113. return true;
  6114. },
  6115. "text/plain");
  6116. ASSERT_TRUE(result);
  6117. EXPECT_EQ(200, result->status);
  6118. result = cli.Post(
  6119. "/hi", content.size(),
  6120. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6121. sink.write(content.c_str(), content.size());
  6122. return true;
  6123. },
  6124. "text/plain");
  6125. ASSERT_TRUE(result);
  6126. EXPECT_EQ(200, result->status);
  6127. }
  6128. #endif
  6129. TEST(ClientProblemDetectionTest, ContentProvider) {
  6130. Server svr;
  6131. size_t content_length = 1024 * 1024;
  6132. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6133. res.set_content_provider(
  6134. content_length, "text/plain",
  6135. [&](size_t offset, size_t length, DataSink &sink) {
  6136. auto out_len = std::min(length, static_cast<size_t>(1024));
  6137. std::string out(out_len, '@');
  6138. sink.write(out.data(), out_len);
  6139. return offset < 4096;
  6140. },
  6141. [](bool success) { ASSERT_FALSE(success); });
  6142. });
  6143. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6144. res.set_content_provider(
  6145. 0, "text/plain",
  6146. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6147. EXPECT_TRUE(false);
  6148. return true;
  6149. },
  6150. [](bool success) { ASSERT_FALSE(success); });
  6151. });
  6152. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6153. auto se = detail::scope_exit([&] {
  6154. svr.stop();
  6155. listen_thread.join();
  6156. ASSERT_FALSE(svr.is_running());
  6157. });
  6158. svr.wait_until_ready();
  6159. Client cli("localhost", PORT);
  6160. {
  6161. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6162. size_t /*data_length*/) { return false; });
  6163. ASSERT_FALSE(res);
  6164. }
  6165. {
  6166. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6167. size_t /*data_length*/) { return false; });
  6168. ASSERT_TRUE(res);
  6169. }
  6170. }
  6171. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6172. Server svr;
  6173. svr.set_error_handler([](Request const &, Response &res) -> void {
  6174. res.set_chunked_content_provider(
  6175. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6176. sink.os << "hello";
  6177. sink.os << "world";
  6178. sink.done();
  6179. return true;
  6180. });
  6181. });
  6182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6183. auto se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. listen_thread.join();
  6186. ASSERT_FALSE(svr.is_running());
  6187. });
  6188. svr.wait_until_ready();
  6189. Client cli("localhost", PORT);
  6190. auto res = cli.Get("/");
  6191. ASSERT_TRUE(res);
  6192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6193. EXPECT_EQ("helloworld", res->body);
  6194. }
  6195. TEST(LongPollingTest, ClientCloseDetection) {
  6196. Server svr;
  6197. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6198. res.set_chunked_content_provider(
  6199. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6200. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6201. sink.os << "hello";
  6202. auto count = 10;
  6203. while (count > 0 && sink.is_writable()) {
  6204. this_thread::sleep_for(chrono::milliseconds(10));
  6205. count--;
  6206. }
  6207. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6208. return true;
  6209. });
  6210. });
  6211. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6212. auto se = detail::scope_exit([&] {
  6213. svr.stop();
  6214. listen_thread.join();
  6215. ASSERT_FALSE(svr.is_running());
  6216. });
  6217. svr.wait_until_ready();
  6218. Client cli("localhost", PORT);
  6219. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6220. EXPECT_EQ("hello", string(data, data_length));
  6221. return false; // close the socket immediately.
  6222. });
  6223. ASSERT_FALSE(res);
  6224. }
  6225. TEST(GetWithParametersTest, GetWithParameters) {
  6226. Server svr;
  6227. svr.Get("/", [&](const Request &req, Response &) {
  6228. EXPECT_EQ("world", req.get_param_value("hello"));
  6229. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6230. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6231. });
  6232. svr.Get("/params", [&](const Request &req, Response &) {
  6233. EXPECT_EQ("world", req.get_param_value("hello"));
  6234. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6235. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6236. });
  6237. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6238. EXPECT_EQ("resource-id", req.matches[1]);
  6239. EXPECT_EQ("foo", req.get_param_value("param1"));
  6240. EXPECT_EQ("bar", req.get_param_value("param2"));
  6241. });
  6242. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6243. EXPECT_EQ("user-id", req.path_params.at("id"));
  6244. EXPECT_EQ("foo", req.get_param_value("param1"));
  6245. EXPECT_EQ("bar", req.get_param_value("param2"));
  6246. });
  6247. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6248. auto se = detail::scope_exit([&] {
  6249. svr.stop();
  6250. listen_thread.join();
  6251. ASSERT_FALSE(svr.is_running());
  6252. });
  6253. svr.wait_until_ready();
  6254. {
  6255. Client cli(HOST, PORT);
  6256. Params params;
  6257. params.emplace("hello", "world");
  6258. params.emplace("hello2", "world2");
  6259. params.emplace("hello3", "world3");
  6260. auto res = cli.Get("/", params, Headers{});
  6261. ASSERT_TRUE(res);
  6262. EXPECT_EQ(StatusCode::OK_200, res->status);
  6263. }
  6264. {
  6265. Client cli(HOST, PORT);
  6266. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6267. ASSERT_TRUE(res);
  6268. EXPECT_EQ(StatusCode::OK_200, res->status);
  6269. }
  6270. {
  6271. Client cli(HOST, PORT);
  6272. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. {
  6277. Client cli(HOST, PORT);
  6278. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. }
  6282. }
  6283. TEST(GetWithParametersTest, GetWithParameters2) {
  6284. Server svr;
  6285. svr.Get("/", [&](const Request &req, Response &res) {
  6286. auto text = req.get_param_value("hello");
  6287. res.set_content(text, "text/plain");
  6288. });
  6289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6290. auto se = detail::scope_exit([&] {
  6291. svr.stop();
  6292. listen_thread.join();
  6293. ASSERT_FALSE(svr.is_running());
  6294. });
  6295. svr.wait_until_ready();
  6296. Client cli("localhost", PORT);
  6297. Params params;
  6298. params.emplace("hello", "world");
  6299. std::string body;
  6300. auto res = cli.Get("/", params, Headers{},
  6301. [&](const char *data, size_t data_length) {
  6302. body.append(data, data_length);
  6303. return true;
  6304. });
  6305. ASSERT_TRUE(res);
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ("world", body);
  6308. }
  6309. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6310. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6311. auto host = "httpbin.org";
  6312. auto path = std::string{"/range/32"};
  6313. #else
  6314. auto host = "nghttp2.org";
  6315. auto path = std::string{"/httpbin/range/32"};
  6316. #endif
  6317. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6318. SSLClient cli(host);
  6319. #else
  6320. Client cli(host);
  6321. #endif
  6322. cli.set_default_headers({make_range_header({{1, 10}})});
  6323. cli.set_connection_timeout(5);
  6324. {
  6325. auto res = cli.Get(path);
  6326. ASSERT_TRUE(res);
  6327. EXPECT_EQ("bcdefghijk", res->body);
  6328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6329. }
  6330. {
  6331. auto res = cli.Get(path);
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ("bcdefghijk", res->body);
  6334. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6335. }
  6336. }
  6337. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6338. Server svr;
  6339. svr.set_default_headers({{"Hello", "World"}});
  6340. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6341. res.set_content("ok", "text/plain");
  6342. });
  6343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6344. auto se = detail::scope_exit([&] {
  6345. svr.stop();
  6346. listen_thread.join();
  6347. ASSERT_FALSE(svr.is_running());
  6348. });
  6349. svr.wait_until_ready();
  6350. Client cli("localhost", PORT);
  6351. auto res = cli.Get("/");
  6352. ASSERT_TRUE(res);
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ("ok", res->body);
  6355. EXPECT_EQ("World", res->get_header_value("Hello"));
  6356. }
  6357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6358. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6360. ASSERT_TRUE(svr.is_valid());
  6361. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6362. std::this_thread::sleep_for(std::chrono::seconds(2));
  6363. res.set_content("a", "text/plain");
  6364. });
  6365. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6366. res.set_content("b", "text/plain");
  6367. });
  6368. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6369. auto se = detail::scope_exit([&] {
  6370. svr.stop();
  6371. listen_thread.join();
  6372. ASSERT_FALSE(svr.is_running());
  6373. });
  6374. svr.wait_until_ready();
  6375. SSLClient cli("localhost", PORT);
  6376. cli.enable_server_certificate_verification(false);
  6377. cli.set_keep_alive(true);
  6378. cli.set_read_timeout(std::chrono::seconds(1));
  6379. auto resa = cli.Get("/a");
  6380. ASSERT_TRUE(!resa);
  6381. EXPECT_EQ(Error::Read, resa.error());
  6382. auto resb = cli.Get("/b");
  6383. ASSERT_TRUE(resb);
  6384. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6385. EXPECT_EQ("b", resb->body);
  6386. }
  6387. #endif
  6388. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6389. protected:
  6390. ServerTestWithAI_PASSIVE()
  6391. : cli_(HOST, PORT)
  6392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6393. ,
  6394. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6395. #endif
  6396. {
  6397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6398. cli_.enable_server_certificate_verification(false);
  6399. #endif
  6400. }
  6401. virtual void SetUp() {
  6402. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6403. res.set_content("Hello World!", "text/plain");
  6404. });
  6405. t_ = thread(
  6406. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6407. svr_.wait_until_ready();
  6408. }
  6409. virtual void TearDown() {
  6410. svr_.stop();
  6411. t_.join();
  6412. }
  6413. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6414. SSLClient cli_;
  6415. SSLServer svr_;
  6416. #else
  6417. Client cli_;
  6418. Server svr_;
  6419. #endif
  6420. thread t_;
  6421. };
  6422. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6423. auto res = cli_.Get("/hi");
  6424. ASSERT_TRUE(res);
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6427. EXPECT_EQ("Hello World!", res->body);
  6428. }
  6429. class ServerUpDownTest : public ::testing::Test {
  6430. protected:
  6431. ServerUpDownTest() : cli_(HOST, PORT) {}
  6432. virtual void SetUp() {
  6433. t_ = thread([&]() {
  6434. svr_.bind_to_any_port(HOST);
  6435. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6436. ASSERT_TRUE(svr_.listen_after_bind());
  6437. });
  6438. svr_.wait_until_ready();
  6439. }
  6440. virtual void TearDown() {
  6441. svr_.stop();
  6442. t_.join();
  6443. }
  6444. Client cli_;
  6445. Server svr_;
  6446. thread t_;
  6447. };
  6448. TEST_F(ServerUpDownTest, QuickStartStop) {
  6449. // Should not crash, especially when run with
  6450. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6451. }
  6452. class PayloadMaxLengthTest : public ::testing::Test {
  6453. protected:
  6454. PayloadMaxLengthTest()
  6455. : cli_(HOST, PORT)
  6456. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6457. ,
  6458. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6459. #endif
  6460. {
  6461. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6462. cli_.enable_server_certificate_verification(false);
  6463. #endif
  6464. }
  6465. virtual void SetUp() {
  6466. svr_.set_payload_max_length(8);
  6467. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6468. res.set_content("test", "text/plain");
  6469. });
  6470. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6471. svr_.wait_until_ready();
  6472. }
  6473. virtual void TearDown() {
  6474. svr_.stop();
  6475. t_.join();
  6476. }
  6477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6478. SSLClient cli_;
  6479. SSLServer svr_;
  6480. #else
  6481. Client cli_;
  6482. Server svr_;
  6483. #endif
  6484. thread t_;
  6485. };
  6486. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6487. auto res = cli_.Post("/test", "123456789", "text/plain");
  6488. ASSERT_TRUE(res);
  6489. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6490. res = cli_.Post("/test", "12345678", "text/plain");
  6491. ASSERT_TRUE(res);
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. }
  6494. TEST(HostAndPortPropertiesTest, NoSSL) {
  6495. httplib::Client cli("www.google.com", 1234);
  6496. ASSERT_EQ("www.google.com", cli.host());
  6497. ASSERT_EQ(1234, cli.port());
  6498. }
  6499. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6500. httplib::Client cli("www.google.com:1234");
  6501. ASSERT_EQ("www.google.com", cli.host());
  6502. ASSERT_EQ(1234, cli.port());
  6503. }
  6504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6505. TEST(HostAndPortPropertiesTest, SSL) {
  6506. httplib::SSLClient cli("www.google.com");
  6507. ASSERT_EQ("www.google.com", cli.host());
  6508. ASSERT_EQ(443, cli.port());
  6509. }
  6510. #endif
  6511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6512. TEST(SSLClientTest, UpdateCAStore) {
  6513. httplib::SSLClient httplib_client("www.google.com");
  6514. auto ca_store_1 = X509_STORE_new();
  6515. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6516. nullptr);
  6517. httplib_client.set_ca_cert_store(ca_store_1);
  6518. auto ca_store_2 = X509_STORE_new();
  6519. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6520. nullptr);
  6521. httplib_client.set_ca_cert_store(ca_store_2);
  6522. }
  6523. TEST(SSLClientTest, ServerNameIndication_Online) {
  6524. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6525. auto host = "httpbin.org";
  6526. auto path = std::string{"/get"};
  6527. #else
  6528. auto host = "nghttp2.org";
  6529. auto path = std::string{"/httpbin/get"};
  6530. #endif
  6531. SSLClient cli(host, 443);
  6532. auto res = cli.Get(path);
  6533. ASSERT_TRUE(res);
  6534. ASSERT_EQ(StatusCode::OK_200, res->status);
  6535. }
  6536. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6537. // Use a site that will cause SSL verification failure due to self-signed cert
  6538. SSLClient cli("self-signed.badssl.com", 443);
  6539. cli.enable_server_certificate_verification(true);
  6540. auto res = cli.Get("/");
  6541. ASSERT_TRUE(!res);
  6542. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6543. // For SSL server verification errors, ssl_error should be 0, only
  6544. // ssl_openssl_error should be set
  6545. EXPECT_EQ(0, res.ssl_error());
  6546. // Verify OpenSSL error is captured for SSLServerVerification
  6547. // This occurs when SSL_get_verify_result() returns a verification failure
  6548. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6549. res.ssl_openssl_error());
  6550. }
  6551. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6552. // Use a site where hostname doesn't match the certificate
  6553. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6554. SSLClient cli("wrong.host.badssl.com", 443);
  6555. cli.enable_server_certificate_verification(true);
  6556. cli.enable_server_hostname_verification(true);
  6557. auto res = cli.Get("/");
  6558. ASSERT_TRUE(!res);
  6559. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6560. // For SSL hostname verification errors, ssl_error should be 0, only
  6561. // ssl_openssl_error should be set
  6562. EXPECT_EQ(0, res.ssl_error());
  6563. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6564. // This occurs when verify_host() fails due to hostname mismatch
  6565. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6566. res.ssl_openssl_error());
  6567. }
  6568. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6569. Client cli("https://google.com");
  6570. auto res = cli.Get("/");
  6571. ASSERT_TRUE(res);
  6572. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6573. }
  6574. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6575. SSLClient cli("google.com");
  6576. cli.set_ca_cert_path(CA_CERT_FILE);
  6577. auto res = cli.Get("/");
  6578. ASSERT_TRUE(res);
  6579. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6580. }
  6581. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6582. SSLClient cli("google.com");
  6583. cli.enable_server_certificate_verification(true);
  6584. cli.set_ca_cert_path("hello");
  6585. auto res = cli.Get("/");
  6586. ASSERT_TRUE(!res);
  6587. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6588. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6589. // should be set
  6590. EXPECT_EQ(0, res.ssl_error());
  6591. // Verify OpenSSL error is captured for SSLLoadingCerts
  6592. // This error occurs when SSL_CTX_load_verify_locations() fails
  6593. // > openssl errstr 0x80000002
  6594. // error:80000002:system library::No such file or directory
  6595. // > openssl errstr 0xA000126
  6596. // error:0A000126:SSL routines::unexpected eof while reading
  6597. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6598. res.ssl_openssl_error() == 0xA000126);
  6599. }
  6600. TEST(SSLClientTest, ServerCertificateVerification4) {
  6601. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6602. ASSERT_TRUE(svr.is_valid());
  6603. svr.Get("/test", [&](const Request &, Response &res) {
  6604. res.set_content("test", "text/plain");
  6605. svr.stop();
  6606. ASSERT_TRUE(true);
  6607. });
  6608. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6609. auto se = detail::scope_exit([&] {
  6610. t.join();
  6611. ASSERT_FALSE(svr.is_running());
  6612. });
  6613. svr.wait_until_ready();
  6614. SSLClient cli("127.0.0.1", PORT);
  6615. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6616. cli.enable_server_certificate_verification(true);
  6617. cli.set_connection_timeout(30);
  6618. auto res = cli.Get("/test");
  6619. ASSERT_TRUE(res);
  6620. ASSERT_EQ(StatusCode::OK_200, res->status);
  6621. }
  6622. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6623. std::string cert;
  6624. read_file(CA_CERT_FILE, cert);
  6625. SSLClient cli("google.com");
  6626. cli.load_ca_cert_store(cert.data(), cert.size());
  6627. const auto res = cli.Get("/");
  6628. ASSERT_TRUE(res);
  6629. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6630. }
  6631. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6632. // clang-format off
  6633. static constexpr char cert[] =
  6634. "GlobalSign Root CA\n"
  6635. "==================\n"
  6636. "-----BEGIN CERTIFICATE-----\n"
  6637. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6638. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6639. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6640. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6641. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6642. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6643. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6644. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6645. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6646. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6647. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6648. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6649. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6650. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6651. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6652. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6653. "-----END CERTIFICATE-----\n";
  6654. // clang-format on
  6655. SSLClient cli("google.com");
  6656. cli.load_ca_cert_store(cert, sizeof(cert));
  6657. const auto res = cli.Get("/");
  6658. ASSERT_TRUE(res);
  6659. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6660. }
  6661. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6662. SSLClient cli("www.youtube.com");
  6663. cli.set_ca_cert_path(CA_CERT_FILE);
  6664. cli.enable_server_certificate_verification(true);
  6665. cli.set_follow_location(true);
  6666. auto res = cli.Get("/");
  6667. ASSERT_TRUE(res);
  6668. ASSERT_EQ(StatusCode::OK_200, res->status);
  6669. }
  6670. TEST(SSLClientTest, Issue2004_Online) {
  6671. Client client("https://google.com");
  6672. client.set_follow_location(true);
  6673. auto res = client.Get("/");
  6674. ASSERT_TRUE(res);
  6675. ASSERT_EQ(StatusCode::OK_200, res->status);
  6676. auto body = res->body;
  6677. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6678. }
  6679. #if 0
  6680. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6681. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6682. ASSERT_TRUE(cli != nullptr);
  6683. cli->set_address_family(AF_INET6);
  6684. cli->set_interface("en0");
  6685. auto res = cli->Get("/get");
  6686. ASSERT_TRUE(res);
  6687. ASSERT_EQ(StatusCode::OK_200, res->status);
  6688. }
  6689. #endif
  6690. void ClientCertPresent(
  6691. const std::string &client_cert_file,
  6692. const std::string &client_private_key_file,
  6693. const std::string &client_encrypted_private_key_pass = std::string()) {
  6694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6695. CLIENT_CA_CERT_DIR);
  6696. ASSERT_TRUE(svr.is_valid());
  6697. svr.Get("/test", [&](const Request &req, Response &res) {
  6698. res.set_content("test", "text/plain");
  6699. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6700. ASSERT_TRUE(peer_cert != nullptr);
  6701. auto subject_name = X509_get_subject_name(peer_cert);
  6702. ASSERT_TRUE(subject_name != nullptr);
  6703. std::string common_name;
  6704. {
  6705. char name[BUFSIZ];
  6706. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6707. name, sizeof(name));
  6708. common_name.assign(name, static_cast<size_t>(name_len));
  6709. }
  6710. EXPECT_EQ("Common Name", common_name);
  6711. X509_free(peer_cert);
  6712. });
  6713. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6714. auto se = detail::scope_exit([&] {
  6715. svr.stop();
  6716. t.join();
  6717. ASSERT_FALSE(svr.is_running());
  6718. });
  6719. svr.wait_until_ready();
  6720. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6721. client_encrypted_private_key_pass);
  6722. cli.enable_server_certificate_verification(false);
  6723. cli.set_connection_timeout(30);
  6724. auto res = cli.Get("/test");
  6725. ASSERT_TRUE(res);
  6726. ASSERT_EQ(StatusCode::OK_200, res->status);
  6727. }
  6728. TEST(SSLClientServerTest, ClientCertPresent) {
  6729. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6730. }
  6731. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6732. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6733. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6734. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6735. }
  6736. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6737. void MemoryClientCertPresent(
  6738. const std::string &client_cert_file,
  6739. const std::string &client_private_key_file,
  6740. const std::string &client_encrypted_private_key_pass = std::string()) {
  6741. auto f = fopen(SERVER_CERT_FILE, "r+");
  6742. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6743. fclose(f);
  6744. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6745. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6746. fclose(f);
  6747. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6748. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6749. auto client_ca_cert_store = X509_STORE_new();
  6750. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6751. X509_free(client_cert);
  6752. fclose(f);
  6753. f = fopen(client_cert_file.c_str(), "r+");
  6754. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6755. fclose(f);
  6756. f = fopen(client_private_key_file.c_str(), "r+");
  6757. auto client_private_key = PEM_read_PrivateKey(
  6758. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6759. fclose(f);
  6760. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6761. ASSERT_TRUE(svr.is_valid());
  6762. svr.Get("/test", [&](const Request &req, Response &res) {
  6763. res.set_content("test", "text/plain");
  6764. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6765. ASSERT_TRUE(peer_cert != nullptr);
  6766. auto subject_name = X509_get_subject_name(peer_cert);
  6767. ASSERT_TRUE(subject_name != nullptr);
  6768. std::string common_name;
  6769. {
  6770. char name[BUFSIZ];
  6771. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6772. name, sizeof(name));
  6773. common_name.assign(name, static_cast<size_t>(name_len));
  6774. }
  6775. EXPECT_EQ("Common Name", common_name);
  6776. X509_free(peer_cert);
  6777. });
  6778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6779. auto se = detail::scope_exit([&] {
  6780. svr.stop();
  6781. t.join();
  6782. ASSERT_FALSE(svr.is_running());
  6783. });
  6784. svr.wait_until_ready();
  6785. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6786. client_encrypted_private_key_pass);
  6787. cli.enable_server_certificate_verification(false);
  6788. cli.set_connection_timeout(30);
  6789. auto res = cli.Get("/test");
  6790. ASSERT_TRUE(res);
  6791. ASSERT_EQ(StatusCode::OK_200, res->status);
  6792. X509_free(server_cert);
  6793. EVP_PKEY_free(server_private_key);
  6794. X509_free(client_cert);
  6795. EVP_PKEY_free(client_private_key);
  6796. }
  6797. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6798. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6799. }
  6800. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6801. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6802. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6803. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6804. }
  6805. #endif
  6806. TEST(SSLClientServerTest, ClientCertMissing) {
  6807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6808. CLIENT_CA_CERT_DIR);
  6809. ASSERT_TRUE(svr.is_valid());
  6810. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6811. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6812. auto se = detail::scope_exit([&] {
  6813. svr.stop();
  6814. t.join();
  6815. ASSERT_FALSE(svr.is_running());
  6816. });
  6817. svr.wait_until_ready();
  6818. SSLClient cli(HOST, PORT);
  6819. cli.set_connection_timeout(30);
  6820. auto res = cli.Get("/test");
  6821. ASSERT_TRUE(!res);
  6822. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6823. // For SSL server verification errors, ssl_error should be 0, only
  6824. // ssl_openssl_error should be set
  6825. EXPECT_EQ(0, res.ssl_error());
  6826. // Verify OpenSSL error is captured for SSLServerVerification
  6827. // Note: This test may have different error codes depending on the exact
  6828. // verification failure
  6829. EXPECT_NE(0UL, res.ssl_openssl_error());
  6830. }
  6831. TEST(SSLClientServerTest, TrustDirOptional) {
  6832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6833. ASSERT_TRUE(svr.is_valid());
  6834. svr.Get("/test", [&](const Request &, Response &res) {
  6835. res.set_content("test", "text/plain");
  6836. });
  6837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6838. auto se = detail::scope_exit([&] {
  6839. svr.stop();
  6840. t.join();
  6841. ASSERT_FALSE(svr.is_running());
  6842. });
  6843. svr.wait_until_ready();
  6844. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6845. cli.enable_server_certificate_verification(false);
  6846. cli.set_connection_timeout(30);
  6847. auto res = cli.Get("/test");
  6848. ASSERT_TRUE(res);
  6849. ASSERT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6852. class NoListenSSLServer : public SSLServer {
  6853. public:
  6854. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6855. const char *client_ca_cert_file_path,
  6856. const char *client_ca_cert_dir_path = nullptr)
  6857. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6858. client_ca_cert_dir_path),
  6859. stop_(false) {}
  6860. std::atomic_bool stop_;
  6861. private:
  6862. bool process_and_close_socket(socket_t /*sock*/) override {
  6863. // Don't create SSL context
  6864. while (!stop_.load()) {
  6865. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6866. }
  6867. return true;
  6868. }
  6869. };
  6870. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6871. CLIENT_CA_CERT_FILE);
  6872. ASSERT_TRUE(svr.is_valid());
  6873. svr.Get("/test", [&](const Request &, Response &res) {
  6874. res.set_content("test", "text/plain");
  6875. });
  6876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6877. auto se = detail::scope_exit([&] {
  6878. svr.stop_ = true;
  6879. svr.stop();
  6880. t.join();
  6881. ASSERT_FALSE(svr.is_running());
  6882. });
  6883. svr.wait_until_ready();
  6884. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6885. cli.enable_server_certificate_verification(false);
  6886. cli.set_connection_timeout(1);
  6887. auto res = cli.Get("/test");
  6888. ASSERT_TRUE(!res);
  6889. EXPECT_EQ(Error::SSLConnection, res.error());
  6890. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  6891. }
  6892. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6893. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6894. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6895. SSL_CTX_set_options(&ssl_ctx,
  6896. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6897. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6898. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6899. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6900. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6901. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6902. "ECDHE-DSS-AES128-SHA256:"
  6903. "ECDHE-RSA-AES256-SHA256:"
  6904. "ECDHE-DSS-AES256-SHA256:";
  6905. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6906. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6907. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6908. SSL_FILETYPE_PEM) != 1) {
  6909. return false;
  6910. }
  6911. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6912. CLIENT_CA_CERT_DIR);
  6913. SSL_CTX_set_verify(
  6914. &ssl_ctx,
  6915. SSL_VERIFY_PEER |
  6916. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6917. nullptr);
  6918. return true;
  6919. };
  6920. SSLServer svr(setup_ssl_ctx_callback);
  6921. ASSERT_TRUE(svr.is_valid());
  6922. svr.Get("/test", [&](const Request &req, Response &res) {
  6923. res.set_content("test", "text/plain");
  6924. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6925. ASSERT_TRUE(peer_cert != nullptr);
  6926. auto subject_name = X509_get_subject_name(peer_cert);
  6927. ASSERT_TRUE(subject_name != nullptr);
  6928. std::string common_name;
  6929. {
  6930. char name[BUFSIZ];
  6931. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6932. name, sizeof(name));
  6933. common_name.assign(name, static_cast<size_t>(name_len));
  6934. }
  6935. EXPECT_EQ("Common Name", common_name);
  6936. X509_free(peer_cert);
  6937. });
  6938. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6939. auto se = detail::scope_exit([&] {
  6940. svr.stop();
  6941. t.join();
  6942. ASSERT_FALSE(svr.is_running());
  6943. });
  6944. svr.wait_until_ready();
  6945. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6946. cli.enable_server_certificate_verification(false);
  6947. cli.set_connection_timeout(30);
  6948. auto res = cli.Get("/test");
  6949. ASSERT_TRUE(res);
  6950. ASSERT_EQ(StatusCode::OK_200, res->status);
  6951. }
  6952. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6953. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6954. // prepare large data
  6955. std::random_device seed_gen;
  6956. std::mt19937 random(seed_gen());
  6957. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6958. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6959. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6960. // server
  6961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6962. ASSERT_TRUE(svr.is_valid());
  6963. svr.Post("/binary", [&](const Request &req, Response &res) {
  6964. EXPECT_EQ(large_size_byte, req.body.size());
  6965. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6966. res.set_content(req.body, "application/octet-stream");
  6967. });
  6968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6969. auto se = detail::scope_exit([&] {
  6970. svr.stop();
  6971. listen_thread.join();
  6972. ASSERT_FALSE(svr.is_running());
  6973. });
  6974. svr.wait_until_ready();
  6975. // client POST
  6976. SSLClient cli("localhost", PORT);
  6977. cli.enable_server_certificate_verification(false);
  6978. cli.set_read_timeout(std::chrono::seconds(100));
  6979. cli.set_write_timeout(std::chrono::seconds(100));
  6980. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6981. large_size_byte, "application/octet-stream");
  6982. // compare
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. EXPECT_EQ(large_size_byte, res->body.size());
  6985. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6986. }
  6987. #endif
  6988. #ifdef _WIN32
  6989. TEST(CleanupTest, WSACleanup) {
  6990. int ret = WSACleanup();
  6991. ASSERT_EQ(0, ret);
  6992. }
  6993. #endif
  6994. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6995. TEST(NoSSLSupport, SimpleInterface) {
  6996. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6997. }
  6998. #endif
  6999. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7000. TEST(InvalidScheme, SimpleInterface) {
  7001. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7002. }
  7003. #endif
  7004. TEST(NoScheme, SimpleInterface) {
  7005. Client cli("yahoo.com:80");
  7006. ASSERT_TRUE(cli.is_valid());
  7007. }
  7008. TEST(SendAPI, SimpleInterface_Online) {
  7009. Client cli("http://yahoo.com");
  7010. Request req;
  7011. req.method = "GET";
  7012. req.path = "/";
  7013. auto res = cli.send(req);
  7014. ASSERT_TRUE(res);
  7015. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7016. }
  7017. TEST(SendAPI, WithParamsInRequest) {
  7018. Server svr;
  7019. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7020. EXPECT_TRUE(req.has_param("test"));
  7021. EXPECT_EQ("test_value", req.get_param_value("test"));
  7022. });
  7023. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7024. auto se = detail::scope_exit([&] {
  7025. svr.stop();
  7026. t.join();
  7027. ASSERT_FALSE(svr.is_running());
  7028. });
  7029. svr.wait_until_ready();
  7030. Client cli(HOST, PORT);
  7031. {
  7032. Request req;
  7033. req.method = "GET";
  7034. req.path = "/";
  7035. req.params.emplace("test", "test_value");
  7036. auto res = cli.send(req);
  7037. ASSERT_TRUE(res);
  7038. }
  7039. {
  7040. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7041. ASSERT_TRUE(res);
  7042. }
  7043. }
  7044. TEST(ClientImplMethods, GetSocketTest) {
  7045. httplib::Server svr;
  7046. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7047. res.status = StatusCode::OK_200;
  7048. });
  7049. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7050. auto se = detail::scope_exit([&] {
  7051. svr.stop();
  7052. thread.join();
  7053. ASSERT_FALSE(svr.is_running());
  7054. });
  7055. svr.wait_until_ready();
  7056. {
  7057. httplib::Client cli("http://127.0.0.1:3333");
  7058. cli.set_keep_alive(true);
  7059. // Use the behavior of cpp-httplib of opening the connection
  7060. // only when the first request happens. If that changes,
  7061. // this test would be obsolete.
  7062. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7063. // This also implicitly tests the server. But other tests would fail much
  7064. // earlier than this one to be considered.
  7065. auto res = cli.Get("/");
  7066. ASSERT_TRUE(res);
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7069. }
  7070. }
  7071. // Disabled due to out-of-memory problem on GitHub Actions
  7072. #ifdef _WIN64
  7073. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7074. // allocate content size larger than 2GB in memory
  7075. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7076. char *content = (char *)malloc(content_size);
  7077. ASSERT_TRUE(content);
  7078. Server svr;
  7079. svr.Get("/foo",
  7080. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7081. res.set_content(content, content_size, "application/octet-stream");
  7082. });
  7083. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7084. auto se = detail::scope_exit([&] {
  7085. svr.stop();
  7086. listen_thread.join();
  7087. if (content) free(content);
  7088. ASSERT_FALSE(svr.is_running());
  7089. });
  7090. svr.wait_until_ready();
  7091. Client cli(HOST, PORT);
  7092. auto res = cli.Get("/foo");
  7093. ASSERT_TRUE(res);
  7094. EXPECT_EQ(StatusCode::OK_200, res->status);
  7095. EXPECT_EQ(content_size, res->body.length());
  7096. }
  7097. #endif
  7098. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7099. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7100. Client cli("http://yahoo.com");
  7101. auto res = cli.Get("/");
  7102. ASSERT_TRUE(res);
  7103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7104. cli.set_follow_location(true);
  7105. res = cli.Get("/");
  7106. ASSERT_TRUE(res);
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7109. }
  7110. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7111. Client cli("https://yahoo.com");
  7112. auto res = cli.Get("/");
  7113. ASSERT_TRUE(res);
  7114. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7115. cli.set_follow_location(true);
  7116. res = cli.Get("/");
  7117. ASSERT_TRUE(res);
  7118. EXPECT_EQ(StatusCode::OK_200, res->status);
  7119. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7120. }
  7121. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7122. Client cli("https://yahoo.com");
  7123. auto res = cli.Get("/");
  7124. ASSERT_TRUE(res);
  7125. ASSERT_FALSE(!res);
  7126. ASSERT_TRUE(res);
  7127. ASSERT_FALSE(res == nullptr);
  7128. ASSERT_TRUE(res != nullptr);
  7129. EXPECT_EQ(Error::Success, res.error());
  7130. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7131. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7132. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7133. cli.set_follow_location(true);
  7134. res = cli.Get("/");
  7135. ASSERT_TRUE(res);
  7136. EXPECT_EQ(Error::Success, res.error());
  7137. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7138. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7141. }
  7142. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7143. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7144. Client cli("https://cdnjs.cloudflare.com");
  7145. auto res =
  7146. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7147. ASSERT_TRUE(res);
  7148. EXPECT_EQ(StatusCode::OK_200, res->status);
  7149. EXPECT_EQ(287630U, res->body.size());
  7150. EXPECT_EQ("application/javascript; charset=utf-8",
  7151. res->get_header_value("Content-Type"));
  7152. }
  7153. #endif
  7154. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7155. #undef REDIR_HOST // Silence compiler warning
  7156. #define REDIR_HOST "https://httpbingo.org"
  7157. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7158. Client cli(REDIR_HOST);
  7159. cli.set_follow_location(true);
  7160. auto res =
  7161. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7162. ASSERT_TRUE(res);
  7163. EXPECT_EQ(StatusCode::OK_200, res->status);
  7164. }
  7165. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7166. Client cli(REDIR_HOST);
  7167. cli.set_follow_location(true);
  7168. Params params;
  7169. params.emplace("url", "http://example.com");
  7170. params.emplace("status_code", "302");
  7171. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. }
  7175. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7176. Client cli(REDIR_HOST);
  7177. cli.set_follow_location(true);
  7178. Params params;
  7179. params.emplace("url", "http://example.com");
  7180. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7181. ASSERT_TRUE(res);
  7182. EXPECT_EQ(StatusCode::OK_200, res->status);
  7183. }
  7184. TEST(HttpToHttpsRedirectTest, CertFile) {
  7185. Server svr;
  7186. ASSERT_TRUE(svr.is_valid());
  7187. svr.Get("/index", [&](const Request &, Response &res) {
  7188. res.set_redirect("https://127.0.0.1:1235/index");
  7189. svr.stop();
  7190. });
  7191. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7192. ASSERT_TRUE(ssl_svr.is_valid());
  7193. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7194. res.set_content("test", "text/plain");
  7195. ssl_svr.stop();
  7196. });
  7197. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7198. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7199. auto se = detail::scope_exit([&] {
  7200. t2.join();
  7201. t.join();
  7202. ASSERT_FALSE(svr.is_running());
  7203. });
  7204. svr.wait_until_ready();
  7205. ssl_svr.wait_until_ready();
  7206. Client cli("127.0.0.1", PORT);
  7207. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7208. cli.enable_server_certificate_verification(true);
  7209. cli.set_follow_location(true);
  7210. cli.set_connection_timeout(30);
  7211. auto res = cli.Get("/index");
  7212. ASSERT_TRUE(res);
  7213. ASSERT_EQ(StatusCode::OK_200, res->status);
  7214. }
  7215. TEST(MultipartFormDataTest, LargeData) {
  7216. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7217. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7218. const ContentReader &content_reader) {
  7219. if (req.is_multipart_form_data()) {
  7220. MultipartFormDataItems files;
  7221. content_reader(
  7222. [&](const MultipartFormData &file) {
  7223. files.push_back(file);
  7224. return true;
  7225. },
  7226. [&](const char *data, size_t data_length) {
  7227. files.back().content.append(data, data_length);
  7228. return true;
  7229. });
  7230. EXPECT_TRUE(std::string(files[0].name) == "document");
  7231. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7232. EXPECT_TRUE(files[0].filename == "2MB_data");
  7233. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7234. EXPECT_TRUE(files[1].name == "hello");
  7235. EXPECT_TRUE(files[1].content == "world");
  7236. EXPECT_TRUE(files[1].filename == "");
  7237. EXPECT_TRUE(files[1].content_type == "");
  7238. } else {
  7239. std::string body;
  7240. content_reader([&](const char *data, size_t data_length) {
  7241. body.append(data, data_length);
  7242. return true;
  7243. });
  7244. }
  7245. });
  7246. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7247. auto se = detail::scope_exit([&] {
  7248. svr.stop();
  7249. t.join();
  7250. ASSERT_FALSE(svr.is_running());
  7251. });
  7252. svr.wait_until_ready();
  7253. {
  7254. std::string data(1024 * 1024 * 2, '.');
  7255. std::stringstream buffer;
  7256. buffer << data;
  7257. Client cli("https://localhost:8080");
  7258. cli.enable_server_certificate_verification(false);
  7259. MultipartFormDataItemsForClientInput items{
  7260. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7261. {"hello", "world", "", ""},
  7262. };
  7263. auto res = cli.Post("/post", items);
  7264. ASSERT_TRUE(res);
  7265. ASSERT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. }
  7268. TEST(MultipartFormDataTest, DataProviderItems) {
  7269. std::random_device seed_gen;
  7270. std::mt19937 random(seed_gen());
  7271. std::string rand1;
  7272. rand1.resize(1000);
  7273. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7274. std::string rand2;
  7275. rand2.resize(3000);
  7276. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7278. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7279. const ContentReader &content_reader) {
  7280. ASSERT_FALSE(req.is_multipart_form_data());
  7281. std::string body;
  7282. content_reader([&](const char *data, size_t data_length) {
  7283. body.append(data, data_length);
  7284. return true;
  7285. });
  7286. EXPECT_EQ(body, "");
  7287. });
  7288. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7289. const ContentReader &content_reader) {
  7290. ASSERT_TRUE(req.is_multipart_form_data());
  7291. MultipartFormDataItems files;
  7292. content_reader(
  7293. [&](const MultipartFormData &file) {
  7294. files.push_back(file);
  7295. return true;
  7296. },
  7297. [&](const char *data, size_t data_length) {
  7298. files.back().content.append(data, data_length);
  7299. return true;
  7300. });
  7301. ASSERT_TRUE(files.size() == 2);
  7302. EXPECT_EQ(std::string(files[0].name), "name1");
  7303. EXPECT_EQ(files[0].content, "Testing123");
  7304. EXPECT_EQ(files[0].filename, "filename1");
  7305. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7306. EXPECT_EQ(files[1].name, "name2");
  7307. EXPECT_EQ(files[1].content, "Testing456");
  7308. EXPECT_EQ(files[1].filename, "");
  7309. EXPECT_EQ(files[1].content_type, "");
  7310. });
  7311. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7312. const ContentReader &content_reader) {
  7313. ASSERT_TRUE(req.is_multipart_form_data());
  7314. MultipartFormDataItems files;
  7315. content_reader(
  7316. [&](const MultipartFormData &file) {
  7317. files.push_back(file);
  7318. return true;
  7319. },
  7320. [&](const char *data, size_t data_length) {
  7321. files.back().content.append(data, data_length);
  7322. return true;
  7323. });
  7324. ASSERT_TRUE(files.size() == 2);
  7325. EXPECT_EQ(files[0].name, "name3");
  7326. EXPECT_EQ(files[0].content, rand1);
  7327. EXPECT_EQ(files[0].filename, "filename3");
  7328. EXPECT_EQ(files[0].content_type, "");
  7329. EXPECT_EQ(files[1].name, "name4");
  7330. EXPECT_EQ(files[1].content, rand2);
  7331. EXPECT_EQ(files[1].filename, "filename4");
  7332. EXPECT_EQ(files[1].content_type, "");
  7333. });
  7334. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7335. const ContentReader &content_reader) {
  7336. ASSERT_TRUE(req.is_multipart_form_data());
  7337. MultipartFormDataItems files;
  7338. content_reader(
  7339. [&](const MultipartFormData &file) {
  7340. files.push_back(file);
  7341. return true;
  7342. },
  7343. [&](const char *data, size_t data_length) {
  7344. files.back().content.append(data, data_length);
  7345. return true;
  7346. });
  7347. ASSERT_TRUE(files.size() == 4);
  7348. EXPECT_EQ(std::string(files[0].name), "name1");
  7349. EXPECT_EQ(files[0].content, "Testing123");
  7350. EXPECT_EQ(files[0].filename, "filename1");
  7351. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7352. EXPECT_EQ(files[1].name, "name2");
  7353. EXPECT_EQ(files[1].content, "Testing456");
  7354. EXPECT_EQ(files[1].filename, "");
  7355. EXPECT_EQ(files[1].content_type, "");
  7356. EXPECT_EQ(files[2].name, "name3");
  7357. EXPECT_EQ(files[2].content, rand1);
  7358. EXPECT_EQ(files[2].filename, "filename3");
  7359. EXPECT_EQ(files[2].content_type, "");
  7360. EXPECT_EQ(files[3].name, "name4");
  7361. EXPECT_EQ(files[3].content, rand2);
  7362. EXPECT_EQ(files[3].filename, "filename4");
  7363. EXPECT_EQ(files[3].content_type, "");
  7364. });
  7365. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7366. auto se = detail::scope_exit([&] {
  7367. svr.stop();
  7368. t.join();
  7369. ASSERT_FALSE(svr.is_running());
  7370. });
  7371. svr.wait_until_ready();
  7372. {
  7373. Client cli("https://localhost:8080");
  7374. cli.enable_server_certificate_verification(false);
  7375. MultipartFormDataItemsForClientInput items{
  7376. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7377. {"name2", "Testing456", "", ""}, // not a file
  7378. };
  7379. {
  7380. auto res = cli.Post("/post-none", {}, {}, {});
  7381. ASSERT_TRUE(res);
  7382. ASSERT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. MultipartFormDataProviderItems providers;
  7385. {
  7386. auto res =
  7387. cli.Post("/post-items", {}, items, providers); // empty providers
  7388. ASSERT_TRUE(res);
  7389. ASSERT_EQ(StatusCode::OK_200, res->status);
  7390. }
  7391. providers.push_back({"name3",
  7392. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7393. // test the offset is given correctly at each step
  7394. if (!offset)
  7395. sink.os.write(rand1.data(), 30);
  7396. else if (offset == 30)
  7397. sink.os.write(rand1.data() + 30, 300);
  7398. else if (offset == 330)
  7399. sink.os.write(rand1.data() + 330, 670);
  7400. else if (offset == rand1.size())
  7401. sink.done();
  7402. return true;
  7403. },
  7404. "filename3",
  7405. {}});
  7406. providers.push_back({"name4",
  7407. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7408. // test the offset is given correctly at each step
  7409. if (!offset)
  7410. sink.os.write(rand2.data(), 2000);
  7411. else if (offset == 2000)
  7412. sink.os.write(rand2.data() + 2000, 1);
  7413. else if (offset == 2001)
  7414. sink.os.write(rand2.data() + 2001, 999);
  7415. else if (offset == rand2.size())
  7416. sink.done();
  7417. return true;
  7418. },
  7419. "filename4",
  7420. {}});
  7421. {
  7422. auto res = cli.Post("/post-providers", {}, {}, providers);
  7423. ASSERT_TRUE(res);
  7424. ASSERT_EQ(StatusCode::OK_200, res->status);
  7425. }
  7426. {
  7427. auto res = cli.Post("/post-both", {}, items, providers);
  7428. ASSERT_TRUE(res);
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. }
  7431. }
  7432. }
  7433. TEST(MultipartFormDataTest, BadHeader) {
  7434. Server svr;
  7435. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7436. res.set_content("ok", "text/plain");
  7437. });
  7438. thread t = thread([&] { svr.listen(HOST, PORT); });
  7439. auto se = detail::scope_exit([&] {
  7440. svr.stop();
  7441. t.join();
  7442. ASSERT_FALSE(svr.is_running());
  7443. });
  7444. svr.wait_until_ready();
  7445. const std::string body =
  7446. "This is the preamble. It is to be ignored, though it\r\n"
  7447. "is a handy place for composition agents to include an\r\n"
  7448. "explanatory note to non-MIME conformant readers.\r\n"
  7449. "\r\n"
  7450. "\r\n"
  7451. "--simple boundary\r\n"
  7452. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7453. ": BAD...\r\n"
  7454. "\r\n"
  7455. "value1\r\n"
  7456. "--simple boundary\r\n"
  7457. "Content-Disposition: form-data; name=\"field2\"; "
  7458. "filename=\"example.txt\"\r\n"
  7459. "\r\n"
  7460. "value2\r\n"
  7461. "--simple boundary--\r\n"
  7462. "This is the epilogue. It is also to be ignored.\r\n";
  7463. std::string content_type =
  7464. R"(multipart/form-data; boundary="simple boundary")";
  7465. Client cli(HOST, PORT);
  7466. auto res = cli.Post("/post", body, content_type.c_str());
  7467. ASSERT_TRUE(res);
  7468. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7469. }
  7470. TEST(MultipartFormDataTest, WithPreamble) {
  7471. Server svr;
  7472. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7473. res.set_content("ok", "text/plain");
  7474. });
  7475. thread t = thread([&] { svr.listen(HOST, PORT); });
  7476. auto se = detail::scope_exit([&] {
  7477. svr.stop();
  7478. t.join();
  7479. ASSERT_FALSE(svr.is_running());
  7480. });
  7481. svr.wait_until_ready();
  7482. const std::string body =
  7483. "This is the preamble. It is to be ignored, though it\r\n"
  7484. "is a handy place for composition agents to include an\r\n"
  7485. "explanatory note to non-MIME conformant readers.\r\n"
  7486. "\r\n"
  7487. "\r\n"
  7488. "--simple boundary\r\n"
  7489. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7490. "\r\n"
  7491. "value1\r\n"
  7492. "--simple boundary\r\n"
  7493. "Content-Disposition: form-data; name=\"field2\"; "
  7494. "filename=\"example.txt\"\r\n"
  7495. "\r\n"
  7496. "value2\r\n"
  7497. "--simple boundary--\r\n"
  7498. "This is the epilogue. It is also to be ignored.\r\n";
  7499. std::string content_type =
  7500. R"(multipart/form-data; boundary="simple boundary")";
  7501. Client cli(HOST, PORT);
  7502. auto res = cli.Post("/post", body, content_type.c_str());
  7503. ASSERT_TRUE(res);
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. }
  7506. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7508. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7509. const ContentReader &content_reader) {
  7510. if (req.is_multipart_form_data()) {
  7511. MultipartFormDataItems files;
  7512. content_reader(
  7513. [&](const MultipartFormData &file) {
  7514. files.push_back(file);
  7515. return true;
  7516. },
  7517. [&](const char *data, size_t data_length) {
  7518. files.back().content.append(data, data_length);
  7519. return true;
  7520. });
  7521. EXPECT_TRUE(std::string(files[0].name) == "document");
  7522. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7523. EXPECT_TRUE(files[0].filename == "2MB_data");
  7524. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7525. EXPECT_TRUE(files[1].name == "hello");
  7526. EXPECT_TRUE(files[1].content == "world");
  7527. EXPECT_TRUE(files[1].filename == "");
  7528. EXPECT_TRUE(files[1].content_type == "");
  7529. } else {
  7530. std::string body;
  7531. content_reader([&](const char *data, size_t data_length) {
  7532. body.append(data, data_length);
  7533. return true;
  7534. });
  7535. }
  7536. });
  7537. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7538. auto se = detail::scope_exit([&] {
  7539. svr.stop();
  7540. t.join();
  7541. ASSERT_FALSE(svr.is_running());
  7542. });
  7543. svr.wait_until_ready();
  7544. {
  7545. std::string data(1024 * 1024 * 2, '.');
  7546. std::stringstream buffer;
  7547. buffer << data;
  7548. Client cli("https://localhost:8080");
  7549. cli.enable_server_certificate_verification(false);
  7550. MultipartFormDataItemsForClientInput items{
  7551. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7552. {"hello", "world", "", ""},
  7553. };
  7554. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7555. ASSERT_TRUE(res);
  7556. ASSERT_EQ(StatusCode::OK_200, res->status);
  7557. }
  7558. }
  7559. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7560. std::string data(1024 * 1024 * 2, '&');
  7561. std::stringstream buffer;
  7562. buffer << data;
  7563. Client cli("https://localhost:8080");
  7564. MultipartFormDataItemsForClientInput items{
  7565. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7566. {"hello", "world", "", ""},
  7567. };
  7568. for (const char &c : " \t\r\n") {
  7569. auto res =
  7570. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7571. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7572. ASSERT_FALSE(res);
  7573. }
  7574. }
  7575. TEST(MultipartFormDataTest, PutFormData) {
  7576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7577. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7578. const ContentReader &content_reader) {
  7579. if (req.is_multipart_form_data()) {
  7580. MultipartFormDataItems files;
  7581. content_reader(
  7582. [&](const MultipartFormData &file) {
  7583. files.push_back(file);
  7584. return true;
  7585. },
  7586. [&](const char *data, size_t data_length) {
  7587. files.back().content.append(data, data_length);
  7588. return true;
  7589. });
  7590. EXPECT_TRUE(std::string(files[0].name) == "document");
  7591. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7592. EXPECT_TRUE(files[0].filename == "2MB_data");
  7593. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7594. EXPECT_TRUE(files[1].name == "hello");
  7595. EXPECT_TRUE(files[1].content == "world");
  7596. EXPECT_TRUE(files[1].filename == "");
  7597. EXPECT_TRUE(files[1].content_type == "");
  7598. } else {
  7599. std::string body;
  7600. content_reader([&](const char *data, size_t data_length) {
  7601. body.append(data, data_length);
  7602. return true;
  7603. });
  7604. }
  7605. });
  7606. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7607. auto se = detail::scope_exit([&] {
  7608. svr.stop();
  7609. t.join();
  7610. ASSERT_FALSE(svr.is_running());
  7611. });
  7612. svr.wait_until_ready();
  7613. {
  7614. std::string data(1024 * 1024 * 2, '&');
  7615. std::stringstream buffer;
  7616. buffer << data;
  7617. Client cli("https://localhost:8080");
  7618. cli.enable_server_certificate_verification(false);
  7619. MultipartFormDataItemsForClientInput items{
  7620. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7621. {"hello", "world", "", ""},
  7622. };
  7623. auto res = cli.Put("/put", items);
  7624. ASSERT_TRUE(res);
  7625. ASSERT_EQ(StatusCode::OK_200, res->status);
  7626. }
  7627. }
  7628. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7630. svr.Put("/put_customboundary",
  7631. [&](const Request &req, const Response & /*res*/,
  7632. const ContentReader &content_reader) {
  7633. if (req.is_multipart_form_data()) {
  7634. MultipartFormDataItems files;
  7635. content_reader(
  7636. [&](const MultipartFormData &file) {
  7637. files.push_back(file);
  7638. return true;
  7639. },
  7640. [&](const char *data, size_t data_length) {
  7641. files.back().content.append(data, data_length);
  7642. return true;
  7643. });
  7644. EXPECT_TRUE(std::string(files[0].name) == "document");
  7645. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7646. EXPECT_TRUE(files[0].filename == "2MB_data");
  7647. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7648. EXPECT_TRUE(files[1].name == "hello");
  7649. EXPECT_TRUE(files[1].content == "world");
  7650. EXPECT_TRUE(files[1].filename == "");
  7651. EXPECT_TRUE(files[1].content_type == "");
  7652. } else {
  7653. std::string body;
  7654. content_reader([&](const char *data, size_t data_length) {
  7655. body.append(data, data_length);
  7656. return true;
  7657. });
  7658. }
  7659. });
  7660. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7661. auto se = detail::scope_exit([&] {
  7662. svr.stop();
  7663. t.join();
  7664. ASSERT_FALSE(svr.is_running());
  7665. });
  7666. svr.wait_until_ready();
  7667. {
  7668. std::string data(1024 * 1024 * 2, '&');
  7669. std::stringstream buffer;
  7670. buffer << data;
  7671. Client cli("https://localhost:8080");
  7672. cli.enable_server_certificate_verification(false);
  7673. MultipartFormDataItemsForClientInput items{
  7674. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7675. {"hello", "world", "", ""},
  7676. };
  7677. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7678. ASSERT_TRUE(res);
  7679. ASSERT_EQ(StatusCode::OK_200, res->status);
  7680. }
  7681. }
  7682. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7683. std::string data(1024 * 1024 * 2, '&');
  7684. std::stringstream buffer;
  7685. buffer << data;
  7686. Client cli("https://localhost:8080");
  7687. cli.enable_server_certificate_verification(false);
  7688. MultipartFormDataItemsForClientInput items{
  7689. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7690. {"hello", "world", "", ""},
  7691. };
  7692. for (const char &c : " \t\r\n") {
  7693. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7694. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7695. ASSERT_FALSE(res);
  7696. }
  7697. }
  7698. TEST(MultipartFormDataTest, AlternateFilename) {
  7699. auto handled = false;
  7700. Server svr;
  7701. svr.Post("/test", [&](const Request &req, Response &res) {
  7702. ASSERT_EQ(3u, req.files.size());
  7703. auto it = req.files.begin();
  7704. ASSERT_EQ("file1", it->second.name);
  7705. ASSERT_EQ("A.txt", it->second.filename);
  7706. ASSERT_EQ("text/plain", it->second.content_type);
  7707. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7708. ++it;
  7709. ASSERT_EQ("file2", it->second.name);
  7710. ASSERT_EQ("a.html", it->second.filename);
  7711. ASSERT_EQ("text/html", it->second.content_type);
  7712. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7713. it->second.content);
  7714. ++it;
  7715. ASSERT_EQ("text", it->second.name);
  7716. ASSERT_EQ("", it->second.filename);
  7717. ASSERT_EQ("", it->second.content_type);
  7718. ASSERT_EQ("text default", it->second.content);
  7719. res.set_content("ok", "text/plain");
  7720. handled = true;
  7721. });
  7722. thread t = thread([&] { svr.listen(HOST, PORT); });
  7723. auto se = detail::scope_exit([&] {
  7724. svr.stop();
  7725. t.join();
  7726. ASSERT_FALSE(svr.is_running());
  7727. ASSERT_TRUE(handled);
  7728. });
  7729. svr.wait_until_ready();
  7730. auto req = "POST /test HTTP/1.1\r\n"
  7731. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7732. "Content-Length: 399\r\n"
  7733. "\r\n"
  7734. "----------\r\n"
  7735. "Content-Disposition: form-data; name=\"text\"\r\n"
  7736. "\r\n"
  7737. "text default\r\n"
  7738. "----------\r\n"
  7739. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7740. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7741. "Content-Type: text/plain\r\n"
  7742. "\r\n"
  7743. "Content of a.txt.\r\n"
  7744. "\r\n"
  7745. "----------\r\n"
  7746. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7747. "\"a.html\"\r\n"
  7748. "Content-Type: text/html\r\n"
  7749. "\r\n"
  7750. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7751. "\r\n"
  7752. "------------\r\n";
  7753. ASSERT_TRUE(send_request(1, req));
  7754. }
  7755. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7756. auto handled = false;
  7757. Server svr;
  7758. svr.Post("/test", [&](const Request &req, Response &) {
  7759. ASSERT_EQ(2u, req.files.size());
  7760. auto it = req.files.begin();
  7761. ASSERT_EQ("text1", it->second.name);
  7762. ASSERT_EQ("text1", it->second.content);
  7763. ++it;
  7764. ASSERT_EQ("text2", it->second.name);
  7765. ASSERT_EQ("text2", it->second.content);
  7766. handled = true;
  7767. });
  7768. thread t = thread([&] { svr.listen(HOST, PORT); });
  7769. auto se = detail::scope_exit([&] {
  7770. svr.stop();
  7771. t.join();
  7772. ASSERT_FALSE(svr.is_running());
  7773. ASSERT_TRUE(handled);
  7774. });
  7775. svr.wait_until_ready();
  7776. auto req = "POST /test HTTP/1.1\r\n"
  7777. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7778. "Content-Length: 146\r\n"
  7779. "\r\n----------\r\n"
  7780. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7781. "\r\n"
  7782. "text1"
  7783. "\r\n----------\r\n"
  7784. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7785. "\r\n"
  7786. "text2"
  7787. "\r\n------------";
  7788. std::string response;
  7789. ASSERT_TRUE(send_request(1, req, &response));
  7790. ASSERT_EQ("200", response.substr(9, 3));
  7791. }
  7792. TEST(MultipartFormDataTest, ContentLength) {
  7793. auto handled = false;
  7794. Server svr;
  7795. svr.Post("/test", [&](const Request &req, Response &) {
  7796. ASSERT_EQ(2u, req.files.size());
  7797. auto it = req.files.begin();
  7798. ASSERT_EQ("text1", it->second.name);
  7799. ASSERT_EQ("text1", it->second.content);
  7800. ++it;
  7801. ASSERT_EQ("text2", it->second.name);
  7802. ASSERT_EQ("text2", it->second.content);
  7803. handled = true;
  7804. });
  7805. thread t = thread([&] { svr.listen(HOST, PORT); });
  7806. auto se = detail::scope_exit([&] {
  7807. svr.stop();
  7808. t.join();
  7809. ASSERT_FALSE(svr.is_running());
  7810. ASSERT_TRUE(handled);
  7811. });
  7812. svr.wait_until_ready();
  7813. auto req = "POST /test HTTP/1.1\r\n"
  7814. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7815. "Content-Length: 167\r\n"
  7816. "\r\n----------\r\n"
  7817. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7818. "Content-Length: 5\r\n"
  7819. "\r\n"
  7820. "text1"
  7821. "\r\n----------\r\n"
  7822. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7823. "\r\n"
  7824. "text2"
  7825. "\r\n------------\r\n";
  7826. std::string response;
  7827. ASSERT_TRUE(send_request(1, req, &response));
  7828. ASSERT_EQ("200", response.substr(9, 3));
  7829. }
  7830. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7831. auto handled = false;
  7832. Server svr;
  7833. svr.Post("/test", [&](const Request &req, Response &) {
  7834. ASSERT_EQ(2u, req.files.size());
  7835. auto it = req.files.begin();
  7836. ASSERT_EQ("text1", it->second.name);
  7837. ASSERT_EQ("text1", it->second.content);
  7838. ASSERT_EQ(1U, it->second.headers.count("Content-Length"));
  7839. auto content_length = it->second.headers.find("CONTENT-length");
  7840. ASSERT_EQ("5", content_length->second);
  7841. ASSERT_EQ(3U, it->second.headers.size());
  7842. ++it;
  7843. ASSERT_EQ("text2", it->second.name);
  7844. ASSERT_EQ("text2", it->second.content);
  7845. auto &headers = it->second.headers;
  7846. ASSERT_EQ(3U, headers.size());
  7847. auto custom_header = headers.find("x-whatever");
  7848. ASSERT_TRUE(custom_header != headers.end());
  7849. ASSERT_NE("customvalue", custom_header->second);
  7850. ASSERT_EQ("CustomValue", custom_header->second);
  7851. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7852. handled = true;
  7853. });
  7854. thread t = thread([&] { svr.listen(HOST, PORT); });
  7855. auto se = detail::scope_exit([&] {
  7856. svr.stop();
  7857. t.join();
  7858. ASSERT_FALSE(svr.is_running());
  7859. ASSERT_TRUE(handled);
  7860. });
  7861. svr.wait_until_ready();
  7862. auto req = "POST /test HTTP/1.1\r\n"
  7863. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7864. "Content-Length: 232\r\n"
  7865. "\r\n----------\r\n"
  7866. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7867. "Content-Length: 5\r\n"
  7868. "X-Test: 1\r\n"
  7869. "\r\n"
  7870. "text1"
  7871. "\r\n----------\r\n"
  7872. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7873. "Content-Type: text/plain\r\n"
  7874. "X-Whatever: CustomValue\r\n"
  7875. "\r\n"
  7876. "text2"
  7877. "\r\n------------\r\n"
  7878. "That should be disregarded. Not even read";
  7879. std::string response;
  7880. ASSERT_TRUE(send_request(1, req, &response));
  7881. ASSERT_EQ("200", response.substr(9, 3));
  7882. }
  7883. #endif
  7884. TEST(MultipartFormDataTest, LargeHeader) {
  7885. auto handled = false;
  7886. Server svr;
  7887. svr.Post("/test", [&](const Request &req, Response &) {
  7888. ASSERT_EQ(1u, req.files.size());
  7889. auto it = req.files.begin();
  7890. ASSERT_EQ("name1", it->second.name);
  7891. ASSERT_EQ("text1", it->second.content);
  7892. handled = true;
  7893. });
  7894. thread t = thread([&] { svr.listen(HOST, PORT); });
  7895. auto se = detail::scope_exit([&] {
  7896. svr.stop();
  7897. t.join();
  7898. ASSERT_FALSE(svr.is_running());
  7899. ASSERT_TRUE(handled);
  7900. });
  7901. svr.wait_until_ready();
  7902. auto boundary = std::string("cpp-httplib-multipart-data");
  7903. std::string content = "--" + boundary +
  7904. "\r\n"
  7905. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7906. "\r\n"
  7907. "text1\r\n"
  7908. "--" +
  7909. boundary + "--\r\n";
  7910. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7911. "Content-Type: multipart/form-data;boundary=" +
  7912. boundary +
  7913. "\r\n"
  7914. "Content-Length: " +
  7915. std::to_string(content.size()) +
  7916. "\r\n"
  7917. "Dummy-Header: ";
  7918. std::string header_suffix = "\r\n"
  7919. "\r\n";
  7920. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7921. size_t header_dummy_size =
  7922. read_buff_size -
  7923. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7924. auto header_dummy = std::string(header_dummy_size, '@');
  7925. auto req = header_prefix + header_dummy + header_suffix + content;
  7926. std::string response;
  7927. ASSERT_TRUE(send_request(1, req, &response));
  7928. ASSERT_EQ("200", response.substr(9, 3));
  7929. }
  7930. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7931. static constexpr unsigned int number_of_tasks{1000000};
  7932. std::atomic_uint count{0};
  7933. std::unique_ptr<TaskQueue> task_queue{
  7934. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7935. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7936. auto queued = task_queue->enqueue(
  7937. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7938. EXPECT_TRUE(queued);
  7939. }
  7940. EXPECT_NO_THROW(task_queue->shutdown());
  7941. EXPECT_EQ(number_of_tasks, count.load());
  7942. }
  7943. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7944. static constexpr unsigned int number_of_tasks{1000000};
  7945. static constexpr unsigned int qlimit{2};
  7946. unsigned int queued_count{0};
  7947. std::atomic_uint count{0};
  7948. std::unique_ptr<TaskQueue> task_queue{
  7949. new ThreadPool{/*num_threads=*/1, qlimit}};
  7950. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7951. if (task_queue->enqueue(
  7952. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7953. queued_count++;
  7954. }
  7955. }
  7956. EXPECT_NO_THROW(task_queue->shutdown());
  7957. EXPECT_EQ(queued_count, count.load());
  7958. EXPECT_TRUE(queued_count <= number_of_tasks);
  7959. EXPECT_TRUE(queued_count >= qlimit);
  7960. }
  7961. TEST(TaskQueueTest, MaxQueuedRequests) {
  7962. static constexpr unsigned int qlimit{3};
  7963. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7964. std::condition_variable sem_cv;
  7965. std::mutex sem_mtx;
  7966. int credits = 0;
  7967. bool queued;
  7968. /* Fill up the queue with tasks that will block until we give them credits to
  7969. * complete. */
  7970. for (unsigned int n = 0; n <= qlimit;) {
  7971. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7972. std::unique_lock<std::mutex> lock(sem_mtx);
  7973. while (credits <= 0) {
  7974. sem_cv.wait(lock);
  7975. }
  7976. /* Consume the credit and signal the test code if they are all gone. */
  7977. if (--credits == 0) { sem_cv.notify_one(); }
  7978. });
  7979. if (n < qlimit) {
  7980. /* The first qlimit enqueues must succeed. */
  7981. EXPECT_TRUE(queued);
  7982. } else {
  7983. /* The last one will succeed only when the worker thread
  7984. * starts and dequeues the first blocking task. Although
  7985. * not necessary for the correctness of this test, we sleep for
  7986. * a short while to avoid busy waiting. */
  7987. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7988. }
  7989. if (queued) { n++; }
  7990. }
  7991. /* Further enqueues must fail since the queue is full. */
  7992. for (auto i = 0; i < 4; i++) {
  7993. queued = task_queue->enqueue([] {});
  7994. EXPECT_FALSE(queued);
  7995. }
  7996. /* Give the credits to allow the previous tasks to complete. */
  7997. {
  7998. std::unique_lock<std::mutex> lock(sem_mtx);
  7999. credits += qlimit + 1;
  8000. }
  8001. sem_cv.notify_all();
  8002. /* Wait for all the credits to be consumed. */
  8003. {
  8004. std::unique_lock<std::mutex> lock(sem_mtx);
  8005. while (credits > 0) {
  8006. sem_cv.wait(lock);
  8007. }
  8008. }
  8009. /* Check that we are able again to enqueue at least qlimit tasks. */
  8010. for (unsigned int i = 0; i < qlimit; i++) {
  8011. queued = task_queue->enqueue([] {});
  8012. EXPECT_TRUE(queued);
  8013. }
  8014. EXPECT_NO_THROW(task_queue->shutdown());
  8015. }
  8016. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8017. Server svr;
  8018. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8019. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8020. });
  8021. svr.Get("/hello", [](const Request &req, Response &res) {
  8022. res.set_content(req.get_param_value("key"), "text/plain");
  8023. });
  8024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8025. auto se = detail::scope_exit([&] {
  8026. svr.stop();
  8027. thread.join();
  8028. ASSERT_FALSE(svr.is_running());
  8029. });
  8030. svr.wait_until_ready();
  8031. {
  8032. Client cli(HOST, PORT);
  8033. cli.set_follow_location(true);
  8034. auto res = cli.Get("/");
  8035. ASSERT_TRUE(res);
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. EXPECT_EQ("val&key2=val2", res->body);
  8038. }
  8039. }
  8040. TEST(VulnerabilityTest, CRLFInjection) {
  8041. Server svr;
  8042. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8043. res.set_content("Hello 1", "text/plain");
  8044. });
  8045. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8046. res.set_content("Hello 2", "text/plain");
  8047. });
  8048. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8049. res.set_content("Hello 3", "text/plain");
  8050. });
  8051. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8052. res.set_content("Hello 4", "text/plain");
  8053. });
  8054. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8055. for (const auto &x : req.headers) {
  8056. auto key = x.first;
  8057. EXPECT_STRNE("evil", key.c_str());
  8058. }
  8059. });
  8060. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8061. auto se = detail::scope_exit([&] {
  8062. svr.stop();
  8063. thread.join();
  8064. ASSERT_FALSE(svr.is_running());
  8065. });
  8066. svr.wait_until_ready();
  8067. {
  8068. Client cli(HOST, PORT);
  8069. cli.Post("/test1", "A=B",
  8070. "application/x-www-form-urlencoded\r\nevil: hello1");
  8071. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8072. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8073. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8074. }
  8075. }
  8076. TEST(PathParamsTest, StaticMatch) {
  8077. const auto pattern = "/users/all";
  8078. detail::PathParamsMatcher matcher(pattern);
  8079. Request request;
  8080. request.path = "/users/all";
  8081. ASSERT_TRUE(matcher.match(request));
  8082. std::unordered_map<std::string, std::string> expected_params = {};
  8083. EXPECT_EQ(request.path_params, expected_params);
  8084. }
  8085. TEST(PathParamsTest, StaticMismatch) {
  8086. const auto pattern = "/users/all";
  8087. detail::PathParamsMatcher matcher(pattern);
  8088. Request request;
  8089. request.path = "/users/1";
  8090. ASSERT_FALSE(matcher.match(request));
  8091. }
  8092. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8093. const auto pattern = "/users/:id/subscriptions";
  8094. detail::PathParamsMatcher matcher(pattern);
  8095. Request request;
  8096. request.path = "/users/42/subscriptions";
  8097. ASSERT_TRUE(matcher.match(request));
  8098. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8099. EXPECT_EQ(request.path_params, expected_params);
  8100. }
  8101. TEST(PathParamsTest, SingleParamInTheEnd) {
  8102. const auto pattern = "/users/:id";
  8103. detail::PathParamsMatcher matcher(pattern);
  8104. Request request;
  8105. request.path = "/users/24";
  8106. ASSERT_TRUE(matcher.match(request));
  8107. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8108. EXPECT_EQ(request.path_params, expected_params);
  8109. }
  8110. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8111. const auto pattern = "/users/:id/";
  8112. detail::PathParamsMatcher matcher(pattern);
  8113. Request request;
  8114. request.path = "/users/42/";
  8115. ASSERT_TRUE(matcher.match(request));
  8116. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8117. EXPECT_EQ(request.path_params, expected_params);
  8118. }
  8119. TEST(PathParamsTest, EmptyParam) {
  8120. const auto pattern = "/users/:id/";
  8121. detail::PathParamsMatcher matcher(pattern);
  8122. Request request;
  8123. request.path = "/users//";
  8124. ASSERT_TRUE(matcher.match(request));
  8125. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8126. EXPECT_EQ(request.path_params, expected_params);
  8127. }
  8128. TEST(PathParamsTest, FragmentMismatch) {
  8129. const auto pattern = "/users/:id/";
  8130. detail::PathParamsMatcher matcher(pattern);
  8131. Request request;
  8132. request.path = "/admins/24/";
  8133. ASSERT_FALSE(matcher.match(request));
  8134. }
  8135. TEST(PathParamsTest, ExtraFragments) {
  8136. const auto pattern = "/users/:id";
  8137. detail::PathParamsMatcher matcher(pattern);
  8138. Request request;
  8139. request.path = "/users/42/subscriptions";
  8140. ASSERT_FALSE(matcher.match(request));
  8141. }
  8142. TEST(PathParamsTest, MissingTrailingParam) {
  8143. const auto pattern = "/users/:id";
  8144. detail::PathParamsMatcher matcher(pattern);
  8145. Request request;
  8146. request.path = "/users";
  8147. ASSERT_FALSE(matcher.match(request));
  8148. }
  8149. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8150. const auto pattern = "/users/:id/subscriptions";
  8151. detail::PathParamsMatcher matcher(pattern);
  8152. Request request;
  8153. request.path = "/users/subscriptions";
  8154. ASSERT_FALSE(matcher.match(request));
  8155. }
  8156. TEST(PathParamsTest, MultipleParams) {
  8157. const auto pattern = "/users/:userid/subscriptions/:subid";
  8158. detail::PathParamsMatcher matcher(pattern);
  8159. Request request;
  8160. request.path = "/users/42/subscriptions/2";
  8161. ASSERT_TRUE(matcher.match(request));
  8162. std::unordered_map<std::string, std::string> expected_params = {
  8163. {"userid", "42"}, {"subid", "2"}};
  8164. EXPECT_EQ(request.path_params, expected_params);
  8165. }
  8166. TEST(PathParamsTest, SequenceOfParams) {
  8167. const auto pattern = "/values/:x/:y/:z";
  8168. detail::PathParamsMatcher matcher(pattern);
  8169. Request request;
  8170. request.path = "/values/1/2/3";
  8171. ASSERT_TRUE(matcher.match(request));
  8172. std::unordered_map<std::string, std::string> expected_params = {
  8173. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8174. EXPECT_EQ(request.path_params, expected_params);
  8175. }
  8176. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8177. const auto pattern = "/prefix:suffix";
  8178. detail::PathParamsMatcher matcher(pattern);
  8179. Request request;
  8180. request.path = "/prefix:suffix";
  8181. ASSERT_TRUE(matcher.match(request));
  8182. const std::unordered_map<std::string, std::string> expected_params = {};
  8183. EXPECT_EQ(request.path_params, expected_params);
  8184. }
  8185. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8186. // If ipv6 regex working, regex match codepath is taken.
  8187. // else port will default to 80 in Client impl
  8188. int clientImplMagicPort = 80;
  8189. int port = 4321;
  8190. // above ports must be different to avoid false negative
  8191. EXPECT_NE(clientImplMagicPort, port);
  8192. std::string ipV6TestURL = "http://[ff06::c3]";
  8193. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8194. CLIENT_PRIVATE_KEY_FILE);
  8195. EXPECT_EQ(cli.port(), port);
  8196. }
  8197. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8198. auto file_path = "./www/dir/index.html";
  8199. auto dir_path = "./www/dir";
  8200. detail::FileStat stat_file(file_path);
  8201. EXPECT_TRUE(stat_file.is_file());
  8202. EXPECT_FALSE(stat_file.is_dir());
  8203. detail::FileStat stat_dir(dir_path);
  8204. EXPECT_FALSE(stat_dir.is_file());
  8205. EXPECT_TRUE(stat_dir.is_dir());
  8206. }
  8207. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8208. Server svr;
  8209. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8210. EXPECT_EQ(res.status, 400);
  8211. });
  8212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8213. auto se = detail::scope_exit([&] {
  8214. svr.stop();
  8215. thread.join();
  8216. ASSERT_FALSE(svr.is_running());
  8217. });
  8218. svr.wait_until_ready();
  8219. Client cli(HOST, PORT);
  8220. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8221. }
  8222. TEST(InvalidHeaderCharsTest, is_field_name) {
  8223. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8224. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8225. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8226. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8227. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8228. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8229. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8230. EXPECT_FALSE(detail::fields::is_field_name(""));
  8231. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8232. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8233. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8234. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8235. }
  8236. TEST(InvalidHeaderCharsTest, is_field_value) {
  8237. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8238. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8239. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8240. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8241. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8242. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8243. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8244. EXPECT_TRUE(detail::fields::is_field_value(""));
  8245. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8246. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8247. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8248. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8249. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8250. }
  8251. TEST(InvalidHeaderCharsTest, OnServer) {
  8252. Server svr;
  8253. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8254. std::string header = "Not Set";
  8255. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8256. res.set_header(header, "value");
  8257. res.set_content("Page Content Page Content", "text/plain");
  8258. });
  8259. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8260. std::string header = "Not Set";
  8261. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8262. res.set_header("X-Test", header);
  8263. res.set_content("Page Content Page Content", "text/plain");
  8264. });
  8265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8266. auto se = detail::scope_exit([&] {
  8267. svr.stop();
  8268. thread.join();
  8269. ASSERT_FALSE(svr.is_running());
  8270. });
  8271. svr.wait_until_ready();
  8272. Client cli(HOST, PORT);
  8273. {
  8274. auto res = cli.Get(
  8275. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8276. ASSERT_TRUE(res);
  8277. EXPECT_EQ("Page Content Page Content", res->body);
  8278. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8279. }
  8280. {
  8281. auto res = cli.Get(
  8282. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8283. ASSERT_TRUE(res);
  8284. EXPECT_EQ("Page Content Page Content", res->body);
  8285. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8286. }
  8287. }
  8288. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8289. auto handled = false;
  8290. Server svr;
  8291. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8292. thread t = thread([&] { svr.listen(HOST, PORT); });
  8293. auto se = detail::scope_exit([&] {
  8294. svr.stop();
  8295. t.join();
  8296. ASSERT_FALSE(svr.is_running());
  8297. ASSERT_FALSE(handled);
  8298. });
  8299. svr.wait_until_ready();
  8300. auto req = "POST /test HTTP/1.1\r\n"
  8301. "Content-Length: x\r\n"
  8302. "\r\n";
  8303. std::string response;
  8304. ASSERT_TRUE(send_request(1, req, &response));
  8305. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8306. response.substr(0, response.find("\r\n")));
  8307. }
  8308. #ifndef _WIN32
  8309. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8310. static constexpr char reject[] = "Unauthorized";
  8311. static constexpr char accept[] = "Upload accepted";
  8312. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8313. Server svr;
  8314. svr.set_expect_100_continue_handler(
  8315. [](const Request & /*req*/, Response &res) {
  8316. res.status = StatusCode::Unauthorized_401;
  8317. res.set_content(reject, "text/plain");
  8318. return res.status;
  8319. });
  8320. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8321. res.set_content(accept, "text/plain");
  8322. });
  8323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8324. auto se = detail::scope_exit([&] {
  8325. svr.stop();
  8326. thread.join();
  8327. ASSERT_FALSE(svr.is_running());
  8328. });
  8329. svr.wait_until_ready();
  8330. {
  8331. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8332. curl_easy_init(), &curl_easy_cleanup};
  8333. ASSERT_NE(curl, nullptr);
  8334. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8335. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8336. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8337. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8338. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8339. &curl_slist_free_all};
  8340. ASSERT_NE(list, nullptr);
  8341. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8342. struct read_data {
  8343. size_t read_size;
  8344. size_t total_size;
  8345. } data = {0, total_size};
  8346. using read_callback_t =
  8347. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8348. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8349. void *userdata) -> size_t {
  8350. read_data *data = (read_data *)userdata;
  8351. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8352. std::fill_n(ptr, size * nmemb, 'A');
  8353. data->read_size += size * nmemb;
  8354. return size * nmemb;
  8355. };
  8356. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8357. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8358. std::vector<char> buffer;
  8359. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8360. using write_callback_t =
  8361. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8362. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8363. void *userdata) -> size_t {
  8364. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8365. buffer->reserve(buffer->size() + size * nmemb + 1);
  8366. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8367. return size * nmemb;
  8368. };
  8369. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8370. {
  8371. const auto res = curl_easy_perform(curl.get());
  8372. ASSERT_EQ(res, CURLE_OK);
  8373. }
  8374. {
  8375. auto response_code = long{};
  8376. const auto res =
  8377. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8378. ASSERT_EQ(res, CURLE_OK);
  8379. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8380. }
  8381. {
  8382. auto dl = curl_off_t{};
  8383. const auto res =
  8384. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8385. ASSERT_EQ(res, CURLE_OK);
  8386. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8387. }
  8388. {
  8389. buffer.push_back('\0');
  8390. ASSERT_STRCASEEQ(buffer.data(), reject);
  8391. }
  8392. }
  8393. }
  8394. #endif
  8395. template <typename S, typename C>
  8396. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8397. svr.Get("/stream", [&](const Request &, Response &res) {
  8398. auto data = new std::string("01234567890123456789");
  8399. res.set_content_provider(
  8400. data->size(), "text/plain",
  8401. [&, data](size_t offset, size_t length, DataSink &sink) {
  8402. const size_t DATA_CHUNK_SIZE = 4;
  8403. const auto &d = *data;
  8404. std::this_thread::sleep_for(std::chrono::seconds(1));
  8405. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8406. return true;
  8407. },
  8408. [data](bool success) {
  8409. EXPECT_FALSE(success);
  8410. delete data;
  8411. });
  8412. });
  8413. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8414. auto i = new size_t(0);
  8415. res.set_content_provider(
  8416. "text/plain",
  8417. [i](size_t, DataSink &sink) {
  8418. if (*i < 5) {
  8419. std::this_thread::sleep_for(std::chrono::seconds(1));
  8420. sink.write("abcd", 4);
  8421. (*i)++;
  8422. } else {
  8423. sink.done();
  8424. }
  8425. return true;
  8426. },
  8427. [i](bool success) {
  8428. EXPECT_FALSE(success);
  8429. delete i;
  8430. });
  8431. });
  8432. svr.Get("/chunked", [&](const Request &, Response &res) {
  8433. auto i = new size_t(0);
  8434. res.set_chunked_content_provider(
  8435. "text/plain",
  8436. [i](size_t, DataSink &sink) {
  8437. if (*i < 5) {
  8438. std::this_thread::sleep_for(std::chrono::seconds(1));
  8439. sink.os << "abcd";
  8440. (*i)++;
  8441. } else {
  8442. sink.done();
  8443. }
  8444. return true;
  8445. },
  8446. [i](bool success) {
  8447. EXPECT_FALSE(success);
  8448. delete i;
  8449. });
  8450. });
  8451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8452. auto se = detail::scope_exit([&] {
  8453. svr.stop();
  8454. listen_thread.join();
  8455. ASSERT_FALSE(svr.is_running());
  8456. });
  8457. svr.wait_until_ready();
  8458. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8459. {
  8460. auto start = std::chrono::steady_clock::now();
  8461. auto res = cli.Get("/stream");
  8462. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8463. std::chrono::steady_clock::now() - start)
  8464. .count();
  8465. ASSERT_FALSE(res);
  8466. EXPECT_EQ(Error::Read, res.error());
  8467. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8468. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8469. }
  8470. {
  8471. auto start = std::chrono::steady_clock::now();
  8472. auto res = cli.Get("/stream_without_length");
  8473. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8474. std::chrono::steady_clock::now() - start)
  8475. .count();
  8476. ASSERT_FALSE(res);
  8477. EXPECT_EQ(Error::Read, res.error());
  8478. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8479. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8480. }
  8481. {
  8482. auto start = std::chrono::steady_clock::now();
  8483. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8484. EXPECT_EQ("abcd", string(data, data_length));
  8485. return true;
  8486. });
  8487. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8488. std::chrono::steady_clock::now() - start)
  8489. .count();
  8490. ASSERT_FALSE(res);
  8491. EXPECT_EQ(Error::Read, res.error());
  8492. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8493. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8494. }
  8495. }
  8496. TEST(MaxTimeoutTest, ContentStream) {
  8497. time_t timeout = 2000;
  8498. time_t threshold = 200;
  8499. Server svr;
  8500. Client cli("localhost", PORT);
  8501. max_timeout_test(svr, cli, timeout, threshold);
  8502. }
  8503. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8504. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8505. time_t timeout = 2000;
  8506. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8508. SSLClient cli("localhost", PORT);
  8509. cli.enable_server_certificate_verification(false);
  8510. max_timeout_test(svr, cli, timeout, threshold);
  8511. }
  8512. #endif
  8513. class EventDispatcher {
  8514. public:
  8515. EventDispatcher() {}
  8516. void wait_event(DataSink *sink) {
  8517. unique_lock<mutex> lk(m_);
  8518. int id = id_;
  8519. cv_.wait(lk, [&] { return cid_ == id; });
  8520. sink->write(message_.data(), message_.size());
  8521. }
  8522. void send_event(const string &message) {
  8523. lock_guard<mutex> lk(m_);
  8524. cid_ = id_++;
  8525. message_ = message;
  8526. cv_.notify_all();
  8527. }
  8528. private:
  8529. mutex m_;
  8530. condition_variable cv_;
  8531. atomic_int id_{0};
  8532. atomic_int cid_{-1};
  8533. string message_;
  8534. };
  8535. TEST(ClientInThreadTest, Issue2068) {
  8536. EventDispatcher ed;
  8537. Server svr;
  8538. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8539. res.set_chunked_content_provider("text/event-stream",
  8540. [&](size_t /*offset*/, DataSink &sink) {
  8541. ed.wait_event(&sink);
  8542. return true;
  8543. });
  8544. });
  8545. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8546. svr.wait_until_ready();
  8547. thread event_thread([&] {
  8548. int id = 0;
  8549. while (svr.is_running()) {
  8550. this_thread::sleep_for(chrono::milliseconds(500));
  8551. std::stringstream ss;
  8552. ss << "data: " << id << "\n\n";
  8553. ed.send_event(ss.str());
  8554. id++;
  8555. }
  8556. });
  8557. auto se = detail::scope_exit([&] {
  8558. svr.stop();
  8559. listen_thread.join();
  8560. event_thread.join();
  8561. ASSERT_FALSE(svr.is_running());
  8562. });
  8563. {
  8564. auto client = detail::make_unique<Client>(HOST, PORT);
  8565. client->set_read_timeout(std::chrono::minutes(10));
  8566. std::atomic<bool> stop{false};
  8567. std::thread t([&] {
  8568. client->Get("/event1",
  8569. [&](const char *, size_t) -> bool { return !stop; });
  8570. });
  8571. std::this_thread::sleep_for(std::chrono::seconds(2));
  8572. stop = true;
  8573. client->stop();
  8574. client.reset();
  8575. t.join();
  8576. }
  8577. }