test.cc 125 KB

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