test.cc 211 KB

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