test.cc 101 KB

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