test.cc 126 KB

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