test.cc 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900
  1. #include <httplib.h>
  2. #include <gtest/gtest.h>
  3. #include <atomic>
  4. #include <chrono>
  5. #include <future>
  6. #include <sstream>
  7. #include <stdexcept>
  8. #include <thread>
  9. #include <type_traits>
  10. #define SERVER_CERT_FILE "./cert.pem"
  11. #define SERVER_CERT2_FILE "./cert2.pem"
  12. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  13. #define CA_CERT_FILE "./ca-bundle.crt"
  14. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  15. #define CLIENT_CA_CERT_DIR "."
  16. #define CLIENT_CERT_FILE "./client.cert.pem"
  17. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  18. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  19. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  20. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  21. using namespace std;
  22. using namespace httplib;
  23. const char *HOST = "localhost";
  24. const int PORT = 1234;
  25. const string LONG_QUERY_VALUE = string(25000, '@');
  26. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  27. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  28. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  29. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  30. const char *key) {
  31. auto it = std::find_if(
  32. files.begin(), files.end(),
  33. [&](const MultipartFormData &file) { return file.name == key; });
  34. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  35. return *it;
  36. #else
  37. if (it != files.end()) { return *it; }
  38. throw std::runtime_error("invalid mulitpart form data name error");
  39. #endif
  40. }
  41. TEST(ConstructorTest, MoveConstructible) {
  42. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  43. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  44. }
  45. #ifdef _WIN32
  46. TEST(StartupTest, WSAStartup) {
  47. WSADATA wsaData;
  48. int ret = WSAStartup(0x0002, &wsaData);
  49. ASSERT_EQ(0, ret);
  50. }
  51. #endif
  52. TEST(DecodeURLTest, PercentCharacter) {
  53. EXPECT_EQ(
  54. detail::decode_url(
  55. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  56. false),
  57. R"(descrip=Gastos áéíóúñÑ 6)");
  58. }
  59. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  60. string unescapedCharacters = "-_.!~*'()";
  61. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  62. }
  63. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  64. string reservedCharacters = ";,/?:@&=+$";
  65. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  66. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  67. }
  68. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  69. string chineseCharacters = "中国語";
  70. string russianCharacters = "дом";
  71. string brazilianCharacters = "óculos";
  72. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  73. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  74. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  75. "%D0%B4%D0%BE%D0%BC");
  76. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  77. }
  78. TEST(TrimTests, TrimStringTests) {
  79. EXPECT_EQ("abc", detail::trim_copy("abc"));
  80. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  81. EXPECT_TRUE(detail::trim_copy("").empty());
  82. }
  83. TEST(SplitTest, ParseQueryString) {
  84. string s = "key1=val1&key2=val2&key3=val3";
  85. Params dic;
  86. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  87. [&](const char *b, const char *e) {
  88. string key, val;
  89. detail::split(b, e, '=', [&](const char *b, const char *e) {
  90. if (key.empty()) {
  91. key.assign(b, e);
  92. } else {
  93. val.assign(b, e);
  94. }
  95. });
  96. dic.emplace(key, val);
  97. });
  98. EXPECT_EQ("val1", dic.find("key1")->second);
  99. EXPECT_EQ("val2", dic.find("key2")->second);
  100. EXPECT_EQ("val3", dic.find("key3")->second);
  101. }
  102. TEST(SplitTest, ParseInvalidQueryTests) {
  103. {
  104. string s = " ";
  105. Params dict;
  106. detail::parse_query_text(s, dict);
  107. EXPECT_TRUE(dict.empty());
  108. }
  109. {
  110. string s = " = =";
  111. Params dict;
  112. detail::parse_query_text(s, dict);
  113. EXPECT_TRUE(dict.empty());
  114. }
  115. }
  116. TEST(ParseQueryTest, ParseQueryString) {
  117. string s = "key1=val1&key2=val2&key3=val3";
  118. Params dic;
  119. detail::parse_query_text(s, dic);
  120. EXPECT_EQ("val1", dic.find("key1")->second);
  121. EXPECT_EQ("val2", dic.find("key2")->second);
  122. EXPECT_EQ("val3", dic.find("key3")->second);
  123. }
  124. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  125. Params dic;
  126. EXPECT_EQ(detail::params_to_query_str(dic), "");
  127. dic.emplace("key1", "val1");
  128. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  129. dic.emplace("key2", "val2");
  130. dic.emplace("key3", "val3");
  131. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  132. }
  133. TEST(GetHeaderValueTest, DefaultValue) {
  134. Headers headers = {{"Dummy", "Dummy"}};
  135. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  136. EXPECT_STREQ("text/plain", val);
  137. }
  138. TEST(GetHeaderValueTest, DefaultValueInt) {
  139. Headers headers = {{"Dummy", "Dummy"}};
  140. auto val =
  141. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  142. EXPECT_EQ(100ull, val);
  143. }
  144. TEST(GetHeaderValueTest, RegularValue) {
  145. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  146. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  147. EXPECT_STREQ("text/html", val);
  148. }
  149. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  150. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  151. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  152. EXPECT_STREQ("text/html", val);
  153. }
  154. TEST(GetHeaderValueTest, SetContent) {
  155. Response res;
  156. res.set_content("html", "text/html");
  157. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  158. res.set_content("text", "text/plain");
  159. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  160. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  161. }
  162. TEST(GetHeaderValueTest, RegularValueInt) {
  163. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  164. auto val =
  165. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  166. EXPECT_EQ(100ull, val);
  167. }
  168. TEST(GetHeaderValueTest, Range) {
  169. {
  170. Headers headers = {make_range_header({{1, -1}})};
  171. auto val = detail::get_header_value(headers, "Range", 0, 0);
  172. EXPECT_STREQ("bytes=1-", val);
  173. }
  174. {
  175. Headers headers = {make_range_header({{-1, 1}})};
  176. auto val = detail::get_header_value(headers, "Range", 0, 0);
  177. EXPECT_STREQ("bytes=-1", val);
  178. }
  179. {
  180. Headers headers = {make_range_header({{1, 10}})};
  181. auto val = detail::get_header_value(headers, "Range", 0, 0);
  182. EXPECT_STREQ("bytes=1-10", val);
  183. }
  184. {
  185. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  186. auto val = detail::get_header_value(headers, "Range", 0, 0);
  187. EXPECT_STREQ("bytes=1-10, 100-", val);
  188. }
  189. {
  190. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  191. auto val = detail::get_header_value(headers, "Range", 0, 0);
  192. EXPECT_STREQ("bytes=1-10, 100-200", val);
  193. }
  194. {
  195. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  196. auto val = detail::get_header_value(headers, "Range", 0, 0);
  197. EXPECT_STREQ("bytes=0-0, -1", val);
  198. }
  199. }
  200. TEST(ParseHeaderValueTest, Range) {
  201. {
  202. Ranges ranges;
  203. auto ret = detail::parse_range_header("bytes=1-", ranges);
  204. EXPECT_TRUE(ret);
  205. EXPECT_EQ(1u, ranges.size());
  206. EXPECT_EQ(1u, ranges[0].first);
  207. EXPECT_EQ(-1, ranges[0].second);
  208. }
  209. {
  210. Ranges ranges;
  211. auto ret = detail::parse_range_header("bytes=-1", ranges);
  212. EXPECT_TRUE(ret);
  213. EXPECT_EQ(1u, ranges.size());
  214. EXPECT_EQ(-1, ranges[0].first);
  215. EXPECT_EQ(1u, ranges[0].second);
  216. }
  217. {
  218. Ranges ranges;
  219. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  220. EXPECT_TRUE(ret);
  221. EXPECT_EQ(1u, ranges.size());
  222. EXPECT_EQ(1u, ranges[0].first);
  223. EXPECT_EQ(10u, ranges[0].second);
  224. }
  225. {
  226. Ranges ranges;
  227. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  228. EXPECT_FALSE(ret);
  229. }
  230. {
  231. Ranges ranges;
  232. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  233. EXPECT_TRUE(ret);
  234. EXPECT_EQ(2u, ranges.size());
  235. EXPECT_EQ(1u, ranges[0].first);
  236. EXPECT_EQ(10u, ranges[0].second);
  237. EXPECT_EQ(100u, ranges[1].first);
  238. EXPECT_EQ(-1, ranges[1].second);
  239. }
  240. {
  241. Ranges ranges;
  242. auto ret =
  243. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  244. EXPECT_TRUE(ret);
  245. EXPECT_EQ(3u, ranges.size());
  246. EXPECT_EQ(1u, ranges[0].first);
  247. EXPECT_EQ(10u, ranges[0].second);
  248. EXPECT_EQ(100u, ranges[1].first);
  249. EXPECT_EQ(200u, ranges[1].second);
  250. EXPECT_EQ(300u, ranges[2].first);
  251. EXPECT_EQ(400u, ranges[2].second);
  252. }
  253. }
  254. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  255. Request req;
  256. req.set_header("Accept-Encoding", "gzip");
  257. Response res;
  258. res.set_header("Content-Type", "text/plain");
  259. auto ret = detail::encoding_type(req, res);
  260. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  261. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  262. #else
  263. EXPECT_TRUE(ret == detail::EncodingType::None);
  264. #endif
  265. }
  266. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  267. Request req;
  268. req.set_header("Accept-Encoding", "gzip, deflate, br");
  269. Response res;
  270. res.set_header("Content-Type", "text/plain");
  271. auto ret = detail::encoding_type(req, res);
  272. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  273. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  274. #elif CPPHTTPLIB_ZLIB_SUPPORT
  275. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  276. #else
  277. EXPECT_TRUE(ret == detail::EncodingType::None);
  278. #endif
  279. }
  280. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  281. Request req;
  282. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  283. Response res;
  284. res.set_header("Content-Type", "text/plain");
  285. auto ret = detail::encoding_type(req, res);
  286. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  287. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  288. #elif CPPHTTPLIB_ZLIB_SUPPORT
  289. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  290. #else
  291. EXPECT_TRUE(ret == detail::EncodingType::None);
  292. #endif
  293. }
  294. TEST(BufferStreamTest, read) {
  295. detail::BufferStream strm1;
  296. Stream &strm = strm1;
  297. EXPECT_EQ(5, strm.write("hello"));
  298. char buf[512];
  299. EXPECT_EQ(2, strm.read(buf, 2));
  300. EXPECT_EQ('h', buf[0]);
  301. EXPECT_EQ('e', buf[1]);
  302. EXPECT_EQ(2, strm.read(buf, 2));
  303. EXPECT_EQ('l', buf[0]);
  304. EXPECT_EQ('l', buf[1]);
  305. EXPECT_EQ(1, strm.read(buf, 1));
  306. EXPECT_EQ('o', buf[0]);
  307. EXPECT_EQ(0, strm.read(buf, 1));
  308. }
  309. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  310. auto host = "www.httpwatch.com";
  311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  312. auto port = 443;
  313. SSLClient cli(host, port);
  314. #else
  315. auto port = 80;
  316. Client cli(host, port);
  317. #endif
  318. cli.set_connection_timeout(2);
  319. auto res =
  320. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  321. ASSERT_TRUE(res);
  322. std::string out;
  323. detail::read_file("./image.jpg", out);
  324. EXPECT_EQ(200, res->status);
  325. EXPECT_EQ(out, res->body);
  326. }
  327. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  328. auto host = "www.httpwatch.com";
  329. auto ip = hosted_at(host);
  330. EXPECT_EQ("191.236.16.12", ip);
  331. std::vector<std::string> addrs;
  332. hosted_at(host, addrs);
  333. EXPECT_EQ(1u, addrs.size());
  334. }
  335. #if 0 // It depends on each test environment...
  336. TEST(HostnameToIPConversionTest, YouTube_Online) {
  337. auto host = "www.youtube.com";
  338. std::vector<std::string> addrs;
  339. hosted_at(host, addrs);
  340. EXPECT_EQ(20u, addrs.size());
  341. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  342. EXPECT_TRUE(it != addrs.end());
  343. }
  344. #endif
  345. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  346. auto host = "www.httpwatch.com";
  347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  348. auto port = 443;
  349. SSLClient cli(host, port);
  350. #else
  351. auto port = 80;
  352. Client cli(host, port);
  353. #endif
  354. cli.set_connection_timeout(2);
  355. std::string body;
  356. auto res =
  357. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  358. [&](const char *data, size_t data_length) {
  359. body.append(data, data_length);
  360. return true;
  361. });
  362. ASSERT_TRUE(res);
  363. std::string out;
  364. detail::read_file("./image.jpg", out);
  365. EXPECT_EQ(200, res->status);
  366. EXPECT_EQ(out, body);
  367. }
  368. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  369. auto host = "www.httpwatch.com";
  370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  371. auto port = 443;
  372. SSLClient cli(host, port);
  373. #else
  374. auto port = 80;
  375. Client cli(host, port);
  376. #endif
  377. cli.set_connection_timeout(2);
  378. std::string body;
  379. auto res = cli.Get(
  380. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  381. [&](const Response &response) {
  382. EXPECT_EQ(200, response.status);
  383. return true;
  384. },
  385. [&](const char *data, size_t data_length) {
  386. body.append(data, data_length);
  387. return true;
  388. });
  389. ASSERT_TRUE(res);
  390. std::string out;
  391. detail::read_file("./image.jpg", out);
  392. EXPECT_EQ(200, res->status);
  393. EXPECT_EQ(out, body);
  394. }
  395. TEST(RangeTest, FromHTTPBin_Online) {
  396. auto host = "httpbin.org";
  397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  398. auto port = 443;
  399. SSLClient cli(host, port);
  400. #else
  401. auto port = 80;
  402. Client cli(host, port);
  403. #endif
  404. cli.set_connection_timeout(5);
  405. {
  406. auto res = cli.Get("/range/32");
  407. ASSERT_TRUE(res);
  408. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  409. EXPECT_EQ(200, res->status);
  410. }
  411. {
  412. Headers headers = {make_range_header({{1, -1}})};
  413. auto res = cli.Get("/range/32", headers);
  414. ASSERT_TRUE(res);
  415. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  416. EXPECT_EQ(206, res->status);
  417. }
  418. {
  419. Headers headers = {make_range_header({{1, 10}})};
  420. auto res = cli.Get("/range/32", headers);
  421. ASSERT_TRUE(res);
  422. EXPECT_EQ("bcdefghijk", res->body);
  423. EXPECT_EQ(206, res->status);
  424. }
  425. {
  426. Headers headers = {make_range_header({{0, 31}})};
  427. auto res = cli.Get("/range/32", headers);
  428. ASSERT_TRUE(res);
  429. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  430. EXPECT_EQ(200, res->status);
  431. }
  432. {
  433. Headers headers = {make_range_header({{0, -1}})};
  434. auto res = cli.Get("/range/32", headers);
  435. ASSERT_TRUE(res);
  436. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  437. EXPECT_EQ(200, res->status);
  438. }
  439. {
  440. Headers headers = {make_range_header({{0, 32}})};
  441. auto res = cli.Get("/range/32", headers);
  442. ASSERT_TRUE(res);
  443. EXPECT_EQ(416, res->status);
  444. }
  445. }
  446. TEST(ConnectionErrorTest, InvalidHost) {
  447. auto host = "-abcde.com";
  448. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  449. auto port = 443;
  450. SSLClient cli(host, port);
  451. #else
  452. auto port = 80;
  453. Client cli(host, port);
  454. #endif
  455. cli.set_connection_timeout(std::chrono::seconds(2));
  456. auto res = cli.Get("/");
  457. ASSERT_TRUE(!res);
  458. EXPECT_EQ(Error::Connection, res.error());
  459. }
  460. TEST(ConnectionErrorTest, InvalidHost2) {
  461. auto host = "httpbin.org/";
  462. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  463. SSLClient cli(host);
  464. #else
  465. Client cli(host);
  466. #endif
  467. cli.set_connection_timeout(std::chrono::seconds(2));
  468. auto res = cli.Get("/");
  469. ASSERT_TRUE(!res);
  470. EXPECT_EQ(Error::Connection, res.error());
  471. }
  472. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  473. auto host = "httpbin.org/";
  474. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  475. SSLClient cli(host);
  476. #else
  477. Client cli(host);
  478. #endif
  479. cli.set_connection_timeout(std::chrono::seconds(2));
  480. auto res = cli.Get("/");
  481. ASSERT_TRUE(!res);
  482. stringstream s;
  483. s << "error code: " << res.error();
  484. EXPECT_EQ("error code: Connection (2)", s.str());
  485. }
  486. TEST(ConnectionErrorTest, InvalidPort) {
  487. auto host = "localhost";
  488. auto port = 44380;
  489. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  490. SSLClient cli(host, port);
  491. #else
  492. Client cli(host, port);
  493. #endif
  494. cli.set_connection_timeout(std::chrono::seconds(2));
  495. auto res = cli.Get("/");
  496. ASSERT_TRUE(!res);
  497. EXPECT_TRUE(Error::Connection == res.error() ||
  498. Error::ConnectionTimeout == res.error());
  499. }
  500. TEST(ConnectionErrorTest, Timeout_Online) {
  501. auto host = "google.com";
  502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  503. auto port = 44380;
  504. SSLClient cli(host, port);
  505. #else
  506. auto port = 8080;
  507. Client cli(host, port);
  508. #endif
  509. cli.set_connection_timeout(std::chrono::seconds(2));
  510. // only probe one address type so that the error reason
  511. // correlates to the timed-out IPv4, not the unsupported
  512. // IPv6 connection attempt
  513. cli.set_address_family(AF_INET);
  514. auto res = cli.Get("/");
  515. ASSERT_TRUE(!res);
  516. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  517. }
  518. TEST(CancelTest, NoCancel_Online) {
  519. auto host = "httpbin.org";
  520. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  521. auto port = 443;
  522. SSLClient cli(host, port);
  523. #else
  524. auto port = 80;
  525. Client cli(host, port);
  526. #endif
  527. cli.set_connection_timeout(std::chrono::seconds(5));
  528. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  529. ASSERT_TRUE(res);
  530. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  531. EXPECT_EQ(200, res->status);
  532. }
  533. TEST(CancelTest, WithCancelSmallPayload_Online) {
  534. auto host = "httpbin.org";
  535. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  536. auto port = 443;
  537. SSLClient cli(host, port);
  538. #else
  539. auto port = 80;
  540. Client cli(host, port);
  541. #endif
  542. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  543. cli.set_connection_timeout(std::chrono::seconds(5));
  544. ASSERT_TRUE(!res);
  545. EXPECT_EQ(Error::Canceled, res.error());
  546. }
  547. TEST(CancelTest, WithCancelLargePayload_Online) {
  548. auto host = "httpbin.org";
  549. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  550. auto port = 443;
  551. SSLClient cli(host, port);
  552. #else
  553. auto port = 80;
  554. Client cli(host, port);
  555. #endif
  556. cli.set_connection_timeout(std::chrono::seconds(5));
  557. uint32_t count = 0;
  558. auto res = cli.Get("/range/65536",
  559. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  560. ASSERT_TRUE(!res);
  561. EXPECT_EQ(Error::Canceled, res.error());
  562. }
  563. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  564. auto host = "httpbin.org";
  565. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  566. auto port = 443;
  567. SSLClient cli(host, port);
  568. #else
  569. auto port = 80;
  570. Client cli(host, port);
  571. #endif
  572. {
  573. auto res = cli.Get("/basic-auth/hello/world");
  574. ASSERT_TRUE(res);
  575. EXPECT_EQ(401, res->status);
  576. }
  577. {
  578. auto res = cli.Get("/basic-auth/hello/world",
  579. {make_basic_authentication_header("hello", "world")});
  580. ASSERT_TRUE(res);
  581. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  582. res->body);
  583. EXPECT_EQ(200, res->status);
  584. }
  585. {
  586. cli.set_basic_auth("hello", "world");
  587. auto res = cli.Get("/basic-auth/hello/world");
  588. ASSERT_TRUE(res);
  589. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  590. res->body);
  591. EXPECT_EQ(200, res->status);
  592. }
  593. {
  594. cli.set_basic_auth("hello", "bad");
  595. auto res = cli.Get("/basic-auth/hello/world");
  596. ASSERT_TRUE(res);
  597. EXPECT_EQ(401, res->status);
  598. }
  599. {
  600. cli.set_basic_auth("bad", "world");
  601. auto res = cli.Get("/basic-auth/hello/world");
  602. ASSERT_TRUE(res);
  603. EXPECT_EQ(401, res->status);
  604. }
  605. }
  606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  607. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  608. auto host = "httpbin.org";
  609. auto port = 443;
  610. SSLClient cli(host, port);
  611. {
  612. auto res = cli.Get("/digest-auth/auth/hello/world");
  613. ASSERT_TRUE(res);
  614. EXPECT_EQ(401, res->status);
  615. }
  616. {
  617. std::vector<std::string> paths = {
  618. "/digest-auth/auth/hello/world/MD5",
  619. "/digest-auth/auth/hello/world/SHA-256",
  620. "/digest-auth/auth/hello/world/SHA-512",
  621. "/digest-auth/auth-int/hello/world/MD5",
  622. };
  623. cli.set_digest_auth("hello", "world");
  624. for (auto path : paths) {
  625. auto res = cli.Get(path.c_str());
  626. ASSERT_TRUE(res);
  627. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  628. res->body);
  629. EXPECT_EQ(200, res->status);
  630. }
  631. cli.set_digest_auth("hello", "bad");
  632. for (auto path : paths) {
  633. auto res = cli.Get(path.c_str());
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(401, res->status);
  636. }
  637. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  638. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  639. // cli.set_digest_auth("bad", "world");
  640. // for (auto path : paths) {
  641. // auto res = cli.Get(path.c_str());
  642. // ASSERT_TRUE(res);
  643. // EXPECT_EQ(400, res->status);
  644. // }
  645. }
  646. }
  647. #endif
  648. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  649. auto host = "google.com";
  650. auto another_host = "example.com";
  651. auto wrong_ip = "0.0.0.0";
  652. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  653. SSLClient cli(host);
  654. #else
  655. Client cli(host);
  656. #endif
  657. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  658. auto res = cli.Get("/");
  659. ASSERT_TRUE(res);
  660. ASSERT_EQ(301, res->status);
  661. }
  662. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  663. auto host = "google.com";
  664. auto wrong_ip = "0.0.0.0";
  665. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  666. SSLClient cli(host);
  667. #else
  668. Client cli(host);
  669. #endif
  670. cli.set_hostname_addr_map({{host, wrong_ip}});
  671. auto res = cli.Get("/");
  672. ASSERT_TRUE(!res);
  673. EXPECT_EQ(Error::Connection, res.error());
  674. }
  675. TEST(AbsoluteRedirectTest, Redirect_Online) {
  676. auto host = "nghttp2.org";
  677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  678. SSLClient cli(host);
  679. #else
  680. Client cli(host);
  681. #endif
  682. cli.set_follow_location(true);
  683. auto res = cli.Get("/httpbin/absolute-redirect/3");
  684. ASSERT_TRUE(res);
  685. EXPECT_EQ(200, res->status);
  686. }
  687. TEST(RedirectTest, Redirect_Online) {
  688. auto host = "nghttp2.org";
  689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  690. SSLClient cli(host);
  691. #else
  692. Client cli(host);
  693. #endif
  694. cli.set_follow_location(true);
  695. auto res = cli.Get("/httpbin/redirect/3");
  696. ASSERT_TRUE(res);
  697. EXPECT_EQ(200, res->status);
  698. }
  699. TEST(RelativeRedirectTest, Redirect_Online) {
  700. auto host = "nghttp2.org";
  701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  702. SSLClient cli(host);
  703. #else
  704. Client cli(host);
  705. #endif
  706. cli.set_follow_location(true);
  707. auto res = cli.Get("/httpbin/relative-redirect/3");
  708. ASSERT_TRUE(res);
  709. EXPECT_EQ(200, res->status);
  710. }
  711. TEST(TooManyRedirectTest, Redirect_Online) {
  712. auto host = "nghttp2.org";
  713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  714. SSLClient cli(host);
  715. #else
  716. Client cli(host);
  717. #endif
  718. cli.set_follow_location(true);
  719. auto res = cli.Get("/httpbin/redirect/21");
  720. ASSERT_TRUE(!res);
  721. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  722. }
  723. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  724. TEST(YahooRedirectTest, Redirect_Online) {
  725. Client cli("yahoo.com");
  726. auto res = cli.Get("/");
  727. ASSERT_TRUE(res);
  728. EXPECT_EQ(301, res->status);
  729. cli.set_follow_location(true);
  730. res = cli.Get("/");
  731. ASSERT_TRUE(res);
  732. EXPECT_EQ(200, res->status);
  733. EXPECT_EQ("https://yahoo.com/", res->location);
  734. }
  735. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  736. SSLClient cli("nghttp2.org");
  737. cli.set_follow_location(true);
  738. auto res = cli.Get(
  739. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  740. ASSERT_TRUE(res);
  741. EXPECT_EQ(200, res->status);
  742. }
  743. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  744. SSLClient cli("nghttp2.org");
  745. cli.set_follow_location(true);
  746. Params params;
  747. params.emplace("url", "http://www.google.com");
  748. params.emplace("status_code", "302");
  749. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  750. ASSERT_TRUE(res);
  751. EXPECT_EQ(200, res->status);
  752. }
  753. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  754. SSLClient cli("nghttp2.org");
  755. cli.set_follow_location(true);
  756. Params params;
  757. params.emplace("url", "http://www.google.com");
  758. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  759. ASSERT_TRUE(res);
  760. EXPECT_EQ(200, res->status);
  761. }
  762. TEST(UrlWithSpace, Redirect_Online) {
  763. SSLClient cli("edge.forgecdn.net");
  764. cli.set_follow_location(true);
  765. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  766. ASSERT_TRUE(res);
  767. EXPECT_EQ(200, res->status);
  768. EXPECT_EQ(18527U, res->get_header_value<uint64_t>("Content-Length"));
  769. }
  770. #endif
  771. TEST(RedirectToDifferentPort, Redirect) {
  772. Server svr1;
  773. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  774. res.set_content("Hello World!", "text/plain");
  775. });
  776. int svr1_port = 0;
  777. auto thread1 = std::thread([&]() {
  778. svr1_port = svr1.bind_to_any_port("localhost");
  779. svr1.listen_after_bind();
  780. });
  781. Server svr2;
  782. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  783. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  784. });
  785. int svr2_port = 0;
  786. auto thread2 = std::thread([&]() {
  787. svr2_port = svr2.bind_to_any_port("localhost");
  788. svr2.listen_after_bind();
  789. });
  790. while (!svr1.is_running() || !svr2.is_running()) {
  791. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  792. }
  793. // Give GET time to get a few messages.
  794. std::this_thread::sleep_for(std::chrono::seconds(1));
  795. Client cli("localhost", svr2_port);
  796. cli.set_follow_location(true);
  797. auto res = cli.Get("/2");
  798. ASSERT_TRUE(res);
  799. EXPECT_EQ(200, res->status);
  800. EXPECT_EQ("Hello World!", res->body);
  801. svr1.stop();
  802. svr2.stop();
  803. thread1.join();
  804. thread2.join();
  805. ASSERT_FALSE(svr1.is_running());
  806. ASSERT_FALSE(svr2.is_running());
  807. }
  808. TEST(RedirectFromPageWithContent, Redirect) {
  809. Server svr;
  810. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  811. res.set_content("___", "text/plain");
  812. res.set_redirect("/2");
  813. });
  814. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  815. res.set_content("Hello World!", "text/plain");
  816. });
  817. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  818. while (!svr.is_running()) {
  819. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  820. }
  821. // Give GET time to get a few messages.
  822. std::this_thread::sleep_for(std::chrono::seconds(1));
  823. {
  824. Client cli("localhost", PORT);
  825. cli.set_follow_location(true);
  826. std::string body;
  827. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  828. body.append(data, data_length);
  829. return true;
  830. });
  831. ASSERT_TRUE(res);
  832. EXPECT_EQ(200, res->status);
  833. EXPECT_EQ("Hello World!", body);
  834. }
  835. {
  836. Client cli("localhost", PORT);
  837. std::string body;
  838. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  839. body.append(data, data_length);
  840. return true;
  841. });
  842. ASSERT_TRUE(res);
  843. EXPECT_EQ(302, res->status);
  844. EXPECT_EQ("___", body);
  845. }
  846. svr.stop();
  847. th.join();
  848. ASSERT_FALSE(svr.is_running());
  849. }
  850. TEST(RedirectFromPageWithContentIP6, Redirect) {
  851. Server svr;
  852. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  853. res.set_content("___", "text/plain");
  854. // res.set_redirect("/2");
  855. res.set_redirect("http://[::1]:1234/2");
  856. });
  857. svr.Get("/2", [&](const Request &req, Response &res) {
  858. auto host_header = req.headers.find("Host");
  859. ASSERT_TRUE(host_header != req.headers.end());
  860. EXPECT_EQ("[::1]:1234", host_header->second);
  861. res.set_content("Hello World!", "text/plain");
  862. });
  863. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  864. // When IPV6 support isn't available svr.listen("::1", 1234) never
  865. // actually starts anything, so the condition !svr.is_running() will
  866. // always remain true, and the loop never stops.
  867. // This basically counts how many milliseconds have passed since the
  868. // call to svr.listen(), and if after 5 seconds nothing started yet
  869. // aborts the test.
  870. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  871. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  872. ASSERT_LT(milliseconds, 5000U);
  873. }
  874. // Give GET time to get a few messages.
  875. std::this_thread::sleep_for(std::chrono::seconds(1));
  876. {
  877. Client cli("http://[::1]:1234");
  878. cli.set_follow_location(true);
  879. std::string body;
  880. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  881. body.append(data, data_length);
  882. return true;
  883. });
  884. ASSERT_TRUE(res);
  885. EXPECT_EQ(200, res->status);
  886. EXPECT_EQ("Hello World!", body);
  887. }
  888. {
  889. Client cli("http://[::1]:1234");
  890. std::string body;
  891. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  892. body.append(data, data_length);
  893. return true;
  894. });
  895. ASSERT_TRUE(res);
  896. EXPECT_EQ(302, res->status);
  897. EXPECT_EQ("___", body);
  898. }
  899. svr.stop();
  900. th.join();
  901. ASSERT_FALSE(svr.is_running());
  902. }
  903. TEST(PathUrlEncodeTest, PathUrlEncode) {
  904. Server svr;
  905. svr.Get("/foo", [](const Request &req, Response &res) {
  906. auto a = req.params.find("a");
  907. if (a != req.params.end()) {
  908. res.set_content((*a).second, "text/plain");
  909. res.status = 200;
  910. } else {
  911. res.status = 400;
  912. }
  913. });
  914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  915. // Give GET time to get a few messages.
  916. std::this_thread::sleep_for(std::chrono::seconds(1));
  917. {
  918. Client cli(HOST, PORT);
  919. cli.set_url_encode(false);
  920. auto res = cli.Get("/foo?a=explicitly+encoded");
  921. ASSERT_TRUE(res);
  922. EXPECT_EQ(200, res->status);
  923. // This expects it back with a space, as the `+` won't have been
  924. // url-encoded, and server-side the params get decoded turning `+`
  925. // into spaces.
  926. EXPECT_EQ("explicitly encoded", res->body);
  927. }
  928. svr.stop();
  929. thread.join();
  930. ASSERT_FALSE(svr.is_running());
  931. }
  932. TEST(BindServerTest, BindDualStack) {
  933. Server svr;
  934. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  935. res.set_content("Hello World!", "text/plain");
  936. });
  937. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  938. // Give GET time to get a few messages.
  939. std::this_thread::sleep_for(std::chrono::seconds(1));
  940. {
  941. Client cli("127.0.0.1", PORT);
  942. auto res = cli.Get("/1");
  943. ASSERT_TRUE(res);
  944. EXPECT_EQ(200, res->status);
  945. EXPECT_EQ("Hello World!", res->body);
  946. }
  947. {
  948. Client cli("::1", PORT);
  949. auto res = cli.Get("/1");
  950. ASSERT_TRUE(res);
  951. EXPECT_EQ(200, res->status);
  952. EXPECT_EQ("Hello World!", res->body);
  953. }
  954. svr.stop();
  955. thread.join();
  956. ASSERT_FALSE(svr.is_running());
  957. }
  958. TEST(BindServerTest, BindAndListenSeparately) {
  959. Server svr;
  960. int port = svr.bind_to_any_port("0.0.0.0");
  961. ASSERT_TRUE(svr.is_valid());
  962. ASSERT_TRUE(port > 0);
  963. svr.stop();
  964. }
  965. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  966. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  968. CLIENT_CA_CERT_DIR);
  969. int port = svr.bind_to_any_port("0.0.0.0");
  970. ASSERT_TRUE(svr.is_valid());
  971. ASSERT_TRUE(port > 0);
  972. svr.stop();
  973. }
  974. #endif
  975. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  976. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  977. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  978. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  979. int port = svr.bind_to_any_port("0.0.0.0");
  980. ASSERT_TRUE(svr.is_valid());
  981. ASSERT_TRUE(port > 0);
  982. svr.stop();
  983. }
  984. #endif
  985. TEST(ErrorHandlerTest, ContentLength) {
  986. Server svr;
  987. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  988. res.status = 200;
  989. res.set_content("abcdefghijklmnopqrstuvwxyz",
  990. "text/html"); // <= Content-Length still 13
  991. });
  992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  993. res.set_content("Hello World!\n", "text/plain");
  994. res.status = 524;
  995. });
  996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  997. // Give GET time to get a few messages.
  998. std::this_thread::sleep_for(std::chrono::seconds(1));
  999. {
  1000. Client cli(HOST, PORT);
  1001. auto res = cli.Get("/hi");
  1002. ASSERT_TRUE(res);
  1003. EXPECT_EQ(200, res->status);
  1004. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1005. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1006. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1007. }
  1008. svr.stop();
  1009. thread.join();
  1010. ASSERT_FALSE(svr.is_running());
  1011. }
  1012. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1013. TEST(ExceptionHandlerTest, ContentLength) {
  1014. Server svr;
  1015. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1016. std::exception &e) {
  1017. EXPECT_EQ("abc", std::string(e.what()));
  1018. res.status = 500;
  1019. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1020. "text/html"); // <= Content-Length still 13 at this point
  1021. });
  1022. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1023. res.set_content("Hello World!\n", "text/plain");
  1024. throw std::runtime_error("abc");
  1025. });
  1026. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1027. // Give GET time to get a few messages.
  1028. std::this_thread::sleep_for(std::chrono::seconds(1));
  1029. for (size_t i = 0; i < 10; i++) {
  1030. Client cli(HOST, PORT);
  1031. for (size_t j = 0; j < 100; j++) {
  1032. auto res = cli.Get("/hi");
  1033. ASSERT_TRUE(res);
  1034. EXPECT_EQ(500, res->status);
  1035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1036. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1037. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1038. }
  1039. cli.set_keep_alive(true);
  1040. for (size_t j = 0; j < 100; j++) {
  1041. auto res = cli.Get("/hi");
  1042. ASSERT_TRUE(res);
  1043. EXPECT_EQ(500, res->status);
  1044. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1045. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1046. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1047. }
  1048. }
  1049. svr.stop();
  1050. thread.join();
  1051. ASSERT_FALSE(svr.is_running());
  1052. }
  1053. #endif
  1054. TEST(NoContentTest, ContentLength) {
  1055. Server svr;
  1056. svr.Get("/hi",
  1057. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1058. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1059. // Give GET time to get a few messages.
  1060. std::this_thread::sleep_for(std::chrono::seconds(1));
  1061. {
  1062. Client cli(HOST, PORT);
  1063. auto res = cli.Get("/hi");
  1064. ASSERT_TRUE(res);
  1065. EXPECT_EQ(204, res->status);
  1066. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1067. }
  1068. svr.stop();
  1069. thread.join();
  1070. ASSERT_FALSE(svr.is_running());
  1071. }
  1072. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1073. Server svr;
  1074. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1075. if (req.path == "/routing_handler") {
  1076. res.set_header("PRE_ROUTING", "on");
  1077. res.set_content("Routing Handler", "text/plain");
  1078. return httplib::Server::HandlerResponse::Handled;
  1079. }
  1080. return httplib::Server::HandlerResponse::Unhandled;
  1081. });
  1082. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1083. res.set_content("Error", "text/html");
  1084. });
  1085. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1086. if (req.path == "/routing_handler") {
  1087. res.set_header("POST_ROUTING", "on");
  1088. }
  1089. });
  1090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1091. res.set_content("Hello World!\n", "text/plain");
  1092. });
  1093. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1094. // Give GET time to get a few messages.
  1095. std::this_thread::sleep_for(std::chrono::seconds(1));
  1096. {
  1097. Client cli(HOST, PORT);
  1098. auto res = cli.Get("/routing_handler");
  1099. ASSERT_TRUE(res);
  1100. EXPECT_EQ(200, res->status);
  1101. EXPECT_EQ("Routing Handler", res->body);
  1102. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1103. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1104. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1105. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1106. }
  1107. {
  1108. Client cli(HOST, PORT);
  1109. auto res = cli.Get("/hi");
  1110. ASSERT_TRUE(res);
  1111. EXPECT_EQ(200, res->status);
  1112. EXPECT_EQ("Hello World!\n", res->body);
  1113. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1114. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1115. }
  1116. {
  1117. Client cli(HOST, PORT);
  1118. auto res = cli.Get("/aaa");
  1119. ASSERT_TRUE(res);
  1120. EXPECT_EQ(404, res->status);
  1121. EXPECT_EQ("Error", res->body);
  1122. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1123. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1124. }
  1125. svr.stop();
  1126. thread.join();
  1127. ASSERT_FALSE(svr.is_running());
  1128. }
  1129. TEST(InvalidFormatTest, StatusCode) {
  1130. Server svr;
  1131. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1132. res.set_content("Hello World!\n", "text/plain");
  1133. res.status = 9999; // Status should be a three-digit code...
  1134. });
  1135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1136. // Give GET time to get a few messages.
  1137. std::this_thread::sleep_for(std::chrono::seconds(1));
  1138. {
  1139. Client cli(HOST, PORT);
  1140. auto res = cli.Get("/hi");
  1141. ASSERT_FALSE(res);
  1142. }
  1143. svr.stop();
  1144. thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. }
  1147. TEST(URLFragmentTest, WithFragment) {
  1148. Server svr;
  1149. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1150. EXPECT_TRUE(req.target == "/hi");
  1151. });
  1152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1153. std::this_thread::sleep_for(std::chrono::seconds(1));
  1154. {
  1155. Client cli(HOST, PORT);
  1156. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1157. EXPECT_TRUE(res);
  1158. EXPECT_EQ(200, res->status);
  1159. res = cli.Get("/hi%23key1=val1=key2=val2");
  1160. EXPECT_TRUE(res);
  1161. EXPECT_EQ(404, res->status);
  1162. }
  1163. svr.stop();
  1164. thread.join();
  1165. ASSERT_FALSE(svr.is_running());
  1166. }
  1167. class ServerTest : public ::testing::Test {
  1168. protected:
  1169. ServerTest()
  1170. : cli_(HOST, PORT)
  1171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1172. ,
  1173. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1174. #endif
  1175. {
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. cli_.enable_server_certificate_verification(false);
  1178. #endif
  1179. }
  1180. virtual void SetUp() {
  1181. svr_.set_mount_point("/", "./www");
  1182. svr_.set_mount_point("/mount", "./www2");
  1183. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1184. svr_.Get("/hi",
  1185. [&](const Request & /*req*/, Response &res) {
  1186. res.set_content("Hello World!", "text/plain");
  1187. })
  1188. .Get("/http_response_splitting",
  1189. [&](const Request & /*req*/, Response &res) {
  1190. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1191. EXPECT_EQ(0U, res.headers.size());
  1192. EXPECT_FALSE(res.has_header("a"));
  1193. res.set_header("a", "1\nSet-Cookie: a=1");
  1194. EXPECT_EQ(0U, res.headers.size());
  1195. EXPECT_FALSE(res.has_header("a"));
  1196. res.set_header("a", "1\rSet-Cookie: a=1");
  1197. EXPECT_EQ(0U, res.headers.size());
  1198. EXPECT_FALSE(res.has_header("a"));
  1199. res.set_header("a\r\nb", "0");
  1200. EXPECT_EQ(0U, res.headers.size());
  1201. EXPECT_FALSE(res.has_header("a"));
  1202. res.set_header("a\rb", "0");
  1203. EXPECT_EQ(0U, res.headers.size());
  1204. EXPECT_FALSE(res.has_header("a"));
  1205. res.set_header("a\nb", "0");
  1206. EXPECT_EQ(0U, res.headers.size());
  1207. EXPECT_FALSE(res.has_header("a"));
  1208. res.set_redirect("1\r\nSet-Cookie: a=1");
  1209. EXPECT_EQ(0U, res.headers.size());
  1210. EXPECT_FALSE(res.has_header("Location"));
  1211. })
  1212. .Get("/slow",
  1213. [&](const Request & /*req*/, Response &res) {
  1214. std::this_thread::sleep_for(std::chrono::seconds(2));
  1215. res.set_content("slow", "text/plain");
  1216. })
  1217. #if 0
  1218. .Post("/slowpost",
  1219. [&](const Request & /*req*/, Response &res) {
  1220. std::this_thread::sleep_for(std::chrono::seconds(2));
  1221. res.set_content("slow", "text/plain");
  1222. })
  1223. #endif
  1224. .Get("/remote_addr",
  1225. [&](const Request &req, Response &res) {
  1226. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1227. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1228. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1229. EXPECT_EQ(req.remote_port,
  1230. std::stoi(req.get_header_value("REMOTE_PORT")));
  1231. res.set_content(remote_addr.c_str(), "text/plain");
  1232. })
  1233. .Get("/endwith%",
  1234. [&](const Request & /*req*/, Response &res) {
  1235. res.set_content("Hello World!", "text/plain");
  1236. })
  1237. .Get("/a\\+\\+b",
  1238. [&](const Request &req, Response &res) {
  1239. ASSERT_TRUE(req.has_param("a +b"));
  1240. auto val = req.get_param_value("a +b");
  1241. res.set_content(val, "text/plain");
  1242. })
  1243. .Get("/", [&](const Request & /*req*/,
  1244. Response &res) { res.set_redirect("/hi"); })
  1245. .Post("/1", [](const Request & /*req*/,
  1246. Response &res) { res.set_redirect("/2", 303); })
  1247. .Get("/2",
  1248. [](const Request & /*req*/, Response &res) {
  1249. res.set_content("redirected.", "text/plain");
  1250. res.status = 200;
  1251. })
  1252. .Post("/person",
  1253. [&](const Request &req, Response &res) {
  1254. if (req.has_param("name") && req.has_param("note")) {
  1255. persons_[req.get_param_value("name")] =
  1256. req.get_param_value("note");
  1257. } else {
  1258. res.status = 400;
  1259. }
  1260. })
  1261. .Put("/person",
  1262. [&](const Request &req, Response &res) {
  1263. if (req.has_param("name") && req.has_param("note")) {
  1264. persons_[req.get_param_value("name")] =
  1265. req.get_param_value("note");
  1266. } else {
  1267. res.status = 400;
  1268. }
  1269. })
  1270. .Get("/person/(.*)",
  1271. [&](const Request &req, Response &res) {
  1272. string name = req.matches[1];
  1273. if (persons_.find(name) != persons_.end()) {
  1274. auto note = persons_[name];
  1275. res.set_content(note, "text/plain");
  1276. } else {
  1277. res.status = 404;
  1278. }
  1279. })
  1280. .Post("/x-www-form-urlencoded-json",
  1281. [&](const Request &req, Response &res) {
  1282. auto json = req.get_param_value("json");
  1283. ASSERT_EQ(JSON_DATA, json);
  1284. res.set_content(json, "appliation/json");
  1285. res.status = 200;
  1286. })
  1287. .Get("/streamed-chunked",
  1288. [&](const Request & /*req*/, Response &res) {
  1289. res.set_chunked_content_provider(
  1290. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1291. EXPECT_TRUE(sink.is_writable());
  1292. sink.os << "123";
  1293. sink.os << "456";
  1294. sink.os << "789";
  1295. sink.done();
  1296. return true;
  1297. });
  1298. })
  1299. .Get("/streamed-chunked2",
  1300. [&](const Request & /*req*/, Response &res) {
  1301. auto i = new int(0);
  1302. res.set_chunked_content_provider(
  1303. "text/plain",
  1304. [i](size_t /*offset*/, DataSink &sink) {
  1305. EXPECT_TRUE(sink.is_writable());
  1306. switch (*i) {
  1307. case 0: sink.os << "123"; break;
  1308. case 1: sink.os << "456"; break;
  1309. case 2: sink.os << "789"; break;
  1310. case 3: sink.done(); break;
  1311. }
  1312. (*i)++;
  1313. return true;
  1314. },
  1315. [i](bool success) {
  1316. EXPECT_TRUE(success);
  1317. delete i;
  1318. });
  1319. })
  1320. .Get("/streamed",
  1321. [&](const Request & /*req*/, Response &res) {
  1322. res.set_content_provider(
  1323. 6, "text/plain",
  1324. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1325. sink.os << (offset < 3 ? "a" : "b");
  1326. return true;
  1327. });
  1328. })
  1329. .Get("/streamed-with-range",
  1330. [&](const Request & /*req*/, Response &res) {
  1331. auto data = new std::string("abcdefg");
  1332. res.set_content_provider(
  1333. data->size(), "text/plain",
  1334. [data](size_t offset, size_t length, DataSink &sink) {
  1335. EXPECT_TRUE(sink.is_writable());
  1336. size_t DATA_CHUNK_SIZE = 4;
  1337. const auto &d = *data;
  1338. auto out_len =
  1339. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1340. auto ret =
  1341. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1342. EXPECT_TRUE(ret);
  1343. return true;
  1344. },
  1345. [data](bool success) {
  1346. EXPECT_TRUE(success);
  1347. delete data;
  1348. });
  1349. })
  1350. .Get("/streamed-cancel",
  1351. [&](const Request & /*req*/, Response &res) {
  1352. res.set_content_provider(
  1353. size_t(-1), "text/plain",
  1354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1355. EXPECT_TRUE(sink.is_writable());
  1356. sink.os << "data_chunk";
  1357. return true;
  1358. });
  1359. })
  1360. .Get("/with-range",
  1361. [&](const Request & /*req*/, Response &res) {
  1362. res.set_content("abcdefg", "text/plain");
  1363. })
  1364. .Post("/chunked",
  1365. [&](const Request &req, Response & /*res*/) {
  1366. EXPECT_EQ(req.body, "dechunked post body");
  1367. })
  1368. .Post("/large-chunked",
  1369. [&](const Request &req, Response & /*res*/) {
  1370. std::string expected(6 * 30 * 1024u, 'a');
  1371. EXPECT_EQ(req.body, expected);
  1372. })
  1373. .Post("/multipart",
  1374. [&](const Request &req, Response & /*res*/) {
  1375. EXPECT_EQ(6u, req.files.size());
  1376. ASSERT_TRUE(!req.has_file("???"));
  1377. ASSERT_TRUE(req.body.empty());
  1378. {
  1379. const auto &file = req.get_file_value("text1");
  1380. EXPECT_TRUE(file.filename.empty());
  1381. EXPECT_EQ("text default", file.content);
  1382. }
  1383. {
  1384. const auto &file = req.get_file_value("text2");
  1385. EXPECT_TRUE(file.filename.empty());
  1386. EXPECT_EQ("aωb", file.content);
  1387. }
  1388. {
  1389. const auto &file = req.get_file_value("file1");
  1390. EXPECT_EQ("hello.txt", file.filename);
  1391. EXPECT_EQ("text/plain", file.content_type);
  1392. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1393. }
  1394. {
  1395. const auto &file = req.get_file_value("file3");
  1396. EXPECT_TRUE(file.filename.empty());
  1397. EXPECT_EQ("application/octet-stream", file.content_type);
  1398. EXPECT_EQ(0u, file.content.size());
  1399. }
  1400. {
  1401. const auto &file = req.get_file_value("file4");
  1402. EXPECT_TRUE(file.filename.empty());
  1403. EXPECT_EQ(0u, file.content.size());
  1404. EXPECT_EQ("application/json tmp-string", file.content_type);
  1405. }
  1406. })
  1407. .Post("/empty",
  1408. [&](const Request &req, Response &res) {
  1409. EXPECT_EQ(req.body, "");
  1410. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1411. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1412. res.set_content("empty", "text/plain");
  1413. })
  1414. .Post("/empty-no-content-type",
  1415. [&](const Request &req, Response &res) {
  1416. EXPECT_EQ(req.body, "");
  1417. EXPECT_FALSE(req.has_header("Content-Type"));
  1418. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1419. res.set_content("empty-no-content-type", "text/plain");
  1420. })
  1421. .Post("/post-large",
  1422. [&](const Request &req, Response &res) {
  1423. EXPECT_EQ(req.body, LARGE_DATA);
  1424. res.set_content(req.body, "text/plain");
  1425. })
  1426. .Put("/empty-no-content-type",
  1427. [&](const Request &req, Response &res) {
  1428. EXPECT_EQ(req.body, "");
  1429. EXPECT_FALSE(req.has_header("Content-Type"));
  1430. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1431. res.set_content("empty-no-content-type", "text/plain");
  1432. })
  1433. .Put("/put",
  1434. [&](const Request &req, Response &res) {
  1435. EXPECT_EQ(req.body, "PUT");
  1436. res.set_content(req.body, "text/plain");
  1437. })
  1438. .Put("/put-large",
  1439. [&](const Request &req, Response &res) {
  1440. EXPECT_EQ(req.body, LARGE_DATA);
  1441. res.set_content(req.body, "text/plain");
  1442. })
  1443. .Patch("/patch",
  1444. [&](const Request &req, Response &res) {
  1445. EXPECT_EQ(req.body, "PATCH");
  1446. res.set_content(req.body, "text/plain");
  1447. })
  1448. .Delete("/delete",
  1449. [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("DELETE", "text/plain");
  1451. })
  1452. .Delete("/delete-body",
  1453. [&](const Request &req, Response &res) {
  1454. EXPECT_EQ(req.body, "content");
  1455. res.set_content(req.body, "text/plain");
  1456. })
  1457. .Options(R"(\*)",
  1458. [&](const Request & /*req*/, Response &res) {
  1459. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1460. })
  1461. .Get("/request-target",
  1462. [&](const Request &req, Response & /*res*/) {
  1463. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1464. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1465. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1466. })
  1467. .Get("/long-query-value",
  1468. [&](const Request &req, Response & /*res*/) {
  1469. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1470. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1471. })
  1472. .Get("/array-param",
  1473. [&](const Request &req, Response & /*res*/) {
  1474. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1475. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1476. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1477. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1478. })
  1479. .Post("/validate-no-multiple-headers",
  1480. [&](const Request &req, Response & /*res*/) {
  1481. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1482. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1483. })
  1484. .Post("/content_receiver",
  1485. [&](const Request &req, Response &res,
  1486. const ContentReader &content_reader) {
  1487. if (req.is_multipart_form_data()) {
  1488. MultipartFormDataItems files;
  1489. content_reader(
  1490. [&](const MultipartFormData &file) {
  1491. files.push_back(file);
  1492. return true;
  1493. },
  1494. [&](const char *data, size_t data_length) {
  1495. files.back().content.append(data, data_length);
  1496. return true;
  1497. });
  1498. EXPECT_EQ(5u, files.size());
  1499. {
  1500. const auto &file = get_file_value(files, "text1");
  1501. EXPECT_TRUE(file.filename.empty());
  1502. EXPECT_EQ("text default", file.content);
  1503. }
  1504. {
  1505. const auto &file = get_file_value(files, "text2");
  1506. EXPECT_TRUE(file.filename.empty());
  1507. EXPECT_EQ("aωb", file.content);
  1508. }
  1509. {
  1510. const auto &file = get_file_value(files, "file1");
  1511. EXPECT_EQ("hello.txt", file.filename);
  1512. EXPECT_EQ("text/plain", file.content_type);
  1513. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1514. }
  1515. {
  1516. const auto &file = get_file_value(files, "file3");
  1517. EXPECT_TRUE(file.filename.empty());
  1518. EXPECT_EQ("application/octet-stream", file.content_type);
  1519. EXPECT_EQ(0u, file.content.size());
  1520. }
  1521. } else {
  1522. std::string body;
  1523. content_reader([&](const char *data, size_t data_length) {
  1524. EXPECT_EQ(7U, data_length);
  1525. body.append(data, data_length);
  1526. return true;
  1527. });
  1528. EXPECT_EQ(body, "content");
  1529. res.set_content(body, "text/plain");
  1530. }
  1531. })
  1532. .Put("/content_receiver",
  1533. [&](const Request & /*req*/, Response &res,
  1534. const ContentReader &content_reader) {
  1535. std::string body;
  1536. content_reader([&](const char *data, size_t data_length) {
  1537. body.append(data, data_length);
  1538. return true;
  1539. });
  1540. EXPECT_EQ(body, "content");
  1541. res.set_content(body, "text/plain");
  1542. })
  1543. .Patch("/content_receiver",
  1544. [&](const Request & /*req*/, Response &res,
  1545. const ContentReader &content_reader) {
  1546. std::string body;
  1547. content_reader([&](const char *data, size_t data_length) {
  1548. body.append(data, data_length);
  1549. return true;
  1550. });
  1551. EXPECT_EQ(body, "content");
  1552. res.set_content(body, "text/plain");
  1553. })
  1554. .Post("/query-string-and-body",
  1555. [&](const Request &req, Response & /*res*/) {
  1556. ASSERT_TRUE(req.has_param("key"));
  1557. EXPECT_EQ(req.get_param_value("key"), "value");
  1558. EXPECT_EQ(req.body, "content");
  1559. })
  1560. .Get("/last-request",
  1561. [&](const Request &req, Response & /*res*/) {
  1562. EXPECT_EQ("close", req.get_header_value("Connection"));
  1563. })
  1564. .Get(R"(/redirect/(\d+))",
  1565. [&](const Request &req, Response &res) {
  1566. auto num = std::stoi(req.matches[1]) + 1;
  1567. std::string url = "/redirect/" + std::to_string(num);
  1568. res.set_redirect(url);
  1569. })
  1570. .Post("/binary",
  1571. [&](const Request &req, Response &res) {
  1572. EXPECT_EQ(4U, req.body.size());
  1573. EXPECT_EQ("application/octet-stream",
  1574. req.get_header_value("Content-Type"));
  1575. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1576. res.set_content(req.body, "application/octet-stream");
  1577. })
  1578. .Put("/binary",
  1579. [&](const Request &req, Response &res) {
  1580. EXPECT_EQ(4U, req.body.size());
  1581. EXPECT_EQ("application/octet-stream",
  1582. req.get_header_value("Content-Type"));
  1583. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1584. res.set_content(req.body, "application/octet-stream");
  1585. })
  1586. .Patch("/binary",
  1587. [&](const Request &req, Response &res) {
  1588. EXPECT_EQ(4U, req.body.size());
  1589. EXPECT_EQ("application/octet-stream",
  1590. req.get_header_value("Content-Type"));
  1591. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1592. res.set_content(req.body, "application/octet-stream");
  1593. })
  1594. .Delete("/binary",
  1595. [&](const Request &req, Response &res) {
  1596. EXPECT_EQ(4U, req.body.size());
  1597. EXPECT_EQ("application/octet-stream",
  1598. req.get_header_value("Content-Type"));
  1599. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1600. res.set_content(req.body, "application/octet-stream");
  1601. })
  1602. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1603. .Get("/compress",
  1604. [&](const Request & /*req*/, Response &res) {
  1605. res.set_content(
  1606. "12345678901234567890123456789012345678901234567890123456789"
  1607. "01234567890123456789012345678901234567890",
  1608. "text/plain");
  1609. })
  1610. .Get("/nocompress",
  1611. [&](const Request & /*req*/, Response &res) {
  1612. res.set_content(
  1613. "12345678901234567890123456789012345678901234567890123456789"
  1614. "01234567890123456789012345678901234567890",
  1615. "application/octet-stream");
  1616. })
  1617. .Post("/compress-multipart",
  1618. [&](const Request &req, Response & /*res*/) {
  1619. EXPECT_EQ(2u, req.files.size());
  1620. ASSERT_TRUE(!req.has_file("???"));
  1621. {
  1622. const auto &file = req.get_file_value("key1");
  1623. EXPECT_TRUE(file.filename.empty());
  1624. EXPECT_EQ("test", file.content);
  1625. }
  1626. {
  1627. const auto &file = req.get_file_value("key2");
  1628. EXPECT_TRUE(file.filename.empty());
  1629. EXPECT_EQ("--abcdefg123", file.content);
  1630. }
  1631. })
  1632. #endif
  1633. ;
  1634. persons_["john"] = "programmer";
  1635. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1636. while (!svr_.is_running()) {
  1637. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1638. }
  1639. }
  1640. virtual void TearDown() {
  1641. svr_.stop();
  1642. if (!request_threads_.empty()) {
  1643. std::this_thread::sleep_for(std::chrono::seconds(1));
  1644. for (auto &t : request_threads_) {
  1645. t.join();
  1646. }
  1647. }
  1648. t_.join();
  1649. }
  1650. map<string, string> persons_;
  1651. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1652. SSLClient cli_;
  1653. SSLServer svr_;
  1654. #else
  1655. Client cli_;
  1656. Server svr_;
  1657. #endif
  1658. thread t_;
  1659. std::vector<thread> request_threads_;
  1660. };
  1661. TEST_F(ServerTest, GetMethod200) {
  1662. auto res = cli_.Get("/hi");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ("HTTP/1.1", res->version);
  1665. EXPECT_EQ(200, res->status);
  1666. EXPECT_EQ("OK", res->reason);
  1667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1668. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1669. EXPECT_EQ("Hello World!", res->body);
  1670. }
  1671. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1672. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1673. ASSERT_TRUE(res);
  1674. EXPECT_EQ("HTTP/1.1", res->version);
  1675. EXPECT_EQ(200, res->status);
  1676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1677. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1678. EXPECT_EQ("Hello World!", res->body);
  1679. }
  1680. TEST_F(ServerTest, GetMethod302) {
  1681. auto res = cli_.Get("/");
  1682. ASSERT_TRUE(res);
  1683. EXPECT_EQ(302, res->status);
  1684. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1685. }
  1686. TEST_F(ServerTest, GetMethod302Redirect) {
  1687. cli_.set_follow_location(true);
  1688. auto res = cli_.Get("/");
  1689. ASSERT_TRUE(res);
  1690. EXPECT_EQ(200, res->status);
  1691. EXPECT_EQ("Hello World!", res->body);
  1692. EXPECT_EQ("/hi", res->location);
  1693. }
  1694. TEST_F(ServerTest, GetMethod404) {
  1695. auto res = cli_.Get("/invalid");
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(404, res->status);
  1698. }
  1699. TEST_F(ServerTest, HeadMethod200) {
  1700. auto res = cli_.Head("/hi");
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(200, res->status);
  1703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1704. EXPECT_TRUE(res->body.empty());
  1705. }
  1706. TEST_F(ServerTest, HeadMethod200Static) {
  1707. auto res = cli_.Head("/mount/dir/index.html");
  1708. ASSERT_TRUE(res);
  1709. EXPECT_EQ(200, res->status);
  1710. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1711. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1712. EXPECT_TRUE(res->body.empty());
  1713. }
  1714. TEST_F(ServerTest, HeadMethod404) {
  1715. auto res = cli_.Head("/invalid");
  1716. ASSERT_TRUE(res);
  1717. EXPECT_EQ(404, res->status);
  1718. EXPECT_TRUE(res->body.empty());
  1719. }
  1720. TEST_F(ServerTest, GetMethodPersonJohn) {
  1721. auto res = cli_.Get("/person/john");
  1722. ASSERT_TRUE(res);
  1723. EXPECT_EQ(200, res->status);
  1724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1725. EXPECT_EQ("programmer", res->body);
  1726. }
  1727. TEST_F(ServerTest, PostMethod1) {
  1728. auto res = cli_.Get("/person/john1");
  1729. ASSERT_TRUE(res);
  1730. ASSERT_EQ(404, res->status);
  1731. res = cli_.Post("/person", "name=john1&note=coder",
  1732. "application/x-www-form-urlencoded");
  1733. ASSERT_TRUE(res);
  1734. ASSERT_EQ(200, res->status);
  1735. res = cli_.Get("/person/john1");
  1736. ASSERT_TRUE(res);
  1737. ASSERT_EQ(200, res->status);
  1738. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1739. ASSERT_EQ("coder", res->body);
  1740. }
  1741. TEST_F(ServerTest, PostMethod2) {
  1742. auto res = cli_.Get("/person/john2");
  1743. ASSERT_TRUE(res);
  1744. ASSERT_EQ(404, res->status);
  1745. Params params;
  1746. params.emplace("name", "john2");
  1747. params.emplace("note", "coder");
  1748. res = cli_.Post("/person", params);
  1749. ASSERT_TRUE(res);
  1750. ASSERT_EQ(200, res->status);
  1751. res = cli_.Get("/person/john2");
  1752. ASSERT_TRUE(res);
  1753. ASSERT_EQ(200, res->status);
  1754. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1755. ASSERT_EQ("coder", res->body);
  1756. }
  1757. TEST_F(ServerTest, PutMethod3) {
  1758. auto res = cli_.Get("/person/john3");
  1759. ASSERT_TRUE(res);
  1760. ASSERT_EQ(404, res->status);
  1761. Params params;
  1762. params.emplace("name", "john3");
  1763. params.emplace("note", "coder");
  1764. res = cli_.Put("/person", params);
  1765. ASSERT_TRUE(res);
  1766. ASSERT_EQ(200, res->status);
  1767. res = cli_.Get("/person/john3");
  1768. ASSERT_TRUE(res);
  1769. ASSERT_EQ(200, res->status);
  1770. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1771. ASSERT_EQ("coder", res->body);
  1772. }
  1773. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1774. Params params;
  1775. params.emplace("json", JSON_DATA);
  1776. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1777. ASSERT_TRUE(res);
  1778. ASSERT_EQ(200, res->status);
  1779. ASSERT_EQ(JSON_DATA, res->body);
  1780. }
  1781. TEST_F(ServerTest, PostEmptyContent) {
  1782. auto res = cli_.Post("/empty", "", "text/plain");
  1783. ASSERT_TRUE(res);
  1784. ASSERT_EQ(200, res->status);
  1785. ASSERT_EQ("empty", res->body);
  1786. }
  1787. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1788. auto res = cli_.Post("/empty-no-content-type");
  1789. ASSERT_TRUE(res);
  1790. ASSERT_EQ(200, res->status);
  1791. ASSERT_EQ("empty-no-content-type", res->body);
  1792. }
  1793. TEST_F(ServerTest, PostLarge) {
  1794. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1795. ASSERT_TRUE(res);
  1796. ASSERT_EQ(200, res->status);
  1797. EXPECT_EQ(LARGE_DATA, res->body);
  1798. }
  1799. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1800. auto res = cli_.Put("/empty-no-content-type");
  1801. ASSERT_TRUE(res);
  1802. ASSERT_EQ(200, res->status);
  1803. ASSERT_EQ("empty-no-content-type", res->body);
  1804. }
  1805. TEST_F(ServerTest, GetMethodDir) {
  1806. auto res = cli_.Get("/dir/");
  1807. ASSERT_TRUE(res);
  1808. EXPECT_EQ(200, res->status);
  1809. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1810. auto body = R"(<html>
  1811. <head>
  1812. </head>
  1813. <body>
  1814. <a href="/dir/test.html">Test</a>
  1815. <a href="/hi">hi</a>
  1816. </body>
  1817. </html>
  1818. )";
  1819. EXPECT_EQ(body, res->body);
  1820. }
  1821. TEST_F(ServerTest, GetMethodDirTest) {
  1822. auto res = cli_.Get("/dir/test.html");
  1823. ASSERT_TRUE(res);
  1824. EXPECT_EQ(200, res->status);
  1825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1826. EXPECT_EQ("test.html", res->body);
  1827. }
  1828. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1829. auto res = cli_.Get("/dir/../dir/test.html");
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(200, res->status);
  1832. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1833. EXPECT_EQ("test.html", res->body);
  1834. }
  1835. TEST_F(ServerTest, GetMethodInvalidPath) {
  1836. auto res = cli_.Get("/dir/../test.html");
  1837. ASSERT_TRUE(res);
  1838. EXPECT_EQ(404, res->status);
  1839. }
  1840. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1841. auto res = cli_.Get("/../www/dir/test.html");
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(404, res->status);
  1844. }
  1845. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1846. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1847. ASSERT_TRUE(res);
  1848. EXPECT_EQ(404, res->status);
  1849. }
  1850. TEST_F(ServerTest, GetMethodDirMountTest) {
  1851. auto res = cli_.Get("/mount/dir/test.html");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(200, res->status);
  1854. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1855. EXPECT_EQ("test.html", res->body);
  1856. }
  1857. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1858. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(200, res->status);
  1861. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1862. EXPECT_EQ("test.html", res->body);
  1863. }
  1864. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1865. auto res = cli_.Get("/mount/dir/../test.html");
  1866. ASSERT_TRUE(res);
  1867. EXPECT_EQ(404, res->status);
  1868. }
  1869. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1870. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(404, res->status);
  1873. }
  1874. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1875. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(404, res->status);
  1878. }
  1879. TEST_F(ServerTest, PostMethod303) {
  1880. auto res = cli_.Post("/1", "body", "text/plain");
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(303, res->status);
  1883. EXPECT_EQ("/2", res->get_header_value("Location"));
  1884. }
  1885. TEST_F(ServerTest, PostMethod303Redirect) {
  1886. cli_.set_follow_location(true);
  1887. auto res = cli_.Post("/1", "body", "text/plain");
  1888. ASSERT_TRUE(res);
  1889. EXPECT_EQ(200, res->status);
  1890. EXPECT_EQ("redirected.", res->body);
  1891. EXPECT_EQ("/2", res->location);
  1892. }
  1893. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1894. auto res = cli_.Get("/dir/test.abcde");
  1895. ASSERT_TRUE(res);
  1896. EXPECT_EQ(200, res->status);
  1897. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1898. EXPECT_EQ("abcde", res->body);
  1899. }
  1900. TEST_F(ServerTest, StaticFileRange) {
  1901. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(206, res->status);
  1904. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1905. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1906. EXPECT_EQ(true, res->has_header("Content-Range"));
  1907. EXPECT_EQ(std::string("cd"), res->body);
  1908. }
  1909. TEST_F(ServerTest, InvalidBaseDirMount) {
  1910. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1911. }
  1912. TEST_F(ServerTest, Binary) {
  1913. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1914. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1915. "application/octet-stream");
  1916. ASSERT_TRUE(res);
  1917. ASSERT_EQ(200, res->status);
  1918. ASSERT_EQ(4U, res->body.size());
  1919. res = cli_.Put("/binary", binary.data(), binary.size(),
  1920. "application/octet-stream");
  1921. ASSERT_TRUE(res);
  1922. ASSERT_EQ(200, res->status);
  1923. ASSERT_EQ(4U, res->body.size());
  1924. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1925. "application/octet-stream");
  1926. ASSERT_TRUE(res);
  1927. ASSERT_EQ(200, res->status);
  1928. ASSERT_EQ(4U, res->body.size());
  1929. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1930. "application/octet-stream");
  1931. ASSERT_TRUE(res);
  1932. ASSERT_EQ(200, res->status);
  1933. ASSERT_EQ(4U, res->body.size());
  1934. }
  1935. TEST_F(ServerTest, BinaryString) {
  1936. auto binary = std::string("\x00\x01\x02\x03", 4);
  1937. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  1938. ASSERT_TRUE(res);
  1939. ASSERT_EQ(200, res->status);
  1940. ASSERT_EQ(4U, res->body.size());
  1941. res = cli_.Put("/binary", binary, "application/octet-stream");
  1942. ASSERT_TRUE(res);
  1943. ASSERT_EQ(200, res->status);
  1944. ASSERT_EQ(4U, res->body.size());
  1945. res = cli_.Patch("/binary", binary, "application/octet-stream");
  1946. ASSERT_TRUE(res);
  1947. ASSERT_EQ(200, res->status);
  1948. ASSERT_EQ(4U, res->body.size());
  1949. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1950. ASSERT_TRUE(res);
  1951. ASSERT_EQ(200, res->status);
  1952. ASSERT_EQ(4U, res->body.size());
  1953. }
  1954. TEST_F(ServerTest, EmptyRequest) {
  1955. auto res = cli_.Get("");
  1956. ASSERT_TRUE(!res);
  1957. EXPECT_EQ(Error::Connection, res.error());
  1958. }
  1959. TEST_F(ServerTest, LongRequest) {
  1960. std::string request;
  1961. for (size_t i = 0; i < 545; i++) {
  1962. request += "/TooLongRequest";
  1963. }
  1964. request += "OK";
  1965. auto res = cli_.Get(request.c_str());
  1966. ASSERT_TRUE(res);
  1967. EXPECT_EQ(404, res->status);
  1968. }
  1969. TEST_F(ServerTest, TooLongRequest) {
  1970. std::string request;
  1971. for (size_t i = 0; i < 545; i++) {
  1972. request += "/TooLongRequest";
  1973. }
  1974. request += "_NG";
  1975. auto res = cli_.Get(request.c_str());
  1976. ASSERT_TRUE(res);
  1977. EXPECT_EQ(414, res->status);
  1978. }
  1979. TEST_F(ServerTest, LongHeader) {
  1980. Request req;
  1981. req.method = "GET";
  1982. req.path = "/hi";
  1983. std::string host_and_port;
  1984. host_and_port += HOST;
  1985. host_and_port += ":";
  1986. host_and_port += std::to_string(PORT);
  1987. req.headers.emplace("Host", host_and_port.c_str());
  1988. req.headers.emplace("Accept", "*/*");
  1989. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1990. req.headers.emplace(
  1991. "Header-Name",
  1992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2020. "@@@@@@@@@@@@@@@@");
  2021. auto res = std::make_shared<Response>();
  2022. auto error = Error::Success;
  2023. auto ret = cli_.send(req, *res, error);
  2024. ASSERT_TRUE(ret);
  2025. EXPECT_EQ(200, res->status);
  2026. }
  2027. TEST_F(ServerTest, LongQueryValue) {
  2028. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2029. ASSERT_TRUE(res);
  2030. EXPECT_EQ(414, res->status);
  2031. }
  2032. TEST_F(ServerTest, TooLongHeader) {
  2033. Request req;
  2034. req.method = "GET";
  2035. req.path = "/hi";
  2036. std::string host_and_port;
  2037. host_and_port += HOST;
  2038. host_and_port += ":";
  2039. host_and_port += std::to_string(PORT);
  2040. req.headers.emplace("Host", host_and_port.c_str());
  2041. req.headers.emplace("Accept", "*/*");
  2042. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2043. req.headers.emplace(
  2044. "Header-Name",
  2045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2073. "@@@@@@@@@@@@@@@@@");
  2074. auto res = std::make_shared<Response>();
  2075. auto error = Error::Success;
  2076. auto ret = cli_.send(req, *res, error);
  2077. ASSERT_TRUE(ret);
  2078. EXPECT_EQ(200, res->status);
  2079. }
  2080. TEST_F(ServerTest, PercentEncoding) {
  2081. auto res = cli_.Get("/e%6edwith%");
  2082. ASSERT_TRUE(res);
  2083. EXPECT_EQ(200, res->status);
  2084. }
  2085. TEST_F(ServerTest, PercentEncodingUnicode) {
  2086. auto res = cli_.Get("/e%u006edwith%");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(200, res->status);
  2089. }
  2090. TEST_F(ServerTest, InvalidPercentEncoding) {
  2091. auto res = cli_.Get("/%endwith%");
  2092. ASSERT_TRUE(res);
  2093. EXPECT_EQ(404, res->status);
  2094. }
  2095. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2096. auto res = cli_.Get("/%uendwith%");
  2097. ASSERT_TRUE(res);
  2098. EXPECT_EQ(404, res->status);
  2099. }
  2100. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2101. auto res = cli_.Get("/hello?aaa=bbb%");
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(404, res->status);
  2104. }
  2105. TEST_F(ServerTest, PlusSignEncoding) {
  2106. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2107. ASSERT_TRUE(res);
  2108. EXPECT_EQ(200, res->status);
  2109. EXPECT_EQ("a +b", res->body);
  2110. }
  2111. TEST_F(ServerTest, MultipartFormData) {
  2112. MultipartFormDataItems items = {
  2113. {"text1", "text default", "", ""},
  2114. {"text2", "aωb", "", ""},
  2115. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2116. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2117. {"file3", "", "", "application/octet-stream"},
  2118. {"file4", "", "", " application/json tmp-string "}};
  2119. auto res = cli_.Post("/multipart", items);
  2120. ASSERT_TRUE(res);
  2121. EXPECT_EQ(200, res->status);
  2122. }
  2123. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2124. auto res = cli_.Get("/hi");
  2125. ASSERT_TRUE(res);
  2126. EXPECT_EQ(200, res->status);
  2127. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2128. EXPECT_EQ("Hello World!", res->body);
  2129. }
  2130. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2131. Request req;
  2132. req.method = "POST";
  2133. req.path = "/chunked";
  2134. std::string host_and_port;
  2135. host_and_port += HOST;
  2136. host_and_port += ":";
  2137. host_and_port += std::to_string(PORT);
  2138. req.headers.emplace("Host", host_and_port.c_str());
  2139. req.headers.emplace("Accept", "*/*");
  2140. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2141. req.headers.emplace("Content-Type", "text/plain");
  2142. req.headers.emplace("Content-Length", "0");
  2143. req.headers.emplace(
  2144. "Transfer-Encoding",
  2145. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2146. // Client does not chunk, so make a chunked body manually.
  2147. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2148. auto res = std::make_shared<Response>();
  2149. auto error = Error::Success;
  2150. auto ret = cli_.send(req, *res, error);
  2151. ASSERT_TRUE(ret);
  2152. EXPECT_EQ(200, res->status);
  2153. }
  2154. TEST_F(ServerTest, GetStreamed2) {
  2155. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(206, res->status);
  2158. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2159. EXPECT_EQ(std::string("ab"), res->body);
  2160. }
  2161. TEST_F(ServerTest, GetStreamed) {
  2162. auto res = cli_.Get("/streamed");
  2163. ASSERT_TRUE(res);
  2164. EXPECT_EQ(200, res->status);
  2165. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2166. EXPECT_EQ(std::string("aaabbb"), res->body);
  2167. }
  2168. TEST_F(ServerTest, GetStreamedWithRange1) {
  2169. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2170. ASSERT_TRUE(res);
  2171. EXPECT_EQ(206, res->status);
  2172. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2173. EXPECT_EQ(true, res->has_header("Content-Range"));
  2174. EXPECT_EQ(std::string("def"), res->body);
  2175. }
  2176. TEST_F(ServerTest, GetStreamedWithRange2) {
  2177. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(206, res->status);
  2180. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2181. EXPECT_EQ(true, res->has_header("Content-Range"));
  2182. EXPECT_EQ(std::string("bcdefg"), res->body);
  2183. }
  2184. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2185. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2186. ASSERT_TRUE(res);
  2187. EXPECT_EQ(206, res->status);
  2188. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2189. EXPECT_EQ(true, res->has_header("Content-Range"));
  2190. EXPECT_EQ(std::string("efg"), res->body);
  2191. }
  2192. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2193. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2194. ASSERT_TRUE(res);
  2195. EXPECT_EQ(206, res->status);
  2196. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2197. EXPECT_EQ(true, res->has_header("Content-Range"));
  2198. EXPECT_EQ(std::string("abcdefg"), res->body);
  2199. }
  2200. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2201. auto res = cli_.Get("/streamed-with-range",
  2202. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2203. "92233720368547758079223372036854775807"}});
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(416, res->status);
  2206. }
  2207. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2208. auto res =
  2209. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2210. EXPECT_EQ(206, res->status);
  2211. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2212. EXPECT_EQ(true, res->has_header("Content-Range"));
  2213. EXPECT_EQ(std::string("abcdefg"), res->body);
  2214. }
  2215. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2216. auto res =
  2217. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2218. ASSERT_TRUE(res);
  2219. EXPECT_EQ(206, res->status);
  2220. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2221. EXPECT_EQ(false, res->has_header("Content-Range"));
  2222. EXPECT_EQ(269U, res->body.size());
  2223. }
  2224. TEST_F(ServerTest, GetStreamedEndless) {
  2225. uint64_t offset = 0;
  2226. auto res = cli_.Get("/streamed-cancel",
  2227. [&](const char * /*data*/, uint64_t data_length) {
  2228. if (offset < 100) {
  2229. offset += data_length;
  2230. return true;
  2231. }
  2232. return false;
  2233. });
  2234. ASSERT_TRUE(!res);
  2235. EXPECT_EQ(Error::Canceled, res.error());
  2236. }
  2237. TEST_F(ServerTest, ClientStop) {
  2238. std::vector<std::thread> threads;
  2239. for (auto i = 0; i < 3; i++) {
  2240. threads.emplace_back(thread([&]() {
  2241. auto res = cli_.Get("/streamed-cancel",
  2242. [&](const char *, uint64_t) { return true; });
  2243. ASSERT_TRUE(!res);
  2244. EXPECT_TRUE(res.error() == Error::Canceled ||
  2245. res.error() == Error::Read || res.error() == Error::Write);
  2246. }));
  2247. }
  2248. std::this_thread::sleep_for(std::chrono::seconds(2));
  2249. while (cli_.is_socket_open()) {
  2250. cli_.stop();
  2251. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2252. }
  2253. for (auto &t : threads) {
  2254. t.join();
  2255. }
  2256. }
  2257. TEST_F(ServerTest, GetWithRange1) {
  2258. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ(206, res->status);
  2261. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2262. EXPECT_EQ(true, res->has_header("Content-Range"));
  2263. EXPECT_EQ(std::string("def"), res->body);
  2264. }
  2265. TEST_F(ServerTest, GetWithRange2) {
  2266. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2267. ASSERT_TRUE(res);
  2268. EXPECT_EQ(206, res->status);
  2269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2270. EXPECT_EQ(true, res->has_header("Content-Range"));
  2271. EXPECT_EQ(std::string("bcdefg"), res->body);
  2272. }
  2273. TEST_F(ServerTest, GetWithRange3) {
  2274. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(206, res->status);
  2277. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2278. EXPECT_EQ(true, res->has_header("Content-Range"));
  2279. EXPECT_EQ(std::string("a"), res->body);
  2280. }
  2281. TEST_F(ServerTest, GetWithRange4) {
  2282. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2283. ASSERT_TRUE(res);
  2284. EXPECT_EQ(206, res->status);
  2285. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2286. EXPECT_EQ(true, res->has_header("Content-Range"));
  2287. EXPECT_EQ(std::string("fg"), res->body);
  2288. }
  2289. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2290. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2291. ASSERT_TRUE(res);
  2292. EXPECT_EQ(416, res->status);
  2293. }
  2294. TEST_F(ServerTest, GetWithRangeMultipart) {
  2295. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2296. ASSERT_TRUE(res);
  2297. EXPECT_EQ(206, res->status);
  2298. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2299. EXPECT_EQ(false, res->has_header("Content-Range"));
  2300. EXPECT_EQ(269U, res->body.size());
  2301. }
  2302. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2303. auto res =
  2304. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(416, res->status);
  2307. }
  2308. TEST_F(ServerTest, GetStreamedChunked) {
  2309. auto res = cli_.Get("/streamed-chunked");
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(200, res->status);
  2312. EXPECT_EQ(std::string("123456789"), res->body);
  2313. }
  2314. TEST_F(ServerTest, GetStreamedChunked2) {
  2315. auto res = cli_.Get("/streamed-chunked2");
  2316. ASSERT_TRUE(res);
  2317. EXPECT_EQ(200, res->status);
  2318. EXPECT_EQ(std::string("123456789"), res->body);
  2319. }
  2320. TEST_F(ServerTest, LargeChunkedPost) {
  2321. Request req;
  2322. req.method = "POST";
  2323. req.path = "/large-chunked";
  2324. std::string host_and_port;
  2325. host_and_port += HOST;
  2326. host_and_port += ":";
  2327. host_and_port += std::to_string(PORT);
  2328. req.headers.emplace("Host", host_and_port.c_str());
  2329. req.headers.emplace("Accept", "*/*");
  2330. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2331. req.headers.emplace("Content-Type", "text/plain");
  2332. req.headers.emplace("Content-Length", "0");
  2333. req.headers.emplace("Transfer-Encoding", "chunked");
  2334. std::string long_string(30 * 1024u, 'a');
  2335. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2336. // Attempt to make a large enough post to exceed OS buffers, to test that
  2337. // the server handles short reads if the full chunk data isn't available.
  2338. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2339. auto res = std::make_shared<Response>();
  2340. auto error = Error::Success;
  2341. auto ret = cli_.send(req, *res, error);
  2342. ASSERT_TRUE(ret);
  2343. EXPECT_EQ(200, res->status);
  2344. }
  2345. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2346. auto res = cli_.Get("/remote_addr");
  2347. ASSERT_TRUE(res);
  2348. EXPECT_EQ(200, res->status);
  2349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2350. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2351. }
  2352. TEST_F(ServerTest, HTTPResponseSplitting) {
  2353. auto res = cli_.Get("/http_response_splitting");
  2354. ASSERT_TRUE(res);
  2355. EXPECT_EQ(200, res->status);
  2356. }
  2357. TEST_F(ServerTest, SlowRequest) {
  2358. request_threads_.push_back(
  2359. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2360. request_threads_.push_back(
  2361. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2362. request_threads_.push_back(
  2363. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2364. }
  2365. #if 0
  2366. TEST_F(ServerTest, SlowPost) {
  2367. char buffer[64 * 1024];
  2368. memset(buffer, 0x42, sizeof(buffer));
  2369. auto res = cli_.Post(
  2370. "/slowpost", 64 * 1024 * 1024,
  2371. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2372. auto ret = sink.write(buffer, sizeof(buffer));
  2373. EXPECT_TRUE(ret);
  2374. return true;
  2375. },
  2376. "text/plain");
  2377. ASSERT_TRUE(res);
  2378. EXPECT_EQ(200, res->status);
  2379. }
  2380. TEST_F(ServerTest, SlowPostFail) {
  2381. char buffer[64 * 1024];
  2382. memset(buffer, 0x42, sizeof(buffer));
  2383. cli_.set_write_timeout(std::chrono::seconds(0));
  2384. auto res = cli_.Post(
  2385. "/slowpost", 64 * 1024 * 1024,
  2386. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2387. sink.write(buffer, sizeof(buffer));
  2388. return true;
  2389. },
  2390. "text/plain");
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::Write, res.error());
  2393. }
  2394. #endif
  2395. TEST_F(ServerTest, Put) {
  2396. auto res = cli_.Put("/put", "PUT", "text/plain");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(200, res->status);
  2399. EXPECT_EQ("PUT", res->body);
  2400. }
  2401. TEST_F(ServerTest, PutWithContentProvider) {
  2402. auto res = cli_.Put(
  2403. "/put", 3,
  2404. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2405. EXPECT_TRUE(sink.is_writable());
  2406. sink.os << "PUT";
  2407. return true;
  2408. },
  2409. "text/plain");
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(200, res->status);
  2412. EXPECT_EQ("PUT", res->body);
  2413. }
  2414. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2415. auto res = cli_.Post(
  2416. "/post", 42,
  2417. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2418. return false;
  2419. },
  2420. "text/plain");
  2421. ASSERT_TRUE(!res);
  2422. EXPECT_EQ(Error::Canceled, res.error());
  2423. }
  2424. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2425. auto res = cli_.Put(
  2426. "/put",
  2427. [](size_t /*offset*/, DataSink &sink) {
  2428. EXPECT_TRUE(sink.is_writable());
  2429. sink.os << "PUT";
  2430. sink.done();
  2431. return true;
  2432. },
  2433. "text/plain");
  2434. ASSERT_TRUE(res);
  2435. EXPECT_EQ(200, res->status);
  2436. EXPECT_EQ("PUT", res->body);
  2437. }
  2438. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2439. auto res = cli_.Post(
  2440. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2441. "text/plain");
  2442. ASSERT_TRUE(!res);
  2443. EXPECT_EQ(Error::Canceled, res.error());
  2444. }
  2445. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2446. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2447. cli_.set_compress(true);
  2448. auto res = cli_.Put(
  2449. "/put", 3,
  2450. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2451. EXPECT_TRUE(sink.is_writable());
  2452. sink.os << "PUT";
  2453. return true;
  2454. },
  2455. "text/plain");
  2456. ASSERT_TRUE(res);
  2457. EXPECT_EQ(200, res->status);
  2458. EXPECT_EQ("PUT", res->body);
  2459. }
  2460. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2461. cli_.set_compress(true);
  2462. auto res = cli_.Post(
  2463. "/post", 42,
  2464. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2465. return false;
  2466. },
  2467. "text/plain");
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2472. cli_.set_compress(true);
  2473. auto res = cli_.Put(
  2474. "/put",
  2475. [](size_t /*offset*/, DataSink &sink) {
  2476. EXPECT_TRUE(sink.is_writable());
  2477. sink.os << "PUT";
  2478. sink.done();
  2479. return true;
  2480. },
  2481. "text/plain");
  2482. ASSERT_TRUE(res);
  2483. EXPECT_EQ(200, res->status);
  2484. EXPECT_EQ("PUT", res->body);
  2485. }
  2486. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2487. cli_.set_compress(true);
  2488. auto res = cli_.Post(
  2489. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2490. "text/plain");
  2491. ASSERT_TRUE(!res);
  2492. EXPECT_EQ(Error::Canceled, res.error());
  2493. }
  2494. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2495. cli_.set_compress(true);
  2496. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2497. ASSERT_TRUE(res);
  2498. EXPECT_EQ(200, res->status);
  2499. EXPECT_EQ(LARGE_DATA, res->body);
  2500. }
  2501. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2503. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2504. Client cli(s.c_str());
  2505. cli.enable_server_certificate_verification(false);
  2506. #else
  2507. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2508. Client cli(s.c_str());
  2509. #endif
  2510. cli.set_compress(true);
  2511. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2512. ASSERT_TRUE(res);
  2513. EXPECT_EQ(200, res->status);
  2514. EXPECT_EQ(LARGE_DATA, res->body);
  2515. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2516. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2517. }
  2518. TEST_F(ServerTest, PutContentWithDeflate) {
  2519. cli_.set_compress(false);
  2520. Headers headers;
  2521. headers.emplace("Content-Encoding", "deflate");
  2522. // PUT in deflate format:
  2523. auto res = cli_.Put("/put", headers,
  2524. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2525. ASSERT_TRUE(res);
  2526. EXPECT_EQ(200, res->status);
  2527. EXPECT_EQ("PUT", res->body);
  2528. }
  2529. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2530. Headers headers;
  2531. headers.emplace("Accept-Encoding", "gzip, deflate");
  2532. auto res = cli_.Get("/streamed-chunked", headers);
  2533. ASSERT_TRUE(res);
  2534. EXPECT_EQ(200, res->status);
  2535. EXPECT_EQ(std::string("123456789"), res->body);
  2536. }
  2537. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2538. Headers headers;
  2539. headers.emplace("Accept-Encoding", "gzip, deflate");
  2540. auto res = cli_.Get("/streamed-chunked2", headers);
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(200, res->status);
  2543. EXPECT_EQ(std::string("123456789"), res->body);
  2544. }
  2545. TEST(GzipDecompressor, ChunkedDecompression) {
  2546. std::string data;
  2547. for (size_t i = 0; i < 32 * 1024; ++i) {
  2548. data.push_back(static_cast<char>('a' + i % 26));
  2549. }
  2550. std::string compressed_data;
  2551. {
  2552. httplib::detail::gzip_compressor compressor;
  2553. bool result = compressor.compress(
  2554. data.data(), data.size(),
  2555. /*last=*/true, [&](const char *data, size_t size) {
  2556. compressed_data.insert(compressed_data.size(), data, size);
  2557. return true;
  2558. });
  2559. ASSERT_TRUE(result);
  2560. }
  2561. std::string decompressed_data;
  2562. {
  2563. httplib::detail::gzip_decompressor decompressor;
  2564. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2565. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2566. size_t chunk_size = 130;
  2567. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2568. chunk_begin += chunk_size) {
  2569. size_t current_chunk_size =
  2570. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2571. bool result = decompressor.decompress(
  2572. compressed_data.data() + chunk_begin, current_chunk_size,
  2573. [&](const char *data, size_t size) {
  2574. decompressed_data.insert(decompressed_data.size(), data, size);
  2575. return true;
  2576. });
  2577. ASSERT_TRUE(result);
  2578. }
  2579. }
  2580. ASSERT_EQ(data, decompressed_data);
  2581. }
  2582. #ifdef _WIN32
  2583. TEST(GzipDecompressor, LargeRandomData) {
  2584. // prepare large random data that is difficult to be compressed and is
  2585. // expected to have large size even when compressed
  2586. std::random_device seed_gen;
  2587. std::mt19937 random(seed_gen());
  2588. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2589. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2590. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2591. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2592. // compress data over 4GiB
  2593. std::string compressed_data;
  2594. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2595. httplib::detail::gzip_compressor compressor;
  2596. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2597. data.size() * sizeof(std::uint32_t), true,
  2598. [&](const char *data, size_t size) {
  2599. compressed_data.insert(
  2600. compressed_data.size(), data, size);
  2601. return true;
  2602. });
  2603. ASSERT_TRUE(result);
  2604. // FIXME: compressed data size is expected to be greater than 4GiB,
  2605. // but there is no guarantee
  2606. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2607. // decompress data over 4GiB
  2608. std::string decompressed_data;
  2609. decompressed_data.reserve(data_size);
  2610. httplib::detail::gzip_decompressor decompressor;
  2611. result = decompressor.decompress(
  2612. compressed_data.data(), compressed_data.size(),
  2613. [&](const char *data, size_t size) {
  2614. decompressed_data.insert(decompressed_data.size(), data, size);
  2615. return true;
  2616. });
  2617. ASSERT_TRUE(result);
  2618. // compare
  2619. ASSERT_EQ(data_size, decompressed_data.size());
  2620. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2621. 0);
  2622. }
  2623. #endif
  2624. #endif
  2625. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2626. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2627. Headers headers;
  2628. headers.emplace("Accept-Encoding", "br");
  2629. auto res = cli_.Get("/streamed-chunked", headers);
  2630. ASSERT_TRUE(res);
  2631. EXPECT_EQ(200, res->status);
  2632. EXPECT_EQ(std::string("123456789"), res->body);
  2633. }
  2634. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2635. Headers headers;
  2636. headers.emplace("Accept-Encoding", "br");
  2637. auto res = cli_.Get("/streamed-chunked2", headers);
  2638. ASSERT_TRUE(res);
  2639. EXPECT_EQ(200, res->status);
  2640. EXPECT_EQ(std::string("123456789"), res->body);
  2641. }
  2642. #endif
  2643. TEST_F(ServerTest, Patch) {
  2644. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2645. ASSERT_TRUE(res);
  2646. EXPECT_EQ(200, res->status);
  2647. EXPECT_EQ("PATCH", res->body);
  2648. }
  2649. TEST_F(ServerTest, Delete) {
  2650. auto res = cli_.Delete("/delete");
  2651. ASSERT_TRUE(res);
  2652. EXPECT_EQ(200, res->status);
  2653. EXPECT_EQ("DELETE", res->body);
  2654. }
  2655. TEST_F(ServerTest, DeleteContentReceiver) {
  2656. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2657. ASSERT_TRUE(res);
  2658. EXPECT_EQ(200, res->status);
  2659. EXPECT_EQ("content", res->body);
  2660. }
  2661. TEST_F(ServerTest, Options) {
  2662. auto res = cli_.Options("*");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(200, res->status);
  2665. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2666. EXPECT_TRUE(res->body.empty());
  2667. }
  2668. TEST_F(ServerTest, URL) {
  2669. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(200, res->status);
  2672. }
  2673. TEST_F(ServerTest, ArrayParam) {
  2674. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2675. ASSERT_TRUE(res);
  2676. EXPECT_EQ(200, res->status);
  2677. }
  2678. TEST_F(ServerTest, NoMultipleHeaders) {
  2679. Headers headers = {{"Content-Length", "5"}};
  2680. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2681. "text/plain");
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(200, res->status);
  2684. }
  2685. TEST_F(ServerTest, PostContentReceiver) {
  2686. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2687. ASSERT_TRUE(res);
  2688. ASSERT_EQ(200, res->status);
  2689. ASSERT_EQ("content", res->body);
  2690. }
  2691. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2692. MultipartFormDataItems items = {
  2693. {"text1", "text default", "", ""},
  2694. {"text2", "aωb", "", ""},
  2695. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2696. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2697. {"file3", "", "", "application/octet-stream"},
  2698. };
  2699. auto res = cli_.Post("/content_receiver", items);
  2700. ASSERT_TRUE(res);
  2701. EXPECT_EQ(200, res->status);
  2702. }
  2703. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2704. MultipartFormDataItems items = {
  2705. {"text1", "text default", "", ""},
  2706. {"text2", "aωb", "", ""},
  2707. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2708. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2709. {"file3", "", "", "application/octet-stream"},
  2710. };
  2711. auto boundary = std::string("+++++");
  2712. std::string body;
  2713. for (const auto &item : items) {
  2714. body += "--" + boundary + "\r\n";
  2715. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2716. if (!item.filename.empty()) {
  2717. body += "; filename=\"" + item.filename + "\"";
  2718. }
  2719. body += "\r\n";
  2720. if (!item.content_type.empty()) {
  2721. body += "Content-Type: " + item.content_type + "\r\n";
  2722. }
  2723. body += "\r\n";
  2724. body += item.content + "\r\n";
  2725. }
  2726. body += "--" + boundary + "--\r\n";
  2727. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2728. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2729. ASSERT_TRUE(res);
  2730. EXPECT_EQ(200, res->status);
  2731. }
  2732. TEST_F(ServerTest, PostContentReceiverGzip) {
  2733. cli_.set_compress(true);
  2734. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2735. ASSERT_TRUE(res);
  2736. ASSERT_EQ(200, res->status);
  2737. ASSERT_EQ("content", res->body);
  2738. }
  2739. TEST_F(ServerTest, PutContentReceiver) {
  2740. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2741. ASSERT_TRUE(res);
  2742. ASSERT_EQ(200, res->status);
  2743. ASSERT_EQ("content", res->body);
  2744. }
  2745. TEST_F(ServerTest, PatchContentReceiver) {
  2746. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2747. ASSERT_TRUE(res);
  2748. ASSERT_EQ(200, res->status);
  2749. ASSERT_EQ("content", res->body);
  2750. }
  2751. TEST_F(ServerTest, PostQueryStringAndBody) {
  2752. auto res =
  2753. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2754. ASSERT_TRUE(res);
  2755. ASSERT_EQ(200, res->status);
  2756. }
  2757. TEST_F(ServerTest, HTTP2Magic) {
  2758. Request req;
  2759. req.method = "PRI";
  2760. req.path = "*";
  2761. req.body = "SM";
  2762. auto res = std::make_shared<Response>();
  2763. auto error = Error::Success;
  2764. auto ret = cli_.send(req, *res, error);
  2765. ASSERT_TRUE(ret);
  2766. EXPECT_EQ(400, res->status);
  2767. }
  2768. TEST_F(ServerTest, KeepAlive) {
  2769. auto res = cli_.Get("/hi");
  2770. ASSERT_TRUE(res);
  2771. EXPECT_EQ(200, res->status);
  2772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2773. EXPECT_EQ("Hello World!", res->body);
  2774. res = cli_.Get("/hi");
  2775. ASSERT_TRUE(res);
  2776. EXPECT_EQ(200, res->status);
  2777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2778. EXPECT_EQ("Hello World!", res->body);
  2779. res = cli_.Get("/hi");
  2780. ASSERT_TRUE(res);
  2781. EXPECT_EQ(200, res->status);
  2782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2783. EXPECT_EQ("Hello World!", res->body);
  2784. res = cli_.Get("/not-exist");
  2785. ASSERT_TRUE(res);
  2786. EXPECT_EQ(404, res->status);
  2787. res = cli_.Post("/empty", "", "text/plain");
  2788. ASSERT_TRUE(res);
  2789. EXPECT_EQ(200, res->status);
  2790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2791. EXPECT_EQ("empty", res->body);
  2792. EXPECT_EQ("close", res->get_header_value("Connection"));
  2793. res = cli_.Post(
  2794. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2795. "text/plain");
  2796. ASSERT_TRUE(res);
  2797. EXPECT_EQ(200, res->status);
  2798. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2799. EXPECT_EQ("empty", res->body);
  2800. cli_.set_keep_alive(false);
  2801. res = cli_.Get("/last-request");
  2802. ASSERT_TRUE(res);
  2803. EXPECT_EQ(200, res->status);
  2804. EXPECT_EQ("close", res->get_header_value("Connection"));
  2805. }
  2806. TEST_F(ServerTest, TooManyRedirect) {
  2807. cli_.set_follow_location(true);
  2808. auto res = cli_.Get("/redirect/0");
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2811. }
  2812. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2813. TEST_F(ServerTest, Gzip) {
  2814. Headers headers;
  2815. headers.emplace("Accept-Encoding", "gzip, deflate");
  2816. auto res = cli_.Get("/compress", headers);
  2817. ASSERT_TRUE(res);
  2818. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2819. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2820. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2821. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2822. "7890123456789012345678901234567890",
  2823. res->body);
  2824. EXPECT_EQ(200, res->status);
  2825. }
  2826. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2827. auto res = cli_.Get("/compress");
  2828. ASSERT_TRUE(res);
  2829. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2831. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2832. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2833. "7890123456789012345678901234567890",
  2834. res->body);
  2835. EXPECT_EQ(200, res->status);
  2836. }
  2837. TEST_F(ServerTest, GzipWithContentReceiver) {
  2838. Headers headers;
  2839. headers.emplace("Accept-Encoding", "gzip, deflate");
  2840. std::string body;
  2841. auto res = cli_.Get("/compress", headers,
  2842. [&](const char *data, uint64_t data_length) {
  2843. EXPECT_EQ(100U, data_length);
  2844. body.append(data, data_length);
  2845. return true;
  2846. });
  2847. ASSERT_TRUE(res);
  2848. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2850. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2852. "7890123456789012345678901234567890",
  2853. body);
  2854. EXPECT_EQ(200, res->status);
  2855. }
  2856. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2857. Headers headers;
  2858. headers.emplace("Accept-Encoding", "gzip, deflate");
  2859. cli_.set_decompress(false);
  2860. auto res = cli_.Get("/compress", headers);
  2861. ASSERT_TRUE(res);
  2862. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2864. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2865. EXPECT_EQ(33U, res->body.size());
  2866. EXPECT_EQ(200, res->status);
  2867. }
  2868. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2869. std::string body;
  2870. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2871. EXPECT_EQ(100U, data_length);
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. ASSERT_TRUE(res);
  2876. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2878. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2879. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2880. "7890123456789012345678901234567890",
  2881. body);
  2882. EXPECT_EQ(200, res->status);
  2883. }
  2884. TEST_F(ServerTest, NoGzip) {
  2885. Headers headers;
  2886. headers.emplace("Accept-Encoding", "gzip, deflate");
  2887. auto res = cli_.Get("/nocompress", headers);
  2888. ASSERT_TRUE(res);
  2889. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2890. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2891. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2893. "7890123456789012345678901234567890",
  2894. res->body);
  2895. EXPECT_EQ(200, res->status);
  2896. }
  2897. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2898. Headers headers;
  2899. headers.emplace("Accept-Encoding", "gzip, deflate");
  2900. std::string body;
  2901. auto res = cli_.Get("/nocompress", headers,
  2902. [&](const char *data, uint64_t data_length) {
  2903. EXPECT_EQ(100U, data_length);
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. ASSERT_TRUE(res);
  2908. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2909. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2912. "7890123456789012345678901234567890",
  2913. body);
  2914. EXPECT_EQ(200, res->status);
  2915. }
  2916. TEST_F(ServerTest, MultipartFormDataGzip) {
  2917. MultipartFormDataItems items = {
  2918. {"key1", "test", "", ""},
  2919. {"key2", "--abcdefg123", "", ""},
  2920. };
  2921. cli_.set_compress(true);
  2922. auto res = cli_.Post("/compress-multipart", items);
  2923. ASSERT_TRUE(res);
  2924. EXPECT_EQ(200, res->status);
  2925. }
  2926. #endif
  2927. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2928. TEST_F(ServerTest, Brotli) {
  2929. Headers headers;
  2930. headers.emplace("Accept-Encoding", "br");
  2931. auto res = cli_.Get("/compress", headers);
  2932. ASSERT_TRUE(res);
  2933. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2934. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2935. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2936. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2937. "7890123456789012345678901234567890",
  2938. res->body);
  2939. EXPECT_EQ(200, res->status);
  2940. }
  2941. #endif
  2942. // Sends a raw request to a server listening at HOST:PORT.
  2943. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2944. std::string *resp = nullptr) {
  2945. auto error = Error::Success;
  2946. auto client_sock = detail::create_client_socket(
  2947. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  2948. /*connection_timeout_sec=*/5, 0,
  2949. /*read_timeout_sec=*/5, 0,
  2950. /*write_timeout_sec=*/5, 0, std::string(), error);
  2951. if (client_sock == INVALID_SOCKET) { return false; }
  2952. auto ret = detail::process_client_socket(
  2953. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2954. if (req.size() !=
  2955. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2956. return false;
  2957. }
  2958. char buf[512];
  2959. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2960. while (line_reader.getline()) {
  2961. if (resp) { *resp += line_reader.ptr(); }
  2962. }
  2963. return true;
  2964. });
  2965. detail::close_socket(client_sock);
  2966. return ret;
  2967. }
  2968. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2969. Server svr;
  2970. std::string header_value;
  2971. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2972. header_value = req.get_header_value("foo");
  2973. res.set_content("ok", "text/plain");
  2974. });
  2975. thread t = thread([&] { svr.listen(HOST, PORT); });
  2976. while (!svr.is_running()) {
  2977. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2978. }
  2979. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2980. // like characters are not treated the same - use vertical tab and escape.
  2981. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2982. "foo: \t \v bar \x1B\t \r\n"
  2983. "Connection: close\r\n"
  2984. "\r\n";
  2985. ASSERT_TRUE(send_request(5, req));
  2986. svr.stop();
  2987. t.join();
  2988. EXPECT_EQ(header_value, "\v bar \x1B");
  2989. }
  2990. // Sends a raw request and verifies that there isn't a crash or exception.
  2991. static void test_raw_request(const std::string &req,
  2992. std::string *out = nullptr) {
  2993. Server svr;
  2994. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2995. res.set_content("ok", "text/plain");
  2996. });
  2997. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2998. res.set_content("ok", "text/plain");
  2999. });
  3000. // Server read timeout must be longer than the client read timeout for the
  3001. // bug to reproduce, probably to force the server to process a request
  3002. // without a trailing blank line.
  3003. const time_t client_read_timeout_sec = 1;
  3004. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3005. bool listen_thread_ok = false;
  3006. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3007. while (!svr.is_running()) {
  3008. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3009. }
  3010. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3011. svr.stop();
  3012. t.join();
  3013. EXPECT_TRUE(listen_thread_ok);
  3014. }
  3015. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3016. // A certain header line causes an exception if the header property is parsed
  3017. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3018. test_raw_request(
  3019. "GET /hi HTTP/1.1\r\n"
  3020. " : "
  3021. " "
  3022. " ");
  3023. }
  3024. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3025. // A certain header line causes an exception if the header property *name* is
  3026. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3027. // greedy matcher and requires backtracking when there are a lot of ":"
  3028. // characters.
  3029. // This occurs with libc++ but not libstdc++.
  3030. test_raw_request(
  3031. "GET /hi HTTP/1.1\r\n"
  3032. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3033. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3034. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3035. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3036. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3037. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3038. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3039. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3040. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3041. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3042. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3043. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3044. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3045. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3046. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3047. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3048. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3049. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3050. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3051. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3052. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3053. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3054. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3055. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3056. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3057. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3058. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3059. "&&&%%%");
  3060. }
  3061. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  3062. // Make sure this doesn't crash the server.
  3063. // In a previous version of the header line regex, the "\r" rendered the line
  3064. // unparseable and the regex engine repeatedly backtracked, trying to look for
  3065. // a new position where the leading white space ended and the field value
  3066. // began.
  3067. // The crash occurs with libc++ but not libstdc++.
  3068. test_raw_request("GET /hi HTTP/1.1\r\n"
  3069. "a:" +
  3070. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3071. "\r\n"
  3072. "\r\n");
  3073. }
  3074. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3075. std::string out;
  3076. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3077. "Content-Type: text/plain\r\n"
  3078. "Transfer-Encoding: chunked\r\n"
  3079. "\r\n"
  3080. "nothex\r\n",
  3081. &out);
  3082. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3083. }
  3084. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3085. std::string out;
  3086. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3087. "Content-Type: text/plain\r\n"
  3088. "Transfer-Encoding: chunked\r\n"
  3089. "\r\n"
  3090. "3\r\n"
  3091. "xyz\r\n"
  3092. "NaN\r\n",
  3093. &out);
  3094. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3095. }
  3096. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3097. std::string out;
  3098. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3099. "Content-Type: text/plain\r\n"
  3100. "Transfer-Encoding: chunked\r\n"
  3101. "\r\n"
  3102. // Length is too large for 64 bits.
  3103. "1ffffffffffffffff\r\n"
  3104. "xyz\r\n",
  3105. &out);
  3106. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3107. }
  3108. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3109. test_raw_request("GET /hi HTTP/1.1\r\n"
  3110. "Content-Type: text/plain\r\n\r");
  3111. }
  3112. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3113. std::string out;
  3114. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3115. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3116. }
  3117. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3118. Server svr;
  3119. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3120. res.set_header("Cache-Control", "no-cache");
  3121. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3122. DataSink &sink) {
  3123. char buffer[27];
  3124. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3125. auto ret = sink.write(buffer, size);
  3126. EXPECT_TRUE(ret);
  3127. std::this_thread::sleep_for(std::chrono::seconds(1));
  3128. return true;
  3129. });
  3130. });
  3131. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3132. while (!svr.is_running()) {
  3133. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3134. }
  3135. Client client(HOST, PORT);
  3136. const Headers headers = {{"Accept", "text/event-stream"}};
  3137. auto get_thread = std::thread([&client, &headers]() {
  3138. auto res = client.Get(
  3139. "/events", headers,
  3140. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3141. });
  3142. // Give GET time to get a few messages.
  3143. std::this_thread::sleep_for(std::chrono::seconds(2));
  3144. svr.stop();
  3145. listen_thread.join();
  3146. get_thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. }
  3149. TEST(StreamingTest, NoContentLengthStreaming) {
  3150. Server svr;
  3151. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3152. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3153. if (offset < 6) {
  3154. sink.os << (offset < 3 ? "a" : "b");
  3155. } else {
  3156. sink.done();
  3157. }
  3158. return true;
  3159. });
  3160. });
  3161. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3162. while (!svr.is_running()) {
  3163. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3164. }
  3165. Client client(HOST, PORT);
  3166. auto get_thread = std::thread([&client]() {
  3167. std::string s;
  3168. auto res =
  3169. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3170. s += std::string(data, len);
  3171. return true;
  3172. });
  3173. EXPECT_EQ("aaabbb", s);
  3174. });
  3175. // Give GET time to get a few messages.
  3176. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3177. svr.stop();
  3178. listen_thread.join();
  3179. get_thread.join();
  3180. ASSERT_FALSE(svr.is_running());
  3181. }
  3182. TEST(MountTest, Unmount) {
  3183. Server svr;
  3184. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3185. while (!svr.is_running()) {
  3186. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3187. }
  3188. // Give GET time to get a few messages.
  3189. std::this_thread::sleep_for(std::chrono::seconds(1));
  3190. Client cli("localhost", PORT);
  3191. svr.set_mount_point("/mount2", "./www2");
  3192. auto res = cli.Get("/");
  3193. ASSERT_TRUE(res);
  3194. EXPECT_EQ(404, res->status);
  3195. res = cli.Get("/mount2/dir/test.html");
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(200, res->status);
  3198. svr.set_mount_point("/", "./www");
  3199. res = cli.Get("/dir/");
  3200. ASSERT_TRUE(res);
  3201. EXPECT_EQ(200, res->status);
  3202. svr.remove_mount_point("/");
  3203. res = cli.Get("/dir/");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_EQ(404, res->status);
  3206. svr.remove_mount_point("/mount2");
  3207. res = cli.Get("/mount2/dir/test.html");
  3208. ASSERT_TRUE(res);
  3209. EXPECT_EQ(404, res->status);
  3210. svr.stop();
  3211. listen_thread.join();
  3212. ASSERT_FALSE(svr.is_running());
  3213. }
  3214. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3215. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3216. Server svr;
  3217. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  3218. throw std::runtime_error("exception...");
  3219. // res.set_content("Hello World!", "text/plain");
  3220. });
  3221. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3222. while (!svr.is_running()) {
  3223. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3224. }
  3225. // Give GET time to get a few messages.
  3226. std::this_thread::sleep_for(std::chrono::seconds(1));
  3227. Client cli("localhost", PORT);
  3228. auto res = cli.Get("/hi");
  3229. ASSERT_TRUE(res);
  3230. EXPECT_EQ(500, res->status);
  3231. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3232. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3233. svr.stop();
  3234. listen_thread.join();
  3235. ASSERT_FALSE(svr.is_running());
  3236. }
  3237. #endif
  3238. TEST(KeepAliveTest, ReadTimeout) {
  3239. Server svr;
  3240. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3241. std::this_thread::sleep_for(std::chrono::seconds(2));
  3242. res.set_content("a", "text/plain");
  3243. });
  3244. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3245. res.set_content("b", "text/plain");
  3246. });
  3247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3248. while (!svr.is_running()) {
  3249. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3250. }
  3251. // Give GET time to get a few messages.
  3252. std::this_thread::sleep_for(std::chrono::seconds(1));
  3253. Client cli("localhost", PORT);
  3254. cli.set_keep_alive(true);
  3255. cli.set_read_timeout(std::chrono::seconds(1));
  3256. auto resa = cli.Get("/a");
  3257. ASSERT_TRUE(!resa);
  3258. EXPECT_EQ(Error::Read, resa.error());
  3259. auto resb = cli.Get("/b");
  3260. ASSERT_TRUE(resb);
  3261. EXPECT_EQ(200, resb->status);
  3262. EXPECT_EQ("b", resb->body);
  3263. svr.stop();
  3264. listen_thread.join();
  3265. ASSERT_FALSE(svr.is_running());
  3266. }
  3267. TEST(KeepAliveTest, Issue1041) {
  3268. const auto resourcePath = "/hi";
  3269. Server svr;
  3270. svr.set_keep_alive_timeout(3);
  3271. svr.Get(resourcePath, [](const httplib::Request &, httplib::Response &res) {
  3272. res.set_content("Hello World!", "text/plain");
  3273. });
  3274. auto a2 = std::async(std::launch::async, [&svr] { svr.listen(HOST, PORT); });
  3275. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3276. Client cli(HOST, PORT);
  3277. cli.set_keep_alive(true);
  3278. auto result = cli.Get(resourcePath);
  3279. ASSERT_TRUE(result);
  3280. EXPECT_EQ(200, result->status);
  3281. std::this_thread::sleep_for(std::chrono::seconds(5));
  3282. result = cli.Get(resourcePath);
  3283. ASSERT_TRUE(result);
  3284. EXPECT_EQ(200, result->status);
  3285. svr.stop();
  3286. a2.wait();
  3287. }
  3288. TEST(ClientProblemDetectionTest, ContentProvider) {
  3289. Server svr;
  3290. size_t content_length = 1024 * 1024;
  3291. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3292. res.set_content_provider(
  3293. content_length, "text/plain",
  3294. [&](size_t offset, size_t length, DataSink &sink) {
  3295. auto out_len = std::min(length, static_cast<size_t>(1024));
  3296. std::string out(out_len, '@');
  3297. sink.write(out.data(), out_len);
  3298. return offset < 4096;
  3299. },
  3300. [](bool success) { ASSERT_FALSE(success); });
  3301. });
  3302. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3303. while (!svr.is_running()) {
  3304. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3305. }
  3306. // Give GET time to get a few messages.
  3307. std::this_thread::sleep_for(std::chrono::seconds(1));
  3308. Client cli("localhost", PORT);
  3309. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3310. return false;
  3311. });
  3312. ASSERT_FALSE(res);
  3313. svr.stop();
  3314. listen_thread.join();
  3315. ASSERT_FALSE(svr.is_running());
  3316. }
  3317. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3318. Server svr;
  3319. svr.set_error_handler([](Request const &, Response &res) -> void {
  3320. res.set_chunked_content_provider(
  3321. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3322. sink.os << "hello";
  3323. sink.os << "world";
  3324. sink.done();
  3325. return true;
  3326. });
  3327. });
  3328. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3329. while (!svr.is_running()) {
  3330. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3331. }
  3332. // Give GET time to get a few messages.
  3333. std::this_thread::sleep_for(std::chrono::seconds(1));
  3334. Client cli("localhost", PORT);
  3335. auto res = cli.Get("/");
  3336. ASSERT_TRUE(res);
  3337. EXPECT_EQ(404, res->status);
  3338. EXPECT_EQ("helloworld", res->body);
  3339. svr.stop();
  3340. listen_thread.join();
  3341. ASSERT_FALSE(svr.is_running());
  3342. }
  3343. TEST(GetWithParametersTest, GetWithParameters) {
  3344. Server svr;
  3345. svr.Get("/", [&](const Request &req, Response &) {
  3346. EXPECT_EQ("world", req.get_param_value("hello"));
  3347. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3348. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3349. });
  3350. svr.Get("/params", [&](const Request &req, Response &) {
  3351. EXPECT_EQ("world", req.get_param_value("hello"));
  3352. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3353. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3354. });
  3355. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3356. EXPECT_EQ("resource-id", req.matches[1]);
  3357. EXPECT_EQ("foo", req.get_param_value("param1"));
  3358. EXPECT_EQ("bar", req.get_param_value("param2"));
  3359. });
  3360. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3361. while (!svr.is_running()) {
  3362. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3363. }
  3364. std::this_thread::sleep_for(std::chrono::seconds(1));
  3365. {
  3366. Client cli(HOST, PORT);
  3367. Params params;
  3368. params.emplace("hello", "world");
  3369. params.emplace("hello2", "world2");
  3370. params.emplace("hello3", "world3");
  3371. auto res = cli.Get("/", params, Headers{});
  3372. ASSERT_TRUE(res);
  3373. EXPECT_EQ(200, res->status);
  3374. }
  3375. {
  3376. Client cli(HOST, PORT);
  3377. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(200, res->status);
  3380. }
  3381. {
  3382. Client cli(HOST, PORT);
  3383. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(200, res->status);
  3386. }
  3387. svr.stop();
  3388. listen_thread.join();
  3389. ASSERT_FALSE(svr.is_running());
  3390. }
  3391. TEST(GetWithParametersTest, GetWithParameters2) {
  3392. Server svr;
  3393. svr.Get("/", [&](const Request &req, Response &res) {
  3394. auto text = req.get_param_value("hello");
  3395. res.set_content(text, "text/plain");
  3396. });
  3397. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3398. while (!svr.is_running()) {
  3399. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3400. }
  3401. std::this_thread::sleep_for(std::chrono::seconds(1));
  3402. Client cli("localhost", PORT);
  3403. Params params;
  3404. params.emplace("hello", "world");
  3405. std::string body;
  3406. auto res = cli.Get("/", params, Headers{},
  3407. [&](const char *data, size_t data_length) {
  3408. body.append(data, data_length);
  3409. return true;
  3410. });
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(200, res->status);
  3413. EXPECT_EQ("world", body);
  3414. svr.stop();
  3415. listen_thread.join();
  3416. ASSERT_FALSE(svr.is_running());
  3417. }
  3418. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3419. Client cli("httpbin.org");
  3420. cli.set_default_headers({make_range_header({{1, 10}})});
  3421. cli.set_connection_timeout(5);
  3422. {
  3423. auto res = cli.Get("/range/32");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ("bcdefghijk", res->body);
  3426. EXPECT_EQ(206, res->status);
  3427. }
  3428. {
  3429. auto res = cli.Get("/range/32");
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ("bcdefghijk", res->body);
  3432. EXPECT_EQ(206, res->status);
  3433. }
  3434. }
  3435. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3436. Server svr;
  3437. svr.set_default_headers({{"Hello", "World"}});
  3438. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3439. res.set_content("ok", "text/plain");
  3440. });
  3441. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3442. while (!svr.is_running()) {
  3443. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3444. }
  3445. std::this_thread::sleep_for(std::chrono::seconds(1));
  3446. Client cli("localhost", PORT);
  3447. auto res = cli.Get("/");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(200, res->status);
  3450. EXPECT_EQ("ok", res->body);
  3451. EXPECT_EQ("World", res->get_header_value("Hello"));
  3452. svr.stop();
  3453. listen_thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. }
  3456. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3457. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3459. ASSERT_TRUE(svr.is_valid());
  3460. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3461. std::this_thread::sleep_for(std::chrono::seconds(2));
  3462. res.set_content("a", "text/plain");
  3463. });
  3464. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3465. res.set_content("b", "text/plain");
  3466. });
  3467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3468. while (!svr.is_running()) {
  3469. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3470. }
  3471. // Give GET time to get a few messages.
  3472. std::this_thread::sleep_for(std::chrono::seconds(1));
  3473. SSLClient cli("localhost", PORT);
  3474. cli.enable_server_certificate_verification(false);
  3475. cli.set_keep_alive(true);
  3476. cli.set_read_timeout(std::chrono::seconds(1));
  3477. auto resa = cli.Get("/a");
  3478. ASSERT_TRUE(!resa);
  3479. EXPECT_EQ(Error::Read, resa.error());
  3480. auto resb = cli.Get("/b");
  3481. ASSERT_TRUE(resb);
  3482. EXPECT_EQ(200, resb->status);
  3483. EXPECT_EQ("b", resb->body);
  3484. svr.stop();
  3485. listen_thread.join();
  3486. ASSERT_FALSE(svr.is_running());
  3487. }
  3488. #endif
  3489. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3490. protected:
  3491. ServerTestWithAI_PASSIVE()
  3492. : cli_(HOST, PORT)
  3493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3494. ,
  3495. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3496. #endif
  3497. {
  3498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3499. cli_.enable_server_certificate_verification(false);
  3500. #endif
  3501. }
  3502. virtual void SetUp() {
  3503. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3504. res.set_content("Hello World!", "text/plain");
  3505. });
  3506. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  3507. while (!svr_.is_running()) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3509. }
  3510. }
  3511. virtual void TearDown() {
  3512. svr_.stop();
  3513. t_.join();
  3514. }
  3515. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3516. SSLClient cli_;
  3517. SSLServer svr_;
  3518. #else
  3519. Client cli_;
  3520. Server svr_;
  3521. #endif
  3522. thread t_;
  3523. };
  3524. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3525. auto res = cli_.Get("/hi");
  3526. ASSERT_TRUE(res);
  3527. EXPECT_EQ(200, res->status);
  3528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3529. EXPECT_EQ("Hello World!", res->body);
  3530. }
  3531. class ServerUpDownTest : public ::testing::Test {
  3532. protected:
  3533. ServerUpDownTest() : cli_(HOST, PORT) {}
  3534. virtual void SetUp() {
  3535. t_ = thread([&]() {
  3536. svr_.bind_to_any_port(HOST);
  3537. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3538. ASSERT_TRUE(svr_.listen_after_bind());
  3539. });
  3540. while (!svr_.is_running()) {
  3541. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3542. }
  3543. }
  3544. virtual void TearDown() {
  3545. svr_.stop();
  3546. t_.join();
  3547. }
  3548. Client cli_;
  3549. Server svr_;
  3550. thread t_;
  3551. };
  3552. TEST_F(ServerUpDownTest, QuickStartStop) {
  3553. // Should not crash, especially when run with
  3554. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3555. }
  3556. class PayloadMaxLengthTest : public ::testing::Test {
  3557. protected:
  3558. PayloadMaxLengthTest()
  3559. : cli_(HOST, PORT)
  3560. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3561. ,
  3562. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3563. #endif
  3564. {
  3565. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3566. cli_.enable_server_certificate_verification(false);
  3567. #endif
  3568. }
  3569. virtual void SetUp() {
  3570. svr_.set_payload_max_length(8);
  3571. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("test", "text/plain");
  3573. });
  3574. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3575. while (!svr_.is_running()) {
  3576. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3577. }
  3578. }
  3579. virtual void TearDown() {
  3580. svr_.stop();
  3581. t_.join();
  3582. }
  3583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3584. SSLClient cli_;
  3585. SSLServer svr_;
  3586. #else
  3587. Client cli_;
  3588. Server svr_;
  3589. #endif
  3590. thread t_;
  3591. };
  3592. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3593. auto res = cli_.Post("/test", "123456789", "text/plain");
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(413, res->status);
  3596. res = cli_.Post("/test", "12345678", "text/plain");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ(200, res->status);
  3599. }
  3600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3601. TEST(SSLClientTest, UpdateCAStore) {
  3602. httplib::SSLClient httplib_client("www.google.com");
  3603. auto ca_store_1 = X509_STORE_new();
  3604. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3605. nullptr);
  3606. httplib_client.set_ca_cert_store(ca_store_1);
  3607. auto ca_store_2 = X509_STORE_new();
  3608. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3609. nullptr);
  3610. httplib_client.set_ca_cert_store(ca_store_2);
  3611. }
  3612. TEST(SSLClientTest, ServerNameIndication_Online) {
  3613. SSLClient cli("httpbin.org", 443);
  3614. auto res = cli.Get("/get");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(200, res->status);
  3617. }
  3618. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3619. SSLClient cli("google.com");
  3620. auto res = cli.Get("/");
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(301, res->status);
  3623. }
  3624. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3625. SSLClient cli("google.com");
  3626. cli.enable_server_certificate_verification(true);
  3627. cli.set_ca_cert_path("hello");
  3628. auto res = cli.Get("/");
  3629. ASSERT_TRUE(!res);
  3630. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3631. }
  3632. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3633. SSLClient cli("google.com");
  3634. cli.set_ca_cert_path(CA_CERT_FILE);
  3635. auto res = cli.Get("/");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(301, res->status);
  3638. }
  3639. TEST(SSLClientTest, ServerCertificateVerification4) {
  3640. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3641. ASSERT_TRUE(svr.is_valid());
  3642. svr.Get("/test", [&](const Request &, Response &res) {
  3643. res.set_content("test", "text/plain");
  3644. svr.stop();
  3645. ASSERT_TRUE(true);
  3646. });
  3647. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3648. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3649. SSLClient cli("127.0.0.1", PORT);
  3650. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3651. cli.enable_server_certificate_verification(true);
  3652. cli.set_connection_timeout(30);
  3653. auto res = cli.Get("/test");
  3654. ASSERT_TRUE(res);
  3655. ASSERT_EQ(200, res->status);
  3656. t.join();
  3657. }
  3658. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3659. SSLClient cli("www.youtube.com");
  3660. cli.set_ca_cert_path(CA_CERT_FILE);
  3661. cli.enable_server_certificate_verification(true);
  3662. cli.set_follow_location(true);
  3663. auto res = cli.Get("/");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(200, res->status);
  3666. }
  3667. #if 0
  3668. TEST(SSLClientTest, SetInterfaceWithINET6) {
  3669. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  3670. ASSERT_TRUE(cli != nullptr);
  3671. cli->set_address_family(AF_INET6);
  3672. cli->set_interface("en0");
  3673. auto res = cli->Get("/get");
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(200, res->status);
  3676. }
  3677. #endif
  3678. TEST(SSLClientServerTest, ClientCertPresent) {
  3679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3680. CLIENT_CA_CERT_DIR);
  3681. ASSERT_TRUE(svr.is_valid());
  3682. svr.Get("/test", [&](const Request &req, Response &res) {
  3683. res.set_content("test", "text/plain");
  3684. svr.stop();
  3685. ASSERT_TRUE(true);
  3686. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3687. ASSERT_TRUE(peer_cert != nullptr);
  3688. auto subject_name = X509_get_subject_name(peer_cert);
  3689. ASSERT_TRUE(subject_name != nullptr);
  3690. std::string common_name;
  3691. {
  3692. char name[BUFSIZ];
  3693. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3694. name, sizeof(name));
  3695. common_name.assign(name, static_cast<size_t>(name_len));
  3696. }
  3697. EXPECT_EQ("Common Name", common_name);
  3698. X509_free(peer_cert);
  3699. });
  3700. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3701. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3702. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3703. cli.enable_server_certificate_verification(false);
  3704. cli.set_connection_timeout(30);
  3705. auto res = cli.Get("/test");
  3706. ASSERT_TRUE(res);
  3707. ASSERT_EQ(200, res->status);
  3708. t.join();
  3709. }
  3710. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3711. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3712. X509 *server_cert;
  3713. EVP_PKEY *server_private_key;
  3714. X509_STORE *client_ca_cert_store;
  3715. X509 *client_cert;
  3716. EVP_PKEY *client_private_key;
  3717. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3718. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3719. fclose(f);
  3720. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3721. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3722. fclose(f);
  3723. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3724. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3725. client_ca_cert_store = X509_STORE_new();
  3726. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3727. X509_free(client_cert);
  3728. fclose(f);
  3729. f = fopen(CLIENT_CERT_FILE, "r+");
  3730. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3731. fclose(f);
  3732. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3733. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3734. fclose(f);
  3735. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3736. ASSERT_TRUE(svr.is_valid());
  3737. svr.Get("/test", [&](const Request &req, Response &res) {
  3738. res.set_content("test", "text/plain");
  3739. svr.stop();
  3740. ASSERT_TRUE(true);
  3741. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3742. ASSERT_TRUE(peer_cert != nullptr);
  3743. auto subject_name = X509_get_subject_name(peer_cert);
  3744. ASSERT_TRUE(subject_name != nullptr);
  3745. std::string common_name;
  3746. {
  3747. char name[BUFSIZ];
  3748. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3749. name, sizeof(name));
  3750. common_name.assign(name, static_cast<size_t>(name_len));
  3751. }
  3752. EXPECT_EQ("Common Name", common_name);
  3753. X509_free(peer_cert);
  3754. });
  3755. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3756. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3757. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3758. cli.enable_server_certificate_verification(false);
  3759. cli.set_connection_timeout(30);
  3760. auto res = cli.Get("/test");
  3761. ASSERT_TRUE(res);
  3762. ASSERT_EQ(200, res->status);
  3763. X509_free(server_cert);
  3764. EVP_PKEY_free(server_private_key);
  3765. X509_free(client_cert);
  3766. EVP_PKEY_free(client_private_key);
  3767. t.join();
  3768. }
  3769. #endif
  3770. TEST(SSLClientServerTest, ClientCertMissing) {
  3771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3772. CLIENT_CA_CERT_DIR);
  3773. ASSERT_TRUE(svr.is_valid());
  3774. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3776. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3777. SSLClient cli(HOST, PORT);
  3778. auto res = cli.Get("/test");
  3779. cli.set_connection_timeout(30);
  3780. ASSERT_TRUE(!res);
  3781. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3782. svr.stop();
  3783. t.join();
  3784. }
  3785. TEST(SSLClientServerTest, TrustDirOptional) {
  3786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3787. ASSERT_TRUE(svr.is_valid());
  3788. svr.Get("/test", [&](const Request &, Response &res) {
  3789. res.set_content("test", "text/plain");
  3790. svr.stop();
  3791. });
  3792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3793. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3794. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3795. cli.enable_server_certificate_verification(false);
  3796. cli.set_connection_timeout(30);
  3797. auto res = cli.Get("/test");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(200, res->status);
  3800. t.join();
  3801. }
  3802. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3803. class NoListenSSLServer : public SSLServer {
  3804. public:
  3805. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3806. const char *client_ca_cert_file_path,
  3807. const char *client_ca_cert_dir_path = nullptr)
  3808. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3809. client_ca_cert_dir_path),
  3810. stop_(false) {}
  3811. bool stop_;
  3812. private:
  3813. bool process_and_close_socket(socket_t /*sock*/) override {
  3814. // Don't create SSL context
  3815. while (!stop_) {
  3816. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3817. }
  3818. return true;
  3819. }
  3820. };
  3821. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3822. CLIENT_CA_CERT_FILE);
  3823. ASSERT_TRUE(svr.is_valid());
  3824. svr.Get("/test", [&](const Request &, Response &res) {
  3825. res.set_content("test", "text/plain");
  3826. });
  3827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3828. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3829. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3830. cli.enable_server_certificate_verification(false);
  3831. cli.set_connection_timeout(1);
  3832. auto res = cli.Get("/test");
  3833. ASSERT_TRUE(!res);
  3834. EXPECT_EQ(Error::SSLConnection, res.error());
  3835. svr.stop_ = true;
  3836. svr.stop();
  3837. t.join();
  3838. }
  3839. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  3840. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  3841. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  3842. SSL_CTX_set_options(&ssl_ctx,
  3843. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3844. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  3845. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  3846. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  3847. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  3848. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  3849. "ECDHE-DSS-AES128-SHA256:"
  3850. "ECDHE-RSA-AES256-SHA256:"
  3851. "ECDHE-DSS-AES256-SHA256:";
  3852. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  3853. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  3854. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  3855. SSL_FILETYPE_PEM) != 1) {
  3856. return false;
  3857. }
  3858. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  3859. CLIENT_CA_CERT_DIR);
  3860. SSL_CTX_set_verify(
  3861. &ssl_ctx,
  3862. SSL_VERIFY_PEER |
  3863. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3864. nullptr);
  3865. return true;
  3866. };
  3867. SSLServer svr(setup_ssl_ctx_callback);
  3868. ASSERT_TRUE(svr.is_valid());
  3869. svr.Get("/test", [&](const Request &req, Response &res) {
  3870. res.set_content("test", "text/plain");
  3871. svr.stop();
  3872. ASSERT_TRUE(true);
  3873. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3874. ASSERT_TRUE(peer_cert != nullptr);
  3875. auto subject_name = X509_get_subject_name(peer_cert);
  3876. ASSERT_TRUE(subject_name != nullptr);
  3877. std::string common_name;
  3878. {
  3879. char name[BUFSIZ];
  3880. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3881. name, sizeof(name));
  3882. common_name.assign(name, static_cast<size_t>(name_len));
  3883. }
  3884. EXPECT_EQ("Common Name", common_name);
  3885. X509_free(peer_cert);
  3886. });
  3887. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3888. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3889. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3890. cli.enable_server_certificate_verification(false);
  3891. cli.set_connection_timeout(30);
  3892. auto res = cli.Get("/test");
  3893. ASSERT_TRUE(res);
  3894. ASSERT_EQ(200, res->status);
  3895. t.join();
  3896. }
  3897. #endif
  3898. #ifdef _WIN32
  3899. TEST(CleanupTest, WSACleanup) {
  3900. int ret = WSACleanup();
  3901. ASSERT_EQ(0, ret);
  3902. }
  3903. #endif
  3904. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3905. TEST(NoSSLSupport, SimpleInterface) {
  3906. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3907. }
  3908. #endif
  3909. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3910. TEST(InvalidScheme, SimpleInterface) {
  3911. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3912. }
  3913. #endif
  3914. TEST(NoScheme, SimpleInterface) {
  3915. Client cli("yahoo.com:80");
  3916. ASSERT_TRUE(cli.is_valid());
  3917. }
  3918. TEST(SendAPI, SimpleInterface_Online) {
  3919. Client cli("http://yahoo.com");
  3920. Request req;
  3921. req.method = "GET";
  3922. req.path = "/";
  3923. auto res = cli.send(req);
  3924. ASSERT_TRUE(res);
  3925. EXPECT_EQ(301, res->status);
  3926. }
  3927. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3928. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  3929. Client cli("http://yahoo.com");
  3930. auto res = cli.Get("/");
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(301, res->status);
  3933. cli.set_follow_location(true);
  3934. res = cli.Get("/");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(200, res->status);
  3937. EXPECT_EQ("https://yahoo.com/", res->location);
  3938. }
  3939. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  3940. Client cli("https://yahoo.com");
  3941. auto res = cli.Get("/");
  3942. ASSERT_TRUE(res);
  3943. EXPECT_EQ(301, res->status);
  3944. cli.set_follow_location(true);
  3945. res = cli.Get("/");
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(200, res->status);
  3948. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3949. }
  3950. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  3951. Client cli("https://yahoo.com");
  3952. auto res = cli.Get("/");
  3953. ASSERT_TRUE(res);
  3954. ASSERT_FALSE(!res);
  3955. ASSERT_TRUE(res);
  3956. ASSERT_FALSE(res == nullptr);
  3957. ASSERT_TRUE(res != nullptr);
  3958. EXPECT_EQ(Error::Success, res.error());
  3959. EXPECT_EQ(301, res.value().status);
  3960. EXPECT_EQ(301, (*res).status);
  3961. EXPECT_EQ(301, res->status);
  3962. cli.set_follow_location(true);
  3963. res = cli.Get("/");
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(Error::Success, res.error());
  3966. EXPECT_EQ(200, res.value().status);
  3967. EXPECT_EQ(200, (*res).status);
  3968. EXPECT_EQ(200, res->status);
  3969. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3970. }
  3971. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3972. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  3973. Client cli("https://cdnjs.cloudflare.com");
  3974. auto res =
  3975. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(200, res->status);
  3978. EXPECT_EQ(287630U, res->body.size());
  3979. EXPECT_EQ("application/javascript; charset=utf-8",
  3980. res->get_header_value("Content-Type"));
  3981. }
  3982. #endif
  3983. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  3984. Client cli("https://nghttp2.org");
  3985. cli.set_follow_location(true);
  3986. auto res =
  3987. cli.Get("/httpbin/"
  3988. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3989. ASSERT_TRUE(res);
  3990. EXPECT_EQ(200, res->status);
  3991. }
  3992. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  3993. Client cli("https://nghttp2.org");
  3994. cli.set_follow_location(true);
  3995. Params params;
  3996. params.emplace("url", "http://www.google.com");
  3997. params.emplace("status_code", "302");
  3998. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(200, res->status);
  4001. }
  4002. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4003. Client cli("https://nghttp2.org");
  4004. cli.set_follow_location(true);
  4005. Params params;
  4006. params.emplace("url", "http://www.google.com");
  4007. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(200, res->status);
  4010. }
  4011. TEST(HttpToHttpsRedirectTest, CertFile) {
  4012. Server svr;
  4013. ASSERT_TRUE(svr.is_valid());
  4014. svr.Get("/index", [&](const Request &, Response &res) {
  4015. res.set_redirect("https://127.0.0.1:1235/index");
  4016. svr.stop();
  4017. });
  4018. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4019. ASSERT_TRUE(ssl_svr.is_valid());
  4020. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4021. res.set_content("test", "text/plain");
  4022. ssl_svr.stop();
  4023. });
  4024. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4025. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4026. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4027. Client cli("127.0.0.1", PORT);
  4028. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4029. cli.enable_server_certificate_verification(true);
  4030. cli.set_follow_location(true);
  4031. cli.set_connection_timeout(30);
  4032. auto res = cli.Get("/index");
  4033. ASSERT_TRUE(res);
  4034. ASSERT_EQ(200, res->status);
  4035. t.join();
  4036. t2.join();
  4037. }
  4038. TEST(MultipartFormDataTest, LargeData) {
  4039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4040. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4041. const ContentReader &content_reader) {
  4042. if (req.is_multipart_form_data()) {
  4043. MultipartFormDataItems files;
  4044. content_reader(
  4045. [&](const MultipartFormData &file) {
  4046. files.push_back(file);
  4047. return true;
  4048. },
  4049. [&](const char *data, size_t data_length) {
  4050. files.back().content.append(data, data_length);
  4051. return true;
  4052. });
  4053. EXPECT_TRUE(std::string(files[0].name) == "document");
  4054. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4055. EXPECT_TRUE(files[0].filename == "2MB_data");
  4056. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4057. EXPECT_TRUE(files[1].name == "hello");
  4058. EXPECT_TRUE(files[1].content == "world");
  4059. EXPECT_TRUE(files[1].filename == "");
  4060. EXPECT_TRUE(files[1].content_type == "");
  4061. } else {
  4062. std::string body;
  4063. content_reader([&](const char *data, size_t data_length) {
  4064. body.append(data, data_length);
  4065. return true;
  4066. });
  4067. }
  4068. });
  4069. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4070. while (!svr.is_running()) {
  4071. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4072. }
  4073. std::this_thread::sleep_for(std::chrono::seconds(1));
  4074. {
  4075. std::string data(1024 * 1024 * 2, '.');
  4076. std::stringstream buffer;
  4077. buffer << data;
  4078. Client cli("https://localhost:8080");
  4079. cli.enable_server_certificate_verification(false);
  4080. MultipartFormDataItems items{
  4081. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4082. {"hello", "world", "", ""},
  4083. };
  4084. auto res = cli.Post("/post", items);
  4085. ASSERT_TRUE(res);
  4086. ASSERT_EQ(200, res->status);
  4087. }
  4088. svr.stop();
  4089. t.join();
  4090. }
  4091. #endif