test.cc 197 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid multipart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  136. string content_type = "multipart/form-data; boundary=something";
  137. string boundary;
  138. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  139. EXPECT_TRUE(ret);
  140. EXPECT_EQ(boundary, "something");
  141. }
  142. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  143. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  144. string boundary;
  145. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  148. }
  149. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  150. string content_type =
  151. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  152. string boundary;
  153. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  154. EXPECT_TRUE(ret);
  155. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  156. }
  157. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  158. string content_type =
  159. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  160. string boundary;
  161. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  162. EXPECT_TRUE(ret);
  163. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  164. }
  165. TEST(GetHeaderValueTest, DefaultValue) {
  166. Headers headers = {{"Dummy", "Dummy"}};
  167. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  168. EXPECT_STREQ("text/plain", val);
  169. }
  170. TEST(GetHeaderValueTest, DefaultValueInt) {
  171. Headers headers = {{"Dummy", "Dummy"}};
  172. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 100);
  173. EXPECT_EQ(100ull, val);
  174. }
  175. TEST(GetHeaderValueTest, RegularValue) {
  176. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  177. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  178. EXPECT_STREQ("text/html", val);
  179. }
  180. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  181. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  182. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  183. EXPECT_STREQ("text/html", val);
  184. }
  185. TEST(GetHeaderValueTest, SetContent) {
  186. Response res;
  187. res.set_content("html", "text/html");
  188. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  189. res.set_content("text", "text/plain");
  190. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  191. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  192. }
  193. TEST(GetHeaderValueTest, RegularValueInt) {
  194. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  195. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  196. EXPECT_EQ(100ull, val);
  197. }
  198. TEST(GetHeaderValueTest, Range) {
  199. {
  200. Headers headers = {make_range_header({{1, -1}})};
  201. auto val = detail::get_header_value(headers, "Range", 0, 0);
  202. EXPECT_STREQ("bytes=1-", val);
  203. }
  204. {
  205. Headers headers = {make_range_header({{-1, 1}})};
  206. auto val = detail::get_header_value(headers, "Range", 0, 0);
  207. EXPECT_STREQ("bytes=-1", val);
  208. }
  209. {
  210. Headers headers = {make_range_header({{1, 10}})};
  211. auto val = detail::get_header_value(headers, "Range", 0, 0);
  212. EXPECT_STREQ("bytes=1-10", val);
  213. }
  214. {
  215. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  216. auto val = detail::get_header_value(headers, "Range", 0, 0);
  217. EXPECT_STREQ("bytes=1-10, 100-", val);
  218. }
  219. {
  220. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  221. auto val = detail::get_header_value(headers, "Range", 0, 0);
  222. EXPECT_STREQ("bytes=1-10, 100-200", val);
  223. }
  224. {
  225. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  226. auto val = detail::get_header_value(headers, "Range", 0, 0);
  227. EXPECT_STREQ("bytes=0-0, -1", val);
  228. }
  229. }
  230. TEST(ParseHeaderValueTest, Range) {
  231. {
  232. Ranges ranges;
  233. auto ret = detail::parse_range_header("bytes=1-", ranges);
  234. EXPECT_TRUE(ret);
  235. EXPECT_EQ(1u, ranges.size());
  236. EXPECT_EQ(1u, ranges[0].first);
  237. EXPECT_EQ(-1, ranges[0].second);
  238. }
  239. {
  240. Ranges ranges;
  241. auto ret = detail::parse_range_header("bytes=-1", ranges);
  242. EXPECT_TRUE(ret);
  243. EXPECT_EQ(1u, ranges.size());
  244. EXPECT_EQ(-1, ranges[0].first);
  245. EXPECT_EQ(1u, ranges[0].second);
  246. }
  247. {
  248. Ranges ranges;
  249. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  250. EXPECT_TRUE(ret);
  251. EXPECT_EQ(1u, ranges.size());
  252. EXPECT_EQ(1u, ranges[0].first);
  253. EXPECT_EQ(10u, ranges[0].second);
  254. }
  255. {
  256. Ranges ranges;
  257. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  258. EXPECT_FALSE(ret);
  259. }
  260. {
  261. Ranges ranges;
  262. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  263. EXPECT_TRUE(ret);
  264. EXPECT_EQ(2u, ranges.size());
  265. EXPECT_EQ(1u, ranges[0].first);
  266. EXPECT_EQ(10u, ranges[0].second);
  267. EXPECT_EQ(100u, ranges[1].first);
  268. EXPECT_EQ(-1, ranges[1].second);
  269. }
  270. {
  271. Ranges ranges;
  272. auto ret =
  273. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  274. EXPECT_TRUE(ret);
  275. EXPECT_EQ(3u, ranges.size());
  276. EXPECT_EQ(1u, ranges[0].first);
  277. EXPECT_EQ(10u, ranges[0].second);
  278. EXPECT_EQ(100u, ranges[1].first);
  279. EXPECT_EQ(200u, ranges[1].second);
  280. EXPECT_EQ(300u, ranges[2].first);
  281. EXPECT_EQ(400u, ranges[2].second);
  282. }
  283. }
  284. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  285. Request req;
  286. req.set_header("Accept-Encoding", "gzip");
  287. Response res;
  288. res.set_header("Content-Type", "text/plain");
  289. auto ret = detail::encoding_type(req, res);
  290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  291. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  292. #else
  293. EXPECT_TRUE(ret == detail::EncodingType::None);
  294. #endif
  295. }
  296. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  297. Request req;
  298. req.set_header("Accept-Encoding", "gzip, deflate, br");
  299. Response res;
  300. res.set_header("Content-Type", "text/plain");
  301. auto ret = detail::encoding_type(req, res);
  302. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  303. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  304. #elif CPPHTTPLIB_ZLIB_SUPPORT
  305. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  306. #else
  307. EXPECT_TRUE(ret == detail::EncodingType::None);
  308. #endif
  309. }
  310. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  311. Request req;
  312. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  313. Response res;
  314. res.set_header("Content-Type", "text/plain");
  315. auto ret = detail::encoding_type(req, res);
  316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  317. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  318. #elif CPPHTTPLIB_ZLIB_SUPPORT
  319. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  320. #else
  321. EXPECT_TRUE(ret == detail::EncodingType::None);
  322. #endif
  323. }
  324. TEST(BufferStreamTest, read) {
  325. detail::BufferStream strm1;
  326. Stream &strm = strm1;
  327. EXPECT_EQ(5, strm.write("hello"));
  328. char buf[512];
  329. EXPECT_EQ(2, strm.read(buf, 2));
  330. EXPECT_EQ('h', buf[0]);
  331. EXPECT_EQ('e', buf[1]);
  332. EXPECT_EQ(2, strm.read(buf, 2));
  333. EXPECT_EQ('l', buf[0]);
  334. EXPECT_EQ('l', buf[1]);
  335. EXPECT_EQ(1, strm.read(buf, 1));
  336. EXPECT_EQ('o', buf[0]);
  337. EXPECT_EQ(0, strm.read(buf, 1));
  338. }
  339. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  340. auto host = "www.httpwatch.com";
  341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  342. auto port = 443;
  343. SSLClient cli(host, port);
  344. #else
  345. auto port = 80;
  346. Client cli(host, port);
  347. #endif
  348. cli.set_connection_timeout(2);
  349. auto res =
  350. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  351. ASSERT_TRUE(res);
  352. std::string out;
  353. detail::read_file("./image.jpg", out);
  354. EXPECT_EQ(200, res->status);
  355. EXPECT_EQ(out, res->body);
  356. }
  357. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  358. auto host = "www.httpwatch.com";
  359. auto ip = hosted_at(host);
  360. EXPECT_EQ("191.236.16.12", ip);
  361. std::vector<std::string> addrs;
  362. hosted_at(host, addrs);
  363. EXPECT_EQ(1u, addrs.size());
  364. }
  365. #if 0 // It depends on each test environment...
  366. TEST(HostnameToIPConversionTest, YouTube_Online) {
  367. auto host = "www.youtube.com";
  368. std::vector<std::string> addrs;
  369. hosted_at(host, addrs);
  370. EXPECT_EQ(20u, addrs.size());
  371. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  372. EXPECT_TRUE(it != addrs.end());
  373. }
  374. #endif
  375. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  376. auto host = "www.httpwatch.com";
  377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  378. auto port = 443;
  379. SSLClient cli(host, port);
  380. #else
  381. auto port = 80;
  382. Client cli(host, port);
  383. #endif
  384. cli.set_connection_timeout(2);
  385. std::string body;
  386. auto res =
  387. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  388. [&](const char *data, size_t data_length) {
  389. body.append(data, data_length);
  390. return true;
  391. });
  392. ASSERT_TRUE(res);
  393. std::string out;
  394. detail::read_file("./image.jpg", out);
  395. EXPECT_EQ(200, res->status);
  396. EXPECT_EQ(out, body);
  397. }
  398. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  399. auto host = "www.httpwatch.com";
  400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  401. auto port = 443;
  402. SSLClient cli(host, port);
  403. #else
  404. auto port = 80;
  405. Client cli(host, port);
  406. #endif
  407. cli.set_connection_timeout(2);
  408. std::string body;
  409. auto res = cli.Get(
  410. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  411. [&](const Response &response) {
  412. EXPECT_EQ(200, response.status);
  413. return true;
  414. },
  415. [&](const char *data, size_t data_length) {
  416. body.append(data, data_length);
  417. return true;
  418. });
  419. ASSERT_TRUE(res);
  420. std::string out;
  421. detail::read_file("./image.jpg", out);
  422. EXPECT_EQ(200, res->status);
  423. EXPECT_EQ(out, body);
  424. }
  425. TEST(RangeTest, FromHTTPBin_Online) {
  426. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  427. auto host = "httpbin.org";
  428. auto path = std::string{"/range/32"};
  429. #else
  430. auto host = "nghttp2.org";
  431. auto path = std::string{"/httpbin/range/32"};
  432. #endif
  433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  434. auto port = 443;
  435. SSLClient cli(host, port);
  436. #else
  437. auto port = 80;
  438. Client cli(host, port);
  439. #endif
  440. cli.set_connection_timeout(5);
  441. {
  442. auto res = cli.Get(path);
  443. ASSERT_TRUE(res);
  444. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  445. EXPECT_EQ(200, res->status);
  446. }
  447. {
  448. Headers headers = {make_range_header({{1, -1}})};
  449. auto res = cli.Get(path, headers);
  450. ASSERT_TRUE(res);
  451. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  452. EXPECT_EQ(206, res->status);
  453. }
  454. {
  455. Headers headers = {make_range_header({{1, 10}})};
  456. auto res = cli.Get(path, headers);
  457. ASSERT_TRUE(res);
  458. EXPECT_EQ("bcdefghijk", res->body);
  459. EXPECT_EQ(206, res->status);
  460. }
  461. {
  462. Headers headers = {make_range_header({{0, 31}})};
  463. auto res = cli.Get(path, headers);
  464. ASSERT_TRUE(res);
  465. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  466. EXPECT_EQ(200, res->status);
  467. }
  468. {
  469. Headers headers = {make_range_header({{0, -1}})};
  470. auto res = cli.Get(path, headers);
  471. ASSERT_TRUE(res);
  472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  473. EXPECT_EQ(200, res->status);
  474. }
  475. {
  476. Headers headers = {make_range_header({{0, 32}})};
  477. auto res = cli.Get(path, headers);
  478. ASSERT_TRUE(res);
  479. EXPECT_EQ(416, res->status);
  480. }
  481. }
  482. TEST(ConnectionErrorTest, InvalidHost) {
  483. auto host = "-abcde.com";
  484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  485. auto port = 443;
  486. SSLClient cli(host, port);
  487. #else
  488. auto port = 80;
  489. Client cli(host, port);
  490. #endif
  491. cli.set_connection_timeout(std::chrono::seconds(2));
  492. auto res = cli.Get("/");
  493. ASSERT_TRUE(!res);
  494. EXPECT_EQ(Error::Connection, res.error());
  495. }
  496. TEST(ConnectionErrorTest, InvalidHost2) {
  497. auto host = "httpbin.org/";
  498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  499. SSLClient cli(host);
  500. #else
  501. Client cli(host);
  502. #endif
  503. cli.set_connection_timeout(std::chrono::seconds(2));
  504. auto res = cli.Get("/");
  505. ASSERT_TRUE(!res);
  506. EXPECT_EQ(Error::Connection, res.error());
  507. }
  508. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  509. auto host = "httpbin.org/";
  510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  511. SSLClient cli(host);
  512. #else
  513. Client cli(host);
  514. #endif
  515. cli.set_connection_timeout(std::chrono::seconds(2));
  516. auto res = cli.Get("/");
  517. ASSERT_TRUE(!res);
  518. stringstream s;
  519. s << "error code: " << res.error();
  520. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  521. }
  522. TEST(ConnectionErrorTest, InvalidPort) {
  523. auto host = "localhost";
  524. auto port = 44380;
  525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  526. SSLClient cli(host, port);
  527. #else
  528. Client cli(host, port);
  529. #endif
  530. cli.set_connection_timeout(std::chrono::seconds(2));
  531. auto res = cli.Get("/");
  532. ASSERT_TRUE(!res);
  533. EXPECT_TRUE(Error::Connection == res.error() ||
  534. Error::ConnectionTimeout == res.error());
  535. }
  536. TEST(ConnectionErrorTest, Timeout_Online) {
  537. auto host = "google.com";
  538. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  539. auto port = 44380;
  540. SSLClient cli(host, port);
  541. #else
  542. auto port = 8080;
  543. Client cli(host, port);
  544. #endif
  545. cli.set_connection_timeout(std::chrono::seconds(2));
  546. // only probe one address type so that the error reason
  547. // correlates to the timed-out IPv4, not the unsupported
  548. // IPv6 connection attempt
  549. cli.set_address_family(AF_INET);
  550. auto res = cli.Get("/");
  551. ASSERT_TRUE(!res);
  552. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  553. }
  554. TEST(CancelTest, NoCancel_Online) {
  555. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  556. auto host = "httpbin.org";
  557. auto path = std::string{"/range/32"};
  558. #else
  559. auto host = "nghttp2.org";
  560. auto path = std::string{"/httpbin/range/32"};
  561. #endif
  562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  563. auto port = 443;
  564. SSLClient cli(host, port);
  565. #else
  566. auto port = 80;
  567. Client cli(host, port);
  568. #endif
  569. cli.set_connection_timeout(std::chrono::seconds(5));
  570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  571. ASSERT_TRUE(res);
  572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  573. EXPECT_EQ(200, res->status);
  574. }
  575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  576. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  577. auto host = "httpbin.org";
  578. auto path = std::string{"/range/32"};
  579. #else
  580. auto host = "nghttp2.org";
  581. auto path = std::string{"/httpbin/range/32"};
  582. #endif
  583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  584. auto port = 443;
  585. SSLClient cli(host, port);
  586. #else
  587. auto port = 80;
  588. Client cli(host, port);
  589. #endif
  590. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  591. cli.set_connection_timeout(std::chrono::seconds(5));
  592. ASSERT_TRUE(!res);
  593. EXPECT_EQ(Error::Canceled, res.error());
  594. }
  595. TEST(CancelTest, WithCancelLargePayload_Online) {
  596. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  597. auto host = "httpbin.org";
  598. auto path = std::string{"/range/65536"};
  599. #else
  600. auto host = "nghttp2.org";
  601. auto path = std::string{"/httpbin/range/65536"};
  602. #endif
  603. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  604. auto port = 443;
  605. SSLClient cli(host, port);
  606. #else
  607. auto port = 80;
  608. Client cli(host, port);
  609. #endif
  610. cli.set_connection_timeout(std::chrono::seconds(5));
  611. uint32_t count = 0;
  612. auto res =
  613. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  614. ASSERT_TRUE(!res);
  615. EXPECT_EQ(Error::Canceled, res.error());
  616. }
  617. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  618. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  619. auto host = "httpbin.org";
  620. auto path = std::string{"/basic-auth/hello/world"};
  621. #else
  622. auto host = "nghttp2.org";
  623. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  624. #endif
  625. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  626. auto port = 443;
  627. SSLClient cli(host, port);
  628. #else
  629. auto port = 80;
  630. Client cli(host, port);
  631. #endif
  632. {
  633. auto res = cli.Get(path);
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(401, res->status);
  636. }
  637. {
  638. auto res =
  639. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  640. ASSERT_TRUE(res);
  641. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  642. res->body);
  643. EXPECT_EQ(200, res->status);
  644. }
  645. {
  646. cli.set_basic_auth("hello", "world");
  647. auto res = cli.Get(path);
  648. ASSERT_TRUE(res);
  649. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  650. res->body);
  651. EXPECT_EQ(200, res->status);
  652. }
  653. {
  654. cli.set_basic_auth("hello", "bad");
  655. auto res = cli.Get(path);
  656. ASSERT_TRUE(res);
  657. EXPECT_EQ(401, res->status);
  658. }
  659. {
  660. cli.set_basic_auth("bad", "world");
  661. auto res = cli.Get(path);
  662. ASSERT_TRUE(res);
  663. EXPECT_EQ(401, res->status);
  664. }
  665. }
  666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  667. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  669. auto host = "httpbin.org";
  670. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  671. auto paths = std::vector<std::string>{
  672. "/digest-auth/auth/hello/world/MD5",
  673. "/digest-auth/auth/hello/world/SHA-256",
  674. "/digest-auth/auth/hello/world/SHA-512",
  675. "/digest-auth/auth-int/hello/world/MD5",
  676. };
  677. #else
  678. auto host = "nghttp2.org";
  679. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  680. auto paths = std::vector<std::string>{
  681. "/httpbin/digest-auth/auth/hello/world/MD5",
  682. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  683. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  684. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  685. };
  686. #endif
  687. auto port = 443;
  688. SSLClient cli(host, port);
  689. {
  690. auto res = cli.Get(unauth_path);
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(401, res->status);
  693. }
  694. {
  695. cli.set_digest_auth("hello", "world");
  696. for (const auto &path : paths) {
  697. auto res = cli.Get(path.c_str());
  698. ASSERT_TRUE(res);
  699. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  700. res->body);
  701. EXPECT_EQ(200, res->status);
  702. }
  703. cli.set_digest_auth("hello", "bad");
  704. for (const auto &path : paths) {
  705. auto res = cli.Get(path.c_str());
  706. ASSERT_TRUE(res);
  707. EXPECT_EQ(401, res->status);
  708. }
  709. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  710. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  711. // cli.set_digest_auth("bad", "world");
  712. // for (const auto& path : paths) {
  713. // auto res = cli.Get(path.c_str());
  714. // ASSERT_TRUE(res);
  715. // EXPECT_EQ(400, res->status);
  716. // }
  717. }
  718. }
  719. #endif
  720. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  721. auto host = "google.com";
  722. auto another_host = "example.com";
  723. auto wrong_ip = "0.0.0.0";
  724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  725. SSLClient cli(host);
  726. #else
  727. Client cli(host);
  728. #endif
  729. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  730. auto res = cli.Get("/");
  731. ASSERT_TRUE(res);
  732. ASSERT_EQ(301, res->status);
  733. }
  734. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  735. auto host = "google.com";
  736. auto wrong_ip = "0.0.0.0";
  737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  738. SSLClient cli(host);
  739. #else
  740. Client cli(host);
  741. #endif
  742. cli.set_hostname_addr_map({{host, wrong_ip}});
  743. auto res = cli.Get("/");
  744. ASSERT_TRUE(!res);
  745. EXPECT_EQ(Error::Connection, res.error());
  746. }
  747. TEST(AbsoluteRedirectTest, Redirect_Online) {
  748. auto host = "nghttp2.org";
  749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  750. SSLClient cli(host);
  751. #else
  752. Client cli(host);
  753. #endif
  754. cli.set_follow_location(true);
  755. auto res = cli.Get("/httpbin/absolute-redirect/3");
  756. ASSERT_TRUE(res);
  757. EXPECT_EQ(200, res->status);
  758. }
  759. TEST(RedirectTest, Redirect_Online) {
  760. auto host = "nghttp2.org";
  761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  762. SSLClient cli(host);
  763. #else
  764. Client cli(host);
  765. #endif
  766. cli.set_follow_location(true);
  767. auto res = cli.Get("/httpbin/redirect/3");
  768. ASSERT_TRUE(res);
  769. EXPECT_EQ(200, res->status);
  770. }
  771. TEST(RelativeRedirectTest, Redirect_Online) {
  772. auto host = "nghttp2.org";
  773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  774. SSLClient cli(host);
  775. #else
  776. Client cli(host);
  777. #endif
  778. cli.set_follow_location(true);
  779. auto res = cli.Get("/httpbin/relative-redirect/3");
  780. ASSERT_TRUE(res);
  781. EXPECT_EQ(200, res->status);
  782. }
  783. TEST(TooManyRedirectTest, Redirect_Online) {
  784. auto host = "nghttp2.org";
  785. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  786. SSLClient cli(host);
  787. #else
  788. Client cli(host);
  789. #endif
  790. cli.set_follow_location(true);
  791. auto res = cli.Get("/httpbin/redirect/21");
  792. ASSERT_TRUE(!res);
  793. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  794. }
  795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  796. TEST(YahooRedirectTest, Redirect_Online) {
  797. Client cli("yahoo.com");
  798. auto res = cli.Get("/");
  799. ASSERT_TRUE(res);
  800. EXPECT_EQ(301, res->status);
  801. cli.set_follow_location(true);
  802. res = cli.Get("/");
  803. ASSERT_TRUE(res);
  804. EXPECT_EQ(200, res->status);
  805. EXPECT_EQ("https://www.yahoo.com/", res->location);
  806. }
  807. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  808. SSLClient cli("nghttp2.org");
  809. cli.set_follow_location(true);
  810. auto res = cli.Get(
  811. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  812. ASSERT_TRUE(res);
  813. EXPECT_EQ(200, res->status);
  814. }
  815. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  816. SSLClient cli("nghttp2.org");
  817. cli.set_follow_location(true);
  818. Params params;
  819. params.emplace("url", "http://www.google.com");
  820. params.emplace("status_code", "302");
  821. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  822. ASSERT_TRUE(res);
  823. EXPECT_EQ(200, res->status);
  824. }
  825. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  826. SSLClient cli("nghttp2.org");
  827. cli.set_follow_location(true);
  828. Params params;
  829. params.emplace("url", "http://www.google.com");
  830. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  831. ASSERT_TRUE(res);
  832. EXPECT_EQ(200, res->status);
  833. }
  834. TEST(UrlWithSpace, Redirect_Online) {
  835. SSLClient cli("edge.forgecdn.net");
  836. cli.set_follow_location(true);
  837. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  838. ASSERT_TRUE(res);
  839. EXPECT_EQ(200, res->status);
  840. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  841. }
  842. #endif
  843. #if !defined(_WIN32) && !defined(_WIN64)
  844. TEST(ReceiveSignals, Signal) {
  845. auto setupSignalHandlers = []() {
  846. struct sigaction act;
  847. sigemptyset(&act.sa_mask);
  848. act.sa_flags = SA_SIGINFO;
  849. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  850. switch (sig) {
  851. case SIGINT:
  852. default: break;
  853. }
  854. };
  855. ::sigaction(SIGINT, &act, nullptr);
  856. };
  857. Server svr;
  858. int port = 0;
  859. auto thread = std::thread([&]() {
  860. setupSignalHandlers();
  861. port = svr.bind_to_any_port("localhost");
  862. svr.listen_after_bind();
  863. });
  864. auto se = detail::scope_exit([&] {
  865. svr.stop();
  866. thread.join();
  867. ASSERT_FALSE(svr.is_running());
  868. });
  869. svr.wait_until_ready();
  870. ASSERT_TRUE(svr.is_running());
  871. pthread_kill(thread.native_handle(), SIGINT);
  872. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  873. ASSERT_TRUE(svr.is_running());
  874. }
  875. #endif
  876. TEST(RedirectToDifferentPort, Redirect) {
  877. Server svr1;
  878. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  879. res.set_content("Hello World!", "text/plain");
  880. });
  881. int svr1_port = 0;
  882. auto thread1 = std::thread([&]() {
  883. svr1_port = svr1.bind_to_any_port("localhost");
  884. svr1.listen_after_bind();
  885. });
  886. Server svr2;
  887. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  888. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  889. });
  890. int svr2_port = 0;
  891. auto thread2 = std::thread([&]() {
  892. svr2_port = svr2.bind_to_any_port("localhost");
  893. svr2.listen_after_bind();
  894. });
  895. auto se = detail::scope_exit([&] {
  896. svr2.stop();
  897. thread2.join();
  898. svr1.stop();
  899. thread1.join();
  900. ASSERT_FALSE(svr2.is_running());
  901. ASSERT_FALSE(svr1.is_running());
  902. });
  903. while (!svr1.is_running() || !svr2.is_running()) {
  904. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  905. }
  906. // Give GET time to get a few messages.
  907. std::this_thread::sleep_for(std::chrono::seconds(1));
  908. Client cli("localhost", svr2_port);
  909. cli.set_follow_location(true);
  910. auto res = cli.Get("/2");
  911. ASSERT_TRUE(res);
  912. EXPECT_EQ(200, res->status);
  913. EXPECT_EQ("Hello World!", res->body);
  914. }
  915. TEST(RedirectFromPageWithContent, Redirect) {
  916. Server svr;
  917. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  918. res.set_content("___", "text/plain");
  919. res.set_redirect("/2");
  920. });
  921. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  922. res.set_content("Hello World!", "text/plain");
  923. });
  924. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  925. auto se = detail::scope_exit([&] {
  926. svr.stop();
  927. th.join();
  928. ASSERT_FALSE(svr.is_running());
  929. });
  930. svr.wait_until_ready();
  931. // Give GET time to get a few messages.
  932. std::this_thread::sleep_for(std::chrono::seconds(1));
  933. {
  934. Client cli("localhost", PORT);
  935. cli.set_follow_location(true);
  936. std::string body;
  937. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  938. body.append(data, data_length);
  939. return true;
  940. });
  941. ASSERT_TRUE(res);
  942. EXPECT_EQ(200, res->status);
  943. EXPECT_EQ("Hello World!", body);
  944. }
  945. {
  946. Client cli("localhost", PORT);
  947. std::string body;
  948. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  949. body.append(data, data_length);
  950. return true;
  951. });
  952. ASSERT_TRUE(res);
  953. EXPECT_EQ(302, res->status);
  954. EXPECT_EQ("___", body);
  955. }
  956. }
  957. TEST(RedirectFromPageWithContentIP6, Redirect) {
  958. Server svr;
  959. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  960. res.set_content("___", "text/plain");
  961. // res.set_redirect("/2");
  962. res.set_redirect("http://[::1]:1234/2");
  963. });
  964. svr.Get("/2", [&](const Request &req, Response &res) {
  965. auto host_header = req.headers.find("Host");
  966. ASSERT_TRUE(host_header != req.headers.end());
  967. EXPECT_EQ("[::1]:1234", host_header->second);
  968. res.set_content("Hello World!", "text/plain");
  969. });
  970. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  971. auto se = detail::scope_exit([&] {
  972. svr.stop();
  973. th.join();
  974. ASSERT_FALSE(svr.is_running());
  975. });
  976. // When IPV6 support isn't available svr.listen("::1", 1234) never
  977. // actually starts anything, so the condition !svr.is_running() will
  978. // always remain true, and the loop never stops.
  979. // This basically counts how many milliseconds have passed since the
  980. // call to svr.listen(), and if after 5 seconds nothing started yet
  981. // aborts the test.
  982. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  983. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  984. ASSERT_LT(milliseconds, 5000U);
  985. }
  986. // Give GET time to get a few messages.
  987. std::this_thread::sleep_for(std::chrono::seconds(1));
  988. {
  989. Client cli("http://[::1]:1234");
  990. cli.set_follow_location(true);
  991. std::string body;
  992. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  993. body.append(data, data_length);
  994. return true;
  995. });
  996. ASSERT_TRUE(res);
  997. EXPECT_EQ(200, res->status);
  998. EXPECT_EQ("Hello World!", body);
  999. }
  1000. {
  1001. Client cli("http://[::1]:1234");
  1002. std::string body;
  1003. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1004. body.append(data, data_length);
  1005. return true;
  1006. });
  1007. ASSERT_TRUE(res);
  1008. EXPECT_EQ(302, res->status);
  1009. EXPECT_EQ("___", body);
  1010. }
  1011. }
  1012. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1013. Server svr;
  1014. svr.Get("/foo", [](const Request &req, Response &res) {
  1015. auto a = req.params.find("a");
  1016. if (a != req.params.end()) {
  1017. res.set_content((*a).second, "text/plain");
  1018. res.status = 200;
  1019. } else {
  1020. res.status = 400;
  1021. }
  1022. });
  1023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1024. auto se = detail::scope_exit([&] {
  1025. svr.stop();
  1026. thread.join();
  1027. ASSERT_FALSE(svr.is_running());
  1028. });
  1029. // Give GET time to get a few messages.
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. {
  1032. Client cli(HOST, PORT);
  1033. cli.set_url_encode(false);
  1034. auto res = cli.Get("/foo?a=explicitly+encoded");
  1035. ASSERT_TRUE(res);
  1036. EXPECT_EQ(200, res->status);
  1037. // This expects it back with a space, as the `+` won't have been
  1038. // url-encoded, and server-side the params get decoded turning `+`
  1039. // into spaces.
  1040. EXPECT_EQ("explicitly encoded", res->body);
  1041. }
  1042. }
  1043. TEST(BindServerTest, DISABLED_BindDualStack) {
  1044. Server svr;
  1045. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1046. res.set_content("Hello World!", "text/plain");
  1047. });
  1048. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1049. auto se = detail::scope_exit([&] {
  1050. svr.stop();
  1051. thread.join();
  1052. ASSERT_FALSE(svr.is_running());
  1053. });
  1054. // Give GET time to get a few messages.
  1055. std::this_thread::sleep_for(std::chrono::seconds(1));
  1056. {
  1057. Client cli("127.0.0.1", PORT);
  1058. auto res = cli.Get("/1");
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ(200, res->status);
  1061. EXPECT_EQ("Hello World!", res->body);
  1062. }
  1063. {
  1064. Client cli("::1", PORT);
  1065. auto res = cli.Get("/1");
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ(200, res->status);
  1068. EXPECT_EQ("Hello World!", res->body);
  1069. }
  1070. }
  1071. TEST(BindServerTest, BindAndListenSeparately) {
  1072. Server svr;
  1073. int port = svr.bind_to_any_port("0.0.0.0");
  1074. ASSERT_TRUE(svr.is_valid());
  1075. ASSERT_TRUE(port > 0);
  1076. svr.stop();
  1077. }
  1078. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1079. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1081. CLIENT_CA_CERT_DIR);
  1082. int port = svr.bind_to_any_port("0.0.0.0");
  1083. ASSERT_TRUE(svr.is_valid());
  1084. ASSERT_TRUE(port > 0);
  1085. svr.stop();
  1086. }
  1087. #endif
  1088. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1089. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1090. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1091. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1092. int port = svr.bind_to_any_port("0.0.0.0");
  1093. ASSERT_TRUE(svr.is_valid());
  1094. ASSERT_TRUE(port > 0);
  1095. svr.stop();
  1096. }
  1097. #endif
  1098. TEST(ErrorHandlerTest, ContentLength) {
  1099. Server svr;
  1100. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1101. res.status = 200;
  1102. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1103. "text/html"); // <= Content-Length still 13
  1104. });
  1105. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1106. res.set_content("Hello World!\n", "text/plain");
  1107. res.status = 524;
  1108. });
  1109. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1110. auto se = detail::scope_exit([&] {
  1111. svr.stop();
  1112. thread.join();
  1113. ASSERT_FALSE(svr.is_running());
  1114. });
  1115. // Give GET time to get a few messages.
  1116. std::this_thread::sleep_for(std::chrono::seconds(1));
  1117. {
  1118. Client cli(HOST, PORT);
  1119. auto res = cli.Get("/hi");
  1120. ASSERT_TRUE(res);
  1121. EXPECT_EQ(200, res->status);
  1122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1123. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1124. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1125. }
  1126. }
  1127. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1128. TEST(ExceptionHandlerTest, ContentLength) {
  1129. Server svr;
  1130. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1131. std::exception_ptr ep) {
  1132. EXPECT_FALSE(ep == nullptr);
  1133. try {
  1134. std::rethrow_exception(ep);
  1135. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1136. res.status = 500;
  1137. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1138. "text/html"); // <= Content-Length still 13 at this point
  1139. });
  1140. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1141. res.set_content("Hello World!\n", "text/plain");
  1142. throw std::runtime_error("abc");
  1143. });
  1144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1145. auto se = detail::scope_exit([&] {
  1146. svr.stop();
  1147. thread.join();
  1148. ASSERT_FALSE(svr.is_running());
  1149. });
  1150. // Give GET time to get a few messages.
  1151. std::this_thread::sleep_for(std::chrono::seconds(1));
  1152. for (size_t i = 0; i < 10; i++) {
  1153. Client cli(HOST, PORT);
  1154. for (size_t j = 0; j < 100; j++) {
  1155. auto res = cli.Get("/hi");
  1156. ASSERT_TRUE(res);
  1157. EXPECT_EQ(500, res->status);
  1158. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1159. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1160. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1161. }
  1162. cli.set_keep_alive(true);
  1163. for (size_t j = 0; j < 100; j++) {
  1164. auto res = cli.Get("/hi");
  1165. ASSERT_TRUE(res);
  1166. EXPECT_EQ(500, res->status);
  1167. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1169. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1170. }
  1171. }
  1172. }
  1173. #endif
  1174. TEST(NoContentTest, ContentLength) {
  1175. Server svr;
  1176. svr.Get("/hi",
  1177. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. thread.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. // Give GET time to get a few messages.
  1185. std::this_thread::sleep_for(std::chrono::seconds(1));
  1186. {
  1187. Client cli(HOST, PORT);
  1188. auto res = cli.Get("/hi");
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ(204, res->status);
  1191. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1192. }
  1193. }
  1194. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1195. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1197. ASSERT_TRUE(svr.is_valid());
  1198. #else
  1199. Server svr;
  1200. #endif
  1201. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1202. if (req.path == "/routing_handler") {
  1203. res.set_header("PRE_ROUTING", "on");
  1204. res.set_content("Routing Handler", "text/plain");
  1205. return httplib::Server::HandlerResponse::Handled;
  1206. }
  1207. return httplib::Server::HandlerResponse::Unhandled;
  1208. });
  1209. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1210. res.set_content("Error", "text/html");
  1211. });
  1212. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1213. if (req.path == "/routing_handler") {
  1214. res.set_header("POST_ROUTING", "on");
  1215. }
  1216. });
  1217. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1218. res.set_content("Hello World!\n", "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. // Give GET time to get a few messages.
  1227. std::this_thread::sleep_for(std::chrono::seconds(1));
  1228. {
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. SSLClient cli(HOST, PORT);
  1231. cli.enable_server_certificate_verification(false);
  1232. #else
  1233. Client cli(HOST, PORT);
  1234. #endif
  1235. auto res = cli.Get("/routing_handler");
  1236. ASSERT_TRUE(res);
  1237. EXPECT_EQ(200, res->status);
  1238. EXPECT_EQ("Routing Handler", res->body);
  1239. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1240. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1241. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1242. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1243. }
  1244. {
  1245. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1246. SSLClient cli(HOST, PORT);
  1247. cli.enable_server_certificate_verification(false);
  1248. #else
  1249. Client cli(HOST, PORT);
  1250. #endif
  1251. auto res = cli.Get("/hi");
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ(200, res->status);
  1254. EXPECT_EQ("Hello World!\n", res->body);
  1255. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1256. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1257. }
  1258. {
  1259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1260. SSLClient cli(HOST, PORT);
  1261. cli.enable_server_certificate_verification(false);
  1262. #else
  1263. Client cli(HOST, PORT);
  1264. #endif
  1265. auto res = cli.Get("/aaa");
  1266. ASSERT_TRUE(res);
  1267. EXPECT_EQ(404, res->status);
  1268. EXPECT_EQ("Error", res->body);
  1269. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1270. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1271. }
  1272. }
  1273. TEST(InvalidFormatTest, StatusCode) {
  1274. Server svr;
  1275. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("Hello World!\n", "text/plain");
  1277. res.status = 9999; // Status should be a three-digit code...
  1278. });
  1279. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1280. auto se = detail::scope_exit([&] {
  1281. svr.stop();
  1282. thread.join();
  1283. ASSERT_FALSE(svr.is_running());
  1284. });
  1285. // Give GET time to get a few messages.
  1286. std::this_thread::sleep_for(std::chrono::seconds(1));
  1287. {
  1288. Client cli(HOST, PORT);
  1289. auto res = cli.Get("/hi");
  1290. ASSERT_FALSE(res);
  1291. }
  1292. }
  1293. TEST(URLFragmentTest, WithFragment) {
  1294. Server svr;
  1295. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1296. EXPECT_TRUE(req.target == "/hi");
  1297. });
  1298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1299. auto se = detail::scope_exit([&] {
  1300. svr.stop();
  1301. thread.join();
  1302. ASSERT_FALSE(svr.is_running());
  1303. });
  1304. std::this_thread::sleep_for(std::chrono::seconds(1));
  1305. {
  1306. Client cli(HOST, PORT);
  1307. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1308. EXPECT_TRUE(res);
  1309. EXPECT_EQ(200, res->status);
  1310. res = cli.Get("/hi%23key1=val1=key2=val2");
  1311. EXPECT_TRUE(res);
  1312. EXPECT_EQ(404, res->status);
  1313. }
  1314. }
  1315. class ServerTest : public ::testing::Test {
  1316. protected:
  1317. ServerTest()
  1318. : cli_(HOST, PORT)
  1319. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1320. ,
  1321. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1322. #endif
  1323. {
  1324. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1325. cli_.enable_server_certificate_verification(false);
  1326. #endif
  1327. }
  1328. virtual void SetUp() {
  1329. svr_.set_mount_point("/", "./www");
  1330. svr_.set_mount_point("/mount", "./www2");
  1331. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1332. svr_.Get("/hi",
  1333. [&](const Request & /*req*/, Response &res) {
  1334. res.set_content("Hello World!", "text/plain");
  1335. })
  1336. .Get("/http_response_splitting",
  1337. [&](const Request & /*req*/, Response &res) {
  1338. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1339. EXPECT_EQ(0U, res.headers.size());
  1340. EXPECT_FALSE(res.has_header("a"));
  1341. res.set_header("a", "1\nSet-Cookie: a=1");
  1342. EXPECT_EQ(0U, res.headers.size());
  1343. EXPECT_FALSE(res.has_header("a"));
  1344. res.set_header("a", "1\rSet-Cookie: a=1");
  1345. EXPECT_EQ(0U, res.headers.size());
  1346. EXPECT_FALSE(res.has_header("a"));
  1347. res.set_header("a\r\nb", "0");
  1348. EXPECT_EQ(0U, res.headers.size());
  1349. EXPECT_FALSE(res.has_header("a"));
  1350. res.set_header("a\rb", "0");
  1351. EXPECT_EQ(0U, res.headers.size());
  1352. EXPECT_FALSE(res.has_header("a"));
  1353. res.set_header("a\nb", "0");
  1354. EXPECT_EQ(0U, res.headers.size());
  1355. EXPECT_FALSE(res.has_header("a"));
  1356. res.set_redirect("1\r\nSet-Cookie: a=1");
  1357. EXPECT_EQ(0U, res.headers.size());
  1358. EXPECT_FALSE(res.has_header("Location"));
  1359. })
  1360. .Get("/slow",
  1361. [&](const Request & /*req*/, Response &res) {
  1362. std::this_thread::sleep_for(std::chrono::seconds(2));
  1363. res.set_content("slow", "text/plain");
  1364. })
  1365. #if 0
  1366. .Post("/slowpost",
  1367. [&](const Request & /*req*/, Response &res) {
  1368. std::this_thread::sleep_for(std::chrono::seconds(2));
  1369. res.set_content("slow", "text/plain");
  1370. })
  1371. #endif
  1372. .Get("/remote_addr",
  1373. [&](const Request &req, Response &res) {
  1374. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1375. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1376. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1377. EXPECT_EQ(req.remote_port,
  1378. std::stoi(req.get_header_value("REMOTE_PORT")));
  1379. res.set_content(remote_addr.c_str(), "text/plain");
  1380. })
  1381. .Get("/local_addr",
  1382. [&](const Request &req, Response &res) {
  1383. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1384. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1385. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1386. auto local_port = req.get_header_value("LOCAL_PORT");
  1387. EXPECT_EQ(req.local_addr, local_addr);
  1388. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1389. res.set_content(local_addr.append(":").append(local_port),
  1390. "text/plain");
  1391. })
  1392. .Get("/endwith%",
  1393. [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. })
  1396. .Get("/a\\+\\+b",
  1397. [&](const Request &req, Response &res) {
  1398. ASSERT_TRUE(req.has_param("a +b"));
  1399. auto val = req.get_param_value("a +b");
  1400. res.set_content(val, "text/plain");
  1401. })
  1402. .Get("/", [&](const Request & /*req*/,
  1403. Response &res) { res.set_redirect("/hi"); })
  1404. .Post("/1", [](const Request & /*req*/,
  1405. Response &res) { res.set_redirect("/2", 303); })
  1406. .Get("/2",
  1407. [](const Request & /*req*/, Response &res) {
  1408. res.set_content("redirected.", "text/plain");
  1409. res.status = 200;
  1410. })
  1411. .Post("/person",
  1412. [&](const Request &req, Response &res) {
  1413. if (req.has_param("name") && req.has_param("note")) {
  1414. persons_[req.get_param_value("name")] =
  1415. req.get_param_value("note");
  1416. } else {
  1417. res.status = 400;
  1418. }
  1419. })
  1420. .Put("/person",
  1421. [&](const Request &req, Response &res) {
  1422. if (req.has_param("name") && req.has_param("note")) {
  1423. persons_[req.get_param_value("name")] =
  1424. req.get_param_value("note");
  1425. } else {
  1426. res.status = 400;
  1427. }
  1428. })
  1429. .Get("/person/(.*)",
  1430. [&](const Request &req, Response &res) {
  1431. string name = req.matches[1];
  1432. if (persons_.find(name) != persons_.end()) {
  1433. auto note = persons_[name];
  1434. res.set_content(note, "text/plain");
  1435. } else {
  1436. res.status = 404;
  1437. }
  1438. })
  1439. .Post("/x-www-form-urlencoded-json",
  1440. [&](const Request &req, Response &res) {
  1441. auto json = req.get_param_value("json");
  1442. ASSERT_EQ(JSON_DATA, json);
  1443. res.set_content(json, "appliation/json");
  1444. res.status = 200;
  1445. })
  1446. .Get("/streamed-chunked",
  1447. [&](const Request & /*req*/, Response &res) {
  1448. res.set_chunked_content_provider(
  1449. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1450. sink.os << "123";
  1451. sink.os << "456";
  1452. sink.os << "789";
  1453. sink.done();
  1454. return true;
  1455. });
  1456. })
  1457. .Get("/streamed-chunked2",
  1458. [&](const Request & /*req*/, Response &res) {
  1459. auto i = new int(0);
  1460. res.set_chunked_content_provider(
  1461. "text/plain",
  1462. [i](size_t /*offset*/, DataSink &sink) {
  1463. switch (*i) {
  1464. case 0: sink.os << "123"; break;
  1465. case 1: sink.os << "456"; break;
  1466. case 2: sink.os << "789"; break;
  1467. case 3: sink.done(); break;
  1468. }
  1469. (*i)++;
  1470. return true;
  1471. },
  1472. [i](bool success) {
  1473. EXPECT_TRUE(success);
  1474. delete i;
  1475. });
  1476. })
  1477. .Get("/streamed-chunked-with-trailer",
  1478. [&](const Request & /*req*/, Response &res) {
  1479. auto i = new int(0);
  1480. res.set_header("Trailer", "Dummy1, Dummy2");
  1481. res.set_chunked_content_provider(
  1482. "text/plain",
  1483. [i](size_t /*offset*/, DataSink &sink) {
  1484. switch (*i) {
  1485. case 0: sink.os << "123"; break;
  1486. case 1: sink.os << "456"; break;
  1487. case 2: sink.os << "789"; break;
  1488. case 3: {
  1489. sink.done_with_trailer(
  1490. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  1491. } break;
  1492. }
  1493. (*i)++;
  1494. return true;
  1495. },
  1496. [i](bool success) {
  1497. EXPECT_TRUE(success);
  1498. delete i;
  1499. });
  1500. })
  1501. .Get("/streamed",
  1502. [&](const Request & /*req*/, Response &res) {
  1503. res.set_content_provider(
  1504. 6, "text/plain",
  1505. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1506. sink.os << (offset < 3 ? "a" : "b");
  1507. return true;
  1508. });
  1509. })
  1510. .Get("/streamed-with-range",
  1511. [&](const Request & /*req*/, Response &res) {
  1512. auto data = new std::string("abcdefg");
  1513. res.set_content_provider(
  1514. data->size(), "text/plain",
  1515. [data](size_t offset, size_t length, DataSink &sink) {
  1516. size_t DATA_CHUNK_SIZE = 4;
  1517. const auto &d = *data;
  1518. auto out_len =
  1519. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1520. auto ret =
  1521. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1522. EXPECT_TRUE(ret);
  1523. return true;
  1524. },
  1525. [data](bool success) {
  1526. EXPECT_TRUE(success);
  1527. delete data;
  1528. });
  1529. })
  1530. .Get("/streamed-cancel",
  1531. [&](const Request & /*req*/, Response &res) {
  1532. res.set_content_provider(
  1533. size_t(-1), "text/plain",
  1534. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1535. sink.os << "data_chunk";
  1536. return true;
  1537. });
  1538. })
  1539. .Get("/with-range",
  1540. [&](const Request & /*req*/, Response &res) {
  1541. res.set_content("abcdefg", "text/plain");
  1542. })
  1543. .Post("/chunked",
  1544. [&](const Request &req, Response & /*res*/) {
  1545. EXPECT_EQ(req.body, "dechunked post body");
  1546. })
  1547. .Post("/large-chunked",
  1548. [&](const Request &req, Response & /*res*/) {
  1549. std::string expected(6 * 30 * 1024u, 'a');
  1550. EXPECT_EQ(req.body, expected);
  1551. })
  1552. .Post("/multipart",
  1553. [&](const Request &req, Response & /*res*/) {
  1554. EXPECT_EQ(6u, req.files.size());
  1555. ASSERT_TRUE(!req.has_file("???"));
  1556. ASSERT_TRUE(req.body.empty());
  1557. {
  1558. const auto &file = req.get_file_value("text1");
  1559. EXPECT_TRUE(file.filename.empty());
  1560. EXPECT_EQ("text default", file.content);
  1561. }
  1562. {
  1563. const auto &file = req.get_file_value("text2");
  1564. EXPECT_TRUE(file.filename.empty());
  1565. EXPECT_EQ("aωb", file.content);
  1566. }
  1567. {
  1568. const auto &file = req.get_file_value("file1");
  1569. EXPECT_EQ("hello.txt", file.filename);
  1570. EXPECT_EQ("text/plain", file.content_type);
  1571. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1572. }
  1573. {
  1574. const auto &file = req.get_file_value("file3");
  1575. EXPECT_TRUE(file.filename.empty());
  1576. EXPECT_EQ("application/octet-stream", file.content_type);
  1577. EXPECT_EQ(0u, file.content.size());
  1578. }
  1579. {
  1580. const auto &file = req.get_file_value("file4");
  1581. EXPECT_TRUE(file.filename.empty());
  1582. EXPECT_EQ(0u, file.content.size());
  1583. EXPECT_EQ("application/json tmp-string", file.content_type);
  1584. }
  1585. })
  1586. .Post("/multipart/multi_file_values",
  1587. [&](const Request &req, Response & /*res*/) {
  1588. EXPECT_EQ(5u, req.files.size());
  1589. ASSERT_TRUE(!req.has_file("???"));
  1590. ASSERT_TRUE(req.body.empty());
  1591. {
  1592. const auto &text_value = req.get_file_values("text");
  1593. EXPECT_EQ(1u, text_value.size());
  1594. auto &text = text_value[0];
  1595. EXPECT_TRUE(text.filename.empty());
  1596. EXPECT_EQ("default text", text.content);
  1597. }
  1598. {
  1599. const auto &text1_values = req.get_file_values("multi_text1");
  1600. EXPECT_EQ(2u, text1_values.size());
  1601. EXPECT_EQ("aaaaa", text1_values[0].content);
  1602. EXPECT_EQ("bbbbb", text1_values[1].content);
  1603. }
  1604. {
  1605. const auto &file1_values = req.get_file_values("multi_file1");
  1606. EXPECT_EQ(2u, file1_values.size());
  1607. auto file1 = file1_values[0];
  1608. EXPECT_EQ(file1.filename, "hello.txt");
  1609. EXPECT_EQ(file1.content_type, "text/plain");
  1610. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1611. auto file2 = file1_values[1];
  1612. EXPECT_EQ(file2.filename, "world.json");
  1613. EXPECT_EQ(file2.content_type, "application/json");
  1614. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1615. }
  1616. })
  1617. .Post("/empty",
  1618. [&](const Request &req, Response &res) {
  1619. EXPECT_EQ(req.body, "");
  1620. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1621. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1622. res.set_content("empty", "text/plain");
  1623. })
  1624. .Post("/empty-no-content-type",
  1625. [&](const Request &req, Response &res) {
  1626. EXPECT_EQ(req.body, "");
  1627. EXPECT_FALSE(req.has_header("Content-Type"));
  1628. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1629. res.set_content("empty-no-content-type", "text/plain");
  1630. })
  1631. .Post("/path-only",
  1632. [&](const Request &req, Response &res) {
  1633. EXPECT_EQ(req.body, "");
  1634. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1636. res.set_content("path-only", "text/plain");
  1637. })
  1638. .Post("/path-headers-only",
  1639. [&](const Request &req, Response &res) {
  1640. EXPECT_EQ(req.body, "");
  1641. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1643. EXPECT_EQ("world", req.get_header_value("hello"));
  1644. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1645. res.set_content("path-headers-only", "text/plain");
  1646. })
  1647. .Post("/post-large",
  1648. [&](const Request &req, Response &res) {
  1649. EXPECT_EQ(req.body, LARGE_DATA);
  1650. res.set_content(req.body, "text/plain");
  1651. })
  1652. .Put("/empty-no-content-type",
  1653. [&](const Request &req, Response &res) {
  1654. EXPECT_EQ(req.body, "");
  1655. EXPECT_FALSE(req.has_header("Content-Type"));
  1656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1657. res.set_content("empty-no-content-type", "text/plain");
  1658. })
  1659. .Put("/put",
  1660. [&](const Request &req, Response &res) {
  1661. EXPECT_EQ(req.body, "PUT");
  1662. res.set_content(req.body, "text/plain");
  1663. })
  1664. .Put("/put-large",
  1665. [&](const Request &req, Response &res) {
  1666. EXPECT_EQ(req.body, LARGE_DATA);
  1667. res.set_content(req.body, "text/plain");
  1668. })
  1669. .Patch("/patch",
  1670. [&](const Request &req, Response &res) {
  1671. EXPECT_EQ(req.body, "PATCH");
  1672. res.set_content(req.body, "text/plain");
  1673. })
  1674. .Delete("/delete",
  1675. [&](const Request & /*req*/, Response &res) {
  1676. res.set_content("DELETE", "text/plain");
  1677. })
  1678. .Delete("/delete-body",
  1679. [&](const Request &req, Response &res) {
  1680. EXPECT_EQ(req.body, "content");
  1681. res.set_content(req.body, "text/plain");
  1682. })
  1683. .Options(R"(\*)",
  1684. [&](const Request & /*req*/, Response &res) {
  1685. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1686. })
  1687. .Get("/request-target",
  1688. [&](const Request &req, Response & /*res*/) {
  1689. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1690. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1691. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1692. })
  1693. .Get("/long-query-value",
  1694. [&](const Request &req, Response & /*res*/) {
  1695. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1696. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1697. })
  1698. .Get("/array-param",
  1699. [&](const Request &req, Response & /*res*/) {
  1700. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1701. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1702. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1703. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1704. })
  1705. .Post("/validate-no-multiple-headers",
  1706. [&](const Request &req, Response & /*res*/) {
  1707. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1708. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1709. })
  1710. .Post("/content_receiver",
  1711. [&](const Request &req, Response &res,
  1712. const ContentReader &content_reader) {
  1713. if (req.is_multipart_form_data()) {
  1714. MultipartFormDataItems files;
  1715. content_reader(
  1716. [&](const MultipartFormData &file) {
  1717. files.push_back(file);
  1718. return true;
  1719. },
  1720. [&](const char *data, size_t data_length) {
  1721. files.back().content.append(data, data_length);
  1722. return true;
  1723. });
  1724. EXPECT_EQ(5u, files.size());
  1725. {
  1726. const auto &file = get_file_value(files, "text1");
  1727. EXPECT_TRUE(file.filename.empty());
  1728. EXPECT_EQ("text default", file.content);
  1729. }
  1730. {
  1731. const auto &file = get_file_value(files, "text2");
  1732. EXPECT_TRUE(file.filename.empty());
  1733. EXPECT_EQ("aωb", file.content);
  1734. }
  1735. {
  1736. const auto &file = get_file_value(files, "file1");
  1737. EXPECT_EQ("hello.txt", file.filename);
  1738. EXPECT_EQ("text/plain", file.content_type);
  1739. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1740. }
  1741. {
  1742. const auto &file = get_file_value(files, "file3");
  1743. EXPECT_TRUE(file.filename.empty());
  1744. EXPECT_EQ("application/octet-stream", file.content_type);
  1745. EXPECT_EQ(0u, file.content.size());
  1746. }
  1747. } else {
  1748. std::string body;
  1749. content_reader([&](const char *data, size_t data_length) {
  1750. EXPECT_EQ(7U, data_length);
  1751. body.append(data, data_length);
  1752. return true;
  1753. });
  1754. EXPECT_EQ(body, "content");
  1755. res.set_content(body, "text/plain");
  1756. }
  1757. })
  1758. .Put("/content_receiver",
  1759. [&](const Request & /*req*/, Response &res,
  1760. const ContentReader &content_reader) {
  1761. std::string body;
  1762. content_reader([&](const char *data, size_t data_length) {
  1763. body.append(data, data_length);
  1764. return true;
  1765. });
  1766. EXPECT_EQ(body, "content");
  1767. res.set_content(body, "text/plain");
  1768. })
  1769. .Patch("/content_receiver",
  1770. [&](const Request & /*req*/, Response &res,
  1771. const ContentReader &content_reader) {
  1772. std::string body;
  1773. content_reader([&](const char *data, size_t data_length) {
  1774. body.append(data, data_length);
  1775. return true;
  1776. });
  1777. EXPECT_EQ(body, "content");
  1778. res.set_content(body, "text/plain");
  1779. })
  1780. .Post("/query-string-and-body",
  1781. [&](const Request &req, Response & /*res*/) {
  1782. ASSERT_TRUE(req.has_param("key"));
  1783. EXPECT_EQ(req.get_param_value("key"), "value");
  1784. EXPECT_EQ(req.body, "content");
  1785. })
  1786. .Get("/last-request",
  1787. [&](const Request &req, Response & /*res*/) {
  1788. EXPECT_EQ("close", req.get_header_value("Connection"));
  1789. })
  1790. .Get(R"(/redirect/(\d+))",
  1791. [&](const Request &req, Response &res) {
  1792. auto num = std::stoi(req.matches[1]) + 1;
  1793. std::string url = "/redirect/" + std::to_string(num);
  1794. res.set_redirect(url);
  1795. })
  1796. .Post("/binary",
  1797. [&](const Request &req, Response &res) {
  1798. EXPECT_EQ(4U, req.body.size());
  1799. EXPECT_EQ("application/octet-stream",
  1800. req.get_header_value("Content-Type"));
  1801. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1802. res.set_content(req.body, "application/octet-stream");
  1803. })
  1804. .Put("/binary",
  1805. [&](const Request &req, Response &res) {
  1806. EXPECT_EQ(4U, req.body.size());
  1807. EXPECT_EQ("application/octet-stream",
  1808. req.get_header_value("Content-Type"));
  1809. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1810. res.set_content(req.body, "application/octet-stream");
  1811. })
  1812. .Patch("/binary",
  1813. [&](const Request &req, Response &res) {
  1814. EXPECT_EQ(4U, req.body.size());
  1815. EXPECT_EQ("application/octet-stream",
  1816. req.get_header_value("Content-Type"));
  1817. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1818. res.set_content(req.body, "application/octet-stream");
  1819. })
  1820. .Delete("/binary",
  1821. [&](const Request &req, Response &res) {
  1822. EXPECT_EQ(4U, req.body.size());
  1823. EXPECT_EQ("application/octet-stream",
  1824. req.get_header_value("Content-Type"));
  1825. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1826. res.set_content(req.body, "application/octet-stream");
  1827. })
  1828. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1829. .Get("/compress",
  1830. [&](const Request & /*req*/, Response &res) {
  1831. res.set_content(
  1832. "12345678901234567890123456789012345678901234567890123456789"
  1833. "01234567890123456789012345678901234567890",
  1834. "text/plain");
  1835. })
  1836. .Get("/nocompress",
  1837. [&](const Request & /*req*/, Response &res) {
  1838. res.set_content(
  1839. "12345678901234567890123456789012345678901234567890123456789"
  1840. "01234567890123456789012345678901234567890",
  1841. "application/octet-stream");
  1842. })
  1843. .Post("/compress-multipart",
  1844. [&](const Request &req, Response & /*res*/) {
  1845. EXPECT_EQ(2u, req.files.size());
  1846. ASSERT_TRUE(!req.has_file("???"));
  1847. {
  1848. const auto &file = req.get_file_value("key1");
  1849. EXPECT_TRUE(file.filename.empty());
  1850. EXPECT_EQ("test", file.content);
  1851. }
  1852. {
  1853. const auto &file = req.get_file_value("key2");
  1854. EXPECT_TRUE(file.filename.empty());
  1855. EXPECT_EQ("--abcdefg123", file.content);
  1856. }
  1857. })
  1858. #endif
  1859. ;
  1860. persons_["john"] = "programmer";
  1861. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1862. while (!svr_.is_running()) {
  1863. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1864. }
  1865. }
  1866. virtual void TearDown() {
  1867. svr_.stop();
  1868. if (!request_threads_.empty()) {
  1869. std::this_thread::sleep_for(std::chrono::seconds(1));
  1870. for (auto &t : request_threads_) {
  1871. t.join();
  1872. }
  1873. }
  1874. t_.join();
  1875. }
  1876. map<string, string> persons_;
  1877. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1878. SSLClient cli_;
  1879. SSLServer svr_;
  1880. #else
  1881. Client cli_;
  1882. Server svr_;
  1883. #endif
  1884. thread t_;
  1885. std::vector<thread> request_threads_;
  1886. };
  1887. TEST_F(ServerTest, GetMethod200) {
  1888. auto res = cli_.Get("/hi");
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ("HTTP/1.1", res->version);
  1891. EXPECT_EQ(200, res->status);
  1892. EXPECT_EQ("OK", res->reason);
  1893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1894. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1895. EXPECT_EQ("Hello World!", res->body);
  1896. }
  1897. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1898. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ("HTTP/1.1", res->version);
  1901. EXPECT_EQ(200, res->status);
  1902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1903. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. }
  1906. TEST_F(ServerTest, GetMethod302) {
  1907. auto res = cli_.Get("/");
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(302, res->status);
  1910. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1911. }
  1912. TEST_F(ServerTest, GetMethod302Redirect) {
  1913. cli_.set_follow_location(true);
  1914. auto res = cli_.Get("/");
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(200, res->status);
  1917. EXPECT_EQ("Hello World!", res->body);
  1918. EXPECT_EQ("/hi", res->location);
  1919. }
  1920. TEST_F(ServerTest, GetMethod404) {
  1921. auto res = cli_.Get("/invalid");
  1922. ASSERT_TRUE(res);
  1923. EXPECT_EQ(404, res->status);
  1924. }
  1925. TEST_F(ServerTest, HeadMethod200) {
  1926. auto res = cli_.Head("/hi");
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(200, res->status);
  1929. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1930. EXPECT_TRUE(res->body.empty());
  1931. }
  1932. TEST_F(ServerTest, HeadMethod200Static) {
  1933. auto res = cli_.Head("/mount/dir/index.html");
  1934. ASSERT_TRUE(res);
  1935. EXPECT_EQ(200, res->status);
  1936. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1937. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1938. EXPECT_TRUE(res->body.empty());
  1939. }
  1940. TEST_F(ServerTest, HeadMethod404) {
  1941. auto res = cli_.Head("/invalid");
  1942. ASSERT_TRUE(res);
  1943. EXPECT_EQ(404, res->status);
  1944. EXPECT_TRUE(res->body.empty());
  1945. }
  1946. TEST_F(ServerTest, GetMethodPersonJohn) {
  1947. auto res = cli_.Get("/person/john");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(200, res->status);
  1950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1951. EXPECT_EQ("programmer", res->body);
  1952. }
  1953. TEST_F(ServerTest, PostMethod1) {
  1954. auto res = cli_.Get("/person/john1");
  1955. ASSERT_TRUE(res);
  1956. ASSERT_EQ(404, res->status);
  1957. res = cli_.Post("/person", "name=john1&note=coder",
  1958. "application/x-www-form-urlencoded");
  1959. ASSERT_TRUE(res);
  1960. ASSERT_EQ(200, res->status);
  1961. res = cli_.Get("/person/john1");
  1962. ASSERT_TRUE(res);
  1963. ASSERT_EQ(200, res->status);
  1964. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1965. ASSERT_EQ("coder", res->body);
  1966. }
  1967. TEST_F(ServerTest, PostMethod2) {
  1968. auto res = cli_.Get("/person/john2");
  1969. ASSERT_TRUE(res);
  1970. ASSERT_EQ(404, res->status);
  1971. Params params;
  1972. params.emplace("name", "john2");
  1973. params.emplace("note", "coder");
  1974. res = cli_.Post("/person", params);
  1975. ASSERT_TRUE(res);
  1976. ASSERT_EQ(200, res->status);
  1977. res = cli_.Get("/person/john2");
  1978. ASSERT_TRUE(res);
  1979. ASSERT_EQ(200, res->status);
  1980. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1981. ASSERT_EQ("coder", res->body);
  1982. }
  1983. TEST_F(ServerTest, PutMethod3) {
  1984. auto res = cli_.Get("/person/john3");
  1985. ASSERT_TRUE(res);
  1986. ASSERT_EQ(404, res->status);
  1987. Params params;
  1988. params.emplace("name", "john3");
  1989. params.emplace("note", "coder");
  1990. res = cli_.Put("/person", params);
  1991. ASSERT_TRUE(res);
  1992. ASSERT_EQ(200, res->status);
  1993. res = cli_.Get("/person/john3");
  1994. ASSERT_TRUE(res);
  1995. ASSERT_EQ(200, res->status);
  1996. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1997. ASSERT_EQ("coder", res->body);
  1998. }
  1999. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2000. Params params;
  2001. params.emplace("json", JSON_DATA);
  2002. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2003. ASSERT_TRUE(res);
  2004. ASSERT_EQ(200, res->status);
  2005. ASSERT_EQ(JSON_DATA, res->body);
  2006. }
  2007. TEST_F(ServerTest, PostEmptyContent) {
  2008. auto res = cli_.Post("/empty", "", "text/plain");
  2009. ASSERT_TRUE(res);
  2010. ASSERT_EQ(200, res->status);
  2011. ASSERT_EQ("empty", res->body);
  2012. }
  2013. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2014. auto res = cli_.Post("/empty-no-content-type");
  2015. ASSERT_TRUE(res);
  2016. ASSERT_EQ(200, res->status);
  2017. ASSERT_EQ("empty-no-content-type", res->body);
  2018. }
  2019. TEST_F(ServerTest, PostPathOnly) {
  2020. auto res = cli_.Post("/path-only");
  2021. ASSERT_TRUE(res);
  2022. ASSERT_EQ(200, res->status);
  2023. ASSERT_EQ("path-only", res->body);
  2024. }
  2025. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2026. auto res = cli_.Post("/path-headers-only",
  2027. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2028. ASSERT_TRUE(res);
  2029. ASSERT_EQ(200, res->status);
  2030. ASSERT_EQ("path-headers-only", res->body);
  2031. }
  2032. TEST_F(ServerTest, PostLarge) {
  2033. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2034. ASSERT_TRUE(res);
  2035. ASSERT_EQ(200, res->status);
  2036. EXPECT_EQ(LARGE_DATA, res->body);
  2037. }
  2038. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2039. auto res = cli_.Put("/empty-no-content-type");
  2040. ASSERT_TRUE(res);
  2041. ASSERT_EQ(200, res->status);
  2042. ASSERT_EQ("empty-no-content-type", res->body);
  2043. }
  2044. TEST_F(ServerTest, GetMethodDir) {
  2045. auto res = cli_.Get("/dir/");
  2046. ASSERT_TRUE(res);
  2047. EXPECT_EQ(200, res->status);
  2048. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2049. auto body = R"(<html>
  2050. <head>
  2051. </head>
  2052. <body>
  2053. <a href="/dir/test.html">Test</a>
  2054. <a href="/hi">hi</a>
  2055. </body>
  2056. </html>
  2057. )";
  2058. EXPECT_EQ(body, res->body);
  2059. }
  2060. TEST_F(ServerTest, GetMethodDirTest) {
  2061. auto res = cli_.Get("/dir/test.html");
  2062. ASSERT_TRUE(res);
  2063. EXPECT_EQ(200, res->status);
  2064. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2065. EXPECT_EQ("test.html", res->body);
  2066. }
  2067. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2068. auto res = cli_.Get("/dir/../dir/test.html");
  2069. ASSERT_TRUE(res);
  2070. EXPECT_EQ(200, res->status);
  2071. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2072. EXPECT_EQ("test.html", res->body);
  2073. }
  2074. TEST_F(ServerTest, GetMethodInvalidPath) {
  2075. auto res = cli_.Get("/dir/../test.html");
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(404, res->status);
  2078. }
  2079. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2080. auto res = cli_.Get("/../www/dir/test.html");
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(404, res->status);
  2083. }
  2084. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2085. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2086. ASSERT_TRUE(res);
  2087. EXPECT_EQ(404, res->status);
  2088. }
  2089. TEST_F(ServerTest, GetMethodDirMountTest) {
  2090. auto res = cli_.Get("/mount/dir/test.html");
  2091. ASSERT_TRUE(res);
  2092. EXPECT_EQ(200, res->status);
  2093. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2094. EXPECT_EQ("test.html", res->body);
  2095. }
  2096. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2097. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(200, res->status);
  2100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2101. EXPECT_EQ("test.html", res->body);
  2102. }
  2103. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2104. auto res = cli_.Get("/mount/dir/../test.html");
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(404, res->status);
  2107. }
  2108. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2109. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(404, res->status);
  2112. }
  2113. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2114. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2115. ASSERT_TRUE(res);
  2116. EXPECT_EQ(404, res->status);
  2117. }
  2118. TEST_F(ServerTest, PostMethod303) {
  2119. auto res = cli_.Post("/1", "body", "text/plain");
  2120. ASSERT_TRUE(res);
  2121. EXPECT_EQ(303, res->status);
  2122. EXPECT_EQ("/2", res->get_header_value("Location"));
  2123. }
  2124. TEST_F(ServerTest, PostMethod303Redirect) {
  2125. cli_.set_follow_location(true);
  2126. auto res = cli_.Post("/1", "body", "text/plain");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(200, res->status);
  2129. EXPECT_EQ("redirected.", res->body);
  2130. EXPECT_EQ("/2", res->location);
  2131. }
  2132. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2133. auto res = cli_.Get("/dir/test.abcde");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(200, res->status);
  2136. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2137. EXPECT_EQ("abcde", res->body);
  2138. }
  2139. TEST_F(ServerTest, StaticFileRange) {
  2140. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2141. ASSERT_TRUE(res);
  2142. EXPECT_EQ(206, res->status);
  2143. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2144. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2145. EXPECT_EQ(true, res->has_header("Content-Range"));
  2146. EXPECT_EQ(std::string("cd"), res->body);
  2147. }
  2148. TEST_F(ServerTest, StaticFileRanges) {
  2149. auto res =
  2150. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2151. ASSERT_TRUE(res);
  2152. EXPECT_EQ(206, res->status);
  2153. EXPECT_TRUE(
  2154. res->get_header_value("Content-Type")
  2155. .find(
  2156. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2157. 0);
  2158. EXPECT_EQ("265", res->get_header_value("Content-Length"));
  2159. }
  2160. TEST_F(ServerTest, StaticFileRangeHead) {
  2161. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(206, res->status);
  2164. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2165. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2166. EXPECT_EQ(true, res->has_header("Content-Range"));
  2167. }
  2168. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2169. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2170. ASSERT_TRUE(res);
  2171. EXPECT_EQ(206, res->status);
  2172. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2173. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2174. EXPECT_EQ(true, res->has_header("Content-Range"));
  2175. EXPECT_EQ("LAST\n", res->body);
  2176. }
  2177. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2178. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2179. ASSERT_TRUE(res);
  2180. EXPECT_EQ(206, res->status);
  2181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2182. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2183. EXPECT_EQ(true, res->has_header("Content-Range"));
  2184. }
  2185. TEST_F(ServerTest, StaticFileBigFile) {
  2186. auto res = cli_.Get("/dir/1MB.txt");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(200, res->status);
  2189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2190. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2191. }
  2192. TEST_F(ServerTest, InvalidBaseDirMount) {
  2193. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2194. }
  2195. TEST_F(ServerTest, Binary) {
  2196. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2197. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2198. "application/octet-stream");
  2199. ASSERT_TRUE(res);
  2200. ASSERT_EQ(200, res->status);
  2201. ASSERT_EQ(4U, res->body.size());
  2202. res = cli_.Put("/binary", binary.data(), binary.size(),
  2203. "application/octet-stream");
  2204. ASSERT_TRUE(res);
  2205. ASSERT_EQ(200, res->status);
  2206. ASSERT_EQ(4U, res->body.size());
  2207. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2208. "application/octet-stream");
  2209. ASSERT_TRUE(res);
  2210. ASSERT_EQ(200, res->status);
  2211. ASSERT_EQ(4U, res->body.size());
  2212. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2213. "application/octet-stream");
  2214. ASSERT_TRUE(res);
  2215. ASSERT_EQ(200, res->status);
  2216. ASSERT_EQ(4U, res->body.size());
  2217. }
  2218. TEST_F(ServerTest, BinaryString) {
  2219. auto binary = std::string("\x00\x01\x02\x03", 4);
  2220. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2221. ASSERT_TRUE(res);
  2222. ASSERT_EQ(200, res->status);
  2223. ASSERT_EQ(4U, res->body.size());
  2224. res = cli_.Put("/binary", binary, "application/octet-stream");
  2225. ASSERT_TRUE(res);
  2226. ASSERT_EQ(200, res->status);
  2227. ASSERT_EQ(4U, res->body.size());
  2228. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2229. ASSERT_TRUE(res);
  2230. ASSERT_EQ(200, res->status);
  2231. ASSERT_EQ(4U, res->body.size());
  2232. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2233. ASSERT_TRUE(res);
  2234. ASSERT_EQ(200, res->status);
  2235. ASSERT_EQ(4U, res->body.size());
  2236. }
  2237. TEST_F(ServerTest, EmptyRequest) {
  2238. auto res = cli_.Get("");
  2239. ASSERT_TRUE(!res);
  2240. EXPECT_EQ(Error::Connection, res.error());
  2241. }
  2242. TEST_F(ServerTest, LongRequest) {
  2243. std::string request;
  2244. for (size_t i = 0; i < 545; i++) {
  2245. request += "/TooLongRequest";
  2246. }
  2247. request += "OK";
  2248. auto res = cli_.Get(request.c_str());
  2249. ASSERT_TRUE(res);
  2250. EXPECT_EQ(404, res->status);
  2251. }
  2252. TEST_F(ServerTest, TooLongRequest) {
  2253. std::string request;
  2254. for (size_t i = 0; i < 545; i++) {
  2255. request += "/TooLongRequest";
  2256. }
  2257. request += "_NG";
  2258. auto res = cli_.Get(request.c_str());
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ(414, res->status);
  2261. }
  2262. TEST_F(ServerTest, LongHeader) {
  2263. Request req;
  2264. req.method = "GET";
  2265. req.path = "/hi";
  2266. std::string host_and_port;
  2267. host_and_port += HOST;
  2268. host_and_port += ":";
  2269. host_and_port += std::to_string(PORT);
  2270. req.headers.emplace("Host", host_and_port.c_str());
  2271. req.headers.emplace("Accept", "*/*");
  2272. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2273. req.headers.emplace(
  2274. "Header-Name",
  2275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2303. "@@@@@@@@@@@@@@@@");
  2304. auto res = std::make_shared<Response>();
  2305. auto error = Error::Success;
  2306. auto ret = cli_.send(req, *res, error);
  2307. ASSERT_TRUE(ret);
  2308. EXPECT_EQ(200, res->status);
  2309. }
  2310. TEST_F(ServerTest, LongQueryValue) {
  2311. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2312. ASSERT_TRUE(res);
  2313. EXPECT_EQ(414, res->status);
  2314. }
  2315. TEST_F(ServerTest, TooLongHeader) {
  2316. Request req;
  2317. req.method = "GET";
  2318. req.path = "/hi";
  2319. std::string host_and_port;
  2320. host_and_port += HOST;
  2321. host_and_port += ":";
  2322. host_and_port += std::to_string(PORT);
  2323. req.headers.emplace("Host", host_and_port.c_str());
  2324. req.headers.emplace("Accept", "*/*");
  2325. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2326. req.headers.emplace(
  2327. "Header-Name",
  2328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2356. "@@@@@@@@@@@@@@@@@");
  2357. auto res = std::make_shared<Response>();
  2358. auto error = Error::Success;
  2359. auto ret = cli_.send(req, *res, error);
  2360. ASSERT_TRUE(ret);
  2361. EXPECT_EQ(200, res->status);
  2362. }
  2363. TEST_F(ServerTest, PercentEncoding) {
  2364. auto res = cli_.Get("/e%6edwith%");
  2365. ASSERT_TRUE(res);
  2366. EXPECT_EQ(200, res->status);
  2367. }
  2368. TEST_F(ServerTest, PercentEncodingUnicode) {
  2369. auto res = cli_.Get("/e%u006edwith%");
  2370. ASSERT_TRUE(res);
  2371. EXPECT_EQ(200, res->status);
  2372. }
  2373. TEST_F(ServerTest, InvalidPercentEncoding) {
  2374. auto res = cli_.Get("/%endwith%");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(404, res->status);
  2377. }
  2378. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2379. auto res = cli_.Get("/%uendwith%");
  2380. ASSERT_TRUE(res);
  2381. EXPECT_EQ(404, res->status);
  2382. }
  2383. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2384. auto res = cli_.Get("/hello?aaa=bbb%");
  2385. ASSERT_TRUE(res);
  2386. EXPECT_EQ(404, res->status);
  2387. }
  2388. TEST_F(ServerTest, PlusSignEncoding) {
  2389. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(200, res->status);
  2392. EXPECT_EQ("a +b", res->body);
  2393. }
  2394. TEST_F(ServerTest, MultipartFormData) {
  2395. MultipartFormDataItems items = {
  2396. {"text1", "text default", "", ""},
  2397. {"text2", "aωb", "", ""},
  2398. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2399. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2400. {"file3", "", "", "application/octet-stream"},
  2401. {"file4", "", "", " application/json tmp-string "}};
  2402. auto res = cli_.Post("/multipart", items);
  2403. ASSERT_TRUE(res);
  2404. EXPECT_EQ(200, res->status);
  2405. }
  2406. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2407. MultipartFormDataItems items = {
  2408. {"text", "default text", "", ""},
  2409. {"multi_text1", "aaaaa", "", ""},
  2410. {"multi_text1", "bbbbb", "", ""},
  2411. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2412. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2413. "application/json"},
  2414. };
  2415. auto res = cli_.Post("/multipart/multi_file_values", items);
  2416. ASSERT_TRUE(res);
  2417. EXPECT_EQ(200, res->status);
  2418. }
  2419. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2420. auto res = cli_.Get("/hi");
  2421. ASSERT_TRUE(res);
  2422. EXPECT_EQ(200, res->status);
  2423. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2424. EXPECT_EQ("Hello World!", res->body);
  2425. }
  2426. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2427. Request req;
  2428. req.method = "POST";
  2429. req.path = "/chunked";
  2430. std::string host_and_port;
  2431. host_and_port += HOST;
  2432. host_and_port += ":";
  2433. host_and_port += std::to_string(PORT);
  2434. req.headers.emplace("Host", host_and_port.c_str());
  2435. req.headers.emplace("Accept", "*/*");
  2436. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2437. req.headers.emplace("Content-Type", "text/plain");
  2438. req.headers.emplace("Content-Length", "0");
  2439. req.headers.emplace(
  2440. "Transfer-Encoding",
  2441. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2442. // Client does not chunk, so make a chunked body manually.
  2443. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2444. auto res = std::make_shared<Response>();
  2445. auto error = Error::Success;
  2446. auto ret = cli_.send(req, *res, error);
  2447. ASSERT_TRUE(ret);
  2448. EXPECT_EQ(200, res->status);
  2449. }
  2450. TEST_F(ServerTest, GetStreamed2) {
  2451. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(206, res->status);
  2454. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2455. EXPECT_EQ(std::string("ab"), res->body);
  2456. }
  2457. TEST_F(ServerTest, GetStreamed) {
  2458. auto res = cli_.Get("/streamed");
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(200, res->status);
  2461. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2462. EXPECT_EQ(std::string("aaabbb"), res->body);
  2463. }
  2464. TEST_F(ServerTest, GetStreamedWithRange1) {
  2465. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2466. ASSERT_TRUE(res);
  2467. EXPECT_EQ(206, res->status);
  2468. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2469. EXPECT_EQ(true, res->has_header("Content-Range"));
  2470. EXPECT_EQ(std::string("def"), res->body);
  2471. }
  2472. TEST_F(ServerTest, GetStreamedWithRange2) {
  2473. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(206, res->status);
  2476. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2477. EXPECT_EQ(true, res->has_header("Content-Range"));
  2478. EXPECT_EQ(std::string("bcdefg"), res->body);
  2479. }
  2480. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2481. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2482. ASSERT_TRUE(res);
  2483. EXPECT_EQ(206, res->status);
  2484. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2485. EXPECT_EQ(true, res->has_header("Content-Range"));
  2486. EXPECT_EQ(std::string("efg"), res->body);
  2487. }
  2488. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2489. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2490. ASSERT_TRUE(res);
  2491. EXPECT_EQ(206, res->status);
  2492. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2493. EXPECT_EQ(true, res->has_header("Content-Range"));
  2494. EXPECT_EQ(std::string("abcdefg"), res->body);
  2495. }
  2496. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2497. auto res = cli_.Get("/streamed-with-range",
  2498. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2499. "92233720368547758079223372036854775807"}});
  2500. ASSERT_TRUE(res);
  2501. EXPECT_EQ(416, res->status);
  2502. }
  2503. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2504. auto res =
  2505. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2506. EXPECT_EQ(206, res->status);
  2507. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2508. EXPECT_EQ(true, res->has_header("Content-Range"));
  2509. EXPECT_EQ(std::string("abcdefg"), res->body);
  2510. }
  2511. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2512. auto res =
  2513. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(206, res->status);
  2516. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2517. EXPECT_EQ(false, res->has_header("Content-Range"));
  2518. EXPECT_EQ(267U, res->body.size());
  2519. }
  2520. TEST_F(ServerTest, GetStreamedEndless) {
  2521. uint64_t offset = 0;
  2522. auto res = cli_.Get("/streamed-cancel",
  2523. [&](const char * /*data*/, uint64_t data_length) {
  2524. if (offset < 100) {
  2525. offset += data_length;
  2526. return true;
  2527. }
  2528. return false;
  2529. });
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_EQ(Error::Canceled, res.error());
  2532. }
  2533. TEST_F(ServerTest, ClientStop) {
  2534. std::atomic_size_t count{4};
  2535. std::vector<std::thread> threads;
  2536. for (auto i = count.load(); i != 0; --i) {
  2537. threads.emplace_back([&]() {
  2538. auto res = cli_.Get("/streamed-cancel",
  2539. [&](const char *, uint64_t) { return true; });
  2540. --count;
  2541. ASSERT_TRUE(!res);
  2542. EXPECT_TRUE(res.error() == Error::Canceled ||
  2543. res.error() == Error::Read || res.error() == Error::Write);
  2544. });
  2545. }
  2546. std::this_thread::sleep_for(std::chrono::seconds(2));
  2547. while (count != 0) {
  2548. cli_.stop();
  2549. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2550. }
  2551. for (auto &t : threads) {
  2552. t.join();
  2553. }
  2554. }
  2555. TEST_F(ServerTest, GetWithRange1) {
  2556. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2557. ASSERT_TRUE(res);
  2558. EXPECT_EQ(206, res->status);
  2559. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2560. EXPECT_EQ(true, res->has_header("Content-Range"));
  2561. EXPECT_EQ(std::string("def"), res->body);
  2562. }
  2563. TEST_F(ServerTest, GetWithRange2) {
  2564. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2565. ASSERT_TRUE(res);
  2566. EXPECT_EQ(206, res->status);
  2567. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2568. EXPECT_EQ(true, res->has_header("Content-Range"));
  2569. EXPECT_EQ(std::string("bcdefg"), res->body);
  2570. }
  2571. TEST_F(ServerTest, GetWithRange3) {
  2572. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2573. ASSERT_TRUE(res);
  2574. EXPECT_EQ(206, res->status);
  2575. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2576. EXPECT_EQ(true, res->has_header("Content-Range"));
  2577. EXPECT_EQ(std::string("a"), res->body);
  2578. }
  2579. TEST_F(ServerTest, GetWithRange4) {
  2580. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2581. ASSERT_TRUE(res);
  2582. EXPECT_EQ(206, res->status);
  2583. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2584. EXPECT_EQ(true, res->has_header("Content-Range"));
  2585. EXPECT_EQ(std::string("fg"), res->body);
  2586. }
  2587. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2588. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2589. ASSERT_TRUE(res);
  2590. EXPECT_EQ(416, res->status);
  2591. }
  2592. TEST_F(ServerTest, GetWithRangeMultipart) {
  2593. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2594. ASSERT_TRUE(res);
  2595. EXPECT_EQ(206, res->status);
  2596. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2597. EXPECT_EQ(false, res->has_header("Content-Range"));
  2598. EXPECT_EQ(267U, res->body.size());
  2599. }
  2600. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2601. auto res =
  2602. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(416, res->status);
  2605. }
  2606. TEST_F(ServerTest, GetStreamedChunked) {
  2607. auto res = cli_.Get("/streamed-chunked");
  2608. ASSERT_TRUE(res);
  2609. EXPECT_EQ(200, res->status);
  2610. EXPECT_EQ(std::string("123456789"), res->body);
  2611. }
  2612. TEST_F(ServerTest, GetStreamedChunked2) {
  2613. auto res = cli_.Get("/streamed-chunked2");
  2614. ASSERT_TRUE(res);
  2615. EXPECT_EQ(200, res->status);
  2616. EXPECT_EQ(std::string("123456789"), res->body);
  2617. }
  2618. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2619. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2620. ASSERT_TRUE(res);
  2621. EXPECT_EQ(200, res->status);
  2622. EXPECT_EQ(std::string("123456789"), res->body);
  2623. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2624. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2625. }
  2626. TEST_F(ServerTest, LargeChunkedPost) {
  2627. Request req;
  2628. req.method = "POST";
  2629. req.path = "/large-chunked";
  2630. std::string host_and_port;
  2631. host_and_port += HOST;
  2632. host_and_port += ":";
  2633. host_and_port += std::to_string(PORT);
  2634. req.headers.emplace("Host", host_and_port.c_str());
  2635. req.headers.emplace("Accept", "*/*");
  2636. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2637. req.headers.emplace("Content-Type", "text/plain");
  2638. req.headers.emplace("Content-Length", "0");
  2639. req.headers.emplace("Transfer-Encoding", "chunked");
  2640. std::string long_string(30 * 1024u, 'a');
  2641. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2642. // Attempt to make a large enough post to exceed OS buffers, to test that
  2643. // the server handles short reads if the full chunk data isn't available.
  2644. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2645. auto res = std::make_shared<Response>();
  2646. auto error = Error::Success;
  2647. auto ret = cli_.send(req, *res, error);
  2648. ASSERT_TRUE(ret);
  2649. EXPECT_EQ(200, res->status);
  2650. }
  2651. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2652. auto res = cli_.Get("/remote_addr");
  2653. ASSERT_TRUE(res);
  2654. EXPECT_EQ(200, res->status);
  2655. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2656. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2657. }
  2658. TEST_F(ServerTest, GetMethodLocalAddr) {
  2659. auto res = cli_.Get("/local_addr");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(200, res->status);
  2662. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2663. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2664. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2665. }
  2666. TEST_F(ServerTest, HTTPResponseSplitting) {
  2667. auto res = cli_.Get("/http_response_splitting");
  2668. ASSERT_TRUE(res);
  2669. EXPECT_EQ(200, res->status);
  2670. }
  2671. TEST_F(ServerTest, SlowRequest) {
  2672. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2673. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2674. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2675. }
  2676. #if 0
  2677. TEST_F(ServerTest, SlowPost) {
  2678. char buffer[64 * 1024];
  2679. memset(buffer, 0x42, sizeof(buffer));
  2680. auto res = cli_.Post(
  2681. "/slowpost", 64 * 1024 * 1024,
  2682. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2683. auto ret = sink.write(buffer, sizeof(buffer));
  2684. EXPECT_TRUE(ret);
  2685. return true;
  2686. },
  2687. "text/plain");
  2688. ASSERT_TRUE(res);
  2689. EXPECT_EQ(200, res->status);
  2690. }
  2691. TEST_F(ServerTest, SlowPostFail) {
  2692. char buffer[64 * 1024];
  2693. memset(buffer, 0x42, sizeof(buffer));
  2694. cli_.set_write_timeout(std::chrono::seconds(0));
  2695. auto res = cli_.Post(
  2696. "/slowpost", 64 * 1024 * 1024,
  2697. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2698. sink.write(buffer, sizeof(buffer));
  2699. return true;
  2700. },
  2701. "text/plain");
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_EQ(Error::Write, res.error());
  2704. }
  2705. #endif
  2706. TEST_F(ServerTest, Put) {
  2707. auto res = cli_.Put("/put", "PUT", "text/plain");
  2708. ASSERT_TRUE(res);
  2709. EXPECT_EQ(200, res->status);
  2710. EXPECT_EQ("PUT", res->body);
  2711. }
  2712. TEST_F(ServerTest, PutWithContentProvider) {
  2713. auto res = cli_.Put(
  2714. "/put", 3,
  2715. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2716. sink.os << "PUT";
  2717. return true;
  2718. },
  2719. "text/plain");
  2720. ASSERT_TRUE(res);
  2721. EXPECT_EQ(200, res->status);
  2722. EXPECT_EQ("PUT", res->body);
  2723. }
  2724. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2725. auto res = cli_.Post(
  2726. "/post", 42,
  2727. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2728. return false;
  2729. },
  2730. "text/plain");
  2731. ASSERT_TRUE(!res);
  2732. EXPECT_EQ(Error::Canceled, res.error());
  2733. }
  2734. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2735. auto res = cli_.Put(
  2736. "/put",
  2737. [](size_t /*offset*/, DataSink &sink) {
  2738. sink.os << "PUT";
  2739. sink.done();
  2740. return true;
  2741. },
  2742. "text/plain");
  2743. ASSERT_TRUE(res);
  2744. EXPECT_EQ(200, res->status);
  2745. EXPECT_EQ("PUT", res->body);
  2746. }
  2747. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2748. auto res = cli_.Post(
  2749. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2750. "text/plain");
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2755. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2756. cli_.set_compress(true);
  2757. auto res = cli_.Put(
  2758. "/put", 3,
  2759. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2760. sink.os << "PUT";
  2761. return true;
  2762. },
  2763. "text/plain");
  2764. ASSERT_TRUE(res);
  2765. EXPECT_EQ(200, res->status);
  2766. EXPECT_EQ("PUT", res->body);
  2767. }
  2768. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2769. cli_.set_compress(true);
  2770. auto res = cli_.Post(
  2771. "/post", 42,
  2772. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2773. return false;
  2774. },
  2775. "text/plain");
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2780. cli_.set_compress(true);
  2781. auto res = cli_.Put(
  2782. "/put",
  2783. [](size_t /*offset*/, DataSink &sink) {
  2784. sink.os << "PUT";
  2785. sink.done();
  2786. return true;
  2787. },
  2788. "text/plain");
  2789. ASSERT_TRUE(res);
  2790. EXPECT_EQ(200, res->status);
  2791. EXPECT_EQ("PUT", res->body);
  2792. }
  2793. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2794. cli_.set_compress(true);
  2795. auto res = cli_.Post(
  2796. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2797. "text/plain");
  2798. ASSERT_TRUE(!res);
  2799. EXPECT_EQ(Error::Canceled, res.error());
  2800. }
  2801. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2802. cli_.set_compress(true);
  2803. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2804. ASSERT_TRUE(res);
  2805. EXPECT_EQ(200, res->status);
  2806. EXPECT_EQ(LARGE_DATA, res->body);
  2807. }
  2808. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2809. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2810. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2811. Client cli(s.c_str());
  2812. cli.enable_server_certificate_verification(false);
  2813. #else
  2814. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2815. Client cli(s.c_str());
  2816. #endif
  2817. cli.set_compress(true);
  2818. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2819. ASSERT_TRUE(res);
  2820. EXPECT_EQ(200, res->status);
  2821. EXPECT_EQ(LARGE_DATA, res->body);
  2822. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  2823. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2824. }
  2825. TEST_F(ServerTest, PutContentWithDeflate) {
  2826. cli_.set_compress(false);
  2827. Headers headers;
  2828. headers.emplace("Content-Encoding", "deflate");
  2829. // PUT in deflate format:
  2830. auto res = cli_.Put("/put", headers,
  2831. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2832. ASSERT_TRUE(res);
  2833. EXPECT_EQ(200, res->status);
  2834. EXPECT_EQ("PUT", res->body);
  2835. }
  2836. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2837. Headers headers;
  2838. headers.emplace("Accept-Encoding", "gzip, deflate");
  2839. auto res = cli_.Get("/streamed-chunked", headers);
  2840. ASSERT_TRUE(res);
  2841. EXPECT_EQ(200, res->status);
  2842. EXPECT_EQ(std::string("123456789"), res->body);
  2843. }
  2844. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2845. Headers headers;
  2846. headers.emplace("Accept-Encoding", "gzip, deflate");
  2847. auto res = cli_.Get("/streamed-chunked2", headers);
  2848. ASSERT_TRUE(res);
  2849. EXPECT_EQ(200, res->status);
  2850. EXPECT_EQ(std::string("123456789"), res->body);
  2851. }
  2852. TEST(GzipDecompressor, ChunkedDecompression) {
  2853. std::string data;
  2854. for (size_t i = 0; i < 32 * 1024; ++i) {
  2855. data.push_back(static_cast<char>('a' + i % 26));
  2856. }
  2857. std::string compressed_data;
  2858. {
  2859. httplib::detail::gzip_compressor compressor;
  2860. bool result = compressor.compress(
  2861. data.data(), data.size(),
  2862. /*last=*/true,
  2863. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2864. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2865. compressed_data_size);
  2866. return true;
  2867. });
  2868. ASSERT_TRUE(result);
  2869. }
  2870. std::string decompressed_data;
  2871. {
  2872. httplib::detail::gzip_decompressor decompressor;
  2873. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2874. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2875. size_t chunk_size = 130;
  2876. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2877. chunk_begin += chunk_size) {
  2878. size_t current_chunk_size =
  2879. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2880. bool result = decompressor.decompress(
  2881. compressed_data.data() + chunk_begin, current_chunk_size,
  2882. [&](const char *decompressed_data_chunk,
  2883. size_t decompressed_data_chunk_size) {
  2884. decompressed_data.insert(decompressed_data.size(),
  2885. decompressed_data_chunk,
  2886. decompressed_data_chunk_size);
  2887. return true;
  2888. });
  2889. ASSERT_TRUE(result);
  2890. }
  2891. }
  2892. ASSERT_EQ(data, decompressed_data);
  2893. }
  2894. TEST(GzipDecompressor, DeflateDecompression) {
  2895. std::string original_text = "Raw deflate without gzip";
  2896. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2897. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2898. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2899. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  2900. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2901. std::string decompressed_data;
  2902. {
  2903. httplib::detail::gzip_decompressor decompressor;
  2904. bool result = decompressor.decompress(
  2905. compressed_data.data(), compressed_data.size(),
  2906. [&](const char *decompressed_data_chunk,
  2907. size_t decompressed_data_chunk_size) {
  2908. decompressed_data.insert(decompressed_data.size(),
  2909. decompressed_data_chunk,
  2910. decompressed_data_chunk_size);
  2911. return true;
  2912. });
  2913. ASSERT_TRUE(result);
  2914. }
  2915. ASSERT_EQ(original_text, decompressed_data);
  2916. }
  2917. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  2918. std::string original_text = "Raw deflate without gzip";
  2919. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2920. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2921. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2922. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  2923. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  2924. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2925. std::string decompressed_data;
  2926. {
  2927. httplib::detail::gzip_decompressor decompressor;
  2928. bool result = decompressor.decompress(
  2929. compressed_data.data(), compressed_data.size(),
  2930. [&](const char *decompressed_data_chunk,
  2931. size_t decompressed_data_chunk_size) {
  2932. decompressed_data.insert(decompressed_data.size(),
  2933. decompressed_data_chunk,
  2934. decompressed_data_chunk_size);
  2935. return true;
  2936. });
  2937. ASSERT_TRUE(result);
  2938. }
  2939. ASSERT_EQ(original_text, decompressed_data);
  2940. }
  2941. #ifdef _WIN32
  2942. TEST(GzipDecompressor, LargeRandomData) {
  2943. // prepare large random data that is difficult to be compressed and is
  2944. // expected to have large size even when compressed
  2945. std::random_device seed_gen;
  2946. std::mt19937 random(seed_gen());
  2947. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2948. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2949. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2950. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2951. // compress data over 4GiB
  2952. std::string compressed_data;
  2953. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2954. httplib::detail::gzip_compressor compressor;
  2955. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2956. data.size() * sizeof(std::uint32_t), true,
  2957. [&](const char *data, size_t size) {
  2958. compressed_data.insert(
  2959. compressed_data.size(), data, size);
  2960. return true;
  2961. });
  2962. ASSERT_TRUE(result);
  2963. // FIXME: compressed data size is expected to be greater than 4GiB,
  2964. // but there is no guarantee
  2965. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2966. // decompress data over 4GiB
  2967. std::string decompressed_data;
  2968. decompressed_data.reserve(data_size);
  2969. httplib::detail::gzip_decompressor decompressor;
  2970. result = decompressor.decompress(
  2971. compressed_data.data(), compressed_data.size(),
  2972. [&](const char *data, size_t size) {
  2973. decompressed_data.insert(decompressed_data.size(), data, size);
  2974. return true;
  2975. });
  2976. ASSERT_TRUE(result);
  2977. // compare
  2978. ASSERT_EQ(data_size, decompressed_data.size());
  2979. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2980. 0);
  2981. }
  2982. #endif
  2983. #endif
  2984. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2985. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2986. Headers headers;
  2987. headers.emplace("Accept-Encoding", "br");
  2988. auto res = cli_.Get("/streamed-chunked", headers);
  2989. ASSERT_TRUE(res);
  2990. EXPECT_EQ(200, res->status);
  2991. EXPECT_EQ(std::string("123456789"), res->body);
  2992. }
  2993. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2994. Headers headers;
  2995. headers.emplace("Accept-Encoding", "br");
  2996. auto res = cli_.Get("/streamed-chunked2", headers);
  2997. ASSERT_TRUE(res);
  2998. EXPECT_EQ(200, res->status);
  2999. EXPECT_EQ(std::string("123456789"), res->body);
  3000. }
  3001. #endif
  3002. TEST_F(ServerTest, Patch) {
  3003. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3004. ASSERT_TRUE(res);
  3005. EXPECT_EQ(200, res->status);
  3006. EXPECT_EQ("PATCH", res->body);
  3007. }
  3008. TEST_F(ServerTest, Delete) {
  3009. auto res = cli_.Delete("/delete");
  3010. ASSERT_TRUE(res);
  3011. EXPECT_EQ(200, res->status);
  3012. EXPECT_EQ("DELETE", res->body);
  3013. }
  3014. TEST_F(ServerTest, DeleteContentReceiver) {
  3015. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3016. ASSERT_TRUE(res);
  3017. EXPECT_EQ(200, res->status);
  3018. EXPECT_EQ("content", res->body);
  3019. }
  3020. TEST_F(ServerTest, Options) {
  3021. auto res = cli_.Options("*");
  3022. ASSERT_TRUE(res);
  3023. EXPECT_EQ(200, res->status);
  3024. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3025. EXPECT_TRUE(res->body.empty());
  3026. }
  3027. TEST_F(ServerTest, URL) {
  3028. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3029. ASSERT_TRUE(res);
  3030. EXPECT_EQ(200, res->status);
  3031. }
  3032. TEST_F(ServerTest, ArrayParam) {
  3033. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3034. ASSERT_TRUE(res);
  3035. EXPECT_EQ(200, res->status);
  3036. }
  3037. TEST_F(ServerTest, NoMultipleHeaders) {
  3038. Headers headers = {{"Content-Length", "5"}};
  3039. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3040. "text/plain");
  3041. ASSERT_TRUE(res);
  3042. EXPECT_EQ(200, res->status);
  3043. }
  3044. TEST_F(ServerTest, PostContentReceiver) {
  3045. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3046. ASSERT_TRUE(res);
  3047. ASSERT_EQ(200, res->status);
  3048. ASSERT_EQ("content", res->body);
  3049. }
  3050. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3051. MultipartFormDataItems items = {
  3052. {"text1", "text default", "", ""},
  3053. {"text2", "aωb", "", ""},
  3054. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3055. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3056. {"file3", "", "", "application/octet-stream"},
  3057. };
  3058. auto res = cli_.Post("/content_receiver", items);
  3059. ASSERT_TRUE(res);
  3060. EXPECT_EQ(200, res->status);
  3061. }
  3062. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3063. MultipartFormDataItems items = {
  3064. {"text1", "text default", "", ""},
  3065. {"text2", "aωb", "", ""},
  3066. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3067. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3068. {"file3", "", "", "application/octet-stream"},
  3069. };
  3070. auto boundary = std::string("+++++");
  3071. std::string body;
  3072. for (const auto &item : items) {
  3073. body += "--" + boundary + "\r\n";
  3074. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3075. if (!item.filename.empty()) {
  3076. body += "; filename=\"" + item.filename + "\"";
  3077. }
  3078. body += "\r\n";
  3079. if (!item.content_type.empty()) {
  3080. body += "Content-Type: " + item.content_type + "\r\n";
  3081. }
  3082. body += "\r\n";
  3083. body += item.content + "\r\n";
  3084. }
  3085. body += "--" + boundary + "--\r\n";
  3086. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3087. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3088. ASSERT_TRUE(res);
  3089. EXPECT_EQ(200, res->status);
  3090. }
  3091. TEST_F(ServerTest, PostContentReceiverGzip) {
  3092. cli_.set_compress(true);
  3093. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3094. ASSERT_TRUE(res);
  3095. ASSERT_EQ(200, res->status);
  3096. ASSERT_EQ("content", res->body);
  3097. }
  3098. TEST_F(ServerTest, PutContentReceiver) {
  3099. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3100. ASSERT_TRUE(res);
  3101. ASSERT_EQ(200, res->status);
  3102. ASSERT_EQ("content", res->body);
  3103. }
  3104. TEST_F(ServerTest, PatchContentReceiver) {
  3105. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3106. ASSERT_TRUE(res);
  3107. ASSERT_EQ(200, res->status);
  3108. ASSERT_EQ("content", res->body);
  3109. }
  3110. TEST_F(ServerTest, PostQueryStringAndBody) {
  3111. auto res =
  3112. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3113. ASSERT_TRUE(res);
  3114. ASSERT_EQ(200, res->status);
  3115. }
  3116. TEST_F(ServerTest, HTTP2Magic) {
  3117. Request req;
  3118. req.method = "PRI";
  3119. req.path = "*";
  3120. req.body = "SM";
  3121. auto res = std::make_shared<Response>();
  3122. auto error = Error::Success;
  3123. auto ret = cli_.send(req, *res, error);
  3124. ASSERT_TRUE(ret);
  3125. EXPECT_EQ(400, res->status);
  3126. }
  3127. TEST_F(ServerTest, KeepAlive) {
  3128. auto res = cli_.Get("/hi");
  3129. ASSERT_TRUE(res);
  3130. EXPECT_EQ(200, res->status);
  3131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3132. EXPECT_EQ("Hello World!", res->body);
  3133. res = cli_.Get("/hi");
  3134. ASSERT_TRUE(res);
  3135. EXPECT_EQ(200, res->status);
  3136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3137. EXPECT_EQ("Hello World!", res->body);
  3138. res = cli_.Get("/hi");
  3139. ASSERT_TRUE(res);
  3140. EXPECT_EQ(200, res->status);
  3141. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. res = cli_.Get("/not-exist");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(404, res->status);
  3146. res = cli_.Post("/empty", "", "text/plain");
  3147. ASSERT_TRUE(res);
  3148. EXPECT_EQ(200, res->status);
  3149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3150. EXPECT_EQ("empty", res->body);
  3151. EXPECT_EQ("close", res->get_header_value("Connection"));
  3152. res = cli_.Post(
  3153. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3154. "text/plain");
  3155. ASSERT_TRUE(res);
  3156. EXPECT_EQ(200, res->status);
  3157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3158. EXPECT_EQ("empty", res->body);
  3159. cli_.set_keep_alive(false);
  3160. res = cli_.Get("/last-request");
  3161. ASSERT_TRUE(res);
  3162. EXPECT_EQ(200, res->status);
  3163. EXPECT_EQ("close", res->get_header_value("Connection"));
  3164. }
  3165. TEST_F(ServerTest, TooManyRedirect) {
  3166. cli_.set_follow_location(true);
  3167. auto res = cli_.Get("/redirect/0");
  3168. ASSERT_TRUE(!res);
  3169. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3170. }
  3171. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3172. TEST_F(ServerTest, Gzip) {
  3173. Headers headers;
  3174. headers.emplace("Accept-Encoding", "gzip, deflate");
  3175. auto res = cli_.Get("/compress", headers);
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3180. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3181. "7890123456789012345678901234567890",
  3182. res->body);
  3183. EXPECT_EQ(200, res->status);
  3184. }
  3185. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3186. auto res = cli_.Get("/compress");
  3187. ASSERT_TRUE(res);
  3188. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3190. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3191. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3192. "7890123456789012345678901234567890",
  3193. res->body);
  3194. EXPECT_EQ(200, res->status);
  3195. }
  3196. TEST_F(ServerTest, GzipWithContentReceiver) {
  3197. Headers headers;
  3198. headers.emplace("Accept-Encoding", "gzip, deflate");
  3199. std::string body;
  3200. auto res = cli_.Get("/compress", headers,
  3201. [&](const char *data, uint64_t data_length) {
  3202. EXPECT_EQ(100U, data_length);
  3203. body.append(data, data_length);
  3204. return true;
  3205. });
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3209. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3210. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3211. "7890123456789012345678901234567890",
  3212. body);
  3213. EXPECT_EQ(200, res->status);
  3214. }
  3215. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3216. Headers headers;
  3217. headers.emplace("Accept-Encoding", "gzip, deflate");
  3218. cli_.set_decompress(false);
  3219. auto res = cli_.Get("/compress", headers);
  3220. ASSERT_TRUE(res);
  3221. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3223. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3224. EXPECT_EQ(33U, res->body.size());
  3225. EXPECT_EQ(200, res->status);
  3226. }
  3227. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3228. std::string body;
  3229. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3230. EXPECT_EQ(100U, data_length);
  3231. body.append(data, data_length);
  3232. return true;
  3233. });
  3234. ASSERT_TRUE(res);
  3235. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3237. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3238. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3239. "7890123456789012345678901234567890",
  3240. body);
  3241. EXPECT_EQ(200, res->status);
  3242. }
  3243. TEST_F(ServerTest, NoGzip) {
  3244. Headers headers;
  3245. headers.emplace("Accept-Encoding", "gzip, deflate");
  3246. auto res = cli_.Get("/nocompress", headers);
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3249. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3250. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3251. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3252. "7890123456789012345678901234567890",
  3253. res->body);
  3254. EXPECT_EQ(200, res->status);
  3255. }
  3256. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3257. Headers headers;
  3258. headers.emplace("Accept-Encoding", "gzip, deflate");
  3259. std::string body;
  3260. auto res = cli_.Get("/nocompress", headers,
  3261. [&](const char *data, uint64_t data_length) {
  3262. EXPECT_EQ(100U, data_length);
  3263. body.append(data, data_length);
  3264. return true;
  3265. });
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3268. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3269. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3270. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3271. "7890123456789012345678901234567890",
  3272. body);
  3273. EXPECT_EQ(200, res->status);
  3274. }
  3275. TEST_F(ServerTest, MultipartFormDataGzip) {
  3276. MultipartFormDataItems items = {
  3277. {"key1", "test", "", ""},
  3278. {"key2", "--abcdefg123", "", ""},
  3279. };
  3280. cli_.set_compress(true);
  3281. auto res = cli_.Post("/compress-multipart", items);
  3282. ASSERT_TRUE(res);
  3283. EXPECT_EQ(200, res->status);
  3284. }
  3285. #endif
  3286. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3287. TEST_F(ServerTest, Brotli) {
  3288. Headers headers;
  3289. headers.emplace("Accept-Encoding", "br");
  3290. auto res = cli_.Get("/compress", headers);
  3291. ASSERT_TRUE(res);
  3292. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3294. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3295. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3296. "7890123456789012345678901234567890",
  3297. res->body);
  3298. EXPECT_EQ(200, res->status);
  3299. }
  3300. #endif
  3301. // Sends a raw request to a server listening at HOST:PORT.
  3302. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3303. std::string *resp = nullptr) {
  3304. auto error = Error::Success;
  3305. auto client_sock = detail::create_client_socket(
  3306. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3307. /*connection_timeout_sec=*/5, 0,
  3308. /*read_timeout_sec=*/5, 0,
  3309. /*write_timeout_sec=*/5, 0, std::string(), error);
  3310. if (client_sock == INVALID_SOCKET) { return false; }
  3311. auto ret = detail::process_client_socket(
  3312. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3313. if (req.size() !=
  3314. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3315. return false;
  3316. }
  3317. char buf[512];
  3318. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3319. while (line_reader.getline()) {
  3320. if (resp) { *resp += line_reader.ptr(); }
  3321. }
  3322. return true;
  3323. });
  3324. detail::close_socket(client_sock);
  3325. return ret;
  3326. }
  3327. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3328. Server svr;
  3329. std::string header_value;
  3330. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3331. header_value = req.get_header_value("foo");
  3332. res.set_content("ok", "text/plain");
  3333. });
  3334. thread t = thread([&] { svr.listen(HOST, PORT); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. t.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3342. // like characters are not treated the same - use vertical tab and escape.
  3343. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3344. "foo: \t \v bar \x1B\t \r\n"
  3345. "Connection: close\r\n"
  3346. "\r\n";
  3347. ASSERT_TRUE(send_request(5, req));
  3348. EXPECT_EQ(header_value, "\v bar \x1B");
  3349. }
  3350. // Sends a raw request and verifies that there isn't a crash or exception.
  3351. static void test_raw_request(const std::string &req,
  3352. std::string *out = nullptr) {
  3353. Server svr;
  3354. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3355. res.set_content("ok", "text/plain");
  3356. });
  3357. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3358. res.set_content("ok", "text/plain");
  3359. });
  3360. // Server read timeout must be longer than the client read timeout for the
  3361. // bug to reproduce, probably to force the server to process a request
  3362. // without a trailing blank line.
  3363. const time_t client_read_timeout_sec = 1;
  3364. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3365. bool listen_thread_ok = false;
  3366. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3367. auto se = detail::scope_exit([&] {
  3368. svr.stop();
  3369. t.join();
  3370. ASSERT_FALSE(svr.is_running());
  3371. EXPECT_TRUE(listen_thread_ok);
  3372. });
  3373. svr.wait_until_ready();
  3374. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3375. }
  3376. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3377. // A certain header line causes an exception if the header property is parsed
  3378. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3379. test_raw_request(
  3380. "GET /hi HTTP/1.1\r\n"
  3381. " : "
  3382. " "
  3383. " ");
  3384. }
  3385. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3386. // A certain header line causes an exception if the header property *name* is
  3387. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3388. // greedy matcher and requires backtracking when there are a lot of ":"
  3389. // characters.
  3390. // This occurs with libc++ but not libstdc++.
  3391. test_raw_request(
  3392. "GET /hi HTTP/1.1\r\n"
  3393. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3394. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3395. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3396. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3397. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3398. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3399. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3400. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3401. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3402. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3403. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3404. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3405. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3406. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3407. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3408. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3409. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3410. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3411. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3412. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3413. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3414. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3415. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3416. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3417. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3418. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3419. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3420. "&&&%%%");
  3421. }
  3422. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3423. // Make sure this doesn't crash the server.
  3424. // In a previous version of the header line regex, the "\r" rendered the line
  3425. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3426. // a new position where the leading white space ended and the field value
  3427. // began.
  3428. // The crash occurs with libc++ but not libstdc++.
  3429. test_raw_request("GET /hi HTTP/1.1\r\n"
  3430. "a:" +
  3431. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3432. "\r\n"
  3433. "\r\n");
  3434. }
  3435. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3436. std::string out;
  3437. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3438. "Content-Type: text/plain\r\n"
  3439. "Transfer-Encoding: chunked\r\n"
  3440. "\r\n"
  3441. "nothex\r\n",
  3442. &out);
  3443. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3444. }
  3445. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3446. std::string out;
  3447. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3448. "Content-Type: text/plain\r\n"
  3449. "Transfer-Encoding: chunked\r\n"
  3450. "\r\n"
  3451. "3\r\n"
  3452. "xyz\r\n"
  3453. "NaN\r\n",
  3454. &out);
  3455. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3456. }
  3457. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3458. std::string out;
  3459. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3460. "Content-Type: text/plain\r\n"
  3461. "Transfer-Encoding: chunked\r\n"
  3462. "\r\n"
  3463. // Length is too large for 64 bits.
  3464. "1ffffffffffffffff\r\n"
  3465. "xyz\r\n",
  3466. &out);
  3467. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3468. }
  3469. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3470. test_raw_request("GET /hi HTTP/1.1\r\n"
  3471. "Content-Type: text/plain\r\n\r");
  3472. }
  3473. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3474. std::string out;
  3475. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3476. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3477. }
  3478. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3479. Server svr;
  3480. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3481. res.set_header("Cache-Control", "no-cache");
  3482. res.set_chunked_content_provider(
  3483. "text/event-stream", [](size_t offset, DataSink &sink) {
  3484. std::string s = "data:";
  3485. s += std::to_string(offset);
  3486. s += "\n\n";
  3487. auto ret = sink.write(s.data(), s.size());
  3488. EXPECT_TRUE(ret);
  3489. std::this_thread::sleep_for(std::chrono::seconds(1));
  3490. return true;
  3491. });
  3492. });
  3493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3494. svr.wait_until_ready();
  3495. Client client(HOST, PORT);
  3496. const Headers headers = {{"Accept", "text/event-stream"}};
  3497. auto get_thread = std::thread([&client, &headers]() {
  3498. auto res = client.Get(
  3499. "/events", headers,
  3500. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3501. });
  3502. auto se = detail::scope_exit([&] {
  3503. svr.stop();
  3504. get_thread.join();
  3505. listen_thread.join();
  3506. ASSERT_FALSE(svr.is_running());
  3507. });
  3508. // Give GET time to get a few messages.
  3509. std::this_thread::sleep_for(std::chrono::seconds(2));
  3510. }
  3511. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3512. httplib::Server svr;
  3513. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3514. httplib::Response &res) { res.status = 200; });
  3515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3516. svr.wait_until_ready();
  3517. Client cli(HOST, PORT);
  3518. auto res = cli.Post("/hi", "data", "text/plain");
  3519. ASSERT_TRUE(res);
  3520. EXPECT_EQ(200, res->status);
  3521. svr.stop();
  3522. thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. res = cli.Post("/hi", "data", "text/plain");
  3525. ASSERT_FALSE(res);
  3526. }
  3527. TEST(ServerStopTest, ListenFailure) {
  3528. Server svr;
  3529. auto t = thread([&]() {
  3530. auto ret = svr.listen("????", PORT);
  3531. EXPECT_FALSE(ret);
  3532. });
  3533. svr.wait_until_ready();
  3534. svr.stop();
  3535. t.join();
  3536. }
  3537. TEST(StreamingTest, NoContentLengthStreaming) {
  3538. Server svr;
  3539. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3540. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3541. if (offset < 6) {
  3542. sink.os << (offset < 3 ? "a" : "b");
  3543. } else {
  3544. sink.done();
  3545. }
  3546. return true;
  3547. });
  3548. });
  3549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3550. auto listen_se = detail::scope_exit([&] {
  3551. svr.stop();
  3552. listen_thread.join();
  3553. ASSERT_FALSE(svr.is_running());
  3554. });
  3555. svr.wait_until_ready();
  3556. Client client(HOST, PORT);
  3557. auto get_thread = std::thread([&client]() {
  3558. std::string s;
  3559. auto res =
  3560. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3561. s += std::string(data, len);
  3562. return true;
  3563. });
  3564. EXPECT_EQ("aaabbb", s);
  3565. });
  3566. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3567. // Give GET time to get a few messages.
  3568. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3569. }
  3570. TEST(MountTest, Unmount) {
  3571. Server svr;
  3572. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3573. auto se = detail::scope_exit([&] {
  3574. svr.stop();
  3575. listen_thread.join();
  3576. ASSERT_FALSE(svr.is_running());
  3577. });
  3578. svr.wait_until_ready();
  3579. // Give GET time to get a few messages.
  3580. std::this_thread::sleep_for(std::chrono::seconds(1));
  3581. Client cli("localhost", PORT);
  3582. svr.set_mount_point("/mount2", "./www2");
  3583. auto res = cli.Get("/");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(404, res->status);
  3586. res = cli.Get("/mount2/dir/test.html");
  3587. ASSERT_TRUE(res);
  3588. EXPECT_EQ(200, res->status);
  3589. svr.set_mount_point("/", "./www");
  3590. res = cli.Get("/dir/");
  3591. ASSERT_TRUE(res);
  3592. EXPECT_EQ(200, res->status);
  3593. svr.remove_mount_point("/");
  3594. res = cli.Get("/dir/");
  3595. ASSERT_TRUE(res);
  3596. EXPECT_EQ(404, res->status);
  3597. svr.remove_mount_point("/mount2");
  3598. res = cli.Get("/mount2/dir/test.html");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(404, res->status);
  3601. }
  3602. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3603. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3604. Server svr;
  3605. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3606. throw std::runtime_error("exception...");
  3607. });
  3608. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3609. throw std::runtime_error("exception\r\n...");
  3610. });
  3611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. listen_thread.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. // Give GET time to get a few messages.
  3619. std::this_thread::sleep_for(std::chrono::seconds(1));
  3620. Client cli("localhost", PORT);
  3621. {
  3622. auto res = cli.Get("/exception");
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(500, res->status);
  3625. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3626. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3627. }
  3628. {
  3629. auto res = cli.Get("/unknown");
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(500, res->status);
  3632. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3633. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3634. }
  3635. }
  3636. #endif
  3637. TEST(KeepAliveTest, ReadTimeout) {
  3638. Server svr;
  3639. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3640. std::this_thread::sleep_for(std::chrono::seconds(2));
  3641. res.set_content("a", "text/plain");
  3642. });
  3643. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3644. res.set_content("b", "text/plain");
  3645. });
  3646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3647. auto se = detail::scope_exit([&] {
  3648. svr.stop();
  3649. listen_thread.join();
  3650. ASSERT_FALSE(svr.is_running());
  3651. });
  3652. svr.wait_until_ready();
  3653. // Give GET time to get a few messages.
  3654. std::this_thread::sleep_for(std::chrono::seconds(1));
  3655. Client cli("localhost", PORT);
  3656. cli.set_keep_alive(true);
  3657. cli.set_read_timeout(std::chrono::seconds(1));
  3658. auto resa = cli.Get("/a");
  3659. ASSERT_FALSE(resa);
  3660. EXPECT_EQ(Error::Read, resa.error());
  3661. auto resb = cli.Get("/b");
  3662. ASSERT_TRUE(resb);
  3663. EXPECT_EQ(200, resb->status);
  3664. EXPECT_EQ("b", resb->body);
  3665. }
  3666. TEST(KeepAliveTest, Issue1041) {
  3667. Server svr;
  3668. svr.set_keep_alive_timeout(3);
  3669. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3670. res.set_content("Hello World!", "text/plain");
  3671. });
  3672. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. listen_thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3679. Client cli(HOST, PORT);
  3680. cli.set_keep_alive(true);
  3681. auto result = cli.Get("/hi");
  3682. ASSERT_TRUE(result);
  3683. EXPECT_EQ(200, result->status);
  3684. std::this_thread::sleep_for(std::chrono::seconds(5));
  3685. result = cli.Get("/hi");
  3686. ASSERT_TRUE(result);
  3687. EXPECT_EQ(200, result->status);
  3688. }
  3689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3690. TEST(KeepAliveTest, SSLClientReconnection) {
  3691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3692. ASSERT_TRUE(svr.is_valid());
  3693. svr.set_keep_alive_timeout(1);
  3694. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3695. res.set_content("Hello World!", "text/plain");
  3696. });
  3697. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3698. auto se = detail::scope_exit([&] {
  3699. svr.stop();
  3700. listen_thread.join();
  3701. ASSERT_FALSE(svr.is_running());
  3702. });
  3703. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3704. SSLClient cli(HOST, PORT);
  3705. cli.enable_server_certificate_verification(false);
  3706. cli.set_keep_alive(true);
  3707. auto result = cli.Get("/hi");
  3708. ASSERT_TRUE(result);
  3709. EXPECT_EQ(200, result->status);
  3710. result = cli.Get("/hi");
  3711. ASSERT_TRUE(result);
  3712. EXPECT_EQ(200, result->status);
  3713. std::this_thread::sleep_for(std::chrono::seconds(2));
  3714. // Recoonect
  3715. result = cli.Get("/hi");
  3716. ASSERT_TRUE(result);
  3717. EXPECT_EQ(200, result->status);
  3718. result = cli.Get("/hi");
  3719. ASSERT_TRUE(result);
  3720. EXPECT_EQ(200, result->status);
  3721. }
  3722. #endif
  3723. TEST(ClientProblemDetectionTest, ContentProvider) {
  3724. Server svr;
  3725. size_t content_length = 1024 * 1024;
  3726. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3727. res.set_content_provider(
  3728. content_length, "text/plain",
  3729. [&](size_t offset, size_t length, DataSink &sink) {
  3730. auto out_len = std::min(length, static_cast<size_t>(1024));
  3731. std::string out(out_len, '@');
  3732. sink.write(out.data(), out_len);
  3733. return offset < 4096;
  3734. },
  3735. [](bool success) { ASSERT_FALSE(success); });
  3736. });
  3737. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3738. res.set_content_provider(
  3739. 0, "text/plain",
  3740. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3741. EXPECT_TRUE(false);
  3742. return true;
  3743. },
  3744. [](bool success) { ASSERT_FALSE(success); });
  3745. });
  3746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. listen_thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. // Give GET time to get a few messages.
  3754. std::this_thread::sleep_for(std::chrono::seconds(1));
  3755. Client cli("localhost", PORT);
  3756. {
  3757. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3758. size_t /*data_length*/) { return false; });
  3759. ASSERT_FALSE(res);
  3760. }
  3761. {
  3762. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3763. size_t /*data_length*/) { return false; });
  3764. ASSERT_TRUE(res);
  3765. }
  3766. }
  3767. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3768. Server svr;
  3769. svr.set_error_handler([](Request const &, Response &res) -> void {
  3770. res.set_chunked_content_provider(
  3771. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3772. sink.os << "hello";
  3773. sink.os << "world";
  3774. sink.done();
  3775. return true;
  3776. });
  3777. });
  3778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3779. auto se = detail::scope_exit([&] {
  3780. svr.stop();
  3781. listen_thread.join();
  3782. ASSERT_FALSE(svr.is_running());
  3783. });
  3784. svr.wait_until_ready();
  3785. // Give GET time to get a few messages.
  3786. std::this_thread::sleep_for(std::chrono::seconds(1));
  3787. Client cli("localhost", PORT);
  3788. auto res = cli.Get("/");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(404, res->status);
  3791. EXPECT_EQ("helloworld", res->body);
  3792. }
  3793. TEST(GetWithParametersTest, GetWithParameters) {
  3794. Server svr;
  3795. svr.Get("/", [&](const Request &req, Response &) {
  3796. EXPECT_EQ("world", req.get_param_value("hello"));
  3797. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3798. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3799. });
  3800. svr.Get("/params", [&](const Request &req, Response &) {
  3801. EXPECT_EQ("world", req.get_param_value("hello"));
  3802. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3803. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3804. });
  3805. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3806. EXPECT_EQ("resource-id", req.matches[1]);
  3807. EXPECT_EQ("foo", req.get_param_value("param1"));
  3808. EXPECT_EQ("bar", req.get_param_value("param2"));
  3809. });
  3810. svr.Get("/users/:id", [&](const Request &req, Response &) {
  3811. EXPECT_EQ("user-id", req.path_params.at("id"));
  3812. EXPECT_EQ("foo", req.get_param_value("param1"));
  3813. EXPECT_EQ("bar", req.get_param_value("param2"));
  3814. });
  3815. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. listen_thread.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. svr.wait_until_ready();
  3822. std::this_thread::sleep_for(std::chrono::seconds(1));
  3823. {
  3824. Client cli(HOST, PORT);
  3825. Params params;
  3826. params.emplace("hello", "world");
  3827. params.emplace("hello2", "world2");
  3828. params.emplace("hello3", "world3");
  3829. auto res = cli.Get("/", params, Headers{});
  3830. ASSERT_TRUE(res);
  3831. EXPECT_EQ(200, res->status);
  3832. }
  3833. {
  3834. Client cli(HOST, PORT);
  3835. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(200, res->status);
  3838. }
  3839. {
  3840. Client cli(HOST, PORT);
  3841. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(200, res->status);
  3844. }
  3845. {
  3846. Client cli(HOST, PORT);
  3847. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  3848. ASSERT_TRUE(res);
  3849. EXPECT_EQ(200, res->status);
  3850. }
  3851. }
  3852. TEST(GetWithParametersTest, GetWithParameters2) {
  3853. Server svr;
  3854. svr.Get("/", [&](const Request &req, Response &res) {
  3855. auto text = req.get_param_value("hello");
  3856. res.set_content(text, "text/plain");
  3857. });
  3858. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. listen_thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. std::this_thread::sleep_for(std::chrono::seconds(1));
  3866. Client cli("localhost", PORT);
  3867. Params params;
  3868. params.emplace("hello", "world");
  3869. std::string body;
  3870. auto res = cli.Get("/", params, Headers{},
  3871. [&](const char *data, size_t data_length) {
  3872. body.append(data, data_length);
  3873. return true;
  3874. });
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(200, res->status);
  3877. EXPECT_EQ("world", body);
  3878. }
  3879. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3880. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  3881. auto host = "httpbin.org";
  3882. auto path = std::string{"/range/32"};
  3883. #else
  3884. auto host = "nghttp2.org";
  3885. auto path = std::string{"/httpbin/range/32"};
  3886. #endif
  3887. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3888. SSLClient cli(host);
  3889. #else
  3890. Client cli(host);
  3891. #endif
  3892. cli.set_default_headers({make_range_header({{1, 10}})});
  3893. cli.set_connection_timeout(5);
  3894. {
  3895. auto res = cli.Get(path);
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ("bcdefghijk", res->body);
  3898. EXPECT_EQ(206, res->status);
  3899. }
  3900. {
  3901. auto res = cli.Get(path);
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ("bcdefghijk", res->body);
  3904. EXPECT_EQ(206, res->status);
  3905. }
  3906. }
  3907. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3908. Server svr;
  3909. svr.set_default_headers({{"Hello", "World"}});
  3910. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3911. res.set_content("ok", "text/plain");
  3912. });
  3913. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3914. auto se = detail::scope_exit([&] {
  3915. svr.stop();
  3916. listen_thread.join();
  3917. ASSERT_FALSE(svr.is_running());
  3918. });
  3919. svr.wait_until_ready();
  3920. std::this_thread::sleep_for(std::chrono::seconds(1));
  3921. Client cli("localhost", PORT);
  3922. auto res = cli.Get("/");
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(200, res->status);
  3925. EXPECT_EQ("ok", res->body);
  3926. EXPECT_EQ("World", res->get_header_value("Hello"));
  3927. }
  3928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3929. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3931. ASSERT_TRUE(svr.is_valid());
  3932. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3933. std::this_thread::sleep_for(std::chrono::seconds(2));
  3934. res.set_content("a", "text/plain");
  3935. });
  3936. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3937. res.set_content("b", "text/plain");
  3938. });
  3939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3940. auto se = detail::scope_exit([&] {
  3941. svr.stop();
  3942. listen_thread.join();
  3943. ASSERT_FALSE(svr.is_running());
  3944. });
  3945. svr.wait_until_ready();
  3946. // Give GET time to get a few messages.
  3947. std::this_thread::sleep_for(std::chrono::seconds(1));
  3948. SSLClient cli("localhost", PORT);
  3949. cli.enable_server_certificate_verification(false);
  3950. cli.set_keep_alive(true);
  3951. cli.set_read_timeout(std::chrono::seconds(1));
  3952. auto resa = cli.Get("/a");
  3953. ASSERT_TRUE(!resa);
  3954. EXPECT_EQ(Error::Read, resa.error());
  3955. auto resb = cli.Get("/b");
  3956. ASSERT_TRUE(resb);
  3957. EXPECT_EQ(200, resb->status);
  3958. EXPECT_EQ("b", resb->body);
  3959. }
  3960. #endif
  3961. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3962. protected:
  3963. ServerTestWithAI_PASSIVE()
  3964. : cli_(HOST, PORT)
  3965. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3966. ,
  3967. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3968. #endif
  3969. {
  3970. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3971. cli_.enable_server_certificate_verification(false);
  3972. #endif
  3973. }
  3974. virtual void SetUp() {
  3975. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3976. res.set_content("Hello World!", "text/plain");
  3977. });
  3978. t_ = thread(
  3979. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3980. while (!svr_.is_running()) {
  3981. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3982. }
  3983. }
  3984. virtual void TearDown() {
  3985. svr_.stop();
  3986. t_.join();
  3987. }
  3988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3989. SSLClient cli_;
  3990. SSLServer svr_;
  3991. #else
  3992. Client cli_;
  3993. Server svr_;
  3994. #endif
  3995. thread t_;
  3996. };
  3997. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3998. auto res = cli_.Get("/hi");
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(200, res->status);
  4001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4002. EXPECT_EQ("Hello World!", res->body);
  4003. }
  4004. class ServerUpDownTest : public ::testing::Test {
  4005. protected:
  4006. ServerUpDownTest() : cli_(HOST, PORT) {}
  4007. virtual void SetUp() {
  4008. t_ = thread([&]() {
  4009. svr_.bind_to_any_port(HOST);
  4010. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4011. ASSERT_TRUE(svr_.listen_after_bind());
  4012. });
  4013. while (!svr_.is_running()) {
  4014. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4015. }
  4016. }
  4017. virtual void TearDown() {
  4018. svr_.stop();
  4019. t_.join();
  4020. }
  4021. Client cli_;
  4022. Server svr_;
  4023. thread t_;
  4024. };
  4025. TEST_F(ServerUpDownTest, QuickStartStop) {
  4026. // Should not crash, especially when run with
  4027. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4028. }
  4029. class PayloadMaxLengthTest : public ::testing::Test {
  4030. protected:
  4031. PayloadMaxLengthTest()
  4032. : cli_(HOST, PORT)
  4033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4034. ,
  4035. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4036. #endif
  4037. {
  4038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4039. cli_.enable_server_certificate_verification(false);
  4040. #endif
  4041. }
  4042. virtual void SetUp() {
  4043. svr_.set_payload_max_length(8);
  4044. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4045. res.set_content("test", "text/plain");
  4046. });
  4047. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4048. while (!svr_.is_running()) {
  4049. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4050. }
  4051. }
  4052. virtual void TearDown() {
  4053. svr_.stop();
  4054. t_.join();
  4055. }
  4056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4057. SSLClient cli_;
  4058. SSLServer svr_;
  4059. #else
  4060. Client cli_;
  4061. Server svr_;
  4062. #endif
  4063. thread t_;
  4064. };
  4065. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4066. auto res = cli_.Post("/test", "123456789", "text/plain");
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(413, res->status);
  4069. res = cli_.Post("/test", "12345678", "text/plain");
  4070. ASSERT_TRUE(res);
  4071. EXPECT_EQ(200, res->status);
  4072. }
  4073. TEST(HostAndPortPropertiesTest, NoSSL) {
  4074. httplib::Client cli("www.google.com", 1234);
  4075. ASSERT_EQ("www.google.com", cli.host());
  4076. ASSERT_EQ(1234, cli.port());
  4077. }
  4078. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4079. httplib::Client cli("www.google.com:1234");
  4080. ASSERT_EQ("www.google.com", cli.host());
  4081. ASSERT_EQ(1234, cli.port());
  4082. }
  4083. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4084. TEST(HostAndPortPropertiesTest, SSL) {
  4085. httplib::SSLClient cli("www.google.com");
  4086. ASSERT_EQ("www.google.com", cli.host());
  4087. ASSERT_EQ(443, cli.port());
  4088. }
  4089. #endif
  4090. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4091. TEST(SSLClientTest, UpdateCAStore) {
  4092. httplib::SSLClient httplib_client("www.google.com");
  4093. auto ca_store_1 = X509_STORE_new();
  4094. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4095. nullptr);
  4096. httplib_client.set_ca_cert_store(ca_store_1);
  4097. auto ca_store_2 = X509_STORE_new();
  4098. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4099. nullptr);
  4100. httplib_client.set_ca_cert_store(ca_store_2);
  4101. }
  4102. TEST(SSLClientTest, ServerNameIndication_Online) {
  4103. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4104. auto host = "httpbin.org";
  4105. auto path = std::string{"/get"};
  4106. #else
  4107. auto host = "nghttp2.org";
  4108. auto path = std::string{"/httpbin/get"};
  4109. #endif
  4110. SSLClient cli(host, 443);
  4111. auto res = cli.Get(path);
  4112. ASSERT_TRUE(res);
  4113. ASSERT_EQ(200, res->status);
  4114. }
  4115. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4116. Client cli("https://google.com");
  4117. auto res = cli.Get("/");
  4118. ASSERT_TRUE(res);
  4119. ASSERT_EQ(301, res->status);
  4120. }
  4121. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4122. SSLClient cli("google.com");
  4123. cli.enable_server_certificate_verification(true);
  4124. cli.set_ca_cert_path("hello");
  4125. auto res = cli.Get("/");
  4126. ASSERT_TRUE(!res);
  4127. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4128. }
  4129. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4130. SSLClient cli("google.com");
  4131. cli.set_ca_cert_path(CA_CERT_FILE);
  4132. auto res = cli.Get("/");
  4133. ASSERT_TRUE(res);
  4134. ASSERT_EQ(301, res->status);
  4135. }
  4136. TEST(SSLClientTest, ServerCertificateVerification4) {
  4137. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4138. ASSERT_TRUE(svr.is_valid());
  4139. svr.Get("/test", [&](const Request &, Response &res) {
  4140. res.set_content("test", "text/plain");
  4141. svr.stop();
  4142. ASSERT_TRUE(true);
  4143. });
  4144. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4145. auto se = detail::scope_exit([&] {
  4146. t.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4150. SSLClient cli("127.0.0.1", PORT);
  4151. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4152. cli.enable_server_certificate_verification(true);
  4153. cli.set_connection_timeout(30);
  4154. auto res = cli.Get("/test");
  4155. ASSERT_TRUE(res);
  4156. ASSERT_EQ(200, res->status);
  4157. }
  4158. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4159. std::string cert;
  4160. detail::read_file(CA_CERT_FILE, cert);
  4161. SSLClient cli("google.com");
  4162. cli.load_ca_cert_store(cert.data(), cert.size());
  4163. const auto res = cli.Get("/");
  4164. ASSERT_TRUE(res);
  4165. ASSERT_EQ(301, res->status);
  4166. }
  4167. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4168. // clang-format off
  4169. static constexpr char cert[] =
  4170. "GlobalSign Root CA\n"
  4171. "==================\n"
  4172. "-----BEGIN CERTIFICATE-----\n"
  4173. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4174. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4175. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4176. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4177. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4178. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4179. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4180. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4181. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4182. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4183. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4184. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4185. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4186. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4187. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4188. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4189. "-----END CERTIFICATE-----\n";
  4190. // clang-format on
  4191. SSLClient cli("google.com");
  4192. cli.load_ca_cert_store(cert, sizeof(cert));
  4193. const auto res = cli.Get("/");
  4194. ASSERT_TRUE(res);
  4195. ASSERT_EQ(301, res->status);
  4196. }
  4197. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4198. SSLClient cli("www.youtube.com");
  4199. cli.set_ca_cert_path(CA_CERT_FILE);
  4200. cli.enable_server_certificate_verification(true);
  4201. cli.set_follow_location(true);
  4202. auto res = cli.Get("/");
  4203. ASSERT_TRUE(res);
  4204. ASSERT_EQ(200, res->status);
  4205. }
  4206. #if 0
  4207. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4208. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4209. ASSERT_TRUE(cli != nullptr);
  4210. cli->set_address_family(AF_INET6);
  4211. cli->set_interface("en0");
  4212. auto res = cli->Get("/get");
  4213. ASSERT_TRUE(res);
  4214. ASSERT_EQ(200, res->status);
  4215. }
  4216. #endif
  4217. TEST(SSLClientServerTest, ClientCertPresent) {
  4218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4219. CLIENT_CA_CERT_DIR);
  4220. ASSERT_TRUE(svr.is_valid());
  4221. svr.Get("/test", [&](const Request &req, Response &res) {
  4222. res.set_content("test", "text/plain");
  4223. svr.stop();
  4224. ASSERT_TRUE(true);
  4225. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4226. ASSERT_TRUE(peer_cert != nullptr);
  4227. auto subject_name = X509_get_subject_name(peer_cert);
  4228. ASSERT_TRUE(subject_name != nullptr);
  4229. std::string common_name;
  4230. {
  4231. char name[BUFSIZ];
  4232. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4233. name, sizeof(name));
  4234. common_name.assign(name, static_cast<size_t>(name_len));
  4235. }
  4236. EXPECT_EQ("Common Name", common_name);
  4237. X509_free(peer_cert);
  4238. });
  4239. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4240. auto se = detail::scope_exit([&] {
  4241. t.join();
  4242. ASSERT_FALSE(svr.is_running());
  4243. });
  4244. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4245. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4246. cli.enable_server_certificate_verification(false);
  4247. cli.set_connection_timeout(30);
  4248. auto res = cli.Get("/test");
  4249. ASSERT_TRUE(res);
  4250. ASSERT_EQ(200, res->status);
  4251. }
  4252. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4253. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4254. X509 *server_cert;
  4255. EVP_PKEY *server_private_key;
  4256. X509_STORE *client_ca_cert_store;
  4257. X509 *client_cert;
  4258. EVP_PKEY *client_private_key;
  4259. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4260. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4261. fclose(f);
  4262. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4263. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4264. fclose(f);
  4265. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4266. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4267. client_ca_cert_store = X509_STORE_new();
  4268. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4269. X509_free(client_cert);
  4270. fclose(f);
  4271. f = fopen(CLIENT_CERT_FILE, "r+");
  4272. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4273. fclose(f);
  4274. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4275. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4276. fclose(f);
  4277. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4278. ASSERT_TRUE(svr.is_valid());
  4279. svr.Get("/test", [&](const Request &req, Response &res) {
  4280. res.set_content("test", "text/plain");
  4281. svr.stop();
  4282. ASSERT_TRUE(true);
  4283. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4284. ASSERT_TRUE(peer_cert != nullptr);
  4285. auto subject_name = X509_get_subject_name(peer_cert);
  4286. ASSERT_TRUE(subject_name != nullptr);
  4287. std::string common_name;
  4288. {
  4289. char name[BUFSIZ];
  4290. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4291. name, sizeof(name));
  4292. common_name.assign(name, static_cast<size_t>(name_len));
  4293. }
  4294. EXPECT_EQ("Common Name", common_name);
  4295. X509_free(peer_cert);
  4296. });
  4297. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4298. auto se = detail::scope_exit([&] {
  4299. t.join();
  4300. ASSERT_FALSE(svr.is_running());
  4301. });
  4302. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4303. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4304. cli.enable_server_certificate_verification(false);
  4305. cli.set_connection_timeout(30);
  4306. auto res = cli.Get("/test");
  4307. ASSERT_TRUE(res);
  4308. ASSERT_EQ(200, res->status);
  4309. X509_free(server_cert);
  4310. EVP_PKEY_free(server_private_key);
  4311. X509_free(client_cert);
  4312. EVP_PKEY_free(client_private_key);
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, ClientCertMissing) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4317. CLIENT_CA_CERT_DIR);
  4318. ASSERT_TRUE(svr.is_valid());
  4319. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. t.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4327. SSLClient cli(HOST, PORT);
  4328. auto res = cli.Get("/test");
  4329. cli.set_connection_timeout(30);
  4330. ASSERT_TRUE(!res);
  4331. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4332. }
  4333. TEST(SSLClientServerTest, TrustDirOptional) {
  4334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4335. ASSERT_TRUE(svr.is_valid());
  4336. svr.Get("/test", [&](const Request &, Response &res) {
  4337. res.set_content("test", "text/plain");
  4338. svr.stop();
  4339. });
  4340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4341. auto se = detail::scope_exit([&] {
  4342. t.join();
  4343. ASSERT_FALSE(svr.is_running());
  4344. });
  4345. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4346. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4347. cli.enable_server_certificate_verification(false);
  4348. cli.set_connection_timeout(30);
  4349. auto res = cli.Get("/test");
  4350. ASSERT_TRUE(res);
  4351. ASSERT_EQ(200, res->status);
  4352. }
  4353. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4354. class NoListenSSLServer : public SSLServer {
  4355. public:
  4356. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4357. const char *client_ca_cert_file_path,
  4358. const char *client_ca_cert_dir_path = nullptr)
  4359. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4360. client_ca_cert_dir_path),
  4361. stop_(false) {}
  4362. bool stop_;
  4363. private:
  4364. bool process_and_close_socket(socket_t /*sock*/) override {
  4365. // Don't create SSL context
  4366. while (!stop_) {
  4367. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4368. }
  4369. return true;
  4370. }
  4371. };
  4372. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4373. CLIENT_CA_CERT_FILE);
  4374. ASSERT_TRUE(svr.is_valid());
  4375. svr.Get("/test", [&](const Request &, Response &res) {
  4376. res.set_content("test", "text/plain");
  4377. });
  4378. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4379. auto se = detail::scope_exit([&] {
  4380. svr.stop_ = true;
  4381. svr.stop();
  4382. t.join();
  4383. ASSERT_FALSE(svr.is_running());
  4384. });
  4385. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4386. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4387. cli.enable_server_certificate_verification(false);
  4388. cli.set_connection_timeout(1);
  4389. auto res = cli.Get("/test");
  4390. ASSERT_TRUE(!res);
  4391. EXPECT_EQ(Error::SSLConnection, res.error());
  4392. }
  4393. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4394. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4395. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4396. SSL_CTX_set_options(&ssl_ctx,
  4397. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4398. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4399. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4400. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4401. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4402. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4403. "ECDHE-DSS-AES128-SHA256:"
  4404. "ECDHE-RSA-AES256-SHA256:"
  4405. "ECDHE-DSS-AES256-SHA256:";
  4406. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4407. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4408. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4409. SSL_FILETYPE_PEM) != 1) {
  4410. return false;
  4411. }
  4412. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4413. CLIENT_CA_CERT_DIR);
  4414. SSL_CTX_set_verify(
  4415. &ssl_ctx,
  4416. SSL_VERIFY_PEER |
  4417. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4418. nullptr);
  4419. return true;
  4420. };
  4421. SSLServer svr(setup_ssl_ctx_callback);
  4422. ASSERT_TRUE(svr.is_valid());
  4423. svr.Get("/test", [&](const Request &req, Response &res) {
  4424. res.set_content("test", "text/plain");
  4425. svr.stop();
  4426. ASSERT_TRUE(true);
  4427. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4428. ASSERT_TRUE(peer_cert != nullptr);
  4429. auto subject_name = X509_get_subject_name(peer_cert);
  4430. ASSERT_TRUE(subject_name != nullptr);
  4431. std::string common_name;
  4432. {
  4433. char name[BUFSIZ];
  4434. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4435. name, sizeof(name));
  4436. common_name.assign(name, static_cast<size_t>(name_len));
  4437. }
  4438. EXPECT_EQ("Common Name", common_name);
  4439. X509_free(peer_cert);
  4440. });
  4441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4442. auto se = detail::scope_exit([&] {
  4443. t.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4447. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4448. cli.enable_server_certificate_verification(false);
  4449. cli.set_connection_timeout(30);
  4450. auto res = cli.Get("/test");
  4451. ASSERT_TRUE(res);
  4452. ASSERT_EQ(200, res->status);
  4453. }
  4454. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4455. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4456. // prepare large data
  4457. std::random_device seed_gen;
  4458. std::mt19937 random(seed_gen());
  4459. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4460. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4461. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4462. // server
  4463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4464. ASSERT_TRUE(svr.is_valid());
  4465. svr.Post("/binary", [&](const Request &req, Response &res) {
  4466. EXPECT_EQ(large_size_byte, req.body.size());
  4467. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4468. res.set_content(req.body, "application/octet-stream");
  4469. });
  4470. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4471. auto se = detail::scope_exit([&] {
  4472. svr.stop();
  4473. listen_thread.join();
  4474. ASSERT_FALSE(svr.is_running());
  4475. });
  4476. svr.wait_until_ready();
  4477. // client POST
  4478. SSLClient cli("localhost", PORT);
  4479. cli.enable_server_certificate_verification(false);
  4480. cli.set_read_timeout(std::chrono::seconds(100));
  4481. cli.set_write_timeout(std::chrono::seconds(100));
  4482. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4483. large_size_byte, "application/octet-stream");
  4484. // compare
  4485. EXPECT_EQ(200, res->status);
  4486. EXPECT_EQ(large_size_byte, res->body.size());
  4487. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4488. }
  4489. #endif
  4490. #ifdef _WIN32
  4491. TEST(CleanupTest, WSACleanup) {
  4492. int ret = WSACleanup();
  4493. ASSERT_EQ(0, ret);
  4494. }
  4495. #endif
  4496. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4497. TEST(NoSSLSupport, SimpleInterface) {
  4498. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4499. }
  4500. #endif
  4501. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4502. TEST(InvalidScheme, SimpleInterface) {
  4503. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4504. }
  4505. #endif
  4506. TEST(NoScheme, SimpleInterface) {
  4507. Client cli("yahoo.com:80");
  4508. ASSERT_TRUE(cli.is_valid());
  4509. }
  4510. TEST(SendAPI, SimpleInterface_Online) {
  4511. Client cli("http://yahoo.com");
  4512. Request req;
  4513. req.method = "GET";
  4514. req.path = "/";
  4515. auto res = cli.send(req);
  4516. ASSERT_TRUE(res);
  4517. EXPECT_EQ(301, res->status);
  4518. }
  4519. TEST(ClientImplMethods, GetSocketTest) {
  4520. httplib::Server svr;
  4521. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4522. res.status = 200;
  4523. });
  4524. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4525. auto se = detail::scope_exit([&] {
  4526. svr.stop();
  4527. thread.join();
  4528. ASSERT_FALSE(svr.is_running());
  4529. });
  4530. svr.wait_until_ready();
  4531. {
  4532. httplib::Client cli("http://127.0.0.1:3333");
  4533. cli.set_keep_alive(true);
  4534. // Use the behavior of cpp-httplib of opening the connection
  4535. // only when the first request happens. If that changes,
  4536. // this test would be obsolete.
  4537. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4538. // This also implicitly tests the server. But other tests would fail much
  4539. // earlier than this one to be considered.
  4540. auto res = cli.Get("/");
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(200, res->status);
  4543. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4544. }
  4545. }
  4546. // Disabled due to out-of-memory problem on GitHub Actions
  4547. #ifdef _WIN64
  4548. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4549. // allocate content size larger than 2GB in memory
  4550. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4551. char *content = (char *)malloc(content_size);
  4552. ASSERT_TRUE(content);
  4553. Server svr;
  4554. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4555. resp.set_content(content, content_size, "application/octet-stream");
  4556. });
  4557. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4558. auto se = detail::scope_exit([&] {
  4559. svr.stop();
  4560. listen_thread.join();
  4561. if (content) free(content);
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. // Give GET time to get a few messages.
  4566. std::this_thread::sleep_for(std::chrono::seconds(1));
  4567. Client cli(HOST, PORT);
  4568. auto res = cli.Get("/foo");
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(200, res->status);
  4571. EXPECT_EQ(content_size, res->body.length());
  4572. }
  4573. #endif
  4574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4575. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4576. Client cli("http://yahoo.com");
  4577. auto res = cli.Get("/");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(301, res->status);
  4580. cli.set_follow_location(true);
  4581. res = cli.Get("/");
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(200, res->status);
  4584. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4585. }
  4586. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4587. Client cli("https://yahoo.com");
  4588. auto res = cli.Get("/");
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(301, res->status);
  4591. cli.set_follow_location(true);
  4592. res = cli.Get("/");
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(200, res->status);
  4595. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4596. }
  4597. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4598. Client cli("https://yahoo.com");
  4599. auto res = cli.Get("/");
  4600. ASSERT_TRUE(res);
  4601. ASSERT_FALSE(!res);
  4602. ASSERT_TRUE(res);
  4603. ASSERT_FALSE(res == nullptr);
  4604. ASSERT_TRUE(res != nullptr);
  4605. EXPECT_EQ(Error::Success, res.error());
  4606. EXPECT_EQ(301, res.value().status);
  4607. EXPECT_EQ(301, (*res).status);
  4608. EXPECT_EQ(301, res->status);
  4609. cli.set_follow_location(true);
  4610. res = cli.Get("/");
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(Error::Success, res.error());
  4613. EXPECT_EQ(200, res.value().status);
  4614. EXPECT_EQ(200, (*res).status);
  4615. EXPECT_EQ(200, res->status);
  4616. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4617. }
  4618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4619. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4620. Client cli("https://cdnjs.cloudflare.com");
  4621. auto res =
  4622. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(200, res->status);
  4625. EXPECT_EQ(287630U, res->body.size());
  4626. EXPECT_EQ("application/javascript; charset=utf-8",
  4627. res->get_header_value("Content-Type"));
  4628. }
  4629. #endif
  4630. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4631. Client cli("https://nghttp2.org");
  4632. cli.set_follow_location(true);
  4633. auto res =
  4634. cli.Get("/httpbin/"
  4635. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(200, res->status);
  4638. }
  4639. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4640. Client cli("https://nghttp2.org");
  4641. cli.set_follow_location(true);
  4642. Params params;
  4643. params.emplace("url", "http://www.google.com");
  4644. params.emplace("status_code", "302");
  4645. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(200, res->status);
  4648. }
  4649. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4650. Client cli("https://nghttp2.org");
  4651. cli.set_follow_location(true);
  4652. Params params;
  4653. params.emplace("url", "http://www.google.com");
  4654. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(200, res->status);
  4657. }
  4658. TEST(HttpToHttpsRedirectTest, CertFile) {
  4659. Server svr;
  4660. ASSERT_TRUE(svr.is_valid());
  4661. svr.Get("/index", [&](const Request &, Response &res) {
  4662. res.set_redirect("https://127.0.0.1:1235/index");
  4663. svr.stop();
  4664. });
  4665. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4666. ASSERT_TRUE(ssl_svr.is_valid());
  4667. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4668. res.set_content("test", "text/plain");
  4669. ssl_svr.stop();
  4670. });
  4671. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4672. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4673. auto se = detail::scope_exit([&] {
  4674. t2.join();
  4675. t.join();
  4676. ASSERT_FALSE(svr.is_running());
  4677. });
  4678. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4679. Client cli("127.0.0.1", PORT);
  4680. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4681. cli.enable_server_certificate_verification(true);
  4682. cli.set_follow_location(true);
  4683. cli.set_connection_timeout(30);
  4684. auto res = cli.Get("/index");
  4685. ASSERT_TRUE(res);
  4686. ASSERT_EQ(200, res->status);
  4687. }
  4688. TEST(MultipartFormDataTest, LargeData) {
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4691. const ContentReader &content_reader) {
  4692. if (req.is_multipart_form_data()) {
  4693. MultipartFormDataItems files;
  4694. content_reader(
  4695. [&](const MultipartFormData &file) {
  4696. files.push_back(file);
  4697. return true;
  4698. },
  4699. [&](const char *data, size_t data_length) {
  4700. files.back().content.append(data, data_length);
  4701. return true;
  4702. });
  4703. EXPECT_TRUE(std::string(files[0].name) == "document");
  4704. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4705. EXPECT_TRUE(files[0].filename == "2MB_data");
  4706. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4707. EXPECT_TRUE(files[1].name == "hello");
  4708. EXPECT_TRUE(files[1].content == "world");
  4709. EXPECT_TRUE(files[1].filename == "");
  4710. EXPECT_TRUE(files[1].content_type == "");
  4711. } else {
  4712. std::string body;
  4713. content_reader([&](const char *data, size_t data_length) {
  4714. body.append(data, data_length);
  4715. return true;
  4716. });
  4717. }
  4718. });
  4719. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4720. auto se = detail::scope_exit([&] {
  4721. svr.stop();
  4722. t.join();
  4723. ASSERT_FALSE(svr.is_running());
  4724. });
  4725. svr.wait_until_ready();
  4726. std::this_thread::sleep_for(std::chrono::seconds(1));
  4727. {
  4728. std::string data(1024 * 1024 * 2, '.');
  4729. std::stringstream buffer;
  4730. buffer << data;
  4731. Client cli("https://localhost:8080");
  4732. cli.enable_server_certificate_verification(false);
  4733. MultipartFormDataItems items{
  4734. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4735. {"hello", "world", "", ""},
  4736. };
  4737. auto res = cli.Post("/post", items);
  4738. ASSERT_TRUE(res);
  4739. ASSERT_EQ(200, res->status);
  4740. }
  4741. }
  4742. TEST(MultipartFormDataTest, DataProviderItems) {
  4743. std::random_device seed_gen;
  4744. std::mt19937 random(seed_gen());
  4745. std::string rand1;
  4746. rand1.resize(1000);
  4747. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4748. std::string rand2;
  4749. rand2.resize(3000);
  4750. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4752. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4753. const ContentReader &content_reader) {
  4754. ASSERT_FALSE(req.is_multipart_form_data());
  4755. std::string body;
  4756. content_reader([&](const char *data, size_t data_length) {
  4757. body.append(data, data_length);
  4758. return true;
  4759. });
  4760. EXPECT_EQ(body, "");
  4761. });
  4762. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4763. const ContentReader &content_reader) {
  4764. ASSERT_TRUE(req.is_multipart_form_data());
  4765. MultipartFormDataItems files;
  4766. content_reader(
  4767. [&](const MultipartFormData &file) {
  4768. files.push_back(file);
  4769. return true;
  4770. },
  4771. [&](const char *data, size_t data_length) {
  4772. files.back().content.append(data, data_length);
  4773. return true;
  4774. });
  4775. ASSERT_TRUE(files.size() == 2);
  4776. EXPECT_EQ(std::string(files[0].name), "name1");
  4777. EXPECT_EQ(files[0].content, "Testing123");
  4778. EXPECT_EQ(files[0].filename, "filename1");
  4779. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4780. EXPECT_EQ(files[1].name, "name2");
  4781. EXPECT_EQ(files[1].content, "Testing456");
  4782. EXPECT_EQ(files[1].filename, "");
  4783. EXPECT_EQ(files[1].content_type, "");
  4784. });
  4785. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4786. const ContentReader &content_reader) {
  4787. ASSERT_TRUE(req.is_multipart_form_data());
  4788. MultipartFormDataItems files;
  4789. content_reader(
  4790. [&](const MultipartFormData &file) {
  4791. files.push_back(file);
  4792. return true;
  4793. },
  4794. [&](const char *data, size_t data_length) {
  4795. files.back().content.append(data, data_length);
  4796. return true;
  4797. });
  4798. ASSERT_TRUE(files.size() == 2);
  4799. EXPECT_EQ(files[0].name, "name3");
  4800. EXPECT_EQ(files[0].content, rand1);
  4801. EXPECT_EQ(files[0].filename, "filename3");
  4802. EXPECT_EQ(files[0].content_type, "");
  4803. EXPECT_EQ(files[1].name, "name4");
  4804. EXPECT_EQ(files[1].content, rand2);
  4805. EXPECT_EQ(files[1].filename, "filename4");
  4806. EXPECT_EQ(files[1].content_type, "");
  4807. });
  4808. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4809. const ContentReader &content_reader) {
  4810. ASSERT_TRUE(req.is_multipart_form_data());
  4811. MultipartFormDataItems files;
  4812. content_reader(
  4813. [&](const MultipartFormData &file) {
  4814. files.push_back(file);
  4815. return true;
  4816. },
  4817. [&](const char *data, size_t data_length) {
  4818. files.back().content.append(data, data_length);
  4819. return true;
  4820. });
  4821. ASSERT_TRUE(files.size() == 4);
  4822. EXPECT_EQ(std::string(files[0].name), "name1");
  4823. EXPECT_EQ(files[0].content, "Testing123");
  4824. EXPECT_EQ(files[0].filename, "filename1");
  4825. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4826. EXPECT_EQ(files[1].name, "name2");
  4827. EXPECT_EQ(files[1].content, "Testing456");
  4828. EXPECT_EQ(files[1].filename, "");
  4829. EXPECT_EQ(files[1].content_type, "");
  4830. EXPECT_EQ(files[2].name, "name3");
  4831. EXPECT_EQ(files[2].content, rand1);
  4832. EXPECT_EQ(files[2].filename, "filename3");
  4833. EXPECT_EQ(files[2].content_type, "");
  4834. EXPECT_EQ(files[3].name, "name4");
  4835. EXPECT_EQ(files[3].content, rand2);
  4836. EXPECT_EQ(files[3].filename, "filename4");
  4837. EXPECT_EQ(files[3].content_type, "");
  4838. });
  4839. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4840. auto se = detail::scope_exit([&] {
  4841. svr.stop();
  4842. t.join();
  4843. ASSERT_FALSE(svr.is_running());
  4844. });
  4845. svr.wait_until_ready();
  4846. std::this_thread::sleep_for(std::chrono::seconds(1));
  4847. {
  4848. Client cli("https://localhost:8080");
  4849. cli.enable_server_certificate_verification(false);
  4850. MultipartFormDataItems items{
  4851. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4852. {"name2", "Testing456", "", ""}, // not a file
  4853. };
  4854. {
  4855. auto res = cli.Post("/post-none", {}, {}, {});
  4856. ASSERT_TRUE(res);
  4857. ASSERT_EQ(200, res->status);
  4858. }
  4859. MultipartFormDataProviderItems providers;
  4860. {
  4861. auto res =
  4862. cli.Post("/post-items", {}, items, providers); // empty providers
  4863. ASSERT_TRUE(res);
  4864. ASSERT_EQ(200, res->status);
  4865. }
  4866. providers.push_back({"name3",
  4867. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4868. // test the offset is given correctly at each step
  4869. if (!offset)
  4870. sink.os.write(rand1.data(), 30);
  4871. else if (offset == 30)
  4872. sink.os.write(rand1.data() + 30, 300);
  4873. else if (offset == 330)
  4874. sink.os.write(rand1.data() + 330, 670);
  4875. else if (offset == rand1.size())
  4876. sink.done();
  4877. return true;
  4878. },
  4879. "filename3",
  4880. {}});
  4881. providers.push_back({"name4",
  4882. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4883. // test the offset is given correctly at each step
  4884. if (!offset)
  4885. sink.os.write(rand2.data(), 2000);
  4886. else if (offset == 2000)
  4887. sink.os.write(rand2.data() + 2000, 1);
  4888. else if (offset == 2001)
  4889. sink.os.write(rand2.data() + 2001, 999);
  4890. else if (offset == rand2.size())
  4891. sink.done();
  4892. return true;
  4893. },
  4894. "filename4",
  4895. {}});
  4896. {
  4897. auto res = cli.Post("/post-providers", {}, {}, providers);
  4898. ASSERT_TRUE(res);
  4899. ASSERT_EQ(200, res->status);
  4900. }
  4901. {
  4902. auto res = cli.Post("/post-both", {}, items, providers);
  4903. ASSERT_TRUE(res);
  4904. ASSERT_EQ(200, res->status);
  4905. }
  4906. }
  4907. }
  4908. TEST(MultipartFormDataTest, BadHeader) {
  4909. Server svr;
  4910. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4911. res.set_content("ok", "text/plain");
  4912. });
  4913. thread t = thread([&] { svr.listen(HOST, PORT); });
  4914. auto se = detail::scope_exit([&] {
  4915. svr.stop();
  4916. t.join();
  4917. ASSERT_FALSE(svr.is_running());
  4918. });
  4919. svr.wait_until_ready();
  4920. const std::string body =
  4921. "This is the preamble. It is to be ignored, though it\r\n"
  4922. "is a handy place for composition agents to include an\r\n"
  4923. "explanatory note to non-MIME conformant readers.\r\n"
  4924. "\r\n"
  4925. "\r\n"
  4926. "--simple boundary\r\n"
  4927. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4928. ": BAD...\r\n"
  4929. "\r\n"
  4930. "value1\r\n"
  4931. "--simple boundary\r\n"
  4932. "Content-Disposition: form-data; name=\"field2\"; "
  4933. "filename=\"example.txt\"\r\n"
  4934. "\r\n"
  4935. "value2\r\n"
  4936. "--simple boundary--\r\n"
  4937. "This is the epilogue. It is also to be ignored.\r\n";
  4938. std::string content_type =
  4939. R"(multipart/form-data; boundary="simple boundary")";
  4940. Client cli(HOST, PORT);
  4941. auto res = cli.Post("/post", body, content_type.c_str());
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(400, res->status);
  4944. }
  4945. TEST(MultipartFormDataTest, WithPreamble) {
  4946. Server svr;
  4947. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4948. res.set_content("ok", "text/plain");
  4949. });
  4950. thread t = thread([&] { svr.listen(HOST, PORT); });
  4951. auto se = detail::scope_exit([&] {
  4952. svr.stop();
  4953. t.join();
  4954. ASSERT_FALSE(svr.is_running());
  4955. });
  4956. svr.wait_until_ready();
  4957. const std::string body =
  4958. "This is the preamble. It is to be ignored, though it\r\n"
  4959. "is a handy place for composition agents to include an\r\n"
  4960. "explanatory note to non-MIME conformant readers.\r\n"
  4961. "\r\n"
  4962. "\r\n"
  4963. "--simple boundary\r\n"
  4964. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4965. "\r\n"
  4966. "value1\r\n"
  4967. "--simple boundary\r\n"
  4968. "Content-Disposition: form-data; name=\"field2\"; "
  4969. "filename=\"example.txt\"\r\n"
  4970. "\r\n"
  4971. "value2\r\n"
  4972. "--simple boundary--\r\n"
  4973. "This is the epilogue. It is also to be ignored.\r\n";
  4974. std::string content_type =
  4975. R"(multipart/form-data; boundary="simple boundary")";
  4976. Client cli(HOST, PORT);
  4977. auto res = cli.Post("/post", body, content_type.c_str());
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(200, res->status);
  4980. }
  4981. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4983. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4984. const ContentReader &content_reader) {
  4985. if (req.is_multipart_form_data()) {
  4986. MultipartFormDataItems files;
  4987. content_reader(
  4988. [&](const MultipartFormData &file) {
  4989. files.push_back(file);
  4990. return true;
  4991. },
  4992. [&](const char *data, size_t data_length) {
  4993. files.back().content.append(data, data_length);
  4994. return true;
  4995. });
  4996. EXPECT_TRUE(std::string(files[0].name) == "document");
  4997. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4998. EXPECT_TRUE(files[0].filename == "2MB_data");
  4999. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5000. EXPECT_TRUE(files[1].name == "hello");
  5001. EXPECT_TRUE(files[1].content == "world");
  5002. EXPECT_TRUE(files[1].filename == "");
  5003. EXPECT_TRUE(files[1].content_type == "");
  5004. } else {
  5005. std::string body;
  5006. content_reader([&](const char *data, size_t data_length) {
  5007. body.append(data, data_length);
  5008. return true;
  5009. });
  5010. }
  5011. });
  5012. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5013. auto se = detail::scope_exit([&] {
  5014. svr.stop();
  5015. t.join();
  5016. ASSERT_FALSE(svr.is_running());
  5017. });
  5018. svr.wait_until_ready();
  5019. std::this_thread::sleep_for(std::chrono::seconds(1));
  5020. {
  5021. std::string data(1024 * 1024 * 2, '.');
  5022. std::stringstream buffer;
  5023. buffer << data;
  5024. Client cli("https://localhost:8080");
  5025. cli.enable_server_certificate_verification(false);
  5026. MultipartFormDataItems items{
  5027. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5028. {"hello", "world", "", ""},
  5029. };
  5030. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5031. ASSERT_TRUE(res);
  5032. ASSERT_EQ(200, res->status);
  5033. }
  5034. }
  5035. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5036. std::this_thread::sleep_for(std::chrono::seconds(1));
  5037. std::string data(1024 * 1024 * 2, '&');
  5038. std::stringstream buffer;
  5039. buffer << data;
  5040. Client cli("https://localhost:8080");
  5041. MultipartFormDataItems items{
  5042. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5043. {"hello", "world", "", ""},
  5044. };
  5045. for (const char &c : " \t\r\n") {
  5046. auto res =
  5047. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5048. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5049. ASSERT_FALSE(res);
  5050. }
  5051. }
  5052. TEST(MultipartFormDataTest, PutFormData) {
  5053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5054. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5055. const ContentReader &content_reader) {
  5056. if (req.is_multipart_form_data()) {
  5057. MultipartFormDataItems files;
  5058. content_reader(
  5059. [&](const MultipartFormData &file) {
  5060. files.push_back(file);
  5061. return true;
  5062. },
  5063. [&](const char *data, size_t data_length) {
  5064. files.back().content.append(data, data_length);
  5065. return true;
  5066. });
  5067. EXPECT_TRUE(std::string(files[0].name) == "document");
  5068. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5069. EXPECT_TRUE(files[0].filename == "2MB_data");
  5070. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5071. EXPECT_TRUE(files[1].name == "hello");
  5072. EXPECT_TRUE(files[1].content == "world");
  5073. EXPECT_TRUE(files[1].filename == "");
  5074. EXPECT_TRUE(files[1].content_type == "");
  5075. } else {
  5076. std::string body;
  5077. content_reader([&](const char *data, size_t data_length) {
  5078. body.append(data, data_length);
  5079. return true;
  5080. });
  5081. }
  5082. });
  5083. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5084. auto se = detail::scope_exit([&] {
  5085. svr.stop();
  5086. t.join();
  5087. ASSERT_FALSE(svr.is_running());
  5088. });
  5089. svr.wait_until_ready();
  5090. std::this_thread::sleep_for(std::chrono::seconds(1));
  5091. {
  5092. std::string data(1024 * 1024 * 2, '&');
  5093. std::stringstream buffer;
  5094. buffer << data;
  5095. Client cli("https://localhost:8080");
  5096. cli.enable_server_certificate_verification(false);
  5097. MultipartFormDataItems items{
  5098. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5099. {"hello", "world", "", ""},
  5100. };
  5101. auto res = cli.Put("/put", items);
  5102. ASSERT_TRUE(res);
  5103. ASSERT_EQ(200, res->status);
  5104. }
  5105. }
  5106. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5108. svr.Put("/put_customboundary",
  5109. [&](const Request &req, const Response & /*res*/,
  5110. const ContentReader &content_reader) {
  5111. if (req.is_multipart_form_data()) {
  5112. MultipartFormDataItems files;
  5113. content_reader(
  5114. [&](const MultipartFormData &file) {
  5115. files.push_back(file);
  5116. return true;
  5117. },
  5118. [&](const char *data, size_t data_length) {
  5119. files.back().content.append(data, data_length);
  5120. return true;
  5121. });
  5122. EXPECT_TRUE(std::string(files[0].name) == "document");
  5123. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5124. EXPECT_TRUE(files[0].filename == "2MB_data");
  5125. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5126. EXPECT_TRUE(files[1].name == "hello");
  5127. EXPECT_TRUE(files[1].content == "world");
  5128. EXPECT_TRUE(files[1].filename == "");
  5129. EXPECT_TRUE(files[1].content_type == "");
  5130. } else {
  5131. std::string body;
  5132. content_reader([&](const char *data, size_t data_length) {
  5133. body.append(data, data_length);
  5134. return true;
  5135. });
  5136. }
  5137. });
  5138. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5139. auto se = detail::scope_exit([&] {
  5140. svr.stop();
  5141. t.join();
  5142. ASSERT_FALSE(svr.is_running());
  5143. });
  5144. svr.wait_until_ready();
  5145. std::this_thread::sleep_for(std::chrono::seconds(1));
  5146. {
  5147. std::string data(1024 * 1024 * 2, '&');
  5148. std::stringstream buffer;
  5149. buffer << data;
  5150. Client cli("https://localhost:8080");
  5151. cli.enable_server_certificate_verification(false);
  5152. MultipartFormDataItems items{
  5153. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5154. {"hello", "world", "", ""},
  5155. };
  5156. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5157. ASSERT_TRUE(res);
  5158. ASSERT_EQ(200, res->status);
  5159. }
  5160. }
  5161. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5162. std::this_thread::sleep_for(std::chrono::seconds(1));
  5163. std::string data(1024 * 1024 * 2, '&');
  5164. std::stringstream buffer;
  5165. buffer << data;
  5166. Client cli("https://localhost:8080");
  5167. cli.enable_server_certificate_verification(false);
  5168. MultipartFormDataItems items{
  5169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5170. {"hello", "world", "", ""},
  5171. };
  5172. for (const char &c : " \t\r\n") {
  5173. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5174. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5175. ASSERT_FALSE(res);
  5176. }
  5177. }
  5178. TEST(MultipartFormDataTest, AlternateFilename) {
  5179. auto handled = false;
  5180. Server svr;
  5181. svr.Post("/test", [&](const Request &req, Response &res) {
  5182. ASSERT_EQ(3u, req.files.size());
  5183. auto it = req.files.begin();
  5184. ASSERT_EQ("file1", it->second.name);
  5185. ASSERT_EQ("A.txt", it->second.filename);
  5186. ASSERT_EQ("text/plain", it->second.content_type);
  5187. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5188. ++it;
  5189. ASSERT_EQ("file2", it->second.name);
  5190. ASSERT_EQ("a.html", it->second.filename);
  5191. ASSERT_EQ("text/html", it->second.content_type);
  5192. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5193. it->second.content);
  5194. ++it;
  5195. ASSERT_EQ("text", it->second.name);
  5196. ASSERT_EQ("", it->second.filename);
  5197. ASSERT_EQ("", it->second.content_type);
  5198. ASSERT_EQ("text default", it->second.content);
  5199. res.set_content("ok", "text/plain");
  5200. handled = true;
  5201. });
  5202. thread t = thread([&] { svr.listen(HOST, PORT); });
  5203. auto se = detail::scope_exit([&] {
  5204. svr.stop();
  5205. t.join();
  5206. ASSERT_FALSE(svr.is_running());
  5207. ASSERT_TRUE(handled);
  5208. });
  5209. svr.wait_until_ready();
  5210. auto req = "POST /test HTTP/1.1\r\n"
  5211. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5212. "Content-Length: 399\r\n"
  5213. "\r\n"
  5214. "----------\r\n"
  5215. "Content-Disposition: form-data; name=\"text\"\r\n"
  5216. "\r\n"
  5217. "text default\r\n"
  5218. "----------\r\n"
  5219. "Content-Disposition: form-data; filename*=\"UTF-8''\%41.txt\"; "
  5220. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5221. "Content-Type: text/plain\r\n"
  5222. "\r\n"
  5223. "Content of a.txt.\r\n"
  5224. "\r\n"
  5225. "----------\r\n"
  5226. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5227. "\"a.html\"\r\n"
  5228. "Content-Type: text/html\r\n"
  5229. "\r\n"
  5230. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5231. "\r\n"
  5232. "------------\r\n";
  5233. ASSERT_TRUE(send_request(1, req));
  5234. }
  5235. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5236. auto handled = false;
  5237. Server svr;
  5238. svr.Post("/test", [&](const Request &req, Response &) {
  5239. ASSERT_EQ(2u, req.files.size());
  5240. auto it = req.files.begin();
  5241. ASSERT_EQ("text1", it->second.name);
  5242. ASSERT_EQ("text1", it->second.content);
  5243. ++it;
  5244. ASSERT_EQ("text2", it->second.name);
  5245. ASSERT_EQ("text2", it->second.content);
  5246. handled = true;
  5247. });
  5248. thread t = thread([&] { svr.listen(HOST, PORT); });
  5249. auto se = detail::scope_exit([&] {
  5250. svr.stop();
  5251. t.join();
  5252. ASSERT_FALSE(svr.is_running());
  5253. ASSERT_TRUE(handled);
  5254. });
  5255. svr.wait_until_ready();
  5256. auto req = "POST /test HTTP/1.1\r\n"
  5257. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5258. "Content-Length: 146\r\n"
  5259. "\r\n----------\r\n"
  5260. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5261. "\r\n"
  5262. "text1"
  5263. "\r\n----------\r\n"
  5264. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5265. "\r\n"
  5266. "text2"
  5267. "\r\n------------";
  5268. std::string resonse;
  5269. ASSERT_TRUE(send_request(1, req, &resonse));
  5270. ASSERT_EQ("200", resonse.substr(9, 3));
  5271. }
  5272. #endif
  5273. #ifndef _WIN32
  5274. class UnixSocketTest : public ::testing::Test {
  5275. protected:
  5276. void TearDown() override { std::remove(pathname_.c_str()); }
  5277. void client_GET(const std::string &addr) {
  5278. httplib::Client cli{addr};
  5279. cli.set_address_family(AF_UNIX);
  5280. ASSERT_TRUE(cli.is_valid());
  5281. const auto &result = cli.Get(pattern_);
  5282. ASSERT_TRUE(result) << "error: " << result.error();
  5283. const auto &resp = result.value();
  5284. EXPECT_EQ(resp.status, 200);
  5285. EXPECT_EQ(resp.body, content_);
  5286. }
  5287. const std::string pathname_{"./httplib-server.sock"};
  5288. const std::string pattern_{"/hi"};
  5289. const std::string content_{"Hello World!"};
  5290. };
  5291. TEST_F(UnixSocketTest, pathname) {
  5292. httplib::Server svr;
  5293. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5294. res.set_content(content_, "text/plain");
  5295. });
  5296. std::thread t{[&] {
  5297. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5298. }};
  5299. auto se = detail::scope_exit([&] {
  5300. svr.stop();
  5301. t.join();
  5302. ASSERT_FALSE(svr.is_running());
  5303. });
  5304. svr.wait_until_ready();
  5305. ASSERT_TRUE(svr.is_running());
  5306. client_GET(pathname_);
  5307. }
  5308. #if defined(__linux__) || \
  5309. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5310. TEST_F(UnixSocketTest, PeerPid) {
  5311. httplib::Server svr;
  5312. std::string remote_port_val;
  5313. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5314. res.set_content(content_, "text/plain");
  5315. remote_port_val = req.get_header_value("REMOTE_PORT");
  5316. });
  5317. std::thread t{[&] {
  5318. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5319. }};
  5320. auto se = detail::scope_exit([&] {
  5321. svr.stop();
  5322. t.join();
  5323. ASSERT_FALSE(svr.is_running());
  5324. });
  5325. svr.wait_until_ready();
  5326. ASSERT_TRUE(svr.is_running());
  5327. client_GET(pathname_);
  5328. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5329. }
  5330. #endif
  5331. #ifdef __linux__
  5332. TEST_F(UnixSocketTest, abstract) {
  5333. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5334. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5335. httplib::Server svr;
  5336. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5337. res.set_content(content_, "text/plain");
  5338. });
  5339. std::thread t{[&] {
  5340. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5341. }};
  5342. auto se = detail::scope_exit([&] {
  5343. svr.stop();
  5344. t.join();
  5345. ASSERT_FALSE(svr.is_running());
  5346. });
  5347. svr.wait_until_ready();
  5348. ASSERT_TRUE(svr.is_running());
  5349. client_GET(abstract_addr);
  5350. }
  5351. #endif
  5352. TEST(SocketStream, is_writable_UNIX) {
  5353. int fds[2];
  5354. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5355. const auto asSocketStream = [&](socket_t fd,
  5356. std::function<bool(Stream &)> func) {
  5357. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5358. };
  5359. asSocketStream(fds[0], [&](Stream &s0) {
  5360. EXPECT_EQ(s0.socket(), fds[0]);
  5361. EXPECT_TRUE(s0.is_writable());
  5362. EXPECT_EQ(0, close(fds[1]));
  5363. EXPECT_FALSE(s0.is_writable());
  5364. return true;
  5365. });
  5366. EXPECT_EQ(0, close(fds[0]));
  5367. }
  5368. TEST(SocketStream, is_writable_INET) {
  5369. sockaddr_in addr;
  5370. memset(&addr, 0, sizeof(addr));
  5371. addr.sin_family = AF_INET;
  5372. addr.sin_port = htons(PORT + 1);
  5373. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5374. int disconnected_svr_sock = -1;
  5375. std::thread svr{[&] {
  5376. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5377. ASSERT_LE(0, s);
  5378. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5379. ASSERT_EQ(0, listen(s, 1));
  5380. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5381. ASSERT_EQ(0, close(s));
  5382. }};
  5383. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5384. std::thread cli{[&] {
  5385. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5386. ASSERT_LE(0, s);
  5387. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5388. ASSERT_EQ(0, close(s));
  5389. }};
  5390. cli.join();
  5391. svr.join();
  5392. ASSERT_NE(disconnected_svr_sock, -1);
  5393. const auto asSocketStream = [&](socket_t fd,
  5394. std::function<bool(Stream &)> func) {
  5395. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5396. };
  5397. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5398. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5399. EXPECT_FALSE(ss.is_writable());
  5400. return true;
  5401. });
  5402. ASSERT_EQ(0, close(disconnected_svr_sock));
  5403. }
  5404. #endif // #ifndef _WIN32
  5405. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5406. static constexpr unsigned int number_of_task{1000000};
  5407. std::atomic_uint count{0};
  5408. std::unique_ptr<TaskQueue> task_queue{
  5409. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5410. for (unsigned int i = 0; i < number_of_task; ++i) {
  5411. task_queue->enqueue(
  5412. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5413. }
  5414. EXPECT_NO_THROW(task_queue->shutdown());
  5415. EXPECT_EQ(number_of_task, count.load());
  5416. }
  5417. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5418. Server svr;
  5419. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5420. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5421. });
  5422. svr.Get("/hello", [](const Request &req, Response &res) {
  5423. res.set_content(req.get_param_value("key"), "text/plain");
  5424. });
  5425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5426. auto se = detail::scope_exit([&] {
  5427. svr.stop();
  5428. thread.join();
  5429. ASSERT_FALSE(svr.is_running());
  5430. });
  5431. std::this_thread::sleep_for(std::chrono::seconds(1));
  5432. {
  5433. Client cli(HOST, PORT);
  5434. cli.set_follow_location(true);
  5435. auto res = cli.Get("/");
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(200, res->status);
  5438. EXPECT_EQ("val&key2=val2", res->body);
  5439. }
  5440. }
  5441. TEST(VulnerabilityTest, CRLFInjection) {
  5442. Server svr;
  5443. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  5444. res.set_content("Hello 1", "text/plain");
  5445. });
  5446. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  5447. res.set_content("Hello 2", "text/plain");
  5448. });
  5449. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  5450. res.set_content("Hello 3", "text/plain");
  5451. });
  5452. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  5453. res.set_content("Hello 4", "text/plain");
  5454. });
  5455. svr.set_logger([](const Request &req, const Response & /*res*/) {
  5456. for (const auto &x : req.headers) {
  5457. auto key = x.first;
  5458. EXPECT_STRNE("evil", key.c_str());
  5459. }
  5460. });
  5461. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5462. auto se = detail::scope_exit([&] {
  5463. svr.stop();
  5464. thread.join();
  5465. ASSERT_FALSE(svr.is_running());
  5466. });
  5467. std::this_thread::sleep_for(std::chrono::seconds(1));
  5468. {
  5469. Client cli(HOST, PORT);
  5470. cli.Post("/test1", "A=B",
  5471. "application/x-www-form-urlencoded\r\nevil: hello1");
  5472. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  5473. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  5474. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  5475. }
  5476. }
  5477. TEST(PathParamsTest, StaticMatch) {
  5478. const auto pattern = "/users/all";
  5479. detail::PathParamsMatcher matcher(pattern);
  5480. Request request;
  5481. request.path = "/users/all";
  5482. ASSERT_TRUE(matcher.match(request));
  5483. std::unordered_map<std::string, std::string> expected_params = {};
  5484. EXPECT_EQ(request.path_params, expected_params);
  5485. }
  5486. TEST(PathParamsTest, StaticMismatch) {
  5487. const auto pattern = "/users/all";
  5488. detail::PathParamsMatcher matcher(pattern);
  5489. Request request;
  5490. request.path = "/users/1";
  5491. ASSERT_FALSE(matcher.match(request));
  5492. }
  5493. TEST(PathParamsTest, SingleParamInTheMiddle) {
  5494. const auto pattern = "/users/:id/subscriptions";
  5495. detail::PathParamsMatcher matcher(pattern);
  5496. Request request;
  5497. request.path = "/users/42/subscriptions";
  5498. ASSERT_TRUE(matcher.match(request));
  5499. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5500. EXPECT_EQ(request.path_params, expected_params);
  5501. }
  5502. TEST(PathParamsTest, SingleParamInTheEnd) {
  5503. const auto pattern = "/users/:id";
  5504. detail::PathParamsMatcher matcher(pattern);
  5505. Request request;
  5506. request.path = "/users/24";
  5507. ASSERT_TRUE(matcher.match(request));
  5508. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  5509. EXPECT_EQ(request.path_params, expected_params);
  5510. }
  5511. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  5512. const auto pattern = "/users/:id/";
  5513. detail::PathParamsMatcher matcher(pattern);
  5514. Request request;
  5515. request.path = "/users/42/";
  5516. ASSERT_TRUE(matcher.match(request));
  5517. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5518. EXPECT_EQ(request.path_params, expected_params);
  5519. }
  5520. TEST(PathParamsTest, EmptyParam) {
  5521. const auto pattern = "/users/:id/";
  5522. detail::PathParamsMatcher matcher(pattern);
  5523. Request request;
  5524. request.path = "/users//";
  5525. ASSERT_TRUE(matcher.match(request));
  5526. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  5527. EXPECT_EQ(request.path_params, expected_params);
  5528. }
  5529. TEST(PathParamsTest, FragmentMismatch) {
  5530. const auto pattern = "/users/:id/";
  5531. detail::PathParamsMatcher matcher(pattern);
  5532. Request request;
  5533. request.path = "/admins/24/";
  5534. ASSERT_FALSE(matcher.match(request));
  5535. }
  5536. TEST(PathParamsTest, ExtraFragments) {
  5537. const auto pattern = "/users/:id";
  5538. detail::PathParamsMatcher matcher(pattern);
  5539. Request request;
  5540. request.path = "/users/42/subscriptions";
  5541. ASSERT_FALSE(matcher.match(request));
  5542. }
  5543. TEST(PathParamsTest, MissingTrailingParam) {
  5544. const auto pattern = "/users/:id";
  5545. detail::PathParamsMatcher matcher(pattern);
  5546. Request request;
  5547. request.path = "/users";
  5548. ASSERT_FALSE(matcher.match(request));
  5549. }
  5550. TEST(PathParamsTest, MissingParamInTheMiddle) {
  5551. const auto pattern = "/users/:id/subscriptions";
  5552. detail::PathParamsMatcher matcher(pattern);
  5553. Request request;
  5554. request.path = "/users/subscriptions";
  5555. ASSERT_FALSE(matcher.match(request));
  5556. }
  5557. TEST(PathParamsTest, MultipleParams) {
  5558. const auto pattern = "/users/:userid/subscriptions/:subid";
  5559. detail::PathParamsMatcher matcher(pattern);
  5560. Request request;
  5561. request.path = "/users/42/subscriptions/2";
  5562. ASSERT_TRUE(matcher.match(request));
  5563. std::unordered_map<std::string, std::string> expected_params = {
  5564. {"userid", "42"}, {"subid", "2"}};
  5565. EXPECT_EQ(request.path_params, expected_params);
  5566. }
  5567. TEST(PathParamsTest, SequenceOfParams) {
  5568. const auto pattern = "/values/:x/:y/:z";
  5569. detail::PathParamsMatcher matcher(pattern);
  5570. Request request;
  5571. request.path = "/values/1/2/3";
  5572. ASSERT_TRUE(matcher.match(request));
  5573. std::unordered_map<std::string, std::string> expected_params = {
  5574. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  5575. EXPECT_EQ(request.path_params, expected_params);
  5576. }