test.cc 116 KB

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