test.cc 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222
  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 =
  337. cli.Get("/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(std::chrono::seconds(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(std::chrono::seconds(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(std::chrono::seconds(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(std::chrono::seconds(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(std::chrono::seconds(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(std::chrono::seconds(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(std::chrono::seconds(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. TEST(RedirectFromPageWithContent, Redirect) {
  728. Server svr;
  729. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  730. res.set_content("___", "text/plain");
  731. res.set_redirect("/2");
  732. });
  733. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  734. res.set_content("Hello World!", "text/plain");
  735. });
  736. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  737. while (!svr.is_running()) {
  738. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  739. }
  740. // Give GET time to get a few messages.
  741. std::this_thread::sleep_for(std::chrono::seconds(1));
  742. {
  743. Client cli("localhost", PORT);
  744. cli.set_follow_location(true);
  745. std::string body;
  746. auto res = cli.Get("/1",
  747. [&](const char *data, size_t data_length) {
  748. body.append(data, data_length);
  749. return true;
  750. });
  751. ASSERT_TRUE(res);
  752. EXPECT_EQ(200, res->status);
  753. EXPECT_EQ("Hello World!", body);
  754. }
  755. {
  756. Client cli("localhost", PORT);
  757. std::string body;
  758. auto res = cli.Get("/1",
  759. [&](const char *data, size_t data_length) {
  760. body.append(data, data_length);
  761. return true;
  762. });
  763. ASSERT_TRUE(res);
  764. EXPECT_EQ(302, res->status);
  765. EXPECT_EQ("___", body);
  766. }
  767. svr.stop();
  768. th.join();
  769. ASSERT_FALSE(svr.is_running());
  770. }
  771. #endif
  772. TEST(BindServerTest, BindDualStack) {
  773. Server svr;
  774. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  775. res.set_content("Hello World!", "text/plain");
  776. });
  777. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  778. // Give GET time to get a few messages.
  779. std::this_thread::sleep_for(std::chrono::seconds(1));
  780. {
  781. Client cli("127.0.0.1", PORT);
  782. auto res = cli.Get("/1");
  783. ASSERT_TRUE(res);
  784. EXPECT_EQ(200, res->status);
  785. EXPECT_EQ("Hello World!", res->body);
  786. }
  787. {
  788. Client cli("::1", PORT);
  789. auto res = cli.Get("/1");
  790. ASSERT_TRUE(res);
  791. EXPECT_EQ(200, res->status);
  792. EXPECT_EQ("Hello World!", res->body);
  793. }
  794. svr.stop();
  795. thread.join();
  796. ASSERT_FALSE(svr.is_running());
  797. }
  798. TEST(BindServerTest, BindAndListenSeparately) {
  799. Server svr;
  800. int port = svr.bind_to_any_port("0.0.0.0");
  801. ASSERT_TRUE(svr.is_valid());
  802. ASSERT_TRUE(port > 0);
  803. svr.stop();
  804. }
  805. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  806. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  808. CLIENT_CA_CERT_DIR);
  809. int port = svr.bind_to_any_port("0.0.0.0");
  810. ASSERT_TRUE(svr.is_valid());
  811. ASSERT_TRUE(port > 0);
  812. svr.stop();
  813. }
  814. #endif
  815. TEST(ErrorHandlerTest, ContentLength) {
  816. Server svr;
  817. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  818. res.status = 200;
  819. res.set_content("abcdefghijklmnopqrstuvwxyz",
  820. "text/html"); // <= Content-Length still 13
  821. });
  822. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  823. res.set_content("Hello World!\n", "text/plain");
  824. res.status = 524;
  825. });
  826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  827. // Give GET time to get a few messages.
  828. std::this_thread::sleep_for(std::chrono::seconds(1));
  829. {
  830. Client cli(HOST, PORT);
  831. auto res = cli.Get("/hi");
  832. ASSERT_TRUE(res);
  833. EXPECT_EQ(200, res->status);
  834. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  835. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  836. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  837. }
  838. svr.stop();
  839. thread.join();
  840. ASSERT_FALSE(svr.is_running());
  841. }
  842. TEST(ExceptionHandlerTest, ContentLength) {
  843. Server svr;
  844. svr.set_exception_handler(
  845. [](const Request & /*req*/, Response &res, std::exception & /*e*/) {
  846. res.status = 500;
  847. res.set_content("abcdefghijklmnopqrstuvwxyz",
  848. "text/html"); // <= Content-Length still 13
  849. });
  850. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  851. res.set_content("Hello World!\n", "text/plain");
  852. throw std::runtime_error("abc");
  853. });
  854. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  855. // Give GET time to get a few messages.
  856. std::this_thread::sleep_for(std::chrono::seconds(1));
  857. {
  858. Client cli(HOST, PORT);
  859. auto res = cli.Get("/hi");
  860. ASSERT_TRUE(res);
  861. EXPECT_EQ(500, res->status);
  862. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  863. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  864. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  865. }
  866. svr.stop();
  867. thread.join();
  868. ASSERT_FALSE(svr.is_running());
  869. }
  870. TEST(NoContentTest, ContentLength) {
  871. Server svr;
  872. svr.Get("/hi",
  873. [](const Request & /*req*/, Response &res) { res.status = 204; });
  874. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  875. // Give GET time to get a few messages.
  876. std::this_thread::sleep_for(std::chrono::seconds(1));
  877. {
  878. Client cli(HOST, PORT);
  879. auto res = cli.Get("/hi");
  880. ASSERT_TRUE(res);
  881. EXPECT_EQ(204, res->status);
  882. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  883. }
  884. svr.stop();
  885. thread.join();
  886. ASSERT_FALSE(svr.is_running());
  887. }
  888. TEST(RoutingHandlerTest, PreRoutingHandler) {
  889. Server svr;
  890. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  891. if (req.path == "/routing_handler") {
  892. res.set_header("PRE_ROUTING", "on");
  893. res.set_content("Routing Handler", "text/plain");
  894. return httplib::Server::HandlerResponse::Handled;
  895. }
  896. return httplib::Server::HandlerResponse::Unhandled;
  897. });
  898. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  899. res.set_content("Error", "text/html");
  900. });
  901. svr.set_post_routing_handler([](const Request &req, Response &res) {
  902. if (req.path == "/routing_handler") {
  903. res.set_header("POST_ROUTING", "on");
  904. }
  905. });
  906. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  907. res.set_content("Hello World!\n", "text/plain");
  908. });
  909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  910. // Give GET time to get a few messages.
  911. std::this_thread::sleep_for(std::chrono::seconds(1));
  912. {
  913. Client cli(HOST, PORT);
  914. auto res = cli.Get("/routing_handler");
  915. ASSERT_TRUE(res);
  916. EXPECT_EQ(200, res->status);
  917. EXPECT_EQ("Routing Handler", res->body);
  918. EXPECT_EQ(1, res->get_header_value_count("PRE_ROUTING"));
  919. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  920. EXPECT_EQ(1, res->get_header_value_count("POST_ROUTING"));
  921. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  922. }
  923. {
  924. Client cli(HOST, PORT);
  925. auto res = cli.Get("/hi");
  926. ASSERT_TRUE(res);
  927. EXPECT_EQ(200, res->status);
  928. EXPECT_EQ("Hello World!\n", res->body);
  929. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  930. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  931. }
  932. {
  933. Client cli(HOST, PORT);
  934. auto res = cli.Get("/aaa");
  935. ASSERT_TRUE(res);
  936. EXPECT_EQ(404, res->status);
  937. EXPECT_EQ("Error", res->body);
  938. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  939. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  940. }
  941. svr.stop();
  942. thread.join();
  943. ASSERT_FALSE(svr.is_running());
  944. }
  945. TEST(InvalidFormatTest, StatusCode) {
  946. Server svr;
  947. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  948. res.set_content("Hello World!\n", "text/plain");
  949. res.status = 9999; // Status should be a three-digit code...
  950. });
  951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  952. // Give GET time to get a few messages.
  953. std::this_thread::sleep_for(std::chrono::seconds(1));
  954. {
  955. Client cli(HOST, PORT);
  956. auto res = cli.Get("/hi");
  957. ASSERT_FALSE(res);
  958. }
  959. svr.stop();
  960. thread.join();
  961. ASSERT_FALSE(svr.is_running());
  962. }
  963. class ServerTest : public ::testing::Test {
  964. protected:
  965. ServerTest()
  966. : cli_(HOST, PORT)
  967. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  968. ,
  969. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  970. #endif
  971. {
  972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  973. cli_.enable_server_certificate_verification(false);
  974. #endif
  975. }
  976. virtual void SetUp() {
  977. svr_.set_mount_point("/", "./www");
  978. svr_.set_mount_point("/mount", "./www2");
  979. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  980. svr_.Get("/hi",
  981. [&](const Request & /*req*/, Response &res) {
  982. res.set_content("Hello World!", "text/plain");
  983. })
  984. .Get("/http_response_splitting",
  985. [&](const Request & /*req*/, Response &res) {
  986. res.set_header("a", "1\r\nSet-Cookie: a=1");
  987. EXPECT_EQ(0, res.headers.size());
  988. EXPECT_FALSE(res.has_header("a"));
  989. res.set_header("a", "1\nSet-Cookie: a=1");
  990. EXPECT_EQ(0, res.headers.size());
  991. EXPECT_FALSE(res.has_header("a"));
  992. res.set_header("a", "1\rSet-Cookie: a=1");
  993. EXPECT_EQ(0, res.headers.size());
  994. EXPECT_FALSE(res.has_header("a"));
  995. res.set_header("a\r\nb", "0");
  996. EXPECT_EQ(0, res.headers.size());
  997. EXPECT_FALSE(res.has_header("a"));
  998. res.set_header("a\rb", "0");
  999. EXPECT_EQ(0, res.headers.size());
  1000. EXPECT_FALSE(res.has_header("a"));
  1001. res.set_header("a\nb", "0");
  1002. EXPECT_EQ(0, res.headers.size());
  1003. EXPECT_FALSE(res.has_header("a"));
  1004. res.set_redirect("1\r\nSet-Cookie: a=1");
  1005. EXPECT_EQ(0, res.headers.size());
  1006. EXPECT_FALSE(res.has_header("Location"));
  1007. })
  1008. .Get("/slow",
  1009. [&](const Request & /*req*/, Response &res) {
  1010. std::this_thread::sleep_for(std::chrono::seconds(2));
  1011. res.set_content("slow", "text/plain");
  1012. })
  1013. .Post("/slowpost",
  1014. [&](const Request & /*req*/, Response &res) {
  1015. std::this_thread::sleep_for(std::chrono::seconds(2));
  1016. res.set_content("slow", "text/plain");
  1017. })
  1018. .Get("/remote_addr",
  1019. [&](const Request &req, Response &res) {
  1020. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1021. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1022. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1023. EXPECT_EQ(req.remote_port,
  1024. std::stoi(req.get_header_value("REMOTE_PORT")));
  1025. res.set_content(remote_addr.c_str(), "text/plain");
  1026. })
  1027. .Get("/endwith%",
  1028. [&](const Request & /*req*/, Response &res) {
  1029. res.set_content("Hello World!", "text/plain");
  1030. })
  1031. .Get("/a\\+\\+b",
  1032. [&](const Request &req, Response &res) {
  1033. ASSERT_TRUE(req.has_param("a +b"));
  1034. auto val = req.get_param_value("a +b");
  1035. res.set_content(val, "text/plain");
  1036. })
  1037. .Get("/", [&](const Request & /*req*/,
  1038. Response &res) { res.set_redirect("/hi"); })
  1039. .Post("/1", [](const Request & /*req*/,
  1040. Response &res) { res.set_redirect("/2", 303); })
  1041. .Get("/2",
  1042. [](const Request & /*req*/, Response &res) {
  1043. res.set_content("redirected.", "text/plain");
  1044. res.status = 200;
  1045. })
  1046. .Post("/person",
  1047. [&](const Request &req, Response &res) {
  1048. if (req.has_param("name") && req.has_param("note")) {
  1049. persons_[req.get_param_value("name")] =
  1050. req.get_param_value("note");
  1051. } else {
  1052. res.status = 400;
  1053. }
  1054. })
  1055. .Put("/person",
  1056. [&](const Request &req, Response &res) {
  1057. if (req.has_param("name") && req.has_param("note")) {
  1058. persons_[req.get_param_value("name")] =
  1059. req.get_param_value("note");
  1060. } else {
  1061. res.status = 400;
  1062. }
  1063. })
  1064. .Get("/person/(.*)",
  1065. [&](const Request &req, Response &res) {
  1066. string name = req.matches[1];
  1067. if (persons_.find(name) != persons_.end()) {
  1068. auto note = persons_[name];
  1069. res.set_content(note, "text/plain");
  1070. } else {
  1071. res.status = 404;
  1072. }
  1073. })
  1074. .Post("/x-www-form-urlencoded-json",
  1075. [&](const Request &req, Response &res) {
  1076. auto json = req.get_param_value("json");
  1077. ASSERT_EQ(JSON_DATA, json);
  1078. res.set_content(json, "appliation/json");
  1079. res.status = 200;
  1080. })
  1081. .Get("/streamed-chunked",
  1082. [&](const Request & /*req*/, Response &res) {
  1083. res.set_chunked_content_provider(
  1084. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1085. EXPECT_TRUE(sink.is_writable());
  1086. sink.os << "123";
  1087. sink.os << "456";
  1088. sink.os << "789";
  1089. sink.done();
  1090. return true;
  1091. });
  1092. })
  1093. .Get("/streamed-chunked2",
  1094. [&](const Request & /*req*/, Response &res) {
  1095. auto i = new int(0);
  1096. res.set_chunked_content_provider(
  1097. "text/plain",
  1098. [i](size_t /*offset*/, DataSink &sink) {
  1099. EXPECT_TRUE(sink.is_writable());
  1100. switch (*i) {
  1101. case 0: sink.os << "123"; break;
  1102. case 1: sink.os << "456"; break;
  1103. case 2: sink.os << "789"; break;
  1104. case 3: sink.done(); break;
  1105. }
  1106. (*i)++;
  1107. return true;
  1108. },
  1109. [i] { delete i; });
  1110. })
  1111. .Get("/streamed",
  1112. [&](const Request & /*req*/, Response &res) {
  1113. res.set_content_provider(
  1114. 6, "text/plain",
  1115. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1116. sink.os << (offset < 3 ? "a" : "b");
  1117. return true;
  1118. });
  1119. })
  1120. .Get("/streamed-with-range",
  1121. [&](const Request & /*req*/, Response &res) {
  1122. auto data = new std::string("abcdefg");
  1123. res.set_content_provider(
  1124. data->size(), "text/plain",
  1125. [data](size_t offset, size_t length, DataSink &sink) {
  1126. EXPECT_TRUE(sink.is_writable());
  1127. size_t DATA_CHUNK_SIZE = 4;
  1128. const auto &d = *data;
  1129. auto out_len =
  1130. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1131. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1132. return true;
  1133. },
  1134. [data] { delete data; });
  1135. })
  1136. .Get("/streamed-cancel",
  1137. [&](const Request & /*req*/, Response &res) {
  1138. res.set_content_provider(
  1139. size_t(-1), "text/plain",
  1140. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1141. EXPECT_TRUE(sink.is_writable());
  1142. sink.os << "data_chunk";
  1143. return true;
  1144. });
  1145. })
  1146. .Get("/with-range",
  1147. [&](const Request & /*req*/, Response &res) {
  1148. res.set_content("abcdefg", "text/plain");
  1149. })
  1150. .Post("/chunked",
  1151. [&](const Request &req, Response & /*res*/) {
  1152. EXPECT_EQ(req.body, "dechunked post body");
  1153. })
  1154. .Post("/large-chunked",
  1155. [&](const Request &req, Response & /*res*/) {
  1156. std::string expected(6 * 30 * 1024u, 'a');
  1157. EXPECT_EQ(req.body, expected);
  1158. })
  1159. .Post("/multipart",
  1160. [&](const Request &req, Response & /*res*/) {
  1161. EXPECT_EQ(6u, req.files.size());
  1162. ASSERT_TRUE(!req.has_file("???"));
  1163. ASSERT_TRUE(req.body.empty());
  1164. {
  1165. const auto &file = req.get_file_value("text1");
  1166. EXPECT_TRUE(file.filename.empty());
  1167. EXPECT_EQ("text default", file.content);
  1168. }
  1169. {
  1170. const auto &file = req.get_file_value("text2");
  1171. EXPECT_TRUE(file.filename.empty());
  1172. EXPECT_EQ("aωb", file.content);
  1173. }
  1174. {
  1175. const auto &file = req.get_file_value("file1");
  1176. EXPECT_EQ("hello.txt", file.filename);
  1177. EXPECT_EQ("text/plain", file.content_type);
  1178. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1179. }
  1180. {
  1181. const auto &file = req.get_file_value("file3");
  1182. EXPECT_TRUE(file.filename.empty());
  1183. EXPECT_EQ("application/octet-stream", file.content_type);
  1184. EXPECT_EQ(0u, file.content.size());
  1185. }
  1186. {
  1187. const auto &file = req.get_file_value("file4");
  1188. EXPECT_TRUE(file.filename.empty());
  1189. EXPECT_EQ(0u, file.content.size());
  1190. EXPECT_EQ("application/json tmp-string", file.content_type);
  1191. }
  1192. })
  1193. .Post("/empty",
  1194. [&](const Request &req, Response &res) {
  1195. EXPECT_EQ(req.body, "");
  1196. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1198. res.set_content("empty", "text/plain");
  1199. })
  1200. .Post("/empty-no-content-type",
  1201. [&](const Request &req, Response &res) {
  1202. EXPECT_EQ(req.body, "");
  1203. EXPECT_FALSE(req.has_header("Content-Type"));
  1204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1205. res.set_content("empty-no-content-type", "text/plain");
  1206. })
  1207. .Put("/empty-no-content-type",
  1208. [&](const Request &req, Response &res) {
  1209. EXPECT_EQ(req.body, "");
  1210. EXPECT_FALSE(req.has_header("Content-Type"));
  1211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1212. res.set_content("empty-no-content-type", "text/plain");
  1213. })
  1214. .Put("/put",
  1215. [&](const Request &req, Response &res) {
  1216. EXPECT_EQ(req.body, "PUT");
  1217. res.set_content(req.body, "text/plain");
  1218. })
  1219. .Put("/put-large",
  1220. [&](const Request &req, Response &res) {
  1221. EXPECT_EQ(req.body, LARGE_DATA);
  1222. res.set_content(req.body, "text/plain");
  1223. })
  1224. .Patch("/patch",
  1225. [&](const Request &req, Response &res) {
  1226. EXPECT_EQ(req.body, "PATCH");
  1227. res.set_content(req.body, "text/plain");
  1228. })
  1229. .Delete("/delete",
  1230. [&](const Request & /*req*/, Response &res) {
  1231. res.set_content("DELETE", "text/plain");
  1232. })
  1233. .Delete("/delete-body",
  1234. [&](const Request &req, Response &res) {
  1235. EXPECT_EQ(req.body, "content");
  1236. res.set_content(req.body, "text/plain");
  1237. })
  1238. .Options(R"(\*)",
  1239. [&](const Request & /*req*/, Response &res) {
  1240. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1241. })
  1242. .Get("/request-target",
  1243. [&](const Request &req, Response & /*res*/) {
  1244. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1245. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1246. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1247. })
  1248. .Get("/long-query-value",
  1249. [&](const Request &req, Response & /*res*/) {
  1250. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1251. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1252. })
  1253. .Get("/array-param",
  1254. [&](const Request &req, Response & /*res*/) {
  1255. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1256. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1257. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1258. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1259. })
  1260. .Post("/validate-no-multiple-headers",
  1261. [&](const Request &req, Response & /*res*/) {
  1262. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1263. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1264. })
  1265. .Post("/content_receiver",
  1266. [&](const Request &req, Response &res,
  1267. const ContentReader &content_reader) {
  1268. if (req.is_multipart_form_data()) {
  1269. MultipartFormDataItems files;
  1270. content_reader(
  1271. [&](const MultipartFormData &file) {
  1272. files.push_back(file);
  1273. return true;
  1274. },
  1275. [&](const char *data, size_t data_length) {
  1276. files.back().content.append(data, data_length);
  1277. return true;
  1278. });
  1279. EXPECT_EQ(5u, files.size());
  1280. {
  1281. const auto &file = get_file_value(files, "text1");
  1282. EXPECT_TRUE(file.filename.empty());
  1283. EXPECT_EQ("text default", file.content);
  1284. }
  1285. {
  1286. const auto &file = get_file_value(files, "text2");
  1287. EXPECT_TRUE(file.filename.empty());
  1288. EXPECT_EQ("aωb", file.content);
  1289. }
  1290. {
  1291. const auto &file = get_file_value(files, "file1");
  1292. EXPECT_EQ("hello.txt", file.filename);
  1293. EXPECT_EQ("text/plain", file.content_type);
  1294. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1295. }
  1296. {
  1297. const auto &file = get_file_value(files, "file3");
  1298. EXPECT_TRUE(file.filename.empty());
  1299. EXPECT_EQ("application/octet-stream", file.content_type);
  1300. EXPECT_EQ(0u, file.content.size());
  1301. }
  1302. } else {
  1303. std::string body;
  1304. content_reader([&](const char *data, size_t data_length) {
  1305. EXPECT_EQ(data_length, 7);
  1306. body.append(data, data_length);
  1307. return true;
  1308. });
  1309. EXPECT_EQ(body, "content");
  1310. res.set_content(body, "text/plain");
  1311. }
  1312. })
  1313. .Put("/content_receiver",
  1314. [&](const Request & /*req*/, Response &res,
  1315. const ContentReader &content_reader) {
  1316. std::string body;
  1317. content_reader([&](const char *data, size_t data_length) {
  1318. body.append(data, data_length);
  1319. return true;
  1320. });
  1321. EXPECT_EQ(body, "content");
  1322. res.set_content(body, "text/plain");
  1323. })
  1324. .Patch("/content_receiver",
  1325. [&](const Request & /*req*/, Response &res,
  1326. const ContentReader &content_reader) {
  1327. std::string body;
  1328. content_reader([&](const char *data, size_t data_length) {
  1329. body.append(data, data_length);
  1330. return true;
  1331. });
  1332. EXPECT_EQ(body, "content");
  1333. res.set_content(body, "text/plain");
  1334. })
  1335. .Post("/query-string-and-body",
  1336. [&](const Request &req, Response & /*res*/) {
  1337. ASSERT_TRUE(req.has_param("key"));
  1338. EXPECT_EQ(req.get_param_value("key"), "value");
  1339. EXPECT_EQ(req.body, "content");
  1340. })
  1341. .Get("/last-request",
  1342. [&](const Request &req, Response & /*res*/) {
  1343. EXPECT_EQ("close", req.get_header_value("Connection"));
  1344. })
  1345. .Get(R"(/redirect/(\d+))",
  1346. [&](const Request &req, Response &res) {
  1347. auto num = std::stoi(req.matches[1]) + 1;
  1348. std::string url = "/redirect/" + std::to_string(num);
  1349. res.set_redirect(url);
  1350. })
  1351. .Post("/binary",
  1352. [&](const Request &req, Response &res) {
  1353. EXPECT_EQ(4, req.body.size());
  1354. EXPECT_EQ("application/octet-stream",
  1355. req.get_header_value("Content-Type"));
  1356. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1357. res.set_content(req.body, "application/octet-stream");
  1358. })
  1359. .Put("/binary",
  1360. [&](const Request &req, Response &res) {
  1361. EXPECT_EQ(4, req.body.size());
  1362. EXPECT_EQ("application/octet-stream",
  1363. req.get_header_value("Content-Type"));
  1364. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1365. res.set_content(req.body, "application/octet-stream");
  1366. })
  1367. .Patch("/binary",
  1368. [&](const Request &req, Response &res) {
  1369. EXPECT_EQ(4, req.body.size());
  1370. EXPECT_EQ("application/octet-stream",
  1371. req.get_header_value("Content-Type"));
  1372. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1373. res.set_content(req.body, "application/octet-stream");
  1374. })
  1375. .Delete("/binary",
  1376. [&](const Request &req, Response &res) {
  1377. EXPECT_EQ(4, req.body.size());
  1378. EXPECT_EQ("application/octet-stream",
  1379. req.get_header_value("Content-Type"));
  1380. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1381. res.set_content(req.body, "application/octet-stream");
  1382. })
  1383. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1384. .Get("/compress",
  1385. [&](const Request & /*req*/, Response &res) {
  1386. res.set_content(
  1387. "12345678901234567890123456789012345678901234567890123456789"
  1388. "01234567890123456789012345678901234567890",
  1389. "text/plain");
  1390. })
  1391. .Get("/nocompress",
  1392. [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(
  1394. "12345678901234567890123456789012345678901234567890123456789"
  1395. "01234567890123456789012345678901234567890",
  1396. "application/octet-stream");
  1397. })
  1398. .Post("/compress-multipart",
  1399. [&](const Request &req, Response & /*res*/) {
  1400. EXPECT_EQ(2u, req.files.size());
  1401. ASSERT_TRUE(!req.has_file("???"));
  1402. {
  1403. const auto &file = req.get_file_value("key1");
  1404. EXPECT_TRUE(file.filename.empty());
  1405. EXPECT_EQ("test", file.content);
  1406. }
  1407. {
  1408. const auto &file = req.get_file_value("key2");
  1409. EXPECT_TRUE(file.filename.empty());
  1410. EXPECT_EQ("--abcdefg123", file.content);
  1411. }
  1412. })
  1413. #endif
  1414. ;
  1415. persons_["john"] = "programmer";
  1416. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1417. while (!svr_.is_running()) {
  1418. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1419. }
  1420. }
  1421. virtual void TearDown() {
  1422. svr_.stop();
  1423. if (!request_threads_.empty()) {
  1424. std::this_thread::sleep_for(std::chrono::seconds(1));
  1425. for (auto &t : request_threads_) {
  1426. t.join();
  1427. }
  1428. }
  1429. t_.join();
  1430. }
  1431. map<string, string> persons_;
  1432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1433. SSLClient cli_;
  1434. SSLServer svr_;
  1435. #else
  1436. Client cli_;
  1437. Server svr_;
  1438. #endif
  1439. thread t_;
  1440. std::vector<thread> request_threads_;
  1441. };
  1442. TEST_F(ServerTest, GetMethod200) {
  1443. auto res = cli_.Get("/hi");
  1444. ASSERT_TRUE(res);
  1445. EXPECT_EQ("HTTP/1.1", res->version);
  1446. EXPECT_EQ(200, res->status);
  1447. EXPECT_EQ("OK", res->reason);
  1448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1449. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1450. EXPECT_EQ("Hello World!", res->body);
  1451. }
  1452. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1453. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1454. ASSERT_TRUE(res);
  1455. EXPECT_EQ("HTTP/1.1", res->version);
  1456. EXPECT_EQ(200, res->status);
  1457. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1458. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1459. EXPECT_EQ("Hello World!", res->body);
  1460. }
  1461. TEST_F(ServerTest, GetMethod302) {
  1462. auto res = cli_.Get("/");
  1463. ASSERT_TRUE(res);
  1464. EXPECT_EQ(302, res->status);
  1465. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1466. }
  1467. TEST_F(ServerTest, GetMethod302Redirect) {
  1468. cli_.set_follow_location(true);
  1469. auto res = cli_.Get("/");
  1470. ASSERT_TRUE(res);
  1471. EXPECT_EQ(200, res->status);
  1472. EXPECT_EQ("Hello World!", res->body);
  1473. EXPECT_EQ("/hi", res->location);
  1474. }
  1475. TEST_F(ServerTest, GetMethod404) {
  1476. auto res = cli_.Get("/invalid");
  1477. ASSERT_TRUE(res);
  1478. EXPECT_EQ(404, res->status);
  1479. }
  1480. TEST_F(ServerTest, HeadMethod200) {
  1481. auto res = cli_.Head("/hi");
  1482. ASSERT_TRUE(res);
  1483. EXPECT_EQ(200, res->status);
  1484. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1485. EXPECT_TRUE(res->body.empty());
  1486. }
  1487. TEST_F(ServerTest, HeadMethod200Static) {
  1488. auto res = cli_.Head("/mount/dir/index.html");
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(200, res->status);
  1491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1492. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1493. EXPECT_TRUE(res->body.empty());
  1494. }
  1495. TEST_F(ServerTest, HeadMethod404) {
  1496. auto res = cli_.Head("/invalid");
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ(404, res->status);
  1499. EXPECT_TRUE(res->body.empty());
  1500. }
  1501. TEST_F(ServerTest, GetMethodPersonJohn) {
  1502. auto res = cli_.Get("/person/john");
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ(200, res->status);
  1505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1506. EXPECT_EQ("programmer", res->body);
  1507. }
  1508. TEST_F(ServerTest, PostMethod1) {
  1509. auto res = cli_.Get("/person/john1");
  1510. ASSERT_TRUE(res);
  1511. ASSERT_EQ(404, res->status);
  1512. res = cli_.Post("/person", "name=john1&note=coder",
  1513. "application/x-www-form-urlencoded");
  1514. ASSERT_TRUE(res);
  1515. ASSERT_EQ(200, res->status);
  1516. res = cli_.Get("/person/john1");
  1517. ASSERT_TRUE(res);
  1518. ASSERT_EQ(200, res->status);
  1519. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1520. ASSERT_EQ("coder", res->body);
  1521. }
  1522. TEST_F(ServerTest, PostMethod2) {
  1523. auto res = cli_.Get("/person/john2");
  1524. ASSERT_TRUE(res);
  1525. ASSERT_EQ(404, res->status);
  1526. Params params;
  1527. params.emplace("name", "john2");
  1528. params.emplace("note", "coder");
  1529. res = cli_.Post("/person", params);
  1530. ASSERT_TRUE(res);
  1531. ASSERT_EQ(200, res->status);
  1532. res = cli_.Get("/person/john2");
  1533. ASSERT_TRUE(res);
  1534. ASSERT_EQ(200, res->status);
  1535. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1536. ASSERT_EQ("coder", res->body);
  1537. }
  1538. TEST_F(ServerTest, PutMethod3) {
  1539. auto res = cli_.Get("/person/john3");
  1540. ASSERT_TRUE(res);
  1541. ASSERT_EQ(404, res->status);
  1542. Params params;
  1543. params.emplace("name", "john3");
  1544. params.emplace("note", "coder");
  1545. res = cli_.Put("/person", params);
  1546. ASSERT_TRUE(res);
  1547. ASSERT_EQ(200, res->status);
  1548. res = cli_.Get("/person/john3");
  1549. ASSERT_TRUE(res);
  1550. ASSERT_EQ(200, res->status);
  1551. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1552. ASSERT_EQ("coder", res->body);
  1553. }
  1554. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1555. Params params;
  1556. params.emplace("json", JSON_DATA);
  1557. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1558. ASSERT_TRUE(res);
  1559. ASSERT_EQ(200, res->status);
  1560. ASSERT_EQ(JSON_DATA, res->body);
  1561. }
  1562. TEST_F(ServerTest, PostEmptyContent) {
  1563. auto res = cli_.Post("/empty", "", "text/plain");
  1564. ASSERT_TRUE(res);
  1565. ASSERT_EQ(200, res->status);
  1566. ASSERT_EQ("empty", res->body);
  1567. }
  1568. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1569. auto res = cli_.Post("/empty-no-content-type");
  1570. ASSERT_TRUE(res);
  1571. ASSERT_EQ(200, res->status);
  1572. ASSERT_EQ("empty-no-content-type", res->body);
  1573. }
  1574. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1575. auto res = cli_.Put("/empty-no-content-type");
  1576. ASSERT_TRUE(res);
  1577. ASSERT_EQ(200, res->status);
  1578. ASSERT_EQ("empty-no-content-type", res->body);
  1579. }
  1580. TEST_F(ServerTest, GetMethodDir) {
  1581. auto res = cli_.Get("/dir/");
  1582. ASSERT_TRUE(res);
  1583. EXPECT_EQ(200, res->status);
  1584. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1585. auto body = R"(<html>
  1586. <head>
  1587. </head>
  1588. <body>
  1589. <a href="/dir/test.html">Test</a>
  1590. <a href="/hi">hi</a>
  1591. </body>
  1592. </html>
  1593. )";
  1594. EXPECT_EQ(body, res->body);
  1595. }
  1596. TEST_F(ServerTest, GetMethodDirTest) {
  1597. auto res = cli_.Get("/dir/test.html");
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(200, res->status);
  1600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1601. EXPECT_EQ("test.html", res->body);
  1602. }
  1603. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1604. auto res = cli_.Get("/dir/../dir/test.html");
  1605. ASSERT_TRUE(res);
  1606. EXPECT_EQ(200, res->status);
  1607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1608. EXPECT_EQ("test.html", res->body);
  1609. }
  1610. TEST_F(ServerTest, GetMethodInvalidPath) {
  1611. auto res = cli_.Get("/dir/../test.html");
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(404, res->status);
  1614. }
  1615. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1616. auto res = cli_.Get("/../www/dir/test.html");
  1617. ASSERT_TRUE(res);
  1618. EXPECT_EQ(404, res->status);
  1619. }
  1620. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1621. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1622. ASSERT_TRUE(res);
  1623. EXPECT_EQ(404, res->status);
  1624. }
  1625. TEST_F(ServerTest, GetMethodDirMountTest) {
  1626. auto res = cli_.Get("/mount/dir/test.html");
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ(200, res->status);
  1629. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1630. EXPECT_EQ("test.html", res->body);
  1631. }
  1632. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1633. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1634. ASSERT_TRUE(res);
  1635. EXPECT_EQ(200, res->status);
  1636. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1637. EXPECT_EQ("test.html", res->body);
  1638. }
  1639. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1640. auto res = cli_.Get("/mount/dir/../test.html");
  1641. ASSERT_TRUE(res);
  1642. EXPECT_EQ(404, res->status);
  1643. }
  1644. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1645. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(404, res->status);
  1648. }
  1649. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1650. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1651. ASSERT_TRUE(res);
  1652. EXPECT_EQ(404, res->status);
  1653. }
  1654. TEST_F(ServerTest, PostMethod303) {
  1655. auto res = cli_.Post("/1", "body", "text/plain");
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ(303, res->status);
  1658. EXPECT_EQ("/2", res->get_header_value("Location"));
  1659. }
  1660. TEST_F(ServerTest, PostMethod303Redirect) {
  1661. cli_.set_follow_location(true);
  1662. auto res = cli_.Post("/1", "body", "text/plain");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(200, res->status);
  1665. EXPECT_EQ("redirected.", res->body);
  1666. EXPECT_EQ("/2", res->location);
  1667. }
  1668. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1669. auto res = cli_.Get("/dir/test.abcde");
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(200, res->status);
  1672. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1673. EXPECT_EQ("abcde", res->body);
  1674. }
  1675. TEST_F(ServerTest, StaticFileRange) {
  1676. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(206, res->status);
  1679. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1680. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1681. EXPECT_EQ(true, res->has_header("Content-Range"));
  1682. EXPECT_EQ(std::string("cd"), res->body);
  1683. }
  1684. TEST_F(ServerTest, InvalidBaseDirMount) {
  1685. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1686. }
  1687. TEST_F(ServerTest, Binary) {
  1688. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1689. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1690. "application/octet-stream");
  1691. ASSERT_TRUE(res);
  1692. ASSERT_EQ(200, res->status);
  1693. ASSERT_EQ(4, res->body.size());
  1694. res = cli_.Put("/binary", binary.data(), binary.size(),
  1695. "application/octet-stream");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(200, res->status);
  1698. ASSERT_EQ(4, res->body.size());
  1699. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1700. "application/octet-stream");
  1701. ASSERT_TRUE(res);
  1702. ASSERT_EQ(200, res->status);
  1703. ASSERT_EQ(4, res->body.size());
  1704. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1705. "application/octet-stream");
  1706. ASSERT_TRUE(res);
  1707. ASSERT_EQ(200, res->status);
  1708. ASSERT_EQ(4, res->body.size());
  1709. }
  1710. TEST_F(ServerTest, BinaryString) {
  1711. auto binary = std::string("\x00\x01\x02\x03", 4);
  1712. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  1713. ASSERT_TRUE(res);
  1714. ASSERT_EQ(200, res->status);
  1715. ASSERT_EQ(4, res->body.size());
  1716. res = cli_.Put("/binary", binary, "application/octet-stream");
  1717. ASSERT_TRUE(res);
  1718. ASSERT_EQ(200, res->status);
  1719. ASSERT_EQ(4, res->body.size());
  1720. res = cli_.Patch("/binary", binary, "application/octet-stream");
  1721. ASSERT_TRUE(res);
  1722. ASSERT_EQ(200, res->status);
  1723. ASSERT_EQ(4, res->body.size());
  1724. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1725. ASSERT_TRUE(res);
  1726. ASSERT_EQ(200, res->status);
  1727. ASSERT_EQ(4, res->body.size());
  1728. }
  1729. TEST_F(ServerTest, EmptyRequest) {
  1730. auto res = cli_.Get("");
  1731. ASSERT_TRUE(!res);
  1732. EXPECT_EQ(Error::Connection, res.error());
  1733. }
  1734. TEST_F(ServerTest, LongRequest) {
  1735. std::string request;
  1736. for (size_t i = 0; i < 545; i++) {
  1737. request += "/TooLongRequest";
  1738. }
  1739. request += "OK";
  1740. auto res = cli_.Get(request.c_str());
  1741. ASSERT_TRUE(res);
  1742. EXPECT_EQ(404, res->status);
  1743. }
  1744. TEST_F(ServerTest, TooLongRequest) {
  1745. std::string request;
  1746. for (size_t i = 0; i < 545; i++) {
  1747. request += "/TooLongRequest";
  1748. }
  1749. request += "_NG";
  1750. auto res = cli_.Get(request.c_str());
  1751. ASSERT_TRUE(res);
  1752. EXPECT_EQ(414, res->status);
  1753. }
  1754. TEST_F(ServerTest, LongHeader) {
  1755. Request req;
  1756. req.method = "GET";
  1757. req.path = "/hi";
  1758. std::string host_and_port;
  1759. host_and_port += HOST;
  1760. host_and_port += ":";
  1761. host_and_port += std::to_string(PORT);
  1762. req.headers.emplace("Host", host_and_port.c_str());
  1763. req.headers.emplace("Accept", "*/*");
  1764. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1765. req.headers.emplace(
  1766. "Header-Name",
  1767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1795. "@@@@@@@@@@@@@@@@");
  1796. auto res = std::make_shared<Response>();
  1797. auto error = Error::Success;
  1798. auto ret = cli_.send(req, *res, error);
  1799. ASSERT_TRUE(ret);
  1800. EXPECT_EQ(200, res->status);
  1801. }
  1802. TEST_F(ServerTest, LongQueryValue) {
  1803. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1804. ASSERT_TRUE(res);
  1805. EXPECT_EQ(414, res->status);
  1806. }
  1807. TEST_F(ServerTest, TooLongHeader) {
  1808. Request req;
  1809. req.method = "GET";
  1810. req.path = "/hi";
  1811. std::string host_and_port;
  1812. host_and_port += HOST;
  1813. host_and_port += ":";
  1814. host_and_port += std::to_string(PORT);
  1815. req.headers.emplace("Host", host_and_port.c_str());
  1816. req.headers.emplace("Accept", "*/*");
  1817. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1818. req.headers.emplace(
  1819. "Header-Name",
  1820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1848. "@@@@@@@@@@@@@@@@@");
  1849. auto res = std::make_shared<Response>();
  1850. auto error = Error::Success;
  1851. auto ret = cli_.send(req, *res, error);
  1852. ASSERT_TRUE(ret);
  1853. EXPECT_EQ(200, res->status);
  1854. }
  1855. TEST_F(ServerTest, PercentEncoding) {
  1856. auto res = cli_.Get("/e%6edwith%");
  1857. ASSERT_TRUE(res);
  1858. EXPECT_EQ(200, res->status);
  1859. }
  1860. TEST_F(ServerTest, PercentEncodingUnicode) {
  1861. auto res = cli_.Get("/e%u006edwith%");
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(200, res->status);
  1864. }
  1865. TEST_F(ServerTest, InvalidPercentEncoding) {
  1866. auto res = cli_.Get("/%endwith%");
  1867. ASSERT_TRUE(res);
  1868. EXPECT_EQ(404, res->status);
  1869. }
  1870. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1871. auto res = cli_.Get("/%uendwith%");
  1872. ASSERT_TRUE(res);
  1873. EXPECT_EQ(404, res->status);
  1874. }
  1875. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1876. auto res = cli_.Get("/hello?aaa=bbb%");
  1877. ASSERT_TRUE(res);
  1878. EXPECT_EQ(404, res->status);
  1879. }
  1880. TEST_F(ServerTest, PlusSignEncoding) {
  1881. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(200, res->status);
  1884. EXPECT_EQ("a +b", res->body);
  1885. }
  1886. TEST_F(ServerTest, MultipartFormData) {
  1887. MultipartFormDataItems items = {
  1888. {"text1", "text default", "", ""},
  1889. {"text2", "aωb", "", ""},
  1890. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1891. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1892. {"file3", "", "", "application/octet-stream"},
  1893. {"file4", "", "", " application/json tmp-string "}};
  1894. auto res = cli_.Post("/multipart", items);
  1895. ASSERT_TRUE(res);
  1896. EXPECT_EQ(200, res->status);
  1897. }
  1898. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1899. auto res = cli_.Get("/hi");
  1900. ASSERT_TRUE(res);
  1901. EXPECT_EQ(200, res->status);
  1902. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1903. EXPECT_EQ("Hello World!", res->body);
  1904. }
  1905. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1906. Request req;
  1907. req.method = "POST";
  1908. req.path = "/chunked";
  1909. std::string host_and_port;
  1910. host_and_port += HOST;
  1911. host_and_port += ":";
  1912. host_and_port += std::to_string(PORT);
  1913. req.headers.emplace("Host", host_and_port.c_str());
  1914. req.headers.emplace("Accept", "*/*");
  1915. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1916. req.headers.emplace("Content-Type", "text/plain");
  1917. req.headers.emplace("Content-Length", "0");
  1918. req.headers.emplace(
  1919. "Transfer-Encoding",
  1920. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1921. // Client does not chunk, so make a chunked body manually.
  1922. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1923. auto res = std::make_shared<Response>();
  1924. auto error = Error::Success;
  1925. auto ret = cli_.send(req, *res, error);
  1926. ASSERT_TRUE(ret);
  1927. EXPECT_EQ(200, res->status);
  1928. }
  1929. TEST_F(ServerTest, GetStreamed2) {
  1930. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(206, res->status);
  1933. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1934. EXPECT_EQ(std::string("ab"), res->body);
  1935. }
  1936. TEST_F(ServerTest, GetStreamed) {
  1937. auto res = cli_.Get("/streamed");
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(200, res->status);
  1940. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1941. EXPECT_EQ(std::string("aaabbb"), res->body);
  1942. }
  1943. TEST_F(ServerTest, GetStreamedWithRange1) {
  1944. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1945. ASSERT_TRUE(res);
  1946. EXPECT_EQ(206, res->status);
  1947. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1948. EXPECT_EQ(true, res->has_header("Content-Range"));
  1949. EXPECT_EQ(std::string("def"), res->body);
  1950. }
  1951. TEST_F(ServerTest, GetStreamedWithRange2) {
  1952. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1953. ASSERT_TRUE(res);
  1954. EXPECT_EQ(206, res->status);
  1955. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1956. EXPECT_EQ(true, res->has_header("Content-Range"));
  1957. EXPECT_EQ(std::string("bcdefg"), res->body);
  1958. }
  1959. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  1960. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(206, res->status);
  1963. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1964. EXPECT_EQ(true, res->has_header("Content-Range"));
  1965. EXPECT_EQ(std::string("efg"), res->body);
  1966. }
  1967. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  1968. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  1969. ASSERT_TRUE(res);
  1970. EXPECT_EQ(206, res->status);
  1971. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1972. EXPECT_EQ(true, res->has_header("Content-Range"));
  1973. EXPECT_EQ(std::string("abcdefg"), res->body);
  1974. }
  1975. TEST_F(ServerTest, GetStreamedWithRangeError) {
  1976. auto res = cli_.Get("/streamed-with-range",
  1977. {{"Range", "bytes=92233720368547758079223372036854775806-"
  1978. "92233720368547758079223372036854775807"}});
  1979. ASSERT_TRUE(res);
  1980. EXPECT_EQ(416, res->status);
  1981. }
  1982. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  1983. auto res =
  1984. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  1985. EXPECT_EQ(206, res->status);
  1986. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1987. EXPECT_EQ(true, res->has_header("Content-Range"));
  1988. EXPECT_EQ(std::string("abcdefg"), res->body);
  1989. }
  1990. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1991. auto res =
  1992. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1993. ASSERT_TRUE(res);
  1994. EXPECT_EQ(206, res->status);
  1995. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1996. EXPECT_EQ(false, res->has_header("Content-Range"));
  1997. EXPECT_EQ(269, res->body.size());
  1998. }
  1999. TEST_F(ServerTest, GetStreamedEndless) {
  2000. uint64_t offset = 0;
  2001. auto res = cli_.Get("/streamed-cancel",
  2002. [&](const char * /*data*/, uint64_t data_length) {
  2003. if (offset < 100) {
  2004. offset += data_length;
  2005. return true;
  2006. }
  2007. return false;
  2008. });
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::Canceled, res.error());
  2011. }
  2012. TEST_F(ServerTest, ClientStop) {
  2013. std::vector<std::thread> threads;
  2014. for (auto i = 0; i < 3; i++) {
  2015. threads.emplace_back(thread([&]() {
  2016. auto res = cli_.Get("/streamed-cancel",
  2017. [&](const char *, uint64_t) { return true; });
  2018. ASSERT_TRUE(!res);
  2019. EXPECT_TRUE(res.error() == Error::Canceled ||
  2020. res.error() == Error::Read || res.error() == Error::Write);
  2021. }));
  2022. }
  2023. std::this_thread::sleep_for(std::chrono::seconds(2));
  2024. while (cli_.is_socket_open()) {
  2025. cli_.stop();
  2026. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2027. }
  2028. for (auto &t : threads) {
  2029. t.join();
  2030. }
  2031. }
  2032. TEST_F(ServerTest, GetWithRange1) {
  2033. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2034. ASSERT_TRUE(res);
  2035. EXPECT_EQ(206, res->status);
  2036. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2037. EXPECT_EQ(true, res->has_header("Content-Range"));
  2038. EXPECT_EQ(std::string("def"), res->body);
  2039. }
  2040. TEST_F(ServerTest, GetWithRange2) {
  2041. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(206, res->status);
  2044. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2045. EXPECT_EQ(true, res->has_header("Content-Range"));
  2046. EXPECT_EQ(std::string("bcdefg"), res->body);
  2047. }
  2048. TEST_F(ServerTest, GetWithRange3) {
  2049. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2050. ASSERT_TRUE(res);
  2051. EXPECT_EQ(206, res->status);
  2052. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2053. EXPECT_EQ(true, res->has_header("Content-Range"));
  2054. EXPECT_EQ(std::string("a"), res->body);
  2055. }
  2056. TEST_F(ServerTest, GetWithRange4) {
  2057. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2058. ASSERT_TRUE(res);
  2059. EXPECT_EQ(206, res->status);
  2060. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2061. EXPECT_EQ(true, res->has_header("Content-Range"));
  2062. EXPECT_EQ(std::string("fg"), res->body);
  2063. }
  2064. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2065. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2066. ASSERT_TRUE(res);
  2067. EXPECT_EQ(416, res->status);
  2068. }
  2069. TEST_F(ServerTest, GetWithRangeMultipart) {
  2070. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(206, res->status);
  2073. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2074. EXPECT_EQ(false, res->has_header("Content-Range"));
  2075. EXPECT_EQ(269, res->body.size());
  2076. }
  2077. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2078. auto res =
  2079. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2080. ASSERT_TRUE(res);
  2081. EXPECT_EQ(416, res->status);
  2082. }
  2083. TEST_F(ServerTest, GetStreamedChunked) {
  2084. auto res = cli_.Get("/streamed-chunked");
  2085. ASSERT_TRUE(res);
  2086. EXPECT_EQ(200, res->status);
  2087. EXPECT_EQ(std::string("123456789"), res->body);
  2088. }
  2089. TEST_F(ServerTest, GetStreamedChunked2) {
  2090. auto res = cli_.Get("/streamed-chunked2");
  2091. ASSERT_TRUE(res);
  2092. EXPECT_EQ(200, res->status);
  2093. EXPECT_EQ(std::string("123456789"), res->body);
  2094. }
  2095. TEST_F(ServerTest, LargeChunkedPost) {
  2096. Request req;
  2097. req.method = "POST";
  2098. req.path = "/large-chunked";
  2099. std::string host_and_port;
  2100. host_and_port += HOST;
  2101. host_and_port += ":";
  2102. host_and_port += std::to_string(PORT);
  2103. req.headers.emplace("Host", host_and_port.c_str());
  2104. req.headers.emplace("Accept", "*/*");
  2105. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2106. req.headers.emplace("Content-Type", "text/plain");
  2107. req.headers.emplace("Content-Length", "0");
  2108. req.headers.emplace("Transfer-Encoding", "chunked");
  2109. std::string long_string(30 * 1024u, 'a');
  2110. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2111. // Attempt to make a large enough post to exceed OS buffers, to test that
  2112. // the server handles short reads if the full chunk data isn't available.
  2113. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2114. auto res = std::make_shared<Response>();
  2115. auto error = Error::Success;
  2116. auto ret = cli_.send(req, *res, error);
  2117. ASSERT_TRUE(ret);
  2118. EXPECT_EQ(200, res->status);
  2119. }
  2120. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2121. auto res = cli_.Get("/remote_addr");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(200, res->status);
  2124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2125. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2126. }
  2127. TEST_F(ServerTest, HTTPResponseSplitting) {
  2128. auto res = cli_.Get("/http_response_splitting");
  2129. ASSERT_TRUE(res);
  2130. EXPECT_EQ(200, res->status);
  2131. }
  2132. TEST_F(ServerTest, SlowRequest) {
  2133. request_threads_.push_back(
  2134. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2135. request_threads_.push_back(
  2136. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2137. request_threads_.push_back(
  2138. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2139. }
  2140. TEST_F(ServerTest, SlowPost) {
  2141. char buffer[64 * 1024];
  2142. memset(buffer, 0x42, sizeof(buffer));
  2143. auto res =
  2144. cli_.Post("/slowpost", 64 * 1024 * 1024,
  2145. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2146. sink.write(buffer, sizeof(buffer));
  2147. return true;
  2148. },
  2149. "text/plain");
  2150. ASSERT_TRUE(res);
  2151. EXPECT_EQ(200, res->status);
  2152. }
  2153. TEST_F(ServerTest, SlowPostFail) {
  2154. char buffer[64 * 1024];
  2155. memset(buffer, 0x42, sizeof(buffer));
  2156. cli_.set_write_timeout(std::chrono::seconds(0));
  2157. auto res =
  2158. cli_.Post("/slowpost", 64 * 1024 * 1024,
  2159. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2160. sink.write(buffer, sizeof(buffer));
  2161. return true;
  2162. },
  2163. "text/plain");
  2164. ASSERT_TRUE(!res);
  2165. EXPECT_EQ(Error::Write, res.error());
  2166. }
  2167. TEST_F(ServerTest, Put) {
  2168. auto res = cli_.Put("/put", "PUT", "text/plain");
  2169. ASSERT_TRUE(res);
  2170. EXPECT_EQ(200, res->status);
  2171. EXPECT_EQ("PUT", res->body);
  2172. }
  2173. TEST_F(ServerTest, PutWithContentProvider) {
  2174. auto res = cli_.Put("/put", 3,
  2175. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2176. EXPECT_TRUE(sink.is_writable());
  2177. sink.os << "PUT";
  2178. return true;
  2179. },
  2180. "text/plain");
  2181. ASSERT_TRUE(res);
  2182. EXPECT_EQ(200, res->status);
  2183. EXPECT_EQ("PUT", res->body);
  2184. }
  2185. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2186. auto res = cli_.Post("/post", 42,
  2187. [](size_t /*offset*/, size_t /*length*/,
  2188. DataSink & /*sink*/) { return false; },
  2189. "text/plain");
  2190. ASSERT_TRUE(!res);
  2191. EXPECT_EQ(Error::Canceled, res.error());
  2192. }
  2193. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2194. auto res = cli_.Put("/put",
  2195. [](size_t /*offset*/, DataSink &sink) {
  2196. EXPECT_TRUE(sink.is_writable());
  2197. sink.os << "PUT";
  2198. sink.done();
  2199. return true;
  2200. },
  2201. "text/plain");
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(200, res->status);
  2204. EXPECT_EQ("PUT", res->body);
  2205. }
  2206. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2207. auto res = cli_.Post(
  2208. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2209. "text/plain");
  2210. ASSERT_TRUE(!res);
  2211. EXPECT_EQ(Error::Canceled, res.error());
  2212. }
  2213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2214. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2215. cli_.set_compress(true);
  2216. auto res = cli_.Put("/put", 3,
  2217. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2218. EXPECT_TRUE(sink.is_writable());
  2219. sink.os << "PUT";
  2220. return true;
  2221. },
  2222. "text/plain");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ(200, res->status);
  2225. EXPECT_EQ("PUT", res->body);
  2226. }
  2227. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2228. cli_.set_compress(true);
  2229. auto res = cli_.Post("/post", 42,
  2230. [](size_t /*offset*/, size_t /*length*/,
  2231. DataSink & /*sink*/) { return false; },
  2232. "text/plain");
  2233. ASSERT_TRUE(!res);
  2234. EXPECT_EQ(Error::Canceled, res.error());
  2235. }
  2236. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2237. cli_.set_compress(true);
  2238. auto res = cli_.Put("/put",
  2239. [](size_t /*offset*/, DataSink &sink) {
  2240. EXPECT_TRUE(sink.is_writable());
  2241. sink.os << "PUT";
  2242. sink.done();
  2243. return true;
  2244. },
  2245. "text/plain");
  2246. ASSERT_TRUE(res);
  2247. EXPECT_EQ(200, res->status);
  2248. EXPECT_EQ("PUT", res->body);
  2249. }
  2250. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2251. cli_.set_compress(true);
  2252. auto res = cli_.Post(
  2253. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2254. "text/plain");
  2255. ASSERT_TRUE(!res);
  2256. EXPECT_EQ(Error::Canceled, res.error());
  2257. }
  2258. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2259. cli_.set_compress(true);
  2260. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2261. ASSERT_TRUE(res);
  2262. EXPECT_EQ(200, res->status);
  2263. EXPECT_EQ(LARGE_DATA, res->body);
  2264. }
  2265. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2266. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2267. Client cli("https://localhost:1234");
  2268. cli.enable_server_certificate_verification(false);
  2269. #else
  2270. Client cli("http://localhost:1234");
  2271. #endif
  2272. cli.set_compress(true);
  2273. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2274. ASSERT_TRUE(res);
  2275. EXPECT_EQ(200, res->status);
  2276. EXPECT_EQ(LARGE_DATA, res->body);
  2277. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2278. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2279. }
  2280. TEST_F(ServerTest, PutContentWithDeflate) {
  2281. cli_.set_compress(false);
  2282. Headers headers;
  2283. headers.emplace("Content-Encoding", "deflate");
  2284. // PUT in deflate format:
  2285. auto res = cli_.Put("/put", headers,
  2286. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2287. ASSERT_TRUE(res);
  2288. EXPECT_EQ(200, res->status);
  2289. EXPECT_EQ("PUT", res->body);
  2290. }
  2291. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2292. Headers headers;
  2293. headers.emplace("Accept-Encoding", "gzip, deflate");
  2294. auto res = cli_.Get("/streamed-chunked", headers);
  2295. ASSERT_TRUE(res);
  2296. EXPECT_EQ(200, res->status);
  2297. EXPECT_EQ(std::string("123456789"), res->body);
  2298. }
  2299. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2300. Headers headers;
  2301. headers.emplace("Accept-Encoding", "gzip, deflate");
  2302. auto res = cli_.Get("/streamed-chunked2", headers);
  2303. ASSERT_TRUE(res);
  2304. EXPECT_EQ(200, res->status);
  2305. EXPECT_EQ(std::string("123456789"), res->body);
  2306. }
  2307. TEST(GzipDecompressor, ChunkedDecompression) {
  2308. std::string data;
  2309. for (size_t i = 0; i < 32 * 1024; ++i) {
  2310. data.push_back(static_cast<char>('a' + i % 26));
  2311. }
  2312. std::string compressed_data;
  2313. {
  2314. httplib::detail::gzip_compressor compressor;
  2315. bool result = compressor.compress(
  2316. data.data(), data.size(),
  2317. /*last=*/true, [&](const char *data, size_t size) {
  2318. compressed_data.insert(compressed_data.size(), data, size);
  2319. return true;
  2320. });
  2321. ASSERT_TRUE(result);
  2322. }
  2323. std::string decompressed_data;
  2324. {
  2325. httplib::detail::gzip_decompressor decompressor;
  2326. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2327. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2328. size_t chunk_size = 130;
  2329. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2330. chunk_begin += chunk_size) {
  2331. size_t current_chunk_size =
  2332. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2333. bool result = decompressor.decompress(
  2334. compressed_data.data() + chunk_begin, current_chunk_size,
  2335. [&](const char *data, size_t size) {
  2336. decompressed_data.insert(decompressed_data.size(), data, size);
  2337. return true;
  2338. });
  2339. ASSERT_TRUE(result);
  2340. }
  2341. }
  2342. ASSERT_EQ(data, decompressed_data);
  2343. }
  2344. #endif
  2345. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2346. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2347. Headers headers;
  2348. headers.emplace("Accept-Encoding", "br");
  2349. auto res = cli_.Get("/streamed-chunked", headers);
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(200, res->status);
  2352. EXPECT_EQ(std::string("123456789"), res->body);
  2353. }
  2354. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2355. Headers headers;
  2356. headers.emplace("Accept-Encoding", "br");
  2357. auto res = cli_.Get("/streamed-chunked2", headers);
  2358. ASSERT_TRUE(res);
  2359. EXPECT_EQ(200, res->status);
  2360. EXPECT_EQ(std::string("123456789"), res->body);
  2361. }
  2362. #endif
  2363. TEST_F(ServerTest, Patch) {
  2364. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2365. ASSERT_TRUE(res);
  2366. EXPECT_EQ(200, res->status);
  2367. EXPECT_EQ("PATCH", res->body);
  2368. }
  2369. TEST_F(ServerTest, Delete) {
  2370. auto res = cli_.Delete("/delete");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(200, res->status);
  2373. EXPECT_EQ("DELETE", res->body);
  2374. }
  2375. TEST_F(ServerTest, DeleteContentReceiver) {
  2376. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2377. ASSERT_TRUE(res);
  2378. EXPECT_EQ(200, res->status);
  2379. EXPECT_EQ("content", res->body);
  2380. }
  2381. TEST_F(ServerTest, Options) {
  2382. auto res = cli_.Options("*");
  2383. ASSERT_TRUE(res);
  2384. EXPECT_EQ(200, res->status);
  2385. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2386. EXPECT_TRUE(res->body.empty());
  2387. }
  2388. TEST_F(ServerTest, URL) {
  2389. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(200, res->status);
  2392. }
  2393. TEST_F(ServerTest, ArrayParam) {
  2394. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2395. ASSERT_TRUE(res);
  2396. EXPECT_EQ(200, res->status);
  2397. }
  2398. TEST_F(ServerTest, NoMultipleHeaders) {
  2399. Headers headers = {{"Content-Length", "5"}};
  2400. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2401. "text/plain");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(200, res->status);
  2404. }
  2405. TEST_F(ServerTest, PostContentReceiver) {
  2406. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2407. ASSERT_TRUE(res);
  2408. ASSERT_EQ(200, res->status);
  2409. ASSERT_EQ("content", res->body);
  2410. }
  2411. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2412. MultipartFormDataItems items = {
  2413. {"text1", "text default", "", ""},
  2414. {"text2", "aωb", "", ""},
  2415. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2416. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2417. {"file3", "", "", "application/octet-stream"},
  2418. };
  2419. auto res = cli_.Post("/content_receiver", items);
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(200, res->status);
  2422. }
  2423. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2424. MultipartFormDataItems items = {
  2425. {"text1", "text default", "", ""},
  2426. {"text2", "aωb", "", ""},
  2427. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2428. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2429. {"file3", "", "", "application/octet-stream"},
  2430. };
  2431. auto boundary = std::string("+++++");
  2432. std::string body;
  2433. for (const auto &item : items) {
  2434. body += "--" + boundary + "\r\n";
  2435. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2436. if (!item.filename.empty()) {
  2437. body += "; filename=\"" + item.filename + "\"";
  2438. }
  2439. body += "\r\n";
  2440. if (!item.content_type.empty()) {
  2441. body += "Content-Type: " + item.content_type + "\r\n";
  2442. }
  2443. body += "\r\n";
  2444. body += item.content + "\r\n";
  2445. }
  2446. body += "--" + boundary + "--\r\n";
  2447. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2448. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2449. ASSERT_TRUE(res);
  2450. EXPECT_EQ(200, res->status);
  2451. }
  2452. TEST_F(ServerTest, PostContentReceiverGzip) {
  2453. cli_.set_compress(true);
  2454. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2455. ASSERT_TRUE(res);
  2456. ASSERT_EQ(200, res->status);
  2457. ASSERT_EQ("content", res->body);
  2458. }
  2459. TEST_F(ServerTest, PutContentReceiver) {
  2460. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2461. ASSERT_TRUE(res);
  2462. ASSERT_EQ(200, res->status);
  2463. ASSERT_EQ("content", res->body);
  2464. }
  2465. TEST_F(ServerTest, PatchContentReceiver) {
  2466. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2467. ASSERT_TRUE(res);
  2468. ASSERT_EQ(200, res->status);
  2469. ASSERT_EQ("content", res->body);
  2470. }
  2471. TEST_F(ServerTest, PostQueryStringAndBody) {
  2472. auto res =
  2473. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2474. ASSERT_TRUE(res);
  2475. ASSERT_EQ(200, res->status);
  2476. }
  2477. TEST_F(ServerTest, HTTP2Magic) {
  2478. Request req;
  2479. req.method = "PRI";
  2480. req.path = "*";
  2481. req.body = "SM";
  2482. auto res = std::make_shared<Response>();
  2483. auto error = Error::Success;
  2484. auto ret = cli_.send(req, *res, error);
  2485. ASSERT_TRUE(ret);
  2486. EXPECT_EQ(400, res->status);
  2487. }
  2488. TEST_F(ServerTest, KeepAlive) {
  2489. auto res = cli_.Get("/hi");
  2490. ASSERT_TRUE(res);
  2491. EXPECT_EQ(200, res->status);
  2492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2493. EXPECT_EQ("Hello World!", res->body);
  2494. res = cli_.Get("/hi");
  2495. ASSERT_TRUE(res);
  2496. EXPECT_EQ(200, res->status);
  2497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2498. EXPECT_EQ("Hello World!", res->body);
  2499. res = cli_.Get("/hi");
  2500. ASSERT_TRUE(res);
  2501. EXPECT_EQ(200, res->status);
  2502. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2503. EXPECT_EQ("Hello World!", res->body);
  2504. res = cli_.Get("/not-exist");
  2505. ASSERT_TRUE(res);
  2506. EXPECT_EQ(404, res->status);
  2507. res = cli_.Post("/empty", "", "text/plain");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ(200, res->status);
  2510. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2511. EXPECT_EQ("empty", res->body);
  2512. EXPECT_EQ("close", res->get_header_value("Connection"));
  2513. res = cli_.Post("/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2514. "text/plain");
  2515. ASSERT_TRUE(res);
  2516. EXPECT_EQ(200, res->status);
  2517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2518. EXPECT_EQ("empty", res->body);
  2519. cli_.set_keep_alive(false);
  2520. res = cli_.Get("/last-request");
  2521. ASSERT_TRUE(res);
  2522. EXPECT_EQ(200, res->status);
  2523. EXPECT_EQ("close", res->get_header_value("Connection"));
  2524. }
  2525. TEST_F(ServerTest, TooManyRedirect) {
  2526. cli_.set_follow_location(true);
  2527. auto res = cli_.Get("/redirect/0");
  2528. ASSERT_TRUE(!res);
  2529. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2530. }
  2531. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2532. TEST_F(ServerTest, Gzip) {
  2533. Headers headers;
  2534. headers.emplace("Accept-Encoding", "gzip, deflate");
  2535. auto res = cli_.Get("/compress", headers);
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2539. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2540. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2541. "7890123456789012345678901234567890",
  2542. res->body);
  2543. EXPECT_EQ(200, res->status);
  2544. }
  2545. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2546. auto res = cli_.Get("/compress");
  2547. ASSERT_TRUE(res);
  2548. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2550. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2551. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2552. "7890123456789012345678901234567890",
  2553. res->body);
  2554. EXPECT_EQ(200, res->status);
  2555. }
  2556. TEST_F(ServerTest, GzipWithContentReceiver) {
  2557. Headers headers;
  2558. headers.emplace("Accept-Encoding", "gzip, deflate");
  2559. std::string body;
  2560. auto res = cli_.Get("/compress", headers,
  2561. [&](const char *data, uint64_t data_length) {
  2562. EXPECT_EQ(data_length, 100);
  2563. body.append(data, data_length);
  2564. return true;
  2565. });
  2566. ASSERT_TRUE(res);
  2567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2569. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2571. "7890123456789012345678901234567890",
  2572. body);
  2573. EXPECT_EQ(200, res->status);
  2574. }
  2575. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2576. Headers headers;
  2577. headers.emplace("Accept-Encoding", "gzip, deflate");
  2578. cli_.set_decompress(false);
  2579. auto res = cli_.Get("/compress", headers);
  2580. ASSERT_TRUE(res);
  2581. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2583. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2584. EXPECT_EQ(33, res->body.size());
  2585. EXPECT_EQ(200, res->status);
  2586. }
  2587. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2588. std::string body;
  2589. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2590. EXPECT_EQ(data_length, 100);
  2591. body.append(data, data_length);
  2592. return true;
  2593. });
  2594. ASSERT_TRUE(res);
  2595. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2597. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2599. "7890123456789012345678901234567890",
  2600. body);
  2601. EXPECT_EQ(200, res->status);
  2602. }
  2603. TEST_F(ServerTest, NoGzip) {
  2604. Headers headers;
  2605. headers.emplace("Accept-Encoding", "gzip, deflate");
  2606. auto res = cli_.Get("/nocompress", headers);
  2607. ASSERT_TRUE(res);
  2608. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2609. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2610. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2611. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2612. "7890123456789012345678901234567890",
  2613. res->body);
  2614. EXPECT_EQ(200, res->status);
  2615. }
  2616. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2617. Headers headers;
  2618. headers.emplace("Accept-Encoding", "gzip, deflate");
  2619. std::string body;
  2620. auto res = cli_.Get("/nocompress", headers,
  2621. [&](const char *data, uint64_t data_length) {
  2622. EXPECT_EQ(data_length, 100);
  2623. body.append(data, data_length);
  2624. return true;
  2625. });
  2626. ASSERT_TRUE(res);
  2627. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2628. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2629. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2630. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2631. "7890123456789012345678901234567890",
  2632. body);
  2633. EXPECT_EQ(200, res->status);
  2634. }
  2635. TEST_F(ServerTest, MultipartFormDataGzip) {
  2636. MultipartFormDataItems items = {
  2637. {"key1", "test", "", ""},
  2638. {"key2", "--abcdefg123", "", ""},
  2639. };
  2640. cli_.set_compress(true);
  2641. auto res = cli_.Post("/compress-multipart", items);
  2642. ASSERT_TRUE(res);
  2643. EXPECT_EQ(200, res->status);
  2644. }
  2645. #endif
  2646. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2647. TEST_F(ServerTest, Brotli) {
  2648. Headers headers;
  2649. headers.emplace("Accept-Encoding", "br");
  2650. auto res = cli_.Get("/compress", headers);
  2651. ASSERT_TRUE(res);
  2652. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2654. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2655. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2656. "7890123456789012345678901234567890",
  2657. res->body);
  2658. EXPECT_EQ(200, res->status);
  2659. }
  2660. #endif
  2661. // Sends a raw request to a server listening at HOST:PORT.
  2662. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2663. std::string *resp = nullptr) {
  2664. auto error = Error::Success;
  2665. auto client_sock =
  2666. detail::create_client_socket(HOST, PORT, AF_UNSPEC, false, nullptr,
  2667. /*timeout_sec=*/5, 0, std::string(), error);
  2668. if (client_sock == INVALID_SOCKET) { return false; }
  2669. auto ret = detail::process_client_socket(
  2670. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2671. if (req.size() !=
  2672. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2673. return false;
  2674. }
  2675. char buf[512];
  2676. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2677. while (line_reader.getline()) {
  2678. if (resp) { *resp += line_reader.ptr(); }
  2679. }
  2680. return true;
  2681. });
  2682. detail::close_socket(client_sock);
  2683. return ret;
  2684. }
  2685. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2686. Server svr;
  2687. std::string header_value;
  2688. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2689. header_value = req.get_header_value("foo");
  2690. res.set_content("ok", "text/plain");
  2691. });
  2692. thread t = thread([&] { svr.listen(HOST, PORT); });
  2693. while (!svr.is_running()) {
  2694. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2695. }
  2696. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2697. // like characters are not treated the same - use vertical tab and escape.
  2698. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2699. "foo: \t \v bar \e\t \r\n"
  2700. "Connection: close\r\n"
  2701. "\r\n";
  2702. ASSERT_TRUE(send_request(5, req));
  2703. svr.stop();
  2704. t.join();
  2705. EXPECT_EQ(header_value, "\v bar \e");
  2706. }
  2707. // Sends a raw request and verifies that there isn't a crash or exception.
  2708. static void test_raw_request(const std::string &req,
  2709. std::string *out = nullptr) {
  2710. Server svr;
  2711. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2712. res.set_content("ok", "text/plain");
  2713. });
  2714. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2715. res.set_content("ok", "text/plain");
  2716. });
  2717. // Server read timeout must be longer than the client read timeout for the
  2718. // bug to reproduce, probably to force the server to process a request
  2719. // without a trailing blank line.
  2720. const time_t client_read_timeout_sec = 1;
  2721. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  2722. bool listen_thread_ok = false;
  2723. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2724. while (!svr.is_running()) {
  2725. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2726. }
  2727. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2728. svr.stop();
  2729. t.join();
  2730. EXPECT_TRUE(listen_thread_ok);
  2731. }
  2732. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2733. // A certain header line causes an exception if the header property is parsed
  2734. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2735. test_raw_request(
  2736. "GET /hi HTTP/1.1\r\n"
  2737. " : "
  2738. " "
  2739. " ");
  2740. }
  2741. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2742. // A certain header line causes an exception if the header property *name* is
  2743. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2744. // greedy matcher and requires backtracking when there are a lot of ":"
  2745. // characters.
  2746. // This occurs with libc++ but not libstdc++.
  2747. test_raw_request(
  2748. "GET /hi HTTP/1.1\r\n"
  2749. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2750. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2751. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2752. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2753. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2754. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2755. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2756. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2757. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2758. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2759. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2760. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2761. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2762. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2763. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2764. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2765. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2766. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2767. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2768. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2769. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2770. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2771. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2772. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2773. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2774. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2775. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2776. "&&&%%%");
  2777. }
  2778. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2779. // Make sure this doesn't crash the server.
  2780. // In a previous version of the header line regex, the "\r" rendered the line
  2781. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2782. // a new position where the leading white space ended and the field value
  2783. // began.
  2784. // The crash occurs with libc++ but not libstdc++.
  2785. test_raw_request("GET /hi HTTP/1.1\r\n"
  2786. "a:" +
  2787. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2788. "\r\n"
  2789. "\r\n");
  2790. }
  2791. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2792. std::string out;
  2793. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2794. "Content-Type: text/plain\r\n"
  2795. "Transfer-Encoding: chunked\r\n"
  2796. "\r\n"
  2797. "nothex\r\n",
  2798. &out);
  2799. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2800. }
  2801. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2802. std::string out;
  2803. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2804. "Content-Type: text/plain\r\n"
  2805. "Transfer-Encoding: chunked\r\n"
  2806. "\r\n"
  2807. "3\r\n"
  2808. "xyz\r\n"
  2809. "NaN\r\n",
  2810. &out);
  2811. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2812. }
  2813. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2814. std::string out;
  2815. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2816. "Content-Type: text/plain\r\n"
  2817. "Transfer-Encoding: chunked\r\n"
  2818. "\r\n"
  2819. // Length is too large for 64 bits.
  2820. "1ffffffffffffffff\r\n"
  2821. "xyz\r\n",
  2822. &out);
  2823. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2824. }
  2825. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2826. test_raw_request("GET /hi HTTP/1.1\r\n"
  2827. "Content-Type: text/plain\r\n\r");
  2828. }
  2829. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  2830. std::string out;
  2831. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  2832. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2833. }
  2834. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2835. Server svr;
  2836. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2837. res.set_header("Cache-Control", "no-cache");
  2838. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2839. DataSink &sink) {
  2840. char buffer[27];
  2841. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2842. sink.write(buffer, size);
  2843. std::this_thread::sleep_for(std::chrono::seconds(1));
  2844. return true;
  2845. });
  2846. });
  2847. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2848. while (!svr.is_running()) {
  2849. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2850. }
  2851. Client client(HOST, PORT);
  2852. const Headers headers = {{"Accept", "text/event-stream"}};
  2853. auto get_thread = std::thread([&client, &headers]() {
  2854. auto res = client.Get(
  2855. "/events", headers,
  2856. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2857. });
  2858. // Give GET time to get a few messages.
  2859. std::this_thread::sleep_for(std::chrono::seconds(2));
  2860. svr.stop();
  2861. listen_thread.join();
  2862. get_thread.join();
  2863. ASSERT_FALSE(svr.is_running());
  2864. }
  2865. TEST(StreamingTest, NoContentLengthStreaming) {
  2866. Server svr;
  2867. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  2868. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  2869. if (offset < 6) {
  2870. sink.os << (offset < 3 ? "a" : "b");
  2871. } else {
  2872. sink.done();
  2873. }
  2874. return true;
  2875. });
  2876. });
  2877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2878. while (!svr.is_running()) {
  2879. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2880. }
  2881. Client client(HOST, PORT);
  2882. auto get_thread = std::thread([&client]() {
  2883. auto res = client.Get("/stream", [](const char *data, size_t len) -> bool {
  2884. EXPECT_EQ("aaabbb", std::string(data, len));
  2885. return true;
  2886. });
  2887. });
  2888. // Give GET time to get a few messages.
  2889. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2890. svr.stop();
  2891. listen_thread.join();
  2892. get_thread.join();
  2893. ASSERT_FALSE(svr.is_running());
  2894. }
  2895. TEST(MountTest, Unmount) {
  2896. Server svr;
  2897. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2898. while (!svr.is_running()) {
  2899. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2900. }
  2901. // Give GET time to get a few messages.
  2902. std::this_thread::sleep_for(std::chrono::seconds(1));
  2903. Client cli("localhost", PORT);
  2904. svr.set_mount_point("/mount2", "./www2");
  2905. auto res = cli.Get("/");
  2906. ASSERT_TRUE(res);
  2907. EXPECT_EQ(404, res->status);
  2908. res = cli.Get("/mount2/dir/test.html");
  2909. ASSERT_TRUE(res);
  2910. EXPECT_EQ(200, res->status);
  2911. svr.set_mount_point("/", "./www");
  2912. res = cli.Get("/dir/");
  2913. ASSERT_TRUE(res);
  2914. EXPECT_EQ(200, res->status);
  2915. svr.remove_mount_point("/");
  2916. res = cli.Get("/dir/");
  2917. ASSERT_TRUE(res);
  2918. EXPECT_EQ(404, res->status);
  2919. svr.remove_mount_point("/mount2");
  2920. res = cli.Get("/mount2/dir/test.html");
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(404, res->status);
  2923. svr.stop();
  2924. listen_thread.join();
  2925. ASSERT_FALSE(svr.is_running());
  2926. }
  2927. TEST(ExceptionTest, ThrowExceptionInHandler) {
  2928. Server svr;
  2929. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  2930. throw std::runtime_error("exception...");
  2931. // res.set_content("Hello World!", "text/plain");
  2932. });
  2933. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2934. while (!svr.is_running()) {
  2935. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2936. }
  2937. // Give GET time to get a few messages.
  2938. std::this_thread::sleep_for(std::chrono::seconds(1));
  2939. Client cli("localhost", PORT);
  2940. auto res = cli.Get("/hi");
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(500, res->status);
  2943. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2944. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2945. svr.stop();
  2946. listen_thread.join();
  2947. ASSERT_FALSE(svr.is_running());
  2948. }
  2949. TEST(KeepAliveTest, ReadTimeout) {
  2950. Server svr;
  2951. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2952. std::this_thread::sleep_for(std::chrono::seconds(2));
  2953. res.set_content("a", "text/plain");
  2954. });
  2955. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2956. res.set_content("b", "text/plain");
  2957. });
  2958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2959. while (!svr.is_running()) {
  2960. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2961. }
  2962. // Give GET time to get a few messages.
  2963. std::this_thread::sleep_for(std::chrono::seconds(1));
  2964. Client cli("localhost", PORT);
  2965. cli.set_keep_alive(true);
  2966. cli.set_read_timeout(std::chrono::seconds(1));
  2967. auto resa = cli.Get("/a");
  2968. ASSERT_TRUE(!resa);
  2969. EXPECT_EQ(Error::Read, resa.error());
  2970. auto resb = cli.Get("/b");
  2971. ASSERT_TRUE(resb);
  2972. EXPECT_EQ(200, resb->status);
  2973. EXPECT_EQ("b", resb->body);
  2974. svr.stop();
  2975. listen_thread.join();
  2976. ASSERT_FALSE(svr.is_running());
  2977. }
  2978. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  2979. Server svr;
  2980. svr.set_error_handler([](Request const &, Response &res) -> void {
  2981. res.set_chunked_content_provider(
  2982. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  2983. sink.os << "hello";
  2984. sink.os << "world";
  2985. sink.done();
  2986. return true;
  2987. });
  2988. });
  2989. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2990. while (!svr.is_running()) {
  2991. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2992. }
  2993. // Give GET time to get a few messages.
  2994. std::this_thread::sleep_for(std::chrono::seconds(1));
  2995. Client cli("localhost", PORT);
  2996. auto res = cli.Get("/");
  2997. ASSERT_TRUE(res);
  2998. EXPECT_EQ(404, res->status);
  2999. EXPECT_EQ("helloworld", res->body);
  3000. svr.stop();
  3001. listen_thread.join();
  3002. ASSERT_FALSE(svr.is_running());
  3003. }
  3004. TEST(GetWithParametersTest, GetWithParameters) {
  3005. Server svr;
  3006. svr.Get("/", [&](const Request & req, Response &res) {
  3007. auto text = req.get_param_value("hello");
  3008. res.set_content(text, "text/plain");
  3009. });
  3010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3011. while (!svr.is_running()) {
  3012. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3013. }
  3014. std::this_thread::sleep_for(std::chrono::seconds(1));
  3015. Client cli("localhost", PORT);
  3016. Params params;
  3017. params.emplace("hello", "world");
  3018. auto res = cli.Get("/", params, Headers{});
  3019. ASSERT_TRUE(res);
  3020. EXPECT_EQ(200, res->status);
  3021. EXPECT_EQ("world", res->body);
  3022. svr.stop();
  3023. listen_thread.join();
  3024. ASSERT_FALSE(svr.is_running());
  3025. }
  3026. TEST(GetWithParametersTest, GetWithParameters2) {
  3027. Server svr;
  3028. svr.Get("/", [&](const Request & req, Response &res) {
  3029. auto text = req.get_param_value("hello");
  3030. res.set_content(text, "text/plain");
  3031. });
  3032. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3033. while (!svr.is_running()) {
  3034. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3035. }
  3036. std::this_thread::sleep_for(std::chrono::seconds(1));
  3037. Client cli("localhost", PORT);
  3038. Params params;
  3039. params.emplace("hello", "world");
  3040. std::string body;
  3041. auto res = cli.Get("/", params, Headers{}, [&](const char *data, size_t data_length) {
  3042. body.append(data, data_length);
  3043. return true;
  3044. });
  3045. ASSERT_TRUE(res);
  3046. EXPECT_EQ(200, res->status);
  3047. EXPECT_EQ("world", body);
  3048. svr.stop();
  3049. listen_thread.join();
  3050. ASSERT_FALSE(svr.is_running());
  3051. }
  3052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3053. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3054. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3055. ASSERT_TRUE(svr.is_valid());
  3056. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3057. std::this_thread::sleep_for(std::chrono::seconds(2));
  3058. res.set_content("a", "text/plain");
  3059. });
  3060. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3061. res.set_content("b", "text/plain");
  3062. });
  3063. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3064. while (!svr.is_running()) {
  3065. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3066. }
  3067. // Give GET time to get a few messages.
  3068. std::this_thread::sleep_for(std::chrono::seconds(1));
  3069. SSLClient cli("localhost", PORT);
  3070. cli.enable_server_certificate_verification(false);
  3071. cli.set_keep_alive(true);
  3072. cli.set_read_timeout(std::chrono::seconds(1));
  3073. auto resa = cli.Get("/a");
  3074. ASSERT_TRUE(!resa);
  3075. EXPECT_EQ(Error::Read, resa.error());
  3076. auto resb = cli.Get("/b");
  3077. ASSERT_TRUE(resb);
  3078. EXPECT_EQ(200, resb->status);
  3079. EXPECT_EQ("b", resb->body);
  3080. svr.stop();
  3081. listen_thread.join();
  3082. ASSERT_FALSE(svr.is_running());
  3083. }
  3084. #endif
  3085. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3086. protected:
  3087. ServerTestWithAI_PASSIVE()
  3088. : cli_(HOST, PORT)
  3089. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3090. ,
  3091. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3092. #endif
  3093. {
  3094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3095. cli_.enable_server_certificate_verification(false);
  3096. #endif
  3097. }
  3098. virtual void SetUp() {
  3099. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3100. res.set_content("Hello World!", "text/plain");
  3101. });
  3102. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  3103. while (!svr_.is_running()) {
  3104. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3105. }
  3106. }
  3107. virtual void TearDown() {
  3108. svr_.stop();
  3109. t_.join();
  3110. }
  3111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3112. SSLClient cli_;
  3113. SSLServer svr_;
  3114. #else
  3115. Client cli_;
  3116. Server svr_;
  3117. #endif
  3118. thread t_;
  3119. };
  3120. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3121. auto res = cli_.Get("/hi");
  3122. ASSERT_TRUE(res);
  3123. EXPECT_EQ(200, res->status);
  3124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3125. EXPECT_EQ("Hello World!", res->body);
  3126. }
  3127. class ServerUpDownTest : public ::testing::Test {
  3128. protected:
  3129. ServerUpDownTest() : cli_(HOST, PORT) {}
  3130. virtual void SetUp() {
  3131. t_ = thread([&]() {
  3132. svr_.bind_to_any_port(HOST);
  3133. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3134. ASSERT_TRUE(svr_.listen_after_bind());
  3135. });
  3136. while (!svr_.is_running()) {
  3137. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3138. }
  3139. }
  3140. virtual void TearDown() {
  3141. svr_.stop();
  3142. t_.join();
  3143. }
  3144. Client cli_;
  3145. Server svr_;
  3146. thread t_;
  3147. };
  3148. TEST_F(ServerUpDownTest, QuickStartStop) {
  3149. // Should not crash, especially when run with
  3150. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3151. }
  3152. class PayloadMaxLengthTest : public ::testing::Test {
  3153. protected:
  3154. PayloadMaxLengthTest()
  3155. : cli_(HOST, PORT)
  3156. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3157. ,
  3158. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3159. #endif
  3160. {
  3161. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3162. cli_.enable_server_certificate_verification(false);
  3163. #endif
  3164. }
  3165. virtual void SetUp() {
  3166. svr_.set_payload_max_length(8);
  3167. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3168. res.set_content("test", "text/plain");
  3169. });
  3170. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3171. while (!svr_.is_running()) {
  3172. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3173. }
  3174. }
  3175. virtual void TearDown() {
  3176. svr_.stop();
  3177. t_.join();
  3178. }
  3179. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3180. SSLClient cli_;
  3181. SSLServer svr_;
  3182. #else
  3183. Client cli_;
  3184. Server svr_;
  3185. #endif
  3186. thread t_;
  3187. };
  3188. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3189. auto res = cli_.Post("/test", "123456789", "text/plain");
  3190. ASSERT_TRUE(res);
  3191. EXPECT_EQ(413, res->status);
  3192. res = cli_.Post("/test", "12345678", "text/plain");
  3193. ASSERT_TRUE(res);
  3194. EXPECT_EQ(200, res->status);
  3195. }
  3196. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3197. TEST(SSLClientTest, UpdateCAStore) {
  3198. httplib::SSLClient httplib_client("www.google.com");
  3199. auto ca_store_1 = X509_STORE_new();
  3200. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3201. nullptr);
  3202. httplib_client.set_ca_cert_store(ca_store_1);
  3203. auto ca_store_2 = X509_STORE_new();
  3204. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3205. nullptr);
  3206. httplib_client.set_ca_cert_store(ca_store_2);
  3207. }
  3208. TEST(SSLClientTest, ServerNameIndication) {
  3209. SSLClient cli("httpbin.org", 443);
  3210. auto res = cli.Get("/get");
  3211. ASSERT_TRUE(res);
  3212. ASSERT_EQ(200, res->status);
  3213. }
  3214. TEST(SSLClientTest, ServerCertificateVerification1) {
  3215. SSLClient cli("google.com");
  3216. auto res = cli.Get("/");
  3217. ASSERT_TRUE(res);
  3218. ASSERT_EQ(301, res->status);
  3219. }
  3220. TEST(SSLClientTest, ServerCertificateVerification2) {
  3221. SSLClient cli("google.com");
  3222. cli.enable_server_certificate_verification(true);
  3223. cli.set_ca_cert_path("hello");
  3224. auto res = cli.Get("/");
  3225. ASSERT_TRUE(!res);
  3226. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3227. }
  3228. TEST(SSLClientTest, ServerCertificateVerification3) {
  3229. SSLClient cli("google.com");
  3230. cli.set_ca_cert_path(CA_CERT_FILE);
  3231. auto res = cli.Get("/");
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(301, res->status);
  3234. }
  3235. TEST(SSLClientTest, ServerCertificateVerification4) {
  3236. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3237. ASSERT_TRUE(svr.is_valid());
  3238. svr.Get("/test", [&](const Request &, Response &res) {
  3239. res.set_content("test", "text/plain");
  3240. svr.stop();
  3241. ASSERT_TRUE(true);
  3242. });
  3243. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3244. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3245. SSLClient cli("127.0.0.1", PORT);
  3246. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3247. cli.enable_server_certificate_verification(true);
  3248. cli.set_connection_timeout(30);
  3249. auto res = cli.Get("/test");
  3250. ASSERT_TRUE(res);
  3251. ASSERT_EQ(200, res->status);
  3252. t.join();
  3253. }
  3254. TEST(SSLClientTest, WildcardHostNameMatch) {
  3255. SSLClient cli("www.youtube.com");
  3256. cli.set_ca_cert_path(CA_CERT_FILE);
  3257. cli.enable_server_certificate_verification(true);
  3258. auto res = cli.Get("/");
  3259. ASSERT_TRUE(res);
  3260. ASSERT_EQ(200, res->status);
  3261. }
  3262. TEST(SSLClientServerTest, ClientCertPresent) {
  3263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3264. CLIENT_CA_CERT_DIR);
  3265. ASSERT_TRUE(svr.is_valid());
  3266. svr.Get("/test", [&](const Request &req, Response &res) {
  3267. res.set_content("test", "text/plain");
  3268. svr.stop();
  3269. ASSERT_TRUE(true);
  3270. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3271. ASSERT_TRUE(peer_cert != nullptr);
  3272. auto subject_name = X509_get_subject_name(peer_cert);
  3273. ASSERT_TRUE(subject_name != nullptr);
  3274. std::string common_name;
  3275. {
  3276. char name[BUFSIZ];
  3277. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3278. name, sizeof(name));
  3279. common_name.assign(name, static_cast<size_t>(name_len));
  3280. }
  3281. EXPECT_EQ("Common Name", common_name);
  3282. X509_free(peer_cert);
  3283. });
  3284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3285. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3286. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3287. cli.enable_server_certificate_verification(false);
  3288. cli.set_connection_timeout(30);
  3289. auto res = cli.Get("/test");
  3290. ASSERT_TRUE(res);
  3291. ASSERT_EQ(200, res->status);
  3292. t.join();
  3293. }
  3294. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3295. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3296. X509 *server_cert;
  3297. EVP_PKEY *server_private_key;
  3298. X509_STORE *client_ca_cert_store;
  3299. X509 *client_cert;
  3300. EVP_PKEY *client_private_key;
  3301. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3302. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3303. fclose(f);
  3304. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3305. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3306. fclose(f);
  3307. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3308. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3309. client_ca_cert_store = X509_STORE_new();
  3310. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3311. X509_free(client_cert);
  3312. fclose(f);
  3313. f = fopen(CLIENT_CERT_FILE, "r+");
  3314. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3315. fclose(f);
  3316. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3317. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3318. fclose(f);
  3319. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3320. ASSERT_TRUE(svr.is_valid());
  3321. svr.Get("/test", [&](const Request &req, Response &res) {
  3322. res.set_content("test", "text/plain");
  3323. svr.stop();
  3324. ASSERT_TRUE(true);
  3325. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3326. ASSERT_TRUE(peer_cert != nullptr);
  3327. auto subject_name = X509_get_subject_name(peer_cert);
  3328. ASSERT_TRUE(subject_name != nullptr);
  3329. std::string common_name;
  3330. {
  3331. char name[BUFSIZ];
  3332. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3333. name, sizeof(name));
  3334. common_name.assign(name, static_cast<size_t>(name_len));
  3335. }
  3336. EXPECT_EQ("Common Name", common_name);
  3337. X509_free(peer_cert);
  3338. });
  3339. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3340. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3341. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3342. cli.enable_server_certificate_verification(false);
  3343. cli.set_connection_timeout(30);
  3344. auto res = cli.Get("/test");
  3345. ASSERT_TRUE(res);
  3346. ASSERT_EQ(200, res->status);
  3347. X509_free(server_cert);
  3348. EVP_PKEY_free(server_private_key);
  3349. X509_free(client_cert);
  3350. EVP_PKEY_free(client_private_key);
  3351. t.join();
  3352. }
  3353. #endif
  3354. TEST(SSLClientServerTest, ClientCertMissing) {
  3355. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3356. CLIENT_CA_CERT_DIR);
  3357. ASSERT_TRUE(svr.is_valid());
  3358. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3359. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3360. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3361. SSLClient cli(HOST, PORT);
  3362. auto res = cli.Get("/test");
  3363. cli.set_connection_timeout(30);
  3364. ASSERT_TRUE(!res);
  3365. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3366. svr.stop();
  3367. t.join();
  3368. }
  3369. TEST(SSLClientServerTest, TrustDirOptional) {
  3370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3371. ASSERT_TRUE(svr.is_valid());
  3372. svr.Get("/test", [&](const Request &, Response &res) {
  3373. res.set_content("test", "text/plain");
  3374. svr.stop();
  3375. });
  3376. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3377. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3378. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3379. cli.enable_server_certificate_verification(false);
  3380. cli.set_connection_timeout(30);
  3381. auto res = cli.Get("/test");
  3382. ASSERT_TRUE(res);
  3383. ASSERT_EQ(200, res->status);
  3384. t.join();
  3385. }
  3386. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3387. class NoListenSSLServer : public SSLServer {
  3388. public:
  3389. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3390. const char *client_ca_cert_file_path,
  3391. const char *client_ca_cert_dir_path = nullptr)
  3392. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3393. client_ca_cert_dir_path),
  3394. stop_(false) {}
  3395. bool stop_;
  3396. private:
  3397. bool process_and_close_socket(socket_t /*sock*/) override {
  3398. // Don't create SSL context
  3399. while (!stop_) {
  3400. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3401. }
  3402. return true;
  3403. }
  3404. };
  3405. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3406. CLIENT_CA_CERT_FILE);
  3407. ASSERT_TRUE(svr.is_valid());
  3408. svr.Get("/test", [&](const Request &, Response &res) {
  3409. res.set_content("test", "text/plain");
  3410. });
  3411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3412. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3413. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3414. cli.enable_server_certificate_verification(false);
  3415. cli.set_connection_timeout(1);
  3416. auto res = cli.Get("/test");
  3417. ASSERT_TRUE(!res);
  3418. EXPECT_EQ(Error::SSLConnection, res.error());
  3419. svr.stop_ = true;
  3420. svr.stop();
  3421. t.join();
  3422. }
  3423. #endif
  3424. #ifdef _WIN32
  3425. TEST(CleanupTest, WSACleanup) {
  3426. int ret = WSACleanup();
  3427. ASSERT_EQ(0, ret);
  3428. }
  3429. #endif
  3430. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3431. TEST(NoSSLSupport, SimpleInterface) {
  3432. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3433. }
  3434. #endif
  3435. TEST(InvalidScheme, SimpleInterface) {
  3436. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3437. }
  3438. TEST(NoScheme, SimpleInterface) {
  3439. Client cli("yahoo.com:80");
  3440. ASSERT_TRUE(cli.is_valid());
  3441. }
  3442. TEST(SendAPI, SimpleInterface) {
  3443. Client cli("http://yahoo.com");
  3444. Request req;
  3445. req.method = "GET";
  3446. req.path = "/";
  3447. auto res = cli.send(req);
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(301, res->status);
  3450. }
  3451. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3452. TEST(YahooRedirectTest2, SimpleInterface) {
  3453. Client cli("http://yahoo.com");
  3454. auto res = cli.Get("/");
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(301, res->status);
  3457. cli.set_follow_location(true);
  3458. res = cli.Get("/");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(200, res->status);
  3461. EXPECT_EQ("https://yahoo.com/", res->location);
  3462. }
  3463. TEST(YahooRedirectTest3, SimpleInterface) {
  3464. Client cli("https://yahoo.com");
  3465. auto res = cli.Get("/");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(301, res->status);
  3468. cli.set_follow_location(true);
  3469. res = cli.Get("/");
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(200, res->status);
  3472. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3473. }
  3474. TEST(YahooRedirectTest3, NewResultInterface) {
  3475. Client cli("https://yahoo.com");
  3476. auto res = cli.Get("/");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_FALSE(!res);
  3479. ASSERT_TRUE(res);
  3480. ASSERT_FALSE(res == nullptr);
  3481. ASSERT_TRUE(res != nullptr);
  3482. EXPECT_EQ(Error::Success, res.error());
  3483. EXPECT_EQ(301, res.value().status);
  3484. EXPECT_EQ(301, (*res).status);
  3485. EXPECT_EQ(301, res->status);
  3486. cli.set_follow_location(true);
  3487. res = cli.Get("/");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(Error::Success, res.error());
  3490. EXPECT_EQ(200, res.value().status);
  3491. EXPECT_EQ(200, (*res).status);
  3492. EXPECT_EQ(200, res->status);
  3493. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3494. }
  3495. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3496. TEST(DecodeWithChunkedEncoding, BrotliEncoding) {
  3497. Client cli("https://cdnjs.cloudflare.com");
  3498. auto res =
  3499. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3500. ASSERT_TRUE(res);
  3501. EXPECT_EQ(200, res->status);
  3502. EXPECT_EQ(287630, res->body.size());
  3503. EXPECT_EQ("application/javascript; charset=utf-8",
  3504. res->get_header_value("Content-Type"));
  3505. }
  3506. #endif
  3507. TEST(HttpsToHttpRedirectTest, SimpleInterface) {
  3508. Client cli("https://nghttp2.org");
  3509. cli.set_follow_location(true);
  3510. auto res =
  3511. cli.Get("/httpbin/"
  3512. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(200, res->status);
  3515. }
  3516. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  3517. Client cli("https://nghttp2.org");
  3518. cli.set_follow_location(true);
  3519. Params params;
  3520. params.emplace("url", "http://www.google.com");
  3521. params.emplace("status_code", "302");
  3522. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(200, res->status);
  3525. }
  3526. TEST(HttpsToHttpRedirectTest3, SimpleInterface) {
  3527. Client cli("https://nghttp2.org");
  3528. cli.set_follow_location(true);
  3529. Params params;
  3530. params.emplace("url", "http://www.google.com");
  3531. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(200, res->status);
  3534. }
  3535. #endif