test.cc 111 KB

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