test.cc 121 KB

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