test.cc 105 KB

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