test.cc 110 KB

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