test.cc 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763
  1. #include <httplib.h>
  2. #include <gtest/gtest.h>
  3. #include <atomic>
  4. #include <chrono>
  5. #include <future>
  6. #include <thread>
  7. #define SERVER_CERT_FILE "./cert.pem"
  8. #define SERVER_CERT2_FILE "./cert2.pem"
  9. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  10. #define CA_CERT_FILE "./ca-bundle.crt"
  11. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  12. #define CLIENT_CA_CERT_DIR "."
  13. #define CLIENT_CERT_FILE "./client.cert.pem"
  14. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  15. using namespace std;
  16. using namespace httplib;
  17. const char *HOST = "localhost";
  18. const int PORT = 1234;
  19. const string LONG_QUERY_VALUE = string(25000, '@');
  20. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  21. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  22. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  23. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  24. const char *key) {
  25. auto it = std::find_if(
  26. files.begin(), files.end(),
  27. [&](const MultipartFormData &file) { return file.name == key; });
  28. if (it != files.end()) { return *it; }
  29. throw std::runtime_error("invalid mulitpart form data name error");
  30. }
  31. #ifdef _WIN32
  32. TEST(StartupTest, WSAStartup) {
  33. WSADATA wsaData;
  34. int ret = WSAStartup(0x0002, &wsaData);
  35. ASSERT_EQ(0, ret);
  36. }
  37. #endif
  38. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest){
  39. string unescapedCharacters = "-_.!~*'()";
  40. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  41. }
  42. TEST(EncodeQueryParamTest, ParseReservedCharactersTest){
  43. string reservedCharacters = ";,/?:@&=+$";
  44. EXPECT_EQ(detail::encode_query_param(reservedCharacters), "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  45. }
  46. TEST(TrimTests, TrimStringTests) {
  47. EXPECT_EQ("abc", detail::trim_copy("abc"));
  48. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  49. EXPECT_TRUE(detail::trim_copy("").empty());
  50. }
  51. TEST(SplitTest, ParseQueryString) {
  52. string s = "key1=val1&key2=val2&key3=val3";
  53. Params dic;
  54. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  55. [&](const char *b, const char *e) {
  56. string key, val;
  57. detail::split(b, e, '=', [&](const char *b, const char *e) {
  58. if (key.empty()) {
  59. key.assign(b, e);
  60. } else {
  61. val.assign(b, e);
  62. }
  63. });
  64. dic.emplace(key, val);
  65. });
  66. EXPECT_EQ("val1", dic.find("key1")->second);
  67. EXPECT_EQ("val2", dic.find("key2")->second);
  68. EXPECT_EQ("val3", dic.find("key3")->second);
  69. }
  70. TEST(SplitTest, ParseInvalidQueryTests) {
  71. {
  72. string s = " ";
  73. Params dict;
  74. detail::parse_query_text(s, dict);
  75. EXPECT_TRUE(dict.empty());
  76. }
  77. {
  78. string s = " = =";
  79. Params dict;
  80. detail::parse_query_text(s, dict);
  81. EXPECT_TRUE(dict.empty());
  82. }
  83. }
  84. TEST(ParseQueryTest, ParseQueryString) {
  85. string s = "key1=val1&key2=val2&key3=val3";
  86. Params dic;
  87. detail::parse_query_text(s, dic);
  88. EXPECT_EQ("val1", dic.find("key1")->second);
  89. EXPECT_EQ("val2", dic.find("key2")->second);
  90. EXPECT_EQ("val3", dic.find("key3")->second);
  91. }
  92. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  93. Params dic;
  94. EXPECT_EQ(detail::params_to_query_str(dic), "");
  95. dic.emplace("key1", "val1");
  96. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  97. dic.emplace("key2", "val2");
  98. dic.emplace("key3", "val3");
  99. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  100. }
  101. TEST(GetHeaderValueTest, DefaultValue) {
  102. Headers headers = {{"Dummy", "Dummy"}};
  103. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  104. EXPECT_STREQ("text/plain", val);
  105. }
  106. TEST(GetHeaderValueTest, DefaultValueInt) {
  107. Headers headers = {{"Dummy", "Dummy"}};
  108. auto val =
  109. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  110. EXPECT_EQ(100ull, val);
  111. }
  112. TEST(GetHeaderValueTest, RegularValue) {
  113. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  114. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  115. EXPECT_STREQ("text/html", val);
  116. }
  117. TEST(GetHeaderValueTest, SetContent) {
  118. Response res;
  119. res.set_content("html", "text/html");
  120. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  121. res.set_content("text", "text/plain");
  122. EXPECT_EQ(1, res.get_header_value_count("Content-Type"));
  123. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  124. }
  125. TEST(GetHeaderValueTest, RegularValueInt) {
  126. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  127. auto val =
  128. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  129. EXPECT_EQ(100ull, val);
  130. }
  131. TEST(GetHeaderValueTest, Range) {
  132. {
  133. Headers headers = {make_range_header({{1, -1}})};
  134. auto val = detail::get_header_value(headers, "Range", 0, 0);
  135. EXPECT_STREQ("bytes=1-", val);
  136. }
  137. {
  138. Headers headers = {make_range_header({{-1, 1}})};
  139. auto val = detail::get_header_value(headers, "Range", 0, 0);
  140. EXPECT_STREQ("bytes=-1", val);
  141. }
  142. {
  143. Headers headers = {make_range_header({{1, 10}})};
  144. auto val = detail::get_header_value(headers, "Range", 0, 0);
  145. EXPECT_STREQ("bytes=1-10", val);
  146. }
  147. {
  148. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  149. auto val = detail::get_header_value(headers, "Range", 0, 0);
  150. EXPECT_STREQ("bytes=1-10, 100-", val);
  151. }
  152. {
  153. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  154. auto val = detail::get_header_value(headers, "Range", 0, 0);
  155. EXPECT_STREQ("bytes=1-10, 100-200", val);
  156. }
  157. {
  158. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  159. auto val = detail::get_header_value(headers, "Range", 0, 0);
  160. EXPECT_STREQ("bytes=0-0, -1", val);
  161. }
  162. }
  163. TEST(ParseHeaderValueTest, Range) {
  164. {
  165. Ranges ranges;
  166. auto ret = detail::parse_range_header("bytes=1-", ranges);
  167. EXPECT_TRUE(ret);
  168. EXPECT_EQ(1u, ranges.size());
  169. EXPECT_EQ(1u, ranges[0].first);
  170. EXPECT_EQ(-1, ranges[0].second);
  171. }
  172. {
  173. Ranges ranges;
  174. auto ret = detail::parse_range_header("bytes=-1", ranges);
  175. EXPECT_TRUE(ret);
  176. EXPECT_EQ(1u, ranges.size());
  177. EXPECT_EQ(-1, ranges[0].first);
  178. EXPECT_EQ(1u, ranges[0].second);
  179. }
  180. {
  181. Ranges ranges;
  182. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  183. EXPECT_TRUE(ret);
  184. EXPECT_EQ(1u, ranges.size());
  185. EXPECT_EQ(1u, ranges[0].first);
  186. EXPECT_EQ(10u, ranges[0].second);
  187. }
  188. {
  189. Ranges ranges;
  190. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  191. EXPECT_FALSE(ret);
  192. }
  193. {
  194. Ranges ranges;
  195. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  196. EXPECT_TRUE(ret);
  197. EXPECT_EQ(2u, ranges.size());
  198. EXPECT_EQ(1u, ranges[0].first);
  199. EXPECT_EQ(10u, ranges[0].second);
  200. EXPECT_EQ(100u, ranges[1].first);
  201. EXPECT_EQ(-1, ranges[1].second);
  202. }
  203. {
  204. Ranges ranges;
  205. auto ret =
  206. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  207. EXPECT_TRUE(ret);
  208. EXPECT_EQ(3u, ranges.size());
  209. EXPECT_EQ(1u, ranges[0].first);
  210. EXPECT_EQ(10u, ranges[0].second);
  211. EXPECT_EQ(100u, ranges[1].first);
  212. EXPECT_EQ(200u, ranges[1].second);
  213. EXPECT_EQ(300u, ranges[2].first);
  214. EXPECT_EQ(400u, ranges[2].second);
  215. }
  216. }
  217. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  218. Request req;
  219. req.set_header("Accept-Encoding", "gzip");
  220. Response res;
  221. res.set_header("Content-Type", "text/plain");
  222. auto ret = detail::encoding_type(req, res);
  223. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  224. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  225. #else
  226. EXPECT_TRUE(ret == detail::EncodingType::None);
  227. #endif
  228. }
  229. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  230. Request req;
  231. req.set_header("Accept-Encoding", "gzip, deflate, br");
  232. Response res;
  233. res.set_header("Content-Type", "text/plain");
  234. auto ret = detail::encoding_type(req, res);
  235. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  236. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  237. #elif CPPHTTPLIB_ZLIB_SUPPORT
  238. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  239. #else
  240. EXPECT_TRUE(ret == detail::EncodingType::None);
  241. #endif
  242. }
  243. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  244. Request req;
  245. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  246. Response res;
  247. res.set_header("Content-Type", "text/plain");
  248. auto ret = detail::encoding_type(req, res);
  249. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  250. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  251. #elif CPPHTTPLIB_ZLIB_SUPPORT
  252. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  253. #else
  254. EXPECT_TRUE(ret == detail::EncodingType::None);
  255. #endif
  256. }
  257. TEST(BufferStreamTest, read) {
  258. detail::BufferStream strm1;
  259. Stream &strm = strm1;
  260. EXPECT_EQ(5, strm.write("hello"));
  261. char buf[512];
  262. EXPECT_EQ(2, strm.read(buf, 2));
  263. EXPECT_EQ('h', buf[0]);
  264. EXPECT_EQ('e', buf[1]);
  265. EXPECT_EQ(2, strm.read(buf, 2));
  266. EXPECT_EQ('l', buf[0]);
  267. EXPECT_EQ('l', buf[1]);
  268. EXPECT_EQ(1, strm.read(buf, 1));
  269. EXPECT_EQ('o', buf[0]);
  270. EXPECT_EQ(0, strm.read(buf, 1));
  271. }
  272. TEST(ChunkedEncodingTest, FromHTTPWatch) {
  273. auto host = "www.httpwatch.com";
  274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  275. auto port = 443;
  276. SSLClient cli(host, port);
  277. #else
  278. auto port = 80;
  279. Client cli(host, port);
  280. #endif
  281. cli.set_connection_timeout(2);
  282. auto res =
  283. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  284. ASSERT_TRUE(res);
  285. std::string out;
  286. detail::read_file("./image.jpg", out);
  287. EXPECT_EQ(200, res->status);
  288. EXPECT_EQ(out, res->body);
  289. }
  290. TEST(ChunkedEncodingTest, WithContentReceiver) {
  291. auto host = "www.httpwatch.com";
  292. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  293. auto port = 443;
  294. SSLClient cli(host, port);
  295. #else
  296. auto port = 80;
  297. Client cli(host, port);
  298. #endif
  299. cli.set_connection_timeout(2);
  300. std::string body;
  301. auto res =
  302. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  303. [&](const char *data, size_t data_length) {
  304. body.append(data, data_length);
  305. return true;
  306. });
  307. ASSERT_TRUE(res);
  308. std::string out;
  309. detail::read_file("./image.jpg", out);
  310. EXPECT_EQ(200, res->status);
  311. EXPECT_EQ(out, body);
  312. }
  313. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  314. auto host = "www.httpwatch.com";
  315. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  316. auto port = 443;
  317. SSLClient cli(host, port);
  318. #else
  319. auto port = 80;
  320. Client cli(host, port);
  321. #endif
  322. cli.set_connection_timeout(2);
  323. std::string body;
  324. auto res = cli.Get(
  325. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  326. [&](const Response &response) {
  327. EXPECT_EQ(200, response.status);
  328. return true;
  329. },
  330. [&](const char *data, size_t data_length) {
  331. body.append(data, data_length);
  332. return true;
  333. });
  334. ASSERT_TRUE(res);
  335. std::string out;
  336. detail::read_file("./image.jpg", out);
  337. EXPECT_EQ(200, res->status);
  338. EXPECT_EQ(out, body);
  339. }
  340. TEST(DefaultHeadersTest, FromHTTPBin) {
  341. Client cli("httpbin.org");
  342. cli.set_default_headers({make_range_header({{1, 10}})});
  343. cli.set_connection_timeout(5);
  344. {
  345. auto res = cli.Get("/range/32");
  346. ASSERT_TRUE(res);
  347. EXPECT_EQ("bcdefghijk", res->body);
  348. EXPECT_EQ(206, res->status);
  349. }
  350. {
  351. auto res = cli.Get("/range/32");
  352. ASSERT_TRUE(res);
  353. EXPECT_EQ("bcdefghijk", res->body);
  354. EXPECT_EQ(206, res->status);
  355. }
  356. }
  357. TEST(RangeTest, FromHTTPBin) {
  358. auto host = "httpbin.org";
  359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  360. auto port = 443;
  361. SSLClient cli(host, port);
  362. #else
  363. auto port = 80;
  364. Client cli(host, port);
  365. #endif
  366. cli.set_connection_timeout(5);
  367. {
  368. auto res = cli.Get("/range/32");
  369. ASSERT_TRUE(res);
  370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  371. EXPECT_EQ(200, res->status);
  372. }
  373. {
  374. Headers headers = {make_range_header({{1, -1}})};
  375. auto res = cli.Get("/range/32", headers);
  376. ASSERT_TRUE(res);
  377. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  378. EXPECT_EQ(206, res->status);
  379. }
  380. {
  381. Headers headers = {make_range_header({{1, 10}})};
  382. auto res = cli.Get("/range/32", headers);
  383. ASSERT_TRUE(res);
  384. EXPECT_EQ("bcdefghijk", res->body);
  385. EXPECT_EQ(206, res->status);
  386. }
  387. {
  388. Headers headers = {make_range_header({{0, 31}})};
  389. auto res = cli.Get("/range/32", headers);
  390. ASSERT_TRUE(res);
  391. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  392. EXPECT_EQ(200, res->status);
  393. }
  394. {
  395. Headers headers = {make_range_header({{0, -1}})};
  396. auto res = cli.Get("/range/32", headers);
  397. ASSERT_TRUE(res);
  398. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  399. EXPECT_EQ(200, res->status);
  400. }
  401. {
  402. Headers headers = {make_range_header({{0, 32}})};
  403. auto res = cli.Get("/range/32", headers);
  404. ASSERT_TRUE(res);
  405. EXPECT_EQ(416, res->status);
  406. }
  407. }
  408. TEST(ConnectionErrorTest, InvalidHost) {
  409. auto host = "-abcde.com";
  410. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  411. auto port = 443;
  412. SSLClient cli(host, port);
  413. #else
  414. auto port = 80;
  415. Client cli(host, port);
  416. #endif
  417. cli.set_connection_timeout(2);
  418. auto res = cli.Get("/");
  419. ASSERT_TRUE(!res);
  420. EXPECT_EQ(Error::Connection, res.error());
  421. }
  422. TEST(ConnectionErrorTest, InvalidHost2) {
  423. auto host = "httpbin.org/";
  424. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  425. SSLClient cli(host);
  426. #else
  427. Client cli(host);
  428. #endif
  429. cli.set_connection_timeout(2);
  430. auto res = cli.Get("/");
  431. ASSERT_TRUE(!res);
  432. EXPECT_EQ(Error::Connection, res.error());
  433. }
  434. TEST(ConnectionErrorTest, InvalidPort) {
  435. auto host = "localhost";
  436. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  437. auto port = 44380;
  438. SSLClient cli(host, port);
  439. #else
  440. auto port = 8080;
  441. Client cli(host, port);
  442. #endif
  443. cli.set_connection_timeout(2);
  444. auto res = cli.Get("/");
  445. ASSERT_TRUE(!res);
  446. EXPECT_EQ(Error::Connection, res.error());
  447. }
  448. TEST(ConnectionErrorTest, Timeout) {
  449. auto host = "google.com";
  450. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  451. auto port = 44380;
  452. SSLClient cli(host, port);
  453. #else
  454. auto port = 8080;
  455. Client cli(host, port);
  456. #endif
  457. cli.set_connection_timeout(2);
  458. auto res = cli.Get("/");
  459. ASSERT_TRUE(!res);
  460. EXPECT_TRUE(res.error() == Error::Connection);
  461. }
  462. TEST(CancelTest, NoCancel) {
  463. auto host = "httpbin.org";
  464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  465. auto port = 443;
  466. SSLClient cli(host, port);
  467. #else
  468. auto port = 80;
  469. Client cli(host, port);
  470. #endif
  471. cli.set_connection_timeout(5);
  472. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  473. ASSERT_TRUE(res);
  474. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  475. EXPECT_EQ(200, res->status);
  476. }
  477. TEST(CancelTest, WithCancelSmallPayload) {
  478. auto host = "httpbin.org";
  479. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  480. auto port = 443;
  481. SSLClient cli(host, port);
  482. #else
  483. auto port = 80;
  484. Client cli(host, port);
  485. #endif
  486. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  487. cli.set_connection_timeout(5);
  488. ASSERT_TRUE(!res);
  489. EXPECT_EQ(Error::Canceled, res.error());
  490. }
  491. TEST(CancelTest, WithCancelLargePayload) {
  492. auto host = "httpbin.org";
  493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  494. auto port = 443;
  495. SSLClient cli(host, port);
  496. #else
  497. auto port = 80;
  498. Client cli(host, port);
  499. #endif
  500. cli.set_connection_timeout(5);
  501. uint32_t count = 0;
  502. auto res = cli.Get("/range/65536",
  503. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  504. ASSERT_TRUE(!res);
  505. EXPECT_EQ(Error::Canceled, res.error());
  506. }
  507. TEST(BaseAuthTest, FromHTTPWatch) {
  508. auto host = "httpbin.org";
  509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  510. auto port = 443;
  511. SSLClient cli(host, port);
  512. #else
  513. auto port = 80;
  514. Client cli(host, port);
  515. #endif
  516. {
  517. auto res = cli.Get("/basic-auth/hello/world");
  518. ASSERT_TRUE(res);
  519. EXPECT_EQ(401, res->status);
  520. }
  521. {
  522. auto res = cli.Get("/basic-auth/hello/world",
  523. {make_basic_authentication_header("hello", "world")});
  524. ASSERT_TRUE(res);
  525. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  526. res->body);
  527. EXPECT_EQ(200, res->status);
  528. }
  529. {
  530. cli.set_basic_auth("hello", "world");
  531. auto res = cli.Get("/basic-auth/hello/world");
  532. ASSERT_TRUE(res);
  533. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  534. res->body);
  535. EXPECT_EQ(200, res->status);
  536. }
  537. {
  538. cli.set_basic_auth("hello", "bad");
  539. auto res = cli.Get("/basic-auth/hello/world");
  540. ASSERT_TRUE(res);
  541. EXPECT_EQ(401, res->status);
  542. }
  543. {
  544. cli.set_basic_auth("bad", "world");
  545. auto res = cli.Get("/basic-auth/hello/world");
  546. ASSERT_TRUE(res);
  547. EXPECT_EQ(401, res->status);
  548. }
  549. }
  550. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  551. TEST(DigestAuthTest, FromHTTPWatch) {
  552. auto host = "httpbin.org";
  553. auto port = 443;
  554. SSLClient cli(host, port);
  555. {
  556. auto res = cli.Get("/digest-auth/auth/hello/world");
  557. ASSERT_TRUE(res);
  558. EXPECT_EQ(401, res->status);
  559. }
  560. {
  561. std::vector<std::string> paths = {
  562. "/digest-auth/auth/hello/world/MD5",
  563. "/digest-auth/auth/hello/world/SHA-256",
  564. "/digest-auth/auth/hello/world/SHA-512",
  565. "/digest-auth/auth-int/hello/world/MD5",
  566. };
  567. cli.set_digest_auth("hello", "world");
  568. for (auto path : paths) {
  569. auto res = cli.Get(path.c_str());
  570. ASSERT_TRUE(res);
  571. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  572. res->body);
  573. EXPECT_EQ(200, res->status);
  574. }
  575. cli.set_digest_auth("hello", "bad");
  576. for (auto path : paths) {
  577. auto res = cli.Get(path.c_str());
  578. ASSERT_TRUE(res);
  579. EXPECT_EQ(401, res->status);
  580. }
  581. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  582. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  583. // cli.set_digest_auth("bad", "world");
  584. // for (auto path : paths) {
  585. // auto res = cli.Get(path.c_str());
  586. // ASSERT_TRUE(res);
  587. // EXPECT_EQ(400, res->status);
  588. // }
  589. }
  590. }
  591. #endif
  592. #if 0
  593. TEST(AbsoluteRedirectTest, Redirect) {
  594. auto host = "httpbin.org";
  595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  596. SSLClient cli(host);
  597. #else
  598. Client cli(host);
  599. #endif
  600. cli.set_follow_location(true);
  601. auto res = cli.Get("/absolute-redirect/3");
  602. ASSERT_TRUE(res);
  603. EXPECT_EQ(200, res->status);
  604. }
  605. TEST(RedirectTest, Redirect) {
  606. auto host = "httpbin.org";
  607. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  608. SSLClient cli(host);
  609. #else
  610. Client cli(host);
  611. #endif
  612. cli.set_follow_location(true);
  613. auto res = cli.Get("/redirect/3");
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(200, res->status);
  616. }
  617. TEST(RelativeRedirectTest, Redirect) {
  618. auto host = "httpbin.org";
  619. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  620. SSLClient cli(host);
  621. #else
  622. Client cli(host);
  623. #endif
  624. cli.set_follow_location(true);
  625. auto res = cli.Get("/relative-redirect/3");
  626. ASSERT_TRUE(res);
  627. EXPECT_EQ(200, res->status);
  628. }
  629. TEST(TooManyRedirectTest, Redirect) {
  630. auto host = "httpbin.org";
  631. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  632. SSLClient cli(host);
  633. #else
  634. Client cli(host);
  635. #endif
  636. cli.set_follow_location(true);
  637. auto res = cli.Get("/redirect/21");
  638. ASSERT_TRUE(!res);
  639. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  640. }
  641. #endif
  642. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  643. TEST(YahooRedirectTest, Redirect) {
  644. Client cli("yahoo.com");
  645. auto res = cli.Get("/");
  646. ASSERT_TRUE(res);
  647. EXPECT_EQ(301, res->status);
  648. cli.set_follow_location(true);
  649. res = cli.Get("/");
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(200, res->status);
  652. EXPECT_EQ("https://yahoo.com/", res->location);
  653. }
  654. #if 0
  655. TEST(HttpsToHttpRedirectTest, Redirect) {
  656. SSLClient cli("httpbin.org");
  657. cli.set_follow_location(true);
  658. auto res =
  659. cli.Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  660. ASSERT_TRUE(res);
  661. EXPECT_EQ(200, res->status);
  662. }
  663. #endif
  664. TEST(RedirectToDifferentPort, Redirect) {
  665. Server svr8080;
  666. Server svr8081;
  667. svr8080.Get("/1", [&](const Request & /*req*/, Response &res) {
  668. res.set_redirect("http://localhost:8081/2");
  669. });
  670. svr8081.Get("/2", [&](const Request & /*req*/, Response &res) {
  671. res.set_content("Hello World!", "text/plain");
  672. });
  673. auto thread8080 = std::thread([&]() { svr8080.listen("localhost", 8080); });
  674. auto thread8081 = std::thread([&]() { svr8081.listen("localhost", 8081); });
  675. while (!svr8080.is_running() || !svr8081.is_running()) {
  676. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  677. }
  678. // Give GET time to get a few messages.
  679. std::this_thread::sleep_for(std::chrono::seconds(1));
  680. Client cli("localhost", 8080);
  681. cli.set_follow_location(true);
  682. auto res = cli.Get("/1");
  683. ASSERT_TRUE(res);
  684. EXPECT_EQ(200, res->status);
  685. EXPECT_EQ("Hello World!", res->body);
  686. svr8080.stop();
  687. svr8081.stop();
  688. thread8080.join();
  689. thread8081.join();
  690. ASSERT_FALSE(svr8080.is_running());
  691. ASSERT_FALSE(svr8081.is_running());
  692. }
  693. TEST(UrlWithSpace, Redirect) {
  694. SSLClient cli("edge.forgecdn.net");
  695. cli.set_follow_location(true);
  696. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ(200, res->status);
  699. EXPECT_EQ(18527, res->get_header_value<uint64_t>("Content-Length"));
  700. }
  701. #endif
  702. TEST(BindServerTest, BindDualStack) {
  703. Server svr;
  704. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  705. res.set_content("Hello World!", "text/plain");
  706. });
  707. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  708. // Give GET time to get a few messages.
  709. std::this_thread::sleep_for(std::chrono::seconds(1));
  710. {
  711. Client cli("127.0.0.1", PORT);
  712. auto res = cli.Get("/1");
  713. ASSERT_TRUE(res);
  714. EXPECT_EQ(200, res->status);
  715. EXPECT_EQ("Hello World!", res->body);
  716. }
  717. {
  718. Client cli("::1", PORT);
  719. auto res = cli.Get("/1");
  720. ASSERT_TRUE(res);
  721. EXPECT_EQ(200, res->status);
  722. EXPECT_EQ("Hello World!", res->body);
  723. }
  724. svr.stop();
  725. thread.join();
  726. ASSERT_FALSE(svr.is_running());
  727. }
  728. TEST(BindServerTest, BindAndListenSeparately) {
  729. Server svr;
  730. int port = svr.bind_to_any_port("0.0.0.0");
  731. ASSERT_TRUE(svr.is_valid());
  732. ASSERT_TRUE(port > 0);
  733. svr.stop();
  734. }
  735. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  736. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  738. CLIENT_CA_CERT_DIR);
  739. int port = svr.bind_to_any_port("0.0.0.0");
  740. ASSERT_TRUE(svr.is_valid());
  741. ASSERT_TRUE(port > 0);
  742. svr.stop();
  743. }
  744. #endif
  745. TEST(ErrorHandlerTest, ContentLength) {
  746. Server svr;
  747. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  748. res.status = 200;
  749. res.set_content("abcdefghijklmnopqrstuvwxyz",
  750. "text/html"); // <= Content-Length still 13
  751. });
  752. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  753. res.set_content("Hello World!\n", "text/plain");
  754. res.status = 524;
  755. });
  756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  757. // Give GET time to get a few messages.
  758. std::this_thread::sleep_for(std::chrono::seconds(1));
  759. {
  760. Client cli(HOST, PORT);
  761. auto res = cli.Get("/hi");
  762. ASSERT_TRUE(res);
  763. EXPECT_EQ(200, res->status);
  764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  765. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  766. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  767. }
  768. svr.stop();
  769. thread.join();
  770. ASSERT_FALSE(svr.is_running());
  771. }
  772. TEST(InvalidFormatTest, StatusCode) {
  773. Server svr;
  774. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  775. res.set_content("Hello World!\n", "text/plain");
  776. res.status = 9999; // Status should be a three-digit code...
  777. });
  778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  779. // Give GET time to get a few messages.
  780. std::this_thread::sleep_for(std::chrono::seconds(1));
  781. {
  782. Client cli(HOST, PORT);
  783. auto res = cli.Get("/hi");
  784. ASSERT_FALSE(res);
  785. }
  786. svr.stop();
  787. thread.join();
  788. ASSERT_FALSE(svr.is_running());
  789. }
  790. class ServerTest : public ::testing::Test {
  791. protected:
  792. ServerTest()
  793. : cli_(HOST, PORT)
  794. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  795. ,
  796. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  797. #endif
  798. {
  799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  800. cli_.enable_server_certificate_verification(false);
  801. #endif
  802. }
  803. virtual void SetUp() {
  804. svr_.set_mount_point("/", "./www");
  805. svr_.set_mount_point("/mount", "./www2");
  806. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  807. svr_.Get("/hi",
  808. [&](const Request & /*req*/, Response &res) {
  809. res.set_content("Hello World!", "text/plain");
  810. })
  811. .Get("/http_response_splitting",
  812. [&](const Request & /*req*/, Response &res) {
  813. res.set_header("a", "1\r\nSet-Cookie: a=1");
  814. EXPECT_EQ(0, res.headers.size());
  815. EXPECT_FALSE(res.has_header("a"));
  816. res.set_header("a", "1\nSet-Cookie: a=1");
  817. EXPECT_EQ(0, res.headers.size());
  818. EXPECT_FALSE(res.has_header("a"));
  819. res.set_header("a", "1\rSet-Cookie: a=1");
  820. EXPECT_EQ(0, res.headers.size());
  821. EXPECT_FALSE(res.has_header("a"));
  822. res.set_header("a\r\nb", "0");
  823. EXPECT_EQ(0, res.headers.size());
  824. EXPECT_FALSE(res.has_header("a"));
  825. res.set_header("a\rb", "0");
  826. EXPECT_EQ(0, res.headers.size());
  827. EXPECT_FALSE(res.has_header("a"));
  828. res.set_header("a\nb", "0");
  829. EXPECT_EQ(0, res.headers.size());
  830. EXPECT_FALSE(res.has_header("a"));
  831. res.set_redirect("1\r\nSet-Cookie: a=1");
  832. EXPECT_EQ(0, res.headers.size());
  833. EXPECT_FALSE(res.has_header("Location"));
  834. })
  835. .Get("/slow",
  836. [&](const Request & /*req*/, Response &res) {
  837. std::this_thread::sleep_for(std::chrono::seconds(2));
  838. res.set_content("slow", "text/plain");
  839. })
  840. .Post("/slowpost",
  841. [&](const Request & /*req*/, Response &res) {
  842. std::this_thread::sleep_for(std::chrono::seconds(2));
  843. res.set_content("slow", "text/plain");
  844. })
  845. .Get("/remote_addr",
  846. [&](const Request &req, Response &res) {
  847. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  848. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  849. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  850. EXPECT_EQ(req.remote_port,
  851. std::stoi(req.get_header_value("REMOTE_PORT")));
  852. res.set_content(remote_addr.c_str(), "text/plain");
  853. })
  854. .Get("/endwith%",
  855. [&](const Request & /*req*/, Response &res) {
  856. res.set_content("Hello World!", "text/plain");
  857. })
  858. .Get("/a\\+\\+b",
  859. [&](const Request &req, Response &res) {
  860. ASSERT_TRUE(req.has_param("a +b"));
  861. auto val = req.get_param_value("a +b");
  862. res.set_content(val, "text/plain");
  863. })
  864. .Get("/", [&](const Request & /*req*/,
  865. Response &res) { res.set_redirect("/hi"); })
  866. .Post("/1", [](const Request & /*req*/,
  867. Response &res) { res.set_redirect("/2", 303); })
  868. .Get("/2",
  869. [](const Request & /*req*/, Response &res) {
  870. res.set_content("redirected.", "text/plain");
  871. res.status = 200;
  872. })
  873. .Post("/person",
  874. [&](const Request &req, Response &res) {
  875. if (req.has_param("name") && req.has_param("note")) {
  876. persons_[req.get_param_value("name")] =
  877. req.get_param_value("note");
  878. } else {
  879. res.status = 400;
  880. }
  881. })
  882. .Put("/person",
  883. [&](const Request &req, Response &res) {
  884. if (req.has_param("name") && req.has_param("note")) {
  885. persons_[req.get_param_value("name")] =
  886. req.get_param_value("note");
  887. } else {
  888. res.status = 400;
  889. }
  890. })
  891. .Get("/person/(.*)",
  892. [&](const Request &req, Response &res) {
  893. string name = req.matches[1];
  894. if (persons_.find(name) != persons_.end()) {
  895. auto note = persons_[name];
  896. res.set_content(note, "text/plain");
  897. } else {
  898. res.status = 404;
  899. }
  900. })
  901. .Post("/x-www-form-urlencoded-json",
  902. [&](const Request &req, Response &res) {
  903. auto json = req.get_param_value("json");
  904. ASSERT_EQ(JSON_DATA, json);
  905. res.set_content(json, "appliation/json");
  906. res.status = 200;
  907. })
  908. .Get("/streamed-chunked",
  909. [&](const Request & /*req*/, Response &res) {
  910. res.set_chunked_content_provider(
  911. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  912. EXPECT_TRUE(sink.is_writable());
  913. sink.os << "123";
  914. sink.os << "456";
  915. sink.os << "789";
  916. sink.done();
  917. return true;
  918. });
  919. })
  920. .Get("/streamed-chunked2",
  921. [&](const Request & /*req*/, Response &res) {
  922. auto i = new int(0);
  923. res.set_chunked_content_provider(
  924. "text/plain",
  925. [i](size_t /*offset*/, DataSink &sink) {
  926. EXPECT_TRUE(sink.is_writable());
  927. switch (*i) {
  928. case 0: sink.os << "123"; break;
  929. case 1: sink.os << "456"; break;
  930. case 2: sink.os << "789"; break;
  931. case 3: sink.done(); break;
  932. }
  933. (*i)++;
  934. return true;
  935. },
  936. [i] { delete i; });
  937. })
  938. .Get("/streamed",
  939. [&](const Request & /*req*/, Response &res) {
  940. res.set_content_provider(
  941. 6, "text/plain",
  942. [](size_t offset, size_t /*length*/, DataSink &sink) {
  943. sink.os << (offset < 3 ? "a" : "b");
  944. return true;
  945. });
  946. })
  947. .Get("/streamed-with-range",
  948. [&](const Request & /*req*/, Response &res) {
  949. auto data = new std::string("abcdefg");
  950. res.set_content_provider(
  951. data->size(), "text/plain",
  952. [data](size_t offset, size_t length, DataSink &sink) {
  953. EXPECT_TRUE(sink.is_writable());
  954. size_t DATA_CHUNK_SIZE = 4;
  955. const auto &d = *data;
  956. auto out_len =
  957. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  958. sink.write(&d[static_cast<size_t>(offset)], out_len);
  959. return true;
  960. },
  961. [data] { delete data; });
  962. })
  963. .Get("/streamed-cancel",
  964. [&](const Request & /*req*/, Response &res) {
  965. res.set_content_provider(
  966. size_t(-1), "text/plain",
  967. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  968. EXPECT_TRUE(sink.is_writable());
  969. sink.os << "data_chunk";
  970. return true;
  971. });
  972. })
  973. .Get("/with-range",
  974. [&](const Request & /*req*/, Response &res) {
  975. res.set_content("abcdefg", "text/plain");
  976. })
  977. .Post("/chunked",
  978. [&](const Request &req, Response & /*res*/) {
  979. EXPECT_EQ(req.body, "dechunked post body");
  980. })
  981. .Post("/large-chunked",
  982. [&](const Request &req, Response & /*res*/) {
  983. std::string expected(6 * 30 * 1024u, 'a');
  984. EXPECT_EQ(req.body, expected);
  985. })
  986. .Post("/multipart",
  987. [&](const Request &req, Response & /*res*/) {
  988. EXPECT_EQ(6u, req.files.size());
  989. ASSERT_TRUE(!req.has_file("???"));
  990. ASSERT_TRUE(req.body.empty());
  991. {
  992. const auto &file = req.get_file_value("text1");
  993. EXPECT_TRUE(file.filename.empty());
  994. EXPECT_EQ("text default", file.content);
  995. }
  996. {
  997. const auto &file = req.get_file_value("text2");
  998. EXPECT_TRUE(file.filename.empty());
  999. EXPECT_EQ("aωb", file.content);
  1000. }
  1001. {
  1002. const auto &file = req.get_file_value("file1");
  1003. EXPECT_EQ("hello.txt", file.filename);
  1004. EXPECT_EQ("text/plain", file.content_type);
  1005. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1006. }
  1007. {
  1008. const auto &file = req.get_file_value("file3");
  1009. EXPECT_TRUE(file.filename.empty());
  1010. EXPECT_EQ("application/octet-stream", file.content_type);
  1011. EXPECT_EQ(0u, file.content.size());
  1012. }
  1013. {
  1014. const auto &file = req.get_file_value("file4");
  1015. EXPECT_TRUE(file.filename.empty());
  1016. EXPECT_EQ(0u, file.content.size());
  1017. EXPECT_EQ("application/json tmp-string", file.content_type);
  1018. }
  1019. })
  1020. .Post("/empty",
  1021. [&](const Request &req, Response &res) {
  1022. EXPECT_EQ(req.body, "");
  1023. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1024. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1025. res.set_content("empty", "text/plain");
  1026. })
  1027. .Post("/empty-no-content-type",
  1028. [&](const Request &req, Response &res) {
  1029. EXPECT_EQ(req.body, "");
  1030. EXPECT_FALSE(req.has_header("Content-Type"));
  1031. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1032. res.set_content("empty-no-content-type", "text/plain");
  1033. })
  1034. .Put("/empty-no-content-type",
  1035. [&](const Request &req, Response &res) {
  1036. EXPECT_EQ(req.body, "");
  1037. EXPECT_FALSE(req.has_header("Content-Type"));
  1038. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1039. res.set_content("empty-no-content-type", "text/plain");
  1040. })
  1041. .Put("/put",
  1042. [&](const Request &req, Response &res) {
  1043. EXPECT_EQ(req.body, "PUT");
  1044. res.set_content(req.body, "text/plain");
  1045. })
  1046. .Put("/put-large",
  1047. [&](const Request &req, Response &res) {
  1048. EXPECT_EQ(req.body, LARGE_DATA);
  1049. res.set_content(req.body, "text/plain");
  1050. })
  1051. .Patch("/patch",
  1052. [&](const Request &req, Response &res) {
  1053. EXPECT_EQ(req.body, "PATCH");
  1054. res.set_content(req.body, "text/plain");
  1055. })
  1056. .Delete("/delete",
  1057. [&](const Request & /*req*/, Response &res) {
  1058. res.set_content("DELETE", "text/plain");
  1059. })
  1060. .Delete("/delete-body",
  1061. [&](const Request &req, Response &res) {
  1062. EXPECT_EQ(req.body, "content");
  1063. res.set_content(req.body, "text/plain");
  1064. })
  1065. .Options(R"(\*)",
  1066. [&](const Request & /*req*/, Response &res) {
  1067. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1068. })
  1069. .Get("/request-target",
  1070. [&](const Request &req, Response & /*res*/) {
  1071. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1072. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1073. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1074. })
  1075. .Get("/long-query-value",
  1076. [&](const Request &req, Response & /*res*/) {
  1077. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1078. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1079. })
  1080. .Get("/array-param",
  1081. [&](const Request &req, Response & /*res*/) {
  1082. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1083. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1084. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1085. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1086. })
  1087. .Post("/validate-no-multiple-headers",
  1088. [&](const Request &req, Response & /*res*/) {
  1089. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1090. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1091. })
  1092. .Post("/content_receiver",
  1093. [&](const Request &req, Response &res,
  1094. const ContentReader &content_reader) {
  1095. if (req.is_multipart_form_data()) {
  1096. MultipartFormDataItems files;
  1097. content_reader(
  1098. [&](const MultipartFormData &file) {
  1099. files.push_back(file);
  1100. return true;
  1101. },
  1102. [&](const char *data, size_t data_length) {
  1103. files.back().content.append(data, data_length);
  1104. return true;
  1105. });
  1106. EXPECT_EQ(5u, files.size());
  1107. {
  1108. const auto &file = get_file_value(files, "text1");
  1109. EXPECT_TRUE(file.filename.empty());
  1110. EXPECT_EQ("text default", file.content);
  1111. }
  1112. {
  1113. const auto &file = get_file_value(files, "text2");
  1114. EXPECT_TRUE(file.filename.empty());
  1115. EXPECT_EQ("aωb", file.content);
  1116. }
  1117. {
  1118. const auto &file = get_file_value(files, "file1");
  1119. EXPECT_EQ("hello.txt", file.filename);
  1120. EXPECT_EQ("text/plain", file.content_type);
  1121. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1122. }
  1123. {
  1124. const auto &file = get_file_value(files, "file3");
  1125. EXPECT_TRUE(file.filename.empty());
  1126. EXPECT_EQ("application/octet-stream", file.content_type);
  1127. EXPECT_EQ(0u, file.content.size());
  1128. }
  1129. } else {
  1130. std::string body;
  1131. content_reader([&](const char *data, size_t data_length) {
  1132. EXPECT_EQ(data_length, 7);
  1133. body.append(data, data_length);
  1134. return true;
  1135. });
  1136. EXPECT_EQ(body, "content");
  1137. res.set_content(body, "text/plain");
  1138. }
  1139. })
  1140. .Put("/content_receiver",
  1141. [&](const Request & /*req*/, Response &res,
  1142. const ContentReader &content_reader) {
  1143. std::string body;
  1144. content_reader([&](const char *data, size_t data_length) {
  1145. body.append(data, data_length);
  1146. return true;
  1147. });
  1148. EXPECT_EQ(body, "content");
  1149. res.set_content(body, "text/plain");
  1150. })
  1151. .Patch("/content_receiver",
  1152. [&](const Request & /*req*/, Response &res,
  1153. const ContentReader &content_reader) {
  1154. std::string body;
  1155. content_reader([&](const char *data, size_t data_length) {
  1156. body.append(data, data_length);
  1157. return true;
  1158. });
  1159. EXPECT_EQ(body, "content");
  1160. res.set_content(body, "text/plain");
  1161. })
  1162. .Post("/query-string-and-body",
  1163. [&](const Request &req, Response & /*res*/) {
  1164. ASSERT_TRUE(req.has_param("key"));
  1165. EXPECT_EQ(req.get_param_value("key"), "value");
  1166. EXPECT_EQ(req.body, "content");
  1167. })
  1168. .Get("/last-request",
  1169. [&](const Request &req, Response & /*res*/) {
  1170. EXPECT_EQ("close", req.get_header_value("Connection"));
  1171. })
  1172. .Get(R"(/redirect/(\d+))",
  1173. [&](const Request &req, Response &res) {
  1174. auto num = std::stoi(req.matches[1]) + 1;
  1175. std::string url = "/redirect/" + std::to_string(num);
  1176. res.set_redirect(url);
  1177. })
  1178. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1179. .Get("/compress",
  1180. [&](const Request & /*req*/, Response &res) {
  1181. res.set_content(
  1182. "12345678901234567890123456789012345678901234567890123456789"
  1183. "01234567890123456789012345678901234567890",
  1184. "text/plain");
  1185. })
  1186. .Get("/nocompress",
  1187. [&](const Request & /*req*/, Response &res) {
  1188. res.set_content(
  1189. "12345678901234567890123456789012345678901234567890123456789"
  1190. "01234567890123456789012345678901234567890",
  1191. "application/octet-stream");
  1192. })
  1193. .Post("/compress-multipart",
  1194. [&](const Request &req, Response & /*res*/) {
  1195. EXPECT_EQ(2u, req.files.size());
  1196. ASSERT_TRUE(!req.has_file("???"));
  1197. {
  1198. const auto &file = req.get_file_value("key1");
  1199. EXPECT_TRUE(file.filename.empty());
  1200. EXPECT_EQ("test", file.content);
  1201. }
  1202. {
  1203. const auto &file = req.get_file_value("key2");
  1204. EXPECT_TRUE(file.filename.empty());
  1205. EXPECT_EQ("--abcdefg123", file.content);
  1206. }
  1207. })
  1208. #endif
  1209. ;
  1210. persons_["john"] = "programmer";
  1211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1212. while (!svr_.is_running()) {
  1213. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1214. }
  1215. }
  1216. virtual void TearDown() {
  1217. svr_.stop();
  1218. if (!request_threads_.empty()) {
  1219. std::this_thread::sleep_for(std::chrono::seconds(1));
  1220. for (auto &t : request_threads_) {
  1221. t.join();
  1222. }
  1223. }
  1224. t_.join();
  1225. }
  1226. map<string, string> persons_;
  1227. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1228. SSLClient cli_;
  1229. SSLServer svr_;
  1230. #else
  1231. Client cli_;
  1232. Server svr_;
  1233. #endif
  1234. thread t_;
  1235. std::vector<thread> request_threads_;
  1236. };
  1237. TEST_F(ServerTest, GetMethod200) {
  1238. auto res = cli_.Get("/hi");
  1239. ASSERT_TRUE(res);
  1240. EXPECT_EQ("HTTP/1.1", res->version);
  1241. EXPECT_EQ(200, res->status);
  1242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1243. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1244. EXPECT_EQ("Hello World!", res->body);
  1245. }
  1246. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1247. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1248. ASSERT_TRUE(res);
  1249. EXPECT_EQ("HTTP/1.1", res->version);
  1250. EXPECT_EQ(200, res->status);
  1251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1252. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1253. EXPECT_EQ("Hello World!", res->body);
  1254. }
  1255. TEST_F(ServerTest, GetMethod302) {
  1256. auto res = cli_.Get("/");
  1257. ASSERT_TRUE(res);
  1258. EXPECT_EQ(302, res->status);
  1259. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1260. }
  1261. TEST_F(ServerTest, GetMethod302Redirect) {
  1262. cli_.set_follow_location(true);
  1263. auto res = cli_.Get("/");
  1264. ASSERT_TRUE(res);
  1265. EXPECT_EQ(200, res->status);
  1266. EXPECT_EQ("Hello World!", res->body);
  1267. EXPECT_EQ("/hi", res->location);
  1268. }
  1269. TEST_F(ServerTest, GetMethod404) {
  1270. auto res = cli_.Get("/invalid");
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ(404, res->status);
  1273. }
  1274. TEST_F(ServerTest, HeadMethod200) {
  1275. auto res = cli_.Head("/hi");
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ(200, res->status);
  1278. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1279. EXPECT_TRUE(res->body.empty());
  1280. }
  1281. TEST_F(ServerTest, HeadMethod200Static) {
  1282. auto res = cli_.Head("/mount/dir/index.html");
  1283. ASSERT_TRUE(res);
  1284. EXPECT_EQ(200, res->status);
  1285. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1286. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1287. EXPECT_TRUE(res->body.empty());
  1288. }
  1289. TEST_F(ServerTest, HeadMethod404) {
  1290. auto res = cli_.Head("/invalid");
  1291. ASSERT_TRUE(res);
  1292. EXPECT_EQ(404, res->status);
  1293. EXPECT_TRUE(res->body.empty());
  1294. }
  1295. TEST_F(ServerTest, GetMethodPersonJohn) {
  1296. auto res = cli_.Get("/person/john");
  1297. ASSERT_TRUE(res);
  1298. EXPECT_EQ(200, res->status);
  1299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1300. EXPECT_EQ("programmer", res->body);
  1301. }
  1302. TEST_F(ServerTest, PostMethod1) {
  1303. auto res = cli_.Get("/person/john1");
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(404, res->status);
  1306. res = cli_.Post("/person", "name=john1&note=coder",
  1307. "application/x-www-form-urlencoded");
  1308. ASSERT_TRUE(res);
  1309. ASSERT_EQ(200, res->status);
  1310. res = cli_.Get("/person/john1");
  1311. ASSERT_TRUE(res);
  1312. ASSERT_EQ(200, res->status);
  1313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1314. ASSERT_EQ("coder", res->body);
  1315. }
  1316. TEST_F(ServerTest, PostMethod2) {
  1317. auto res = cli_.Get("/person/john2");
  1318. ASSERT_TRUE(res);
  1319. ASSERT_EQ(404, res->status);
  1320. Params params;
  1321. params.emplace("name", "john2");
  1322. params.emplace("note", "coder");
  1323. res = cli_.Post("/person", params);
  1324. ASSERT_TRUE(res);
  1325. ASSERT_EQ(200, res->status);
  1326. res = cli_.Get("/person/john2");
  1327. ASSERT_TRUE(res);
  1328. ASSERT_EQ(200, res->status);
  1329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1330. ASSERT_EQ("coder", res->body);
  1331. }
  1332. TEST_F(ServerTest, PutMethod3) {
  1333. auto res = cli_.Get("/person/john3");
  1334. ASSERT_TRUE(res);
  1335. ASSERT_EQ(404, res->status);
  1336. Params params;
  1337. params.emplace("name", "john3");
  1338. params.emplace("note", "coder");
  1339. res = cli_.Put("/person", params);
  1340. ASSERT_TRUE(res);
  1341. ASSERT_EQ(200, res->status);
  1342. res = cli_.Get("/person/john3");
  1343. ASSERT_TRUE(res);
  1344. ASSERT_EQ(200, res->status);
  1345. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1346. ASSERT_EQ("coder", res->body);
  1347. }
  1348. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1349. Params params;
  1350. params.emplace("json", JSON_DATA);
  1351. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1352. ASSERT_TRUE(res);
  1353. ASSERT_EQ(200, res->status);
  1354. ASSERT_EQ(JSON_DATA, res->body);
  1355. }
  1356. TEST_F(ServerTest, PostEmptyContent) {
  1357. auto res = cli_.Post("/empty", "", "text/plain");
  1358. ASSERT_TRUE(res);
  1359. ASSERT_EQ(200, res->status);
  1360. ASSERT_EQ("empty", res->body);
  1361. }
  1362. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1363. auto res = cli_.Post("/empty-no-content-type");
  1364. ASSERT_TRUE(res);
  1365. ASSERT_EQ(200, res->status);
  1366. ASSERT_EQ("empty-no-content-type", res->body);
  1367. }
  1368. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1369. auto res = cli_.Put("/empty-no-content-type");
  1370. ASSERT_TRUE(res);
  1371. ASSERT_EQ(200, res->status);
  1372. ASSERT_EQ("empty-no-content-type", res->body);
  1373. }
  1374. TEST_F(ServerTest, GetMethodDir) {
  1375. auto res = cli_.Get("/dir/");
  1376. ASSERT_TRUE(res);
  1377. EXPECT_EQ(200, res->status);
  1378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1379. auto body = R"(<html>
  1380. <head>
  1381. </head>
  1382. <body>
  1383. <a href="/dir/test.html">Test</a>
  1384. <a href="/hi">hi</a>
  1385. </body>
  1386. </html>
  1387. )";
  1388. EXPECT_EQ(body, res->body);
  1389. }
  1390. TEST_F(ServerTest, GetMethodDirTest) {
  1391. auto res = cli_.Get("/dir/test.html");
  1392. ASSERT_TRUE(res);
  1393. EXPECT_EQ(200, res->status);
  1394. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1395. EXPECT_EQ("test.html", res->body);
  1396. }
  1397. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1398. auto res = cli_.Get("/dir/../dir/test.html");
  1399. ASSERT_TRUE(res);
  1400. EXPECT_EQ(200, res->status);
  1401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1402. EXPECT_EQ("test.html", res->body);
  1403. }
  1404. TEST_F(ServerTest, GetMethodInvalidPath) {
  1405. auto res = cli_.Get("/dir/../test.html");
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ(404, res->status);
  1408. }
  1409. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1410. auto res = cli_.Get("/../www/dir/test.html");
  1411. ASSERT_TRUE(res);
  1412. EXPECT_EQ(404, res->status);
  1413. }
  1414. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1415. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1416. ASSERT_TRUE(res);
  1417. EXPECT_EQ(404, res->status);
  1418. }
  1419. TEST_F(ServerTest, GetMethodDirMountTest) {
  1420. auto res = cli_.Get("/mount/dir/test.html");
  1421. ASSERT_TRUE(res);
  1422. EXPECT_EQ(200, res->status);
  1423. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1424. EXPECT_EQ("test.html", res->body);
  1425. }
  1426. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1427. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ(200, res->status);
  1430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1431. EXPECT_EQ("test.html", res->body);
  1432. }
  1433. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1434. auto res = cli_.Get("/mount/dir/../test.html");
  1435. ASSERT_TRUE(res);
  1436. EXPECT_EQ(404, res->status);
  1437. }
  1438. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1439. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1440. ASSERT_TRUE(res);
  1441. EXPECT_EQ(404, res->status);
  1442. }
  1443. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1444. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1445. ASSERT_TRUE(res);
  1446. EXPECT_EQ(404, res->status);
  1447. }
  1448. TEST_F(ServerTest, PostMethod303) {
  1449. auto res = cli_.Post("/1", "body", "text/plain");
  1450. ASSERT_TRUE(res);
  1451. EXPECT_EQ(303, res->status);
  1452. EXPECT_EQ("/2", res->get_header_value("Location"));
  1453. }
  1454. TEST_F(ServerTest, PostMethod303Redirect) {
  1455. cli_.set_follow_location(true);
  1456. auto res = cli_.Post("/1", "body", "text/plain");
  1457. ASSERT_TRUE(res);
  1458. EXPECT_EQ(200, res->status);
  1459. EXPECT_EQ("redirected.", res->body);
  1460. EXPECT_EQ("/2", res->location);
  1461. }
  1462. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1463. auto res = cli_.Get("/dir/test.abcde");
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ(200, res->status);
  1466. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1467. EXPECT_EQ("abcde", res->body);
  1468. }
  1469. TEST_F(ServerTest, StaticFileRange) {
  1470. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ(206, res->status);
  1473. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1474. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1475. EXPECT_EQ(true, res->has_header("Content-Range"));
  1476. EXPECT_EQ(std::string("cd"), res->body);
  1477. }
  1478. TEST_F(ServerTest, InvalidBaseDirMount) {
  1479. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1480. }
  1481. TEST_F(ServerTest, EmptyRequest) {
  1482. auto res = cli_.Get("");
  1483. ASSERT_TRUE(!res);
  1484. EXPECT_EQ(Error::Connection, res.error());
  1485. }
  1486. TEST_F(ServerTest, LongRequest) {
  1487. std::string request;
  1488. for (size_t i = 0; i < 545; i++) {
  1489. request += "/TooLongRequest";
  1490. }
  1491. request += "OK";
  1492. auto res = cli_.Get(request.c_str());
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ(404, res->status);
  1495. }
  1496. TEST_F(ServerTest, TooLongRequest) {
  1497. std::string request;
  1498. for (size_t i = 0; i < 545; i++) {
  1499. request += "/TooLongRequest";
  1500. }
  1501. request += "_NG";
  1502. auto res = cli_.Get(request.c_str());
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ(414, res->status);
  1505. }
  1506. TEST_F(ServerTest, LongHeader) {
  1507. Request req;
  1508. req.method = "GET";
  1509. req.path = "/hi";
  1510. std::string host_and_port;
  1511. host_and_port += HOST;
  1512. host_and_port += ":";
  1513. host_and_port += std::to_string(PORT);
  1514. req.headers.emplace("Host", host_and_port.c_str());
  1515. req.headers.emplace("Accept", "*/*");
  1516. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1517. req.headers.emplace(
  1518. "Header-Name",
  1519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1534. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1535. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1536. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1537. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1538. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1539. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1541. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1547. "@@@@@@@@@@@@@@@@");
  1548. auto res = std::make_shared<Response>();
  1549. auto error = Error::Success;
  1550. auto ret = cli_.send(req, *res, error);
  1551. ASSERT_TRUE(ret);
  1552. EXPECT_EQ(200, res->status);
  1553. }
  1554. TEST_F(ServerTest, LongQueryValue) {
  1555. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1556. ASSERT_TRUE(res);
  1557. EXPECT_EQ(414, res->status);
  1558. }
  1559. TEST_F(ServerTest, TooLongHeader) {
  1560. Request req;
  1561. req.method = "GET";
  1562. req.path = "/hi";
  1563. std::string host_and_port;
  1564. host_and_port += HOST;
  1565. host_and_port += ":";
  1566. host_and_port += std::to_string(PORT);
  1567. req.headers.emplace("Host", host_and_port.c_str());
  1568. req.headers.emplace("Accept", "*/*");
  1569. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1570. req.headers.emplace(
  1571. "Header-Name",
  1572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1600. "@@@@@@@@@@@@@@@@@");
  1601. auto res = std::make_shared<Response>();
  1602. auto error = Error::Success;
  1603. auto ret = cli_.send(req, *res, error);
  1604. ASSERT_TRUE(ret);
  1605. EXPECT_EQ(200, res->status);
  1606. }
  1607. TEST_F(ServerTest, PercentEncoding) {
  1608. auto res = cli_.Get("/e%6edwith%");
  1609. ASSERT_TRUE(res);
  1610. EXPECT_EQ(200, res->status);
  1611. }
  1612. TEST_F(ServerTest, PercentEncodingUnicode) {
  1613. auto res = cli_.Get("/e%u006edwith%");
  1614. ASSERT_TRUE(res);
  1615. EXPECT_EQ(200, res->status);
  1616. }
  1617. TEST_F(ServerTest, InvalidPercentEncoding) {
  1618. auto res = cli_.Get("/%endwith%");
  1619. ASSERT_TRUE(res);
  1620. EXPECT_EQ(404, res->status);
  1621. }
  1622. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1623. auto res = cli_.Get("/%uendwith%");
  1624. ASSERT_TRUE(res);
  1625. EXPECT_EQ(404, res->status);
  1626. }
  1627. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1628. auto res = cli_.Get("/hello?aaa=bbb%");
  1629. ASSERT_TRUE(res);
  1630. EXPECT_EQ(404, res->status);
  1631. }
  1632. TEST_F(ServerTest, PlusSignEncoding) {
  1633. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1634. ASSERT_TRUE(res);
  1635. EXPECT_EQ(200, res->status);
  1636. EXPECT_EQ("a +b", res->body);
  1637. }
  1638. TEST_F(ServerTest, MultipartFormData) {
  1639. MultipartFormDataItems items = {
  1640. {"text1", "text default", "", ""},
  1641. {"text2", "aωb", "", ""},
  1642. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1643. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1644. {"file3", "", "", "application/octet-stream"},
  1645. {"file4", "", "", " application/json tmp-string "}};
  1646. auto res = cli_.Post("/multipart", items);
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ(200, res->status);
  1649. }
  1650. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1651. auto res = cli_.Get("/hi");
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(200, res->status);
  1654. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1655. EXPECT_EQ("Hello World!", res->body);
  1656. }
  1657. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1658. Request req;
  1659. req.method = "POST";
  1660. req.path = "/chunked";
  1661. std::string host_and_port;
  1662. host_and_port += HOST;
  1663. host_and_port += ":";
  1664. host_and_port += std::to_string(PORT);
  1665. req.headers.emplace("Host", host_and_port.c_str());
  1666. req.headers.emplace("Accept", "*/*");
  1667. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1668. req.headers.emplace("Content-Type", "text/plain");
  1669. req.headers.emplace("Content-Length", "0");
  1670. req.headers.emplace(
  1671. "Transfer-Encoding",
  1672. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1673. // Client does not chunk, so make a chunked body manually.
  1674. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1675. auto res = std::make_shared<Response>();
  1676. auto error = Error::Success;
  1677. auto ret = cli_.send(req, *res, error);
  1678. ASSERT_TRUE(ret);
  1679. EXPECT_EQ(200, res->status);
  1680. }
  1681. TEST_F(ServerTest, GetStreamed2) {
  1682. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1683. ASSERT_TRUE(res);
  1684. EXPECT_EQ(206, res->status);
  1685. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1686. EXPECT_EQ(std::string("ab"), res->body);
  1687. }
  1688. TEST_F(ServerTest, GetStreamed) {
  1689. auto res = cli_.Get("/streamed");
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(200, res->status);
  1692. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1693. EXPECT_EQ(std::string("aaabbb"), res->body);
  1694. }
  1695. TEST_F(ServerTest, GetStreamedWithRange1) {
  1696. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(206, res->status);
  1699. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1700. EXPECT_EQ(true, res->has_header("Content-Range"));
  1701. EXPECT_EQ(std::string("def"), res->body);
  1702. }
  1703. TEST_F(ServerTest, GetStreamedWithRange2) {
  1704. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1705. ASSERT_TRUE(res);
  1706. EXPECT_EQ(206, res->status);
  1707. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1708. EXPECT_EQ(true, res->has_header("Content-Range"));
  1709. EXPECT_EQ(std::string("bcdefg"), res->body);
  1710. }
  1711. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  1712. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(206, res->status);
  1715. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1716. EXPECT_EQ(true, res->has_header("Content-Range"));
  1717. EXPECT_EQ(std::string("efg"), res->body);
  1718. }
  1719. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  1720. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(206, res->status);
  1723. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1724. EXPECT_EQ(true, res->has_header("Content-Range"));
  1725. EXPECT_EQ(std::string("abcdefg"), res->body);
  1726. }
  1727. TEST_F(ServerTest, GetStreamedWithRangeError) {
  1728. auto res = cli_.Get("/streamed-with-range",
  1729. {{"Range", "bytes=92233720368547758079223372036854775806-"
  1730. "92233720368547758079223372036854775807"}});
  1731. ASSERT_TRUE(res);
  1732. EXPECT_EQ(416, res->status);
  1733. }
  1734. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  1735. auto res =
  1736. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  1737. EXPECT_EQ(206, res->status);
  1738. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1739. EXPECT_EQ(true, res->has_header("Content-Range"));
  1740. EXPECT_EQ(std::string("abcdefg"), res->body);
  1741. }
  1742. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1743. auto res =
  1744. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(206, res->status);
  1747. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1748. EXPECT_EQ(false, res->has_header("Content-Range"));
  1749. EXPECT_EQ(269, res->body.size());
  1750. }
  1751. TEST_F(ServerTest, GetStreamedEndless) {
  1752. uint64_t offset = 0;
  1753. auto res = cli_.Get("/streamed-cancel",
  1754. [&](const char * /*data*/, uint64_t data_length) {
  1755. if (offset < 100) {
  1756. offset += data_length;
  1757. return true;
  1758. }
  1759. return false;
  1760. });
  1761. ASSERT_TRUE(!res);
  1762. EXPECT_EQ(Error::Canceled, res.error());
  1763. }
  1764. TEST_F(ServerTest, ClientStop) {
  1765. std::vector<std::thread> threads;
  1766. for (auto i = 0; i < 3; i++) {
  1767. threads.emplace_back(thread([&]() {
  1768. auto res = cli_.Get("/streamed-cancel",
  1769. [&](const char *, uint64_t) { return true; });
  1770. ASSERT_TRUE(!res);
  1771. EXPECT_TRUE(res.error() == Error::Canceled || res.error() == Error::Read);
  1772. }));
  1773. }
  1774. std::this_thread::sleep_for(std::chrono::seconds(2));
  1775. while (cli_.is_socket_open()) {
  1776. cli_.stop();
  1777. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1778. }
  1779. for (auto &t : threads) {
  1780. t.join();
  1781. }
  1782. }
  1783. TEST_F(ServerTest, GetWithRange1) {
  1784. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1785. ASSERT_TRUE(res);
  1786. EXPECT_EQ(206, res->status);
  1787. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1788. EXPECT_EQ(true, res->has_header("Content-Range"));
  1789. EXPECT_EQ(std::string("def"), res->body);
  1790. }
  1791. TEST_F(ServerTest, GetWithRange2) {
  1792. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1793. ASSERT_TRUE(res);
  1794. EXPECT_EQ(206, res->status);
  1795. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1796. EXPECT_EQ(true, res->has_header("Content-Range"));
  1797. EXPECT_EQ(std::string("bcdefg"), res->body);
  1798. }
  1799. TEST_F(ServerTest, GetWithRange3) {
  1800. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(206, res->status);
  1803. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1804. EXPECT_EQ(true, res->has_header("Content-Range"));
  1805. EXPECT_EQ(std::string("a"), res->body);
  1806. }
  1807. TEST_F(ServerTest, GetWithRange4) {
  1808. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1809. ASSERT_TRUE(res);
  1810. EXPECT_EQ(206, res->status);
  1811. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1812. EXPECT_EQ(true, res->has_header("Content-Range"));
  1813. EXPECT_EQ(std::string("fg"), res->body);
  1814. }
  1815. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  1816. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(416, res->status);
  1819. }
  1820. TEST_F(ServerTest, GetWithRangeMultipart) {
  1821. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(206, res->status);
  1824. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1825. EXPECT_EQ(false, res->has_header("Content-Range"));
  1826. EXPECT_EQ(269, res->body.size());
  1827. }
  1828. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  1829. auto res =
  1830. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  1831. ASSERT_TRUE(res);
  1832. EXPECT_EQ(416, res->status);
  1833. }
  1834. TEST_F(ServerTest, GetStreamedChunked) {
  1835. auto res = cli_.Get("/streamed-chunked");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(200, res->status);
  1838. EXPECT_EQ(std::string("123456789"), res->body);
  1839. }
  1840. TEST_F(ServerTest, GetStreamedChunked2) {
  1841. auto res = cli_.Get("/streamed-chunked2");
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(200, res->status);
  1844. EXPECT_EQ(std::string("123456789"), res->body);
  1845. }
  1846. TEST_F(ServerTest, LargeChunkedPost) {
  1847. Request req;
  1848. req.method = "POST";
  1849. req.path = "/large-chunked";
  1850. std::string host_and_port;
  1851. host_and_port += HOST;
  1852. host_and_port += ":";
  1853. host_and_port += std::to_string(PORT);
  1854. req.headers.emplace("Host", host_and_port.c_str());
  1855. req.headers.emplace("Accept", "*/*");
  1856. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1857. req.headers.emplace("Content-Type", "text/plain");
  1858. req.headers.emplace("Content-Length", "0");
  1859. req.headers.emplace("Transfer-Encoding", "chunked");
  1860. std::string long_string(30 * 1024u, 'a');
  1861. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1862. // Attempt to make a large enough post to exceed OS buffers, to test that
  1863. // the server handles short reads if the full chunk data isn't available.
  1864. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1865. auto res = std::make_shared<Response>();
  1866. auto error = Error::Success;
  1867. auto ret = cli_.send(req, *res, error);
  1868. ASSERT_TRUE(ret);
  1869. EXPECT_EQ(200, res->status);
  1870. }
  1871. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1872. auto res = cli_.Get("/remote_addr");
  1873. ASSERT_TRUE(res);
  1874. EXPECT_EQ(200, res->status);
  1875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1876. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1877. }
  1878. TEST_F(ServerTest, HTTPResponseSplitting) {
  1879. auto res = cli_.Get("/http_response_splitting");
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(200, res->status);
  1882. }
  1883. TEST_F(ServerTest, SlowRequest) {
  1884. request_threads_.push_back(
  1885. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1886. request_threads_.push_back(
  1887. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1888. request_threads_.push_back(
  1889. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1890. }
  1891. TEST_F(ServerTest, SlowPost) {
  1892. char buffer[64 * 1024];
  1893. memset(buffer, 0x42, sizeof(buffer));
  1894. auto res = cli_.Post(
  1895. "/slowpost", 64 * 1024 * 1024,
  1896. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1897. sink.write(buffer, sizeof(buffer));
  1898. return true;
  1899. },
  1900. "text/plain");
  1901. ASSERT_TRUE(res);
  1902. EXPECT_EQ(200, res->status);
  1903. }
  1904. TEST_F(ServerTest, SlowPostFail) {
  1905. char buffer[64 * 1024];
  1906. memset(buffer, 0x42, sizeof(buffer));
  1907. cli_.set_write_timeout(0, 0);
  1908. auto res = cli_.Post(
  1909. "/slowpost", 64 * 1024 * 1024,
  1910. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1911. sink.write(buffer, sizeof(buffer));
  1912. return true;
  1913. },
  1914. "text/plain");
  1915. ASSERT_TRUE(!res);
  1916. EXPECT_EQ(Error::Write, res.error());
  1917. }
  1918. TEST_F(ServerTest, Put) {
  1919. auto res = cli_.Put("/put", "PUT", "text/plain");
  1920. ASSERT_TRUE(res);
  1921. EXPECT_EQ(200, res->status);
  1922. EXPECT_EQ("PUT", res->body);
  1923. }
  1924. TEST_F(ServerTest, PutWithContentProvider) {
  1925. auto res = cli_.Put(
  1926. "/put", 3,
  1927. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1928. EXPECT_TRUE(sink.is_writable());
  1929. sink.os << "PUT";
  1930. return true;
  1931. },
  1932. "text/plain");
  1933. ASSERT_TRUE(res);
  1934. EXPECT_EQ(200, res->status);
  1935. EXPECT_EQ("PUT", res->body);
  1936. }
  1937. TEST_F(ServerTest, PostWithContentProviderAbort) {
  1938. auto res = cli_.Post(
  1939. "/post", 42,
  1940. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1941. return false;
  1942. },
  1943. "text/plain");
  1944. ASSERT_TRUE(!res);
  1945. EXPECT_EQ(Error::Canceled, res.error());
  1946. }
  1947. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  1948. auto res = cli_.Put(
  1949. "/put",
  1950. [](size_t /*offset*/, DataSink &sink) {
  1951. EXPECT_TRUE(sink.is_writable());
  1952. sink.os << "PUT";
  1953. sink.done();
  1954. return true;
  1955. },
  1956. "text/plain");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(200, res->status);
  1959. EXPECT_EQ("PUT", res->body);
  1960. }
  1961. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  1962. auto res = cli_.Post(
  1963. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  1964. "text/plain");
  1965. ASSERT_TRUE(!res);
  1966. EXPECT_EQ(Error::Canceled, res.error());
  1967. }
  1968. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1969. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1970. cli_.set_compress(true);
  1971. auto res = cli_.Put(
  1972. "/put", 3,
  1973. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1974. EXPECT_TRUE(sink.is_writable());
  1975. sink.os << "PUT";
  1976. return true;
  1977. },
  1978. "text/plain");
  1979. ASSERT_TRUE(res);
  1980. EXPECT_EQ(200, res->status);
  1981. EXPECT_EQ("PUT", res->body);
  1982. }
  1983. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  1984. cli_.set_compress(true);
  1985. auto res = cli_.Post(
  1986. "/post", 42,
  1987. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1988. return false;
  1989. },
  1990. "text/plain");
  1991. ASSERT_TRUE(!res);
  1992. EXPECT_EQ(Error::Canceled, res.error());
  1993. }
  1994. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  1995. cli_.set_compress(true);
  1996. auto res = cli_.Put(
  1997. "/put",
  1998. [](size_t /*offset*/, DataSink &sink) {
  1999. EXPECT_TRUE(sink.is_writable());
  2000. sink.os << "PUT";
  2001. sink.done();
  2002. return true;
  2003. },
  2004. "text/plain");
  2005. ASSERT_TRUE(res);
  2006. EXPECT_EQ(200, res->status);
  2007. EXPECT_EQ("PUT", res->body);
  2008. }
  2009. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2010. cli_.set_compress(true);
  2011. auto res = cli_.Post(
  2012. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2013. "text/plain");
  2014. ASSERT_TRUE(!res);
  2015. EXPECT_EQ(Error::Canceled, res.error());
  2016. }
  2017. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2018. cli_.set_compress(true);
  2019. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2020. ASSERT_TRUE(res);
  2021. EXPECT_EQ(200, res->status);
  2022. EXPECT_EQ(LARGE_DATA, res->body);
  2023. }
  2024. TEST_F(ServerTest, PutContentWithDeflate) {
  2025. cli_.set_compress(false);
  2026. Headers headers;
  2027. headers.emplace("Content-Encoding", "deflate");
  2028. // PUT in deflate format:
  2029. auto res = cli_.Put("/put", headers,
  2030. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(200, res->status);
  2033. EXPECT_EQ("PUT", res->body);
  2034. }
  2035. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2036. Headers headers;
  2037. headers.emplace("Accept-Encoding", "gzip, deflate");
  2038. auto res = cli_.Get("/streamed-chunked", headers);
  2039. ASSERT_TRUE(res);
  2040. EXPECT_EQ(200, res->status);
  2041. EXPECT_EQ(std::string("123456789"), res->body);
  2042. }
  2043. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2044. Headers headers;
  2045. headers.emplace("Accept-Encoding", "gzip, deflate");
  2046. auto res = cli_.Get("/streamed-chunked2", headers);
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(200, res->status);
  2049. EXPECT_EQ(std::string("123456789"), res->body);
  2050. }
  2051. TEST(GzipDecompressor, ChunkedDecompression) {
  2052. std::string data;
  2053. for (size_t i = 0; i < 32 * 1024; ++i) {
  2054. data.push_back(static_cast<char>('a' + i % 26));
  2055. }
  2056. std::string compressed_data;
  2057. {
  2058. httplib::detail::gzip_compressor compressor;
  2059. bool result = compressor.compress(
  2060. data.data(), data.size(),
  2061. /*last=*/true, [&](const char *data, size_t size) {
  2062. compressed_data.insert(compressed_data.size(), data, size);
  2063. return true;
  2064. });
  2065. ASSERT_TRUE(result);
  2066. }
  2067. std::string decompressed_data;
  2068. {
  2069. httplib::detail::gzip_decompressor decompressor;
  2070. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2071. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2072. size_t chunk_size = 130;
  2073. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2074. chunk_begin += chunk_size) {
  2075. size_t current_chunk_size =
  2076. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2077. bool result = decompressor.decompress(
  2078. compressed_data.data() + chunk_begin, current_chunk_size,
  2079. [&](const char *data, size_t size) {
  2080. decompressed_data.insert(decompressed_data.size(), data, size);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(result);
  2084. }
  2085. }
  2086. ASSERT_EQ(data, decompressed_data);
  2087. }
  2088. #endif
  2089. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2090. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2091. Headers headers;
  2092. headers.emplace("Accept-Encoding", "br");
  2093. auto res = cli_.Get("/streamed-chunked", headers);
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(200, res->status);
  2096. EXPECT_EQ(std::string("123456789"), res->body);
  2097. }
  2098. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2099. Headers headers;
  2100. headers.emplace("Accept-Encoding", "br");
  2101. auto res = cli_.Get("/streamed-chunked2", headers);
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(200, res->status);
  2104. EXPECT_EQ(std::string("123456789"), res->body);
  2105. }
  2106. #endif
  2107. TEST_F(ServerTest, Patch) {
  2108. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2109. ASSERT_TRUE(res);
  2110. EXPECT_EQ(200, res->status);
  2111. EXPECT_EQ("PATCH", res->body);
  2112. }
  2113. TEST_F(ServerTest, Delete) {
  2114. auto res = cli_.Delete("/delete");
  2115. ASSERT_TRUE(res);
  2116. EXPECT_EQ(200, res->status);
  2117. EXPECT_EQ("DELETE", res->body);
  2118. }
  2119. TEST_F(ServerTest, DeleteContentReceiver) {
  2120. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(200, res->status);
  2123. EXPECT_EQ("content", res->body);
  2124. }
  2125. TEST_F(ServerTest, Options) {
  2126. auto res = cli_.Options("*");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(200, res->status);
  2129. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2130. EXPECT_TRUE(res->body.empty());
  2131. }
  2132. TEST_F(ServerTest, URL) {
  2133. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(200, res->status);
  2136. }
  2137. TEST_F(ServerTest, ArrayParam) {
  2138. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(200, res->status);
  2141. }
  2142. TEST_F(ServerTest, NoMultipleHeaders) {
  2143. Headers headers = {{"Content-Length", "5"}};
  2144. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2145. "text/plain");
  2146. ASSERT_TRUE(res);
  2147. EXPECT_EQ(200, res->status);
  2148. }
  2149. TEST_F(ServerTest, PostContentReceiver) {
  2150. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2151. ASSERT_TRUE(res);
  2152. ASSERT_EQ(200, res->status);
  2153. ASSERT_EQ("content", res->body);
  2154. }
  2155. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2156. MultipartFormDataItems items = {
  2157. {"text1", "text default", "", ""},
  2158. {"text2", "aωb", "", ""},
  2159. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2160. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2161. {"file3", "", "", "application/octet-stream"},
  2162. };
  2163. auto res = cli_.Post("/content_receiver", items);
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(200, res->status);
  2166. }
  2167. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2168. MultipartFormDataItems items = {
  2169. {"text1", "text default", "", ""},
  2170. {"text2", "aωb", "", ""},
  2171. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2172. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2173. {"file3", "", "", "application/octet-stream"},
  2174. };
  2175. auto boundary = std::string("+++++");
  2176. std::string body;
  2177. for (const auto &item : items) {
  2178. body += "--" + boundary + "\r\n";
  2179. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2180. if (!item.filename.empty()) {
  2181. body += "; filename=\"" + item.filename + "\"";
  2182. }
  2183. body += "\r\n";
  2184. if (!item.content_type.empty()) {
  2185. body += "Content-Type: " + item.content_type + "\r\n";
  2186. }
  2187. body += "\r\n";
  2188. body += item.content + "\r\n";
  2189. }
  2190. body += "--" + boundary + "--\r\n";
  2191. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2192. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2193. ASSERT_TRUE(res);
  2194. EXPECT_EQ(200, res->status);
  2195. }
  2196. TEST_F(ServerTest, PostContentReceiverGzip) {
  2197. cli_.set_compress(true);
  2198. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2199. ASSERT_TRUE(res);
  2200. ASSERT_EQ(200, res->status);
  2201. ASSERT_EQ("content", res->body);
  2202. }
  2203. TEST_F(ServerTest, PutContentReceiver) {
  2204. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2205. ASSERT_TRUE(res);
  2206. ASSERT_EQ(200, res->status);
  2207. ASSERT_EQ("content", res->body);
  2208. }
  2209. TEST_F(ServerTest, PatchContentReceiver) {
  2210. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2211. ASSERT_TRUE(res);
  2212. ASSERT_EQ(200, res->status);
  2213. ASSERT_EQ("content", res->body);
  2214. }
  2215. TEST_F(ServerTest, PostQueryStringAndBody) {
  2216. auto res =
  2217. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2218. ASSERT_TRUE(res);
  2219. ASSERT_EQ(200, res->status);
  2220. }
  2221. TEST_F(ServerTest, HTTP2Magic) {
  2222. Request req;
  2223. req.method = "PRI";
  2224. req.path = "*";
  2225. req.body = "SM";
  2226. auto res = std::make_shared<Response>();
  2227. auto error = Error::Success;
  2228. auto ret = cli_.send(req, *res, error);
  2229. ASSERT_TRUE(ret);
  2230. EXPECT_EQ(400, res->status);
  2231. }
  2232. TEST_F(ServerTest, KeepAlive) {
  2233. auto res = cli_.Get("/hi");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(200, res->status);
  2236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2237. EXPECT_EQ("Hello World!", res->body);
  2238. res = cli_.Get("/hi");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(200, res->status);
  2241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2242. EXPECT_EQ("Hello World!", res->body);
  2243. res = cli_.Get("/hi");
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(200, res->status);
  2246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("Hello World!", res->body);
  2248. res = cli_.Get("/not-exist");
  2249. ASSERT_TRUE(res);
  2250. EXPECT_EQ(404, res->status);
  2251. res = cli_.Post("/empty", "", "text/plain");
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ(200, res->status);
  2254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2255. EXPECT_EQ("empty", res->body);
  2256. EXPECT_EQ("close", res->get_header_value("Connection"));
  2257. res = cli_.Post(
  2258. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2259. "text/plain");
  2260. ASSERT_TRUE(res);
  2261. EXPECT_EQ(200, res->status);
  2262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2263. EXPECT_EQ("empty", res->body);
  2264. cli_.set_keep_alive(false);
  2265. res = cli_.Get("/last-request");
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(200, res->status);
  2268. EXPECT_EQ("close", res->get_header_value("Connection"));
  2269. }
  2270. TEST_F(ServerTest, TooManyRedirect) {
  2271. cli_.set_follow_location(true);
  2272. auto res = cli_.Get("/redirect/0");
  2273. ASSERT_TRUE(!res);
  2274. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2275. }
  2276. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2277. TEST_F(ServerTest, Gzip) {
  2278. Headers headers;
  2279. headers.emplace("Accept-Encoding", "gzip, deflate");
  2280. auto res = cli_.Get("/compress", headers);
  2281. ASSERT_TRUE(res);
  2282. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2284. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2285. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2286. "7890123456789012345678901234567890",
  2287. res->body);
  2288. EXPECT_EQ(200, res->status);
  2289. }
  2290. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2291. auto res = cli_.Get("/compress");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2295. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2296. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2297. "7890123456789012345678901234567890",
  2298. res->body);
  2299. EXPECT_EQ(200, res->status);
  2300. }
  2301. TEST_F(ServerTest, GzipWithContentReceiver) {
  2302. Headers headers;
  2303. headers.emplace("Accept-Encoding", "gzip, deflate");
  2304. std::string body;
  2305. auto res = cli_.Get("/compress", headers,
  2306. [&](const char *data, uint64_t data_length) {
  2307. EXPECT_EQ(data_length, 100);
  2308. body.append(data, data_length);
  2309. return true;
  2310. });
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2314. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2316. "7890123456789012345678901234567890",
  2317. body);
  2318. EXPECT_EQ(200, res->status);
  2319. }
  2320. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2321. Headers headers;
  2322. headers.emplace("Accept-Encoding", "gzip, deflate");
  2323. cli_.set_decompress(false);
  2324. auto res = cli_.Get("/compress", headers);
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2328. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2329. EXPECT_EQ(33, res->body.size());
  2330. EXPECT_EQ(200, res->status);
  2331. }
  2332. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2333. std::string body;
  2334. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2335. EXPECT_EQ(data_length, 100);
  2336. body.append(data, data_length);
  2337. return true;
  2338. });
  2339. ASSERT_TRUE(res);
  2340. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2342. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2343. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2344. "7890123456789012345678901234567890",
  2345. body);
  2346. EXPECT_EQ(200, res->status);
  2347. }
  2348. TEST_F(ServerTest, NoGzip) {
  2349. Headers headers;
  2350. headers.emplace("Accept-Encoding", "gzip, deflate");
  2351. auto res = cli_.Get("/nocompress", headers);
  2352. ASSERT_TRUE(res);
  2353. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2354. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2355. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2356. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2357. "7890123456789012345678901234567890",
  2358. res->body);
  2359. EXPECT_EQ(200, res->status);
  2360. }
  2361. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2362. Headers headers;
  2363. headers.emplace("Accept-Encoding", "gzip, deflate");
  2364. std::string body;
  2365. auto res = cli_.Get("/nocompress", headers,
  2366. [&](const char *data, uint64_t data_length) {
  2367. EXPECT_EQ(data_length, 100);
  2368. body.append(data, data_length);
  2369. return true;
  2370. });
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2373. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2374. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2375. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2376. "7890123456789012345678901234567890",
  2377. body);
  2378. EXPECT_EQ(200, res->status);
  2379. }
  2380. TEST_F(ServerTest, MultipartFormDataGzip) {
  2381. MultipartFormDataItems items = {
  2382. {"key1", "test", "", ""},
  2383. {"key2", "--abcdefg123", "", ""},
  2384. };
  2385. cli_.set_compress(true);
  2386. auto res = cli_.Post("/compress-multipart", items);
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(200, res->status);
  2389. }
  2390. #endif
  2391. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2392. TEST_F(ServerTest, Brotli) {
  2393. Headers headers;
  2394. headers.emplace("Accept-Encoding", "br");
  2395. auto res = cli_.Get("/compress", headers);
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2399. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2401. "7890123456789012345678901234567890",
  2402. res->body);
  2403. EXPECT_EQ(200, res->status);
  2404. }
  2405. #endif
  2406. // Sends a raw request to a server listening at HOST:PORT.
  2407. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2408. std::string *resp = nullptr) {
  2409. auto error = Error::Success;
  2410. auto client_sock =
  2411. detail::create_client_socket(HOST, PORT, false, nullptr,
  2412. /*timeout_sec=*/5, 0, std::string(), error);
  2413. if (client_sock == INVALID_SOCKET) { return false; }
  2414. auto ret = detail::process_client_socket(
  2415. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2416. if (req.size() !=
  2417. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2418. return false;
  2419. }
  2420. char buf[512];
  2421. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2422. while (line_reader.getline()) {
  2423. if (resp) { *resp += line_reader.ptr(); }
  2424. }
  2425. return true;
  2426. });
  2427. detail::close_socket(client_sock);
  2428. return ret;
  2429. }
  2430. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2431. Server svr;
  2432. std::string header_value;
  2433. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2434. header_value = req.get_header_value("foo");
  2435. res.set_content("ok", "text/plain");
  2436. });
  2437. thread t = thread([&] { svr.listen(HOST, PORT); });
  2438. while (!svr.is_running()) {
  2439. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2440. }
  2441. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2442. // like characters are not treated the same - use vertical tab and escape.
  2443. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2444. "foo: \t \v bar \e\t \r\n"
  2445. "Connection: close\r\n"
  2446. "\r\n";
  2447. ASSERT_TRUE(send_request(5, req));
  2448. svr.stop();
  2449. t.join();
  2450. EXPECT_EQ(header_value, "\v bar \e");
  2451. }
  2452. // Sends a raw request and verifies that there isn't a crash or exception.
  2453. static void test_raw_request(const std::string &req,
  2454. std::string *out = nullptr) {
  2455. Server svr;
  2456. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2457. res.set_content("ok", "text/plain");
  2458. });
  2459. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2460. res.set_content("ok", "text/plain");
  2461. });
  2462. // Server read timeout must be longer than the client read timeout for the
  2463. // bug to reproduce, probably to force the server to process a request
  2464. // without a trailing blank line.
  2465. const time_t client_read_timeout_sec = 1;
  2466. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  2467. bool listen_thread_ok = false;
  2468. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2469. while (!svr.is_running()) {
  2470. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2471. }
  2472. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2473. svr.stop();
  2474. t.join();
  2475. EXPECT_TRUE(listen_thread_ok);
  2476. }
  2477. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2478. // A certain header line causes an exception if the header property is parsed
  2479. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2480. test_raw_request(
  2481. "GET /hi HTTP/1.1\r\n"
  2482. " : "
  2483. " "
  2484. " ");
  2485. }
  2486. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2487. // A certain header line causes an exception if the header property *name* is
  2488. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2489. // greedy matcher and requires backtracking when there are a lot of ":"
  2490. // characters.
  2491. // This occurs with libc++ but not libstdc++.
  2492. test_raw_request(
  2493. "GET /hi HTTP/1.1\r\n"
  2494. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2495. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2496. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2497. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2498. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2499. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2500. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2501. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2502. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2503. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2504. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2505. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2506. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2507. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2508. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2509. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2510. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2511. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2512. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2513. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2514. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2515. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2516. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2517. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2518. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2519. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2520. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2521. "&&&%%%");
  2522. }
  2523. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2524. // Make sure this doesn't crash the server.
  2525. // In a previous version of the header line regex, the "\r" rendered the line
  2526. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2527. // a new position where the leading white space ended and the field value
  2528. // began.
  2529. // The crash occurs with libc++ but not libstdc++.
  2530. test_raw_request("GET /hi HTTP/1.1\r\n"
  2531. "a:" +
  2532. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2533. "\r\n"
  2534. "\r\n");
  2535. }
  2536. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2537. std::string out;
  2538. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2539. "Content-Type: text/plain\r\n"
  2540. "Transfer-Encoding: chunked\r\n"
  2541. "\r\n"
  2542. "nothex\r\n",
  2543. &out);
  2544. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2545. }
  2546. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2547. std::string out;
  2548. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2549. "Content-Type: text/plain\r\n"
  2550. "Transfer-Encoding: chunked\r\n"
  2551. "\r\n"
  2552. "3\r\n"
  2553. "xyz\r\n"
  2554. "NaN\r\n",
  2555. &out);
  2556. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2557. }
  2558. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2559. std::string out;
  2560. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2561. "Content-Type: text/plain\r\n"
  2562. "Transfer-Encoding: chunked\r\n"
  2563. "\r\n"
  2564. // Length is too large for 64 bits.
  2565. "1ffffffffffffffff\r\n"
  2566. "xyz\r\n",
  2567. &out);
  2568. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2569. }
  2570. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2571. test_raw_request("GET /hi HTTP/1.1\r\n"
  2572. "Content-Type: text/plain\r\n\r");
  2573. }
  2574. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2575. Server svr;
  2576. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2577. res.set_header("Cache-Control", "no-cache");
  2578. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2579. DataSink &sink) {
  2580. char buffer[27];
  2581. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2582. sink.write(buffer, size);
  2583. std::this_thread::sleep_for(std::chrono::seconds(1));
  2584. return true;
  2585. });
  2586. });
  2587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2588. while (!svr.is_running()) {
  2589. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2590. }
  2591. Client client(HOST, PORT);
  2592. const Headers headers = {{"Accept", "text/event-stream"}};
  2593. auto get_thread = std::thread([&client, &headers]() {
  2594. auto res = client.Get(
  2595. "/events", headers,
  2596. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2597. });
  2598. // Give GET time to get a few messages.
  2599. std::this_thread::sleep_for(std::chrono::seconds(2));
  2600. svr.stop();
  2601. listen_thread.join();
  2602. get_thread.join();
  2603. ASSERT_FALSE(svr.is_running());
  2604. }
  2605. TEST(StreamingTest, NoContentLengthStreaming) {
  2606. Server svr;
  2607. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  2608. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  2609. if (offset < 6) {
  2610. sink.os << (offset < 3 ? "a" : "b");
  2611. } else {
  2612. sink.done();
  2613. }
  2614. return true;
  2615. });
  2616. });
  2617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2618. while (!svr.is_running()) {
  2619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2620. }
  2621. Client client(HOST, PORT);
  2622. auto get_thread = std::thread([&client]() {
  2623. auto res = client.Get("/stream", [](const char *data, size_t len) -> bool {
  2624. EXPECT_EQ("aaabbb", std::string(data, len));
  2625. return true;
  2626. });
  2627. });
  2628. // Give GET time to get a few messages.
  2629. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2630. svr.stop();
  2631. listen_thread.join();
  2632. get_thread.join();
  2633. ASSERT_FALSE(svr.is_running());
  2634. }
  2635. TEST(MountTest, Unmount) {
  2636. Server svr;
  2637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2638. while (!svr.is_running()) {
  2639. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2640. }
  2641. // Give GET time to get a few messages.
  2642. std::this_thread::sleep_for(std::chrono::seconds(1));
  2643. Client cli("localhost", PORT);
  2644. svr.set_mount_point("/mount2", "./www2");
  2645. auto res = cli.Get("/");
  2646. ASSERT_TRUE(res);
  2647. EXPECT_EQ(404, res->status);
  2648. res = cli.Get("/mount2/dir/test.html");
  2649. ASSERT_TRUE(res);
  2650. EXPECT_EQ(200, res->status);
  2651. svr.set_mount_point("/", "./www");
  2652. res = cli.Get("/dir/");
  2653. ASSERT_TRUE(res);
  2654. EXPECT_EQ(200, res->status);
  2655. svr.remove_mount_point("/");
  2656. res = cli.Get("/dir/");
  2657. ASSERT_TRUE(res);
  2658. EXPECT_EQ(404, res->status);
  2659. svr.remove_mount_point("/mount2");
  2660. res = cli.Get("/mount2/dir/test.html");
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(404, res->status);
  2663. svr.stop();
  2664. listen_thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. }
  2667. TEST(ExceptionTest, ThrowExceptionInHandler) {
  2668. Server svr;
  2669. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2670. throw std::runtime_error("exception...");
  2671. res.set_content("Hello World!", "text/plain");
  2672. });
  2673. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2674. while (!svr.is_running()) {
  2675. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2676. }
  2677. // Give GET time to get a few messages.
  2678. std::this_thread::sleep_for(std::chrono::seconds(1));
  2679. Client cli("localhost", PORT);
  2680. auto res = cli.Get("/hi");
  2681. ASSERT_TRUE(res);
  2682. EXPECT_EQ(500, res->status);
  2683. ASSERT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2684. svr.stop();
  2685. listen_thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. }
  2688. TEST(KeepAliveTest, ReadTimeout) {
  2689. Server svr;
  2690. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2691. std::this_thread::sleep_for(std::chrono::seconds(2));
  2692. res.set_content("a", "text/plain");
  2693. });
  2694. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content("b", "text/plain");
  2696. });
  2697. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2698. while (!svr.is_running()) {
  2699. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2700. }
  2701. // Give GET time to get a few messages.
  2702. std::this_thread::sleep_for(std::chrono::seconds(1));
  2703. Client cli("localhost", PORT);
  2704. cli.set_keep_alive(true);
  2705. cli.set_read_timeout(1);
  2706. auto resa = cli.Get("/a");
  2707. ASSERT_TRUE(!resa);
  2708. EXPECT_EQ(Error::Read, resa.error());
  2709. auto resb = cli.Get("/b");
  2710. ASSERT_TRUE(resb);
  2711. EXPECT_EQ(200, resb->status);
  2712. EXPECT_EQ("b", resb->body);
  2713. svr.stop();
  2714. listen_thread.join();
  2715. ASSERT_FALSE(svr.is_running());
  2716. }
  2717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2718. TEST(KeepAliveTest, ReadTimeoutSSL) {
  2719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2720. ASSERT_TRUE(svr.is_valid());
  2721. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2722. std::this_thread::sleep_for(std::chrono::seconds(2));
  2723. res.set_content("a", "text/plain");
  2724. });
  2725. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("b", "text/plain");
  2727. });
  2728. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2729. while (!svr.is_running()) {
  2730. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2731. }
  2732. // Give GET time to get a few messages.
  2733. std::this_thread::sleep_for(std::chrono::seconds(1));
  2734. SSLClient cli("localhost", PORT);
  2735. cli.enable_server_certificate_verification(false);
  2736. cli.set_keep_alive(true);
  2737. cli.set_read_timeout(1);
  2738. auto resa = cli.Get("/a");
  2739. ASSERT_TRUE(!resa);
  2740. EXPECT_EQ(Error::Read, resa.error());
  2741. auto resb = cli.Get("/b");
  2742. ASSERT_TRUE(resb);
  2743. EXPECT_EQ(200, resb->status);
  2744. EXPECT_EQ("b", resb->body);
  2745. svr.stop();
  2746. listen_thread.join();
  2747. ASSERT_FALSE(svr.is_running());
  2748. }
  2749. #endif
  2750. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  2751. protected:
  2752. ServerTestWithAI_PASSIVE()
  2753. : cli_(HOST, PORT)
  2754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2755. ,
  2756. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2757. #endif
  2758. {
  2759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2760. cli_.enable_server_certificate_verification(false);
  2761. #endif
  2762. }
  2763. virtual void SetUp() {
  2764. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2765. res.set_content("Hello World!", "text/plain");
  2766. });
  2767. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  2768. while (!svr_.is_running()) {
  2769. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2770. }
  2771. }
  2772. virtual void TearDown() {
  2773. svr_.stop();
  2774. t_.join();
  2775. }
  2776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2777. SSLClient cli_;
  2778. SSLServer svr_;
  2779. #else
  2780. Client cli_;
  2781. Server svr_;
  2782. #endif
  2783. thread t_;
  2784. };
  2785. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  2786. auto res = cli_.Get("/hi");
  2787. ASSERT_TRUE(res);
  2788. EXPECT_EQ(200, res->status);
  2789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2790. EXPECT_EQ("Hello World!", res->body);
  2791. }
  2792. class ServerUpDownTest : public ::testing::Test {
  2793. protected:
  2794. ServerUpDownTest() : cli_(HOST, PORT) {}
  2795. virtual void SetUp() {
  2796. t_ = thread([&]() {
  2797. svr_.bind_to_any_port(HOST);
  2798. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2799. ASSERT_TRUE(svr_.listen_after_bind());
  2800. });
  2801. while (!svr_.is_running()) {
  2802. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2803. }
  2804. }
  2805. virtual void TearDown() {
  2806. svr_.stop();
  2807. t_.join();
  2808. }
  2809. Client cli_;
  2810. Server svr_;
  2811. thread t_;
  2812. };
  2813. TEST_F(ServerUpDownTest, QuickStartStop) {
  2814. // Should not crash, especially when run with
  2815. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  2816. }
  2817. class PayloadMaxLengthTest : public ::testing::Test {
  2818. protected:
  2819. PayloadMaxLengthTest()
  2820. : cli_(HOST, PORT)
  2821. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2822. ,
  2823. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2824. #endif
  2825. {
  2826. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2827. cli_.enable_server_certificate_verification(false);
  2828. #endif
  2829. }
  2830. virtual void SetUp() {
  2831. svr_.set_payload_max_length(8);
  2832. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  2833. res.set_content("test", "text/plain");
  2834. });
  2835. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2836. while (!svr_.is_running()) {
  2837. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2838. }
  2839. }
  2840. virtual void TearDown() {
  2841. svr_.stop();
  2842. t_.join();
  2843. }
  2844. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2845. SSLClient cli_;
  2846. SSLServer svr_;
  2847. #else
  2848. Client cli_;
  2849. Server svr_;
  2850. #endif
  2851. thread t_;
  2852. };
  2853. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  2854. auto res = cli_.Post("/test", "123456789", "text/plain");
  2855. ASSERT_TRUE(res);
  2856. EXPECT_EQ(413, res->status);
  2857. res = cli_.Post("/test", "12345678", "text/plain");
  2858. ASSERT_TRUE(res);
  2859. EXPECT_EQ(200, res->status);
  2860. }
  2861. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2862. TEST(SSLClientTest, UpdateCAStore) {
  2863. httplib::SSLClient httplib_client("www.google.com");
  2864. auto ca_store_1 = X509_STORE_new();
  2865. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  2866. nullptr);
  2867. httplib_client.set_ca_cert_store(ca_store_1);
  2868. auto ca_store_2 = X509_STORE_new();
  2869. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  2870. nullptr);
  2871. httplib_client.set_ca_cert_store(ca_store_2);
  2872. }
  2873. TEST(SSLClientTest, ServerNameIndication) {
  2874. SSLClient cli("httpbin.org", 443);
  2875. auto res = cli.Get("/get");
  2876. ASSERT_TRUE(res);
  2877. ASSERT_EQ(200, res->status);
  2878. }
  2879. TEST(SSLClientTest, ServerCertificateVerification1) {
  2880. SSLClient cli("google.com");
  2881. auto res = cli.Get("/");
  2882. ASSERT_TRUE(res);
  2883. ASSERT_EQ(301, res->status);
  2884. }
  2885. TEST(SSLClientTest, ServerCertificateVerification2) {
  2886. SSLClient cli("google.com");
  2887. cli.enable_server_certificate_verification(true);
  2888. cli.set_ca_cert_path("hello");
  2889. auto res = cli.Get("/");
  2890. ASSERT_TRUE(!res);
  2891. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  2892. }
  2893. TEST(SSLClientTest, ServerCertificateVerification3) {
  2894. SSLClient cli("google.com");
  2895. cli.set_ca_cert_path(CA_CERT_FILE);
  2896. auto res = cli.Get("/");
  2897. ASSERT_TRUE(res);
  2898. ASSERT_EQ(301, res->status);
  2899. }
  2900. TEST(SSLClientTest, ServerCertificateVerification4) {
  2901. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  2902. ASSERT_TRUE(svr.is_valid());
  2903. svr.Get("/test", [&](const Request &, Response &res) {
  2904. res.set_content("test", "text/plain");
  2905. svr.stop();
  2906. ASSERT_TRUE(true);
  2907. });
  2908. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  2909. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2910. SSLClient cli("127.0.0.1", PORT);
  2911. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  2912. cli.enable_server_certificate_verification(true);
  2913. cli.set_connection_timeout(30);
  2914. auto res = cli.Get("/test");
  2915. ASSERT_TRUE(res);
  2916. ASSERT_EQ(200, res->status);
  2917. t.join();
  2918. }
  2919. TEST(SSLClientTest, WildcardHostNameMatch) {
  2920. SSLClient cli("www.youtube.com");
  2921. cli.set_ca_cert_path(CA_CERT_FILE);
  2922. cli.enable_server_certificate_verification(true);
  2923. auto res = cli.Get("/");
  2924. ASSERT_TRUE(res);
  2925. ASSERT_EQ(200, res->status);
  2926. }
  2927. TEST(SSLClientServerTest, ClientCertPresent) {
  2928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2929. CLIENT_CA_CERT_DIR);
  2930. ASSERT_TRUE(svr.is_valid());
  2931. svr.Get("/test", [&](const Request &req, Response &res) {
  2932. res.set_content("test", "text/plain");
  2933. svr.stop();
  2934. ASSERT_TRUE(true);
  2935. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2936. ASSERT_TRUE(peer_cert != nullptr);
  2937. auto subject_name = X509_get_subject_name(peer_cert);
  2938. ASSERT_TRUE(subject_name != nullptr);
  2939. std::string common_name;
  2940. {
  2941. char name[BUFSIZ];
  2942. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2943. name, sizeof(name));
  2944. common_name.assign(name, static_cast<size_t>(name_len));
  2945. }
  2946. EXPECT_EQ("Common Name", common_name);
  2947. X509_free(peer_cert);
  2948. });
  2949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2950. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2951. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2952. cli.enable_server_certificate_verification(false);
  2953. cli.set_connection_timeout(30);
  2954. auto res = cli.Get("/test");
  2955. ASSERT_TRUE(res);
  2956. ASSERT_EQ(200, res->status);
  2957. t.join();
  2958. }
  2959. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  2960. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  2961. X509 *server_cert;
  2962. EVP_PKEY *server_private_key;
  2963. X509_STORE *client_ca_cert_store;
  2964. X509 *client_cert;
  2965. EVP_PKEY *client_private_key;
  2966. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  2967. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2968. fclose(f);
  2969. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  2970. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2971. fclose(f);
  2972. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  2973. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2974. client_ca_cert_store = X509_STORE_new();
  2975. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  2976. X509_free(client_cert);
  2977. fclose(f);
  2978. f = fopen(CLIENT_CERT_FILE, "r+");
  2979. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2980. fclose(f);
  2981. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  2982. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2983. fclose(f);
  2984. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  2985. ASSERT_TRUE(svr.is_valid());
  2986. svr.Get("/test", [&](const Request &req, Response &res) {
  2987. res.set_content("test", "text/plain");
  2988. svr.stop();
  2989. ASSERT_TRUE(true);
  2990. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2991. ASSERT_TRUE(peer_cert != nullptr);
  2992. auto subject_name = X509_get_subject_name(peer_cert);
  2993. ASSERT_TRUE(subject_name != nullptr);
  2994. std::string common_name;
  2995. {
  2996. char name[BUFSIZ];
  2997. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2998. name, sizeof(name));
  2999. common_name.assign(name, static_cast<size_t>(name_len));
  3000. }
  3001. EXPECT_EQ("Common Name", common_name);
  3002. X509_free(peer_cert);
  3003. });
  3004. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3005. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3006. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3007. cli.enable_server_certificate_verification(false);
  3008. cli.set_connection_timeout(30);
  3009. auto res = cli.Get("/test");
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(200, res->status);
  3012. X509_free(server_cert);
  3013. EVP_PKEY_free(server_private_key);
  3014. X509_free(client_cert);
  3015. EVP_PKEY_free(client_private_key);
  3016. t.join();
  3017. }
  3018. #endif
  3019. TEST(SSLClientServerTest, ClientCertMissing) {
  3020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3021. CLIENT_CA_CERT_DIR);
  3022. ASSERT_TRUE(svr.is_valid());
  3023. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3024. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3025. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3026. SSLClient cli(HOST, PORT);
  3027. auto res = cli.Get("/test");
  3028. cli.set_connection_timeout(30);
  3029. ASSERT_TRUE(!res);
  3030. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3031. svr.stop();
  3032. t.join();
  3033. }
  3034. TEST(SSLClientServerTest, TrustDirOptional) {
  3035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3036. ASSERT_TRUE(svr.is_valid());
  3037. svr.Get("/test", [&](const Request &, Response &res) {
  3038. res.set_content("test", "text/plain");
  3039. svr.stop();
  3040. });
  3041. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3042. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3043. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3044. cli.enable_server_certificate_verification(false);
  3045. cli.set_connection_timeout(30);
  3046. auto res = cli.Get("/test");
  3047. ASSERT_TRUE(res);
  3048. ASSERT_EQ(200, res->status);
  3049. t.join();
  3050. }
  3051. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3052. class NoListenSSLServer : public SSLServer {
  3053. public:
  3054. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3055. const char *client_ca_cert_file_path,
  3056. const char *client_ca_cert_dir_path = nullptr)
  3057. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3058. client_ca_cert_dir_path),
  3059. stop_(false) {}
  3060. bool stop_;
  3061. private:
  3062. bool process_and_close_socket(socket_t /*sock*/) override {
  3063. // Don't create SSL context
  3064. while (!stop_) {
  3065. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3066. }
  3067. return true;
  3068. }
  3069. };
  3070. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3071. CLIENT_CA_CERT_FILE);
  3072. ASSERT_TRUE(svr.is_valid());
  3073. svr.Get("/test", [&](const Request &, Response &res) {
  3074. res.set_content("test", "text/plain");
  3075. });
  3076. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3077. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3078. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3079. cli.enable_server_certificate_verification(false);
  3080. cli.set_connection_timeout(1);
  3081. auto res = cli.Get("/test");
  3082. ASSERT_TRUE(!res);
  3083. EXPECT_EQ(Error::SSLConnection, res.error());
  3084. svr.stop_ = true;
  3085. svr.stop();
  3086. t.join();
  3087. }
  3088. #endif
  3089. #ifdef _WIN32
  3090. TEST(CleanupTest, WSACleanup) {
  3091. int ret = WSACleanup();
  3092. ASSERT_EQ(0, ret);
  3093. }
  3094. #endif
  3095. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3096. TEST(NoSSLSupport, SimpleInterface) {
  3097. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3098. }
  3099. #endif
  3100. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3101. TEST(InvalidScheme, SimpleInterface) {
  3102. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3103. }
  3104. TEST(NoScheme, SimpleInterface) {
  3105. Client cli("yahoo.com:80");
  3106. ASSERT_TRUE(cli.is_valid());
  3107. }
  3108. TEST(YahooRedirectTest2, SimpleInterface) {
  3109. Client cli("http://yahoo.com");
  3110. auto res = cli.Get("/");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(301, res->status);
  3113. cli.set_follow_location(true);
  3114. res = cli.Get("/");
  3115. ASSERT_TRUE(res);
  3116. EXPECT_EQ(200, res->status);
  3117. EXPECT_EQ("https://yahoo.com/", res->location);
  3118. }
  3119. TEST(YahooRedirectTest3, SimpleInterface) {
  3120. Client cli("https://yahoo.com");
  3121. auto res = cli.Get("/");
  3122. ASSERT_TRUE(res);
  3123. EXPECT_EQ(301, res->status);
  3124. cli.set_follow_location(true);
  3125. res = cli.Get("/");
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(200, res->status);
  3128. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3129. }
  3130. TEST(YahooRedirectTest3, NewResultInterface) {
  3131. Client cli("https://yahoo.com");
  3132. auto res = cli.Get("/");
  3133. ASSERT_TRUE(res);
  3134. ASSERT_FALSE(!res);
  3135. ASSERT_TRUE(res);
  3136. ASSERT_FALSE(res == nullptr);
  3137. ASSERT_TRUE(res != nullptr);
  3138. EXPECT_EQ(Error::Success, res.error());
  3139. EXPECT_EQ(301, res.value().status);
  3140. EXPECT_EQ(301, (*res).status);
  3141. EXPECT_EQ(301, res->status);
  3142. cli.set_follow_location(true);
  3143. res = cli.Get("/");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(Error::Success, res.error());
  3146. EXPECT_EQ(200, res.value().status);
  3147. EXPECT_EQ(200, (*res).status);
  3148. EXPECT_EQ(200, res->status);
  3149. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3150. }
  3151. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3152. TEST(DecodeWithChunkedEncoding, BrotliEncoding) {
  3153. Client cli("https://cdnjs.cloudflare.com");
  3154. auto res =
  3155. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(200, res->status);
  3158. EXPECT_EQ(287630, res->body.size());
  3159. EXPECT_EQ("application/javascript; charset=utf-8",
  3160. res->get_header_value("Content-Type"));
  3161. }
  3162. #endif
  3163. #if 0
  3164. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  3165. auto res =
  3166. Client("https://httpbin.org")
  3167. .set_follow_location(true)
  3168. .Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3169. ASSERT_TRUE(res);
  3170. EXPECT_EQ(200, res->status);
  3171. }
  3172. #endif
  3173. #endif