test.cc 100 KB

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