test.cc 110 KB

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