test.cc 128 KB

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