test.cc 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992
  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(NoContentTest, ContentLength) {
  780. Server svr;
  781. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  782. res.status = 204;
  783. });
  784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  785. // Give GET time to get a few messages.
  786. std::this_thread::sleep_for(std::chrono::seconds(1));
  787. {
  788. Client cli(HOST, PORT);
  789. auto res = cli.Get("/hi");
  790. ASSERT_TRUE(res);
  791. EXPECT_EQ(204, res->status);
  792. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  793. }
  794. svr.stop();
  795. thread.join();
  796. ASSERT_FALSE(svr.is_running());
  797. }
  798. TEST(RoutingHandlerTest, PreRoutingHandler) {
  799. Server svr;
  800. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  801. if (req.path == "/routing_handler") {
  802. res.set_header("PRE_ROUTING", "on");
  803. res.set_content("Routing Handler", "text/plain");
  804. return true;
  805. }
  806. return false;
  807. });
  808. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  809. res.set_content("Error", "text/html");
  810. });
  811. svr.set_post_routing_handler([](const Request &req, Response &res) {
  812. if (req.path == "/routing_handler") {
  813. res.set_header("POST_ROUTING", "on");
  814. }
  815. });
  816. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  817. res.set_content("Hello World!\n", "text/plain");
  818. });
  819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  820. // Give GET time to get a few messages.
  821. std::this_thread::sleep_for(std::chrono::seconds(1));
  822. {
  823. Client cli(HOST, PORT);
  824. auto res = cli.Get("/routing_handler");
  825. ASSERT_TRUE(res);
  826. EXPECT_EQ(200, res->status);
  827. EXPECT_EQ("Routing Handler", res->body);
  828. EXPECT_EQ(1, res->get_header_value_count("PRE_ROUTING"));
  829. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  830. EXPECT_EQ(1, res->get_header_value_count("POST_ROUTING"));
  831. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  832. }
  833. {
  834. Client cli(HOST, PORT);
  835. auto res = cli.Get("/hi");
  836. ASSERT_TRUE(res);
  837. EXPECT_EQ(200, res->status);
  838. EXPECT_EQ("Hello World!\n", res->body);
  839. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  840. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  841. }
  842. {
  843. Client cli(HOST, PORT);
  844. auto res = cli.Get("/aaa");
  845. ASSERT_TRUE(res);
  846. EXPECT_EQ(404, res->status);
  847. EXPECT_EQ("Error", res->body);
  848. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  849. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  850. }
  851. svr.stop();
  852. thread.join();
  853. ASSERT_FALSE(svr.is_running());
  854. }
  855. TEST(InvalidFormatTest, StatusCode) {
  856. Server svr;
  857. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  858. res.set_content("Hello World!\n", "text/plain");
  859. res.status = 9999; // Status should be a three-digit code...
  860. });
  861. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  862. // Give GET time to get a few messages.
  863. std::this_thread::sleep_for(std::chrono::seconds(1));
  864. {
  865. Client cli(HOST, PORT);
  866. auto res = cli.Get("/hi");
  867. ASSERT_FALSE(res);
  868. }
  869. svr.stop();
  870. thread.join();
  871. ASSERT_FALSE(svr.is_running());
  872. }
  873. class ServerTest : public ::testing::Test {
  874. protected:
  875. ServerTest()
  876. : cli_(HOST, PORT)
  877. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  878. ,
  879. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  880. #endif
  881. {
  882. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  883. cli_.enable_server_certificate_verification(false);
  884. #endif
  885. }
  886. virtual void SetUp() {
  887. svr_.set_mount_point("/", "./www");
  888. svr_.set_mount_point("/mount", "./www2");
  889. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  890. svr_.Get("/hi",
  891. [&](const Request & /*req*/, Response &res) {
  892. res.set_content("Hello World!", "text/plain");
  893. })
  894. .Get("/http_response_splitting",
  895. [&](const Request & /*req*/, Response &res) {
  896. res.set_header("a", "1\r\nSet-Cookie: a=1");
  897. EXPECT_EQ(0, res.headers.size());
  898. EXPECT_FALSE(res.has_header("a"));
  899. res.set_header("a", "1\nSet-Cookie: a=1");
  900. EXPECT_EQ(0, res.headers.size());
  901. EXPECT_FALSE(res.has_header("a"));
  902. res.set_header("a", "1\rSet-Cookie: a=1");
  903. EXPECT_EQ(0, res.headers.size());
  904. EXPECT_FALSE(res.has_header("a"));
  905. res.set_header("a\r\nb", "0");
  906. EXPECT_EQ(0, res.headers.size());
  907. EXPECT_FALSE(res.has_header("a"));
  908. res.set_header("a\rb", "0");
  909. EXPECT_EQ(0, res.headers.size());
  910. EXPECT_FALSE(res.has_header("a"));
  911. res.set_header("a\nb", "0");
  912. EXPECT_EQ(0, res.headers.size());
  913. EXPECT_FALSE(res.has_header("a"));
  914. res.set_redirect("1\r\nSet-Cookie: a=1");
  915. EXPECT_EQ(0, res.headers.size());
  916. EXPECT_FALSE(res.has_header("Location"));
  917. })
  918. .Get("/slow",
  919. [&](const Request & /*req*/, Response &res) {
  920. std::this_thread::sleep_for(std::chrono::seconds(2));
  921. res.set_content("slow", "text/plain");
  922. })
  923. .Post("/slowpost",
  924. [&](const Request & /*req*/, Response &res) {
  925. std::this_thread::sleep_for(std::chrono::seconds(2));
  926. res.set_content("slow", "text/plain");
  927. })
  928. .Get("/remote_addr",
  929. [&](const Request &req, Response &res) {
  930. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  931. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  932. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  933. EXPECT_EQ(req.remote_port,
  934. std::stoi(req.get_header_value("REMOTE_PORT")));
  935. res.set_content(remote_addr.c_str(), "text/plain");
  936. })
  937. .Get("/endwith%",
  938. [&](const Request & /*req*/, Response &res) {
  939. res.set_content("Hello World!", "text/plain");
  940. })
  941. .Get("/a\\+\\+b",
  942. [&](const Request &req, Response &res) {
  943. ASSERT_TRUE(req.has_param("a +b"));
  944. auto val = req.get_param_value("a +b");
  945. res.set_content(val, "text/plain");
  946. })
  947. .Get("/", [&](const Request & /*req*/,
  948. Response &res) { res.set_redirect("/hi"); })
  949. .Post("/1", [](const Request & /*req*/,
  950. Response &res) { res.set_redirect("/2", 303); })
  951. .Get("/2",
  952. [](const Request & /*req*/, Response &res) {
  953. res.set_content("redirected.", "text/plain");
  954. res.status = 200;
  955. })
  956. .Post("/person",
  957. [&](const Request &req, Response &res) {
  958. if (req.has_param("name") && req.has_param("note")) {
  959. persons_[req.get_param_value("name")] =
  960. req.get_param_value("note");
  961. } else {
  962. res.status = 400;
  963. }
  964. })
  965. .Put("/person",
  966. [&](const Request &req, Response &res) {
  967. if (req.has_param("name") && req.has_param("note")) {
  968. persons_[req.get_param_value("name")] =
  969. req.get_param_value("note");
  970. } else {
  971. res.status = 400;
  972. }
  973. })
  974. .Get("/person/(.*)",
  975. [&](const Request &req, Response &res) {
  976. string name = req.matches[1];
  977. if (persons_.find(name) != persons_.end()) {
  978. auto note = persons_[name];
  979. res.set_content(note, "text/plain");
  980. } else {
  981. res.status = 404;
  982. }
  983. })
  984. .Post("/x-www-form-urlencoded-json",
  985. [&](const Request &req, Response &res) {
  986. auto json = req.get_param_value("json");
  987. ASSERT_EQ(JSON_DATA, json);
  988. res.set_content(json, "appliation/json");
  989. res.status = 200;
  990. })
  991. .Get("/streamed-chunked",
  992. [&](const Request & /*req*/, Response &res) {
  993. res.set_chunked_content_provider(
  994. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  995. EXPECT_TRUE(sink.is_writable());
  996. sink.os << "123";
  997. sink.os << "456";
  998. sink.os << "789";
  999. sink.done();
  1000. return true;
  1001. });
  1002. })
  1003. .Get("/streamed-chunked2",
  1004. [&](const Request & /*req*/, Response &res) {
  1005. auto i = new int(0);
  1006. res.set_chunked_content_provider(
  1007. "text/plain",
  1008. [i](size_t /*offset*/, DataSink &sink) {
  1009. EXPECT_TRUE(sink.is_writable());
  1010. switch (*i) {
  1011. case 0: sink.os << "123"; break;
  1012. case 1: sink.os << "456"; break;
  1013. case 2: sink.os << "789"; break;
  1014. case 3: sink.done(); break;
  1015. }
  1016. (*i)++;
  1017. return true;
  1018. },
  1019. [i] { delete i; });
  1020. })
  1021. .Get("/streamed",
  1022. [&](const Request & /*req*/, Response &res) {
  1023. res.set_content_provider(
  1024. 6, "text/plain",
  1025. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1026. sink.os << (offset < 3 ? "a" : "b");
  1027. return true;
  1028. });
  1029. })
  1030. .Get("/streamed-with-range",
  1031. [&](const Request & /*req*/, Response &res) {
  1032. auto data = new std::string("abcdefg");
  1033. res.set_content_provider(
  1034. data->size(), "text/plain",
  1035. [data](size_t offset, size_t length, DataSink &sink) {
  1036. EXPECT_TRUE(sink.is_writable());
  1037. size_t DATA_CHUNK_SIZE = 4;
  1038. const auto &d = *data;
  1039. auto out_len =
  1040. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1041. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1042. return true;
  1043. },
  1044. [data] { delete data; });
  1045. })
  1046. .Get("/streamed-cancel",
  1047. [&](const Request & /*req*/, Response &res) {
  1048. res.set_content_provider(
  1049. size_t(-1), "text/plain",
  1050. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1051. EXPECT_TRUE(sink.is_writable());
  1052. sink.os << "data_chunk";
  1053. return true;
  1054. });
  1055. })
  1056. .Get("/with-range",
  1057. [&](const Request & /*req*/, Response &res) {
  1058. res.set_content("abcdefg", "text/plain");
  1059. })
  1060. .Post("/chunked",
  1061. [&](const Request &req, Response & /*res*/) {
  1062. EXPECT_EQ(req.body, "dechunked post body");
  1063. })
  1064. .Post("/large-chunked",
  1065. [&](const Request &req, Response & /*res*/) {
  1066. std::string expected(6 * 30 * 1024u, 'a');
  1067. EXPECT_EQ(req.body, expected);
  1068. })
  1069. .Post("/multipart",
  1070. [&](const Request &req, Response & /*res*/) {
  1071. EXPECT_EQ(6u, req.files.size());
  1072. ASSERT_TRUE(!req.has_file("???"));
  1073. ASSERT_TRUE(req.body.empty());
  1074. {
  1075. const auto &file = req.get_file_value("text1");
  1076. EXPECT_TRUE(file.filename.empty());
  1077. EXPECT_EQ("text default", file.content);
  1078. }
  1079. {
  1080. const auto &file = req.get_file_value("text2");
  1081. EXPECT_TRUE(file.filename.empty());
  1082. EXPECT_EQ("aωb", file.content);
  1083. }
  1084. {
  1085. const auto &file = req.get_file_value("file1");
  1086. EXPECT_EQ("hello.txt", file.filename);
  1087. EXPECT_EQ("text/plain", file.content_type);
  1088. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1089. }
  1090. {
  1091. const auto &file = req.get_file_value("file3");
  1092. EXPECT_TRUE(file.filename.empty());
  1093. EXPECT_EQ("application/octet-stream", file.content_type);
  1094. EXPECT_EQ(0u, file.content.size());
  1095. }
  1096. {
  1097. const auto &file = req.get_file_value("file4");
  1098. EXPECT_TRUE(file.filename.empty());
  1099. EXPECT_EQ(0u, file.content.size());
  1100. EXPECT_EQ("application/json tmp-string", file.content_type);
  1101. }
  1102. })
  1103. .Post("/empty",
  1104. [&](const Request &req, Response &res) {
  1105. EXPECT_EQ(req.body, "");
  1106. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1107. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1108. res.set_content("empty", "text/plain");
  1109. })
  1110. .Post("/empty-no-content-type",
  1111. [&](const Request &req, Response &res) {
  1112. EXPECT_EQ(req.body, "");
  1113. EXPECT_FALSE(req.has_header("Content-Type"));
  1114. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1115. res.set_content("empty-no-content-type", "text/plain");
  1116. })
  1117. .Put("/empty-no-content-type",
  1118. [&](const Request &req, Response &res) {
  1119. EXPECT_EQ(req.body, "");
  1120. EXPECT_FALSE(req.has_header("Content-Type"));
  1121. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1122. res.set_content("empty-no-content-type", "text/plain");
  1123. })
  1124. .Put("/put",
  1125. [&](const Request &req, Response &res) {
  1126. EXPECT_EQ(req.body, "PUT");
  1127. res.set_content(req.body, "text/plain");
  1128. })
  1129. .Put("/put-large",
  1130. [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.body, LARGE_DATA);
  1132. res.set_content(req.body, "text/plain");
  1133. })
  1134. .Patch("/patch",
  1135. [&](const Request &req, Response &res) {
  1136. EXPECT_EQ(req.body, "PATCH");
  1137. res.set_content(req.body, "text/plain");
  1138. })
  1139. .Delete("/delete",
  1140. [&](const Request & /*req*/, Response &res) {
  1141. res.set_content("DELETE", "text/plain");
  1142. })
  1143. .Delete("/delete-body",
  1144. [&](const Request &req, Response &res) {
  1145. EXPECT_EQ(req.body, "content");
  1146. res.set_content(req.body, "text/plain");
  1147. })
  1148. .Options(R"(\*)",
  1149. [&](const Request & /*req*/, Response &res) {
  1150. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1151. })
  1152. .Get("/request-target",
  1153. [&](const Request &req, Response & /*res*/) {
  1154. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1155. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1156. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1157. })
  1158. .Get("/long-query-value",
  1159. [&](const Request &req, Response & /*res*/) {
  1160. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1161. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1162. })
  1163. .Get("/array-param",
  1164. [&](const Request &req, Response & /*res*/) {
  1165. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1166. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1167. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1168. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1169. })
  1170. .Post("/validate-no-multiple-headers",
  1171. [&](const Request &req, Response & /*res*/) {
  1172. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1173. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1174. })
  1175. .Post("/content_receiver",
  1176. [&](const Request &req, Response &res,
  1177. const ContentReader &content_reader) {
  1178. if (req.is_multipart_form_data()) {
  1179. MultipartFormDataItems files;
  1180. content_reader(
  1181. [&](const MultipartFormData &file) {
  1182. files.push_back(file);
  1183. return true;
  1184. },
  1185. [&](const char *data, size_t data_length) {
  1186. files.back().content.append(data, data_length);
  1187. return true;
  1188. });
  1189. EXPECT_EQ(5u, files.size());
  1190. {
  1191. const auto &file = get_file_value(files, "text1");
  1192. EXPECT_TRUE(file.filename.empty());
  1193. EXPECT_EQ("text default", file.content);
  1194. }
  1195. {
  1196. const auto &file = get_file_value(files, "text2");
  1197. EXPECT_TRUE(file.filename.empty());
  1198. EXPECT_EQ("aωb", file.content);
  1199. }
  1200. {
  1201. const auto &file = get_file_value(files, "file1");
  1202. EXPECT_EQ("hello.txt", file.filename);
  1203. EXPECT_EQ("text/plain", file.content_type);
  1204. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1205. }
  1206. {
  1207. const auto &file = get_file_value(files, "file3");
  1208. EXPECT_TRUE(file.filename.empty());
  1209. EXPECT_EQ("application/octet-stream", file.content_type);
  1210. EXPECT_EQ(0u, file.content.size());
  1211. }
  1212. } else {
  1213. std::string body;
  1214. content_reader([&](const char *data, size_t data_length) {
  1215. EXPECT_EQ(data_length, 7);
  1216. body.append(data, data_length);
  1217. return true;
  1218. });
  1219. EXPECT_EQ(body, "content");
  1220. res.set_content(body, "text/plain");
  1221. }
  1222. })
  1223. .Put("/content_receiver",
  1224. [&](const Request & /*req*/, Response &res,
  1225. const ContentReader &content_reader) {
  1226. std::string body;
  1227. content_reader([&](const char *data, size_t data_length) {
  1228. body.append(data, data_length);
  1229. return true;
  1230. });
  1231. EXPECT_EQ(body, "content");
  1232. res.set_content(body, "text/plain");
  1233. })
  1234. .Patch("/content_receiver",
  1235. [&](const Request & /*req*/, Response &res,
  1236. const ContentReader &content_reader) {
  1237. std::string body;
  1238. content_reader([&](const char *data, size_t data_length) {
  1239. body.append(data, data_length);
  1240. return true;
  1241. });
  1242. EXPECT_EQ(body, "content");
  1243. res.set_content(body, "text/plain");
  1244. })
  1245. .Post("/query-string-and-body",
  1246. [&](const Request &req, Response & /*res*/) {
  1247. ASSERT_TRUE(req.has_param("key"));
  1248. EXPECT_EQ(req.get_param_value("key"), "value");
  1249. EXPECT_EQ(req.body, "content");
  1250. })
  1251. .Get("/last-request",
  1252. [&](const Request &req, Response & /*res*/) {
  1253. EXPECT_EQ("close", req.get_header_value("Connection"));
  1254. })
  1255. .Get(R"(/redirect/(\d+))",
  1256. [&](const Request &req, Response &res) {
  1257. auto num = std::stoi(req.matches[1]) + 1;
  1258. std::string url = "/redirect/" + std::to_string(num);
  1259. res.set_redirect(url);
  1260. })
  1261. .Post("/binary",
  1262. [&](const Request &req, Response &res) {
  1263. EXPECT_EQ(4, req.body.size());
  1264. EXPECT_EQ("application/octet-stream",
  1265. req.get_header_value("Content-Type"));
  1266. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1267. res.set_content(req.body, "application/octet-stream");
  1268. })
  1269. .Put("/binary",
  1270. [&](const Request &req, Response &res) {
  1271. EXPECT_EQ(4, req.body.size());
  1272. EXPECT_EQ("application/octet-stream",
  1273. req.get_header_value("Content-Type"));
  1274. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1275. res.set_content(req.body, "application/octet-stream");
  1276. })
  1277. .Patch("/binary",
  1278. [&](const Request &req, Response &res) {
  1279. EXPECT_EQ(4, req.body.size());
  1280. EXPECT_EQ("application/octet-stream",
  1281. req.get_header_value("Content-Type"));
  1282. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1283. res.set_content(req.body, "application/octet-stream");
  1284. })
  1285. .Delete("/binary",
  1286. [&](const Request &req, Response &res) {
  1287. EXPECT_EQ(4, req.body.size());
  1288. EXPECT_EQ("application/octet-stream",
  1289. req.get_header_value("Content-Type"));
  1290. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1291. res.set_content(req.body, "application/octet-stream");
  1292. })
  1293. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1294. .Get("/compress",
  1295. [&](const Request & /*req*/, Response &res) {
  1296. res.set_content(
  1297. "12345678901234567890123456789012345678901234567890123456789"
  1298. "01234567890123456789012345678901234567890",
  1299. "text/plain");
  1300. })
  1301. .Get("/nocompress",
  1302. [&](const Request & /*req*/, Response &res) {
  1303. res.set_content(
  1304. "12345678901234567890123456789012345678901234567890123456789"
  1305. "01234567890123456789012345678901234567890",
  1306. "application/octet-stream");
  1307. })
  1308. .Post("/compress-multipart",
  1309. [&](const Request &req, Response & /*res*/) {
  1310. EXPECT_EQ(2u, req.files.size());
  1311. ASSERT_TRUE(!req.has_file("???"));
  1312. {
  1313. const auto &file = req.get_file_value("key1");
  1314. EXPECT_TRUE(file.filename.empty());
  1315. EXPECT_EQ("test", file.content);
  1316. }
  1317. {
  1318. const auto &file = req.get_file_value("key2");
  1319. EXPECT_TRUE(file.filename.empty());
  1320. EXPECT_EQ("--abcdefg123", file.content);
  1321. }
  1322. })
  1323. #endif
  1324. ;
  1325. persons_["john"] = "programmer";
  1326. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1327. while (!svr_.is_running()) {
  1328. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1329. }
  1330. }
  1331. virtual void TearDown() {
  1332. svr_.stop();
  1333. if (!request_threads_.empty()) {
  1334. std::this_thread::sleep_for(std::chrono::seconds(1));
  1335. for (auto &t : request_threads_) {
  1336. t.join();
  1337. }
  1338. }
  1339. t_.join();
  1340. }
  1341. map<string, string> persons_;
  1342. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1343. SSLClient cli_;
  1344. SSLServer svr_;
  1345. #else
  1346. Client cli_;
  1347. Server svr_;
  1348. #endif
  1349. thread t_;
  1350. std::vector<thread> request_threads_;
  1351. };
  1352. TEST_F(ServerTest, GetMethod200) {
  1353. auto res = cli_.Get("/hi");
  1354. ASSERT_TRUE(res);
  1355. EXPECT_EQ("HTTP/1.1", res->version);
  1356. EXPECT_EQ(200, res->status);
  1357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1358. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1359. EXPECT_EQ("Hello World!", res->body);
  1360. }
  1361. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1362. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1363. ASSERT_TRUE(res);
  1364. EXPECT_EQ("HTTP/1.1", res->version);
  1365. EXPECT_EQ(200, res->status);
  1366. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1367. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1368. EXPECT_EQ("Hello World!", res->body);
  1369. }
  1370. TEST_F(ServerTest, GetMethod302) {
  1371. auto res = cli_.Get("/");
  1372. ASSERT_TRUE(res);
  1373. EXPECT_EQ(302, res->status);
  1374. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1375. }
  1376. TEST_F(ServerTest, GetMethod302Redirect) {
  1377. cli_.set_follow_location(true);
  1378. auto res = cli_.Get("/");
  1379. ASSERT_TRUE(res);
  1380. EXPECT_EQ(200, res->status);
  1381. EXPECT_EQ("Hello World!", res->body);
  1382. EXPECT_EQ("/hi", res->location);
  1383. }
  1384. TEST_F(ServerTest, GetMethod404) {
  1385. auto res = cli_.Get("/invalid");
  1386. ASSERT_TRUE(res);
  1387. EXPECT_EQ(404, res->status);
  1388. }
  1389. TEST_F(ServerTest, HeadMethod200) {
  1390. auto res = cli_.Head("/hi");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ(200, res->status);
  1393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1394. EXPECT_TRUE(res->body.empty());
  1395. }
  1396. TEST_F(ServerTest, HeadMethod200Static) {
  1397. auto res = cli_.Head("/mount/dir/index.html");
  1398. ASSERT_TRUE(res);
  1399. EXPECT_EQ(200, res->status);
  1400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1401. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1402. EXPECT_TRUE(res->body.empty());
  1403. }
  1404. TEST_F(ServerTest, HeadMethod404) {
  1405. auto res = cli_.Head("/invalid");
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ(404, res->status);
  1408. EXPECT_TRUE(res->body.empty());
  1409. }
  1410. TEST_F(ServerTest, GetMethodPersonJohn) {
  1411. auto res = cli_.Get("/person/john");
  1412. ASSERT_TRUE(res);
  1413. EXPECT_EQ(200, res->status);
  1414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1415. EXPECT_EQ("programmer", res->body);
  1416. }
  1417. TEST_F(ServerTest, PostMethod1) {
  1418. auto res = cli_.Get("/person/john1");
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(404, res->status);
  1421. res = cli_.Post("/person", "name=john1&note=coder",
  1422. "application/x-www-form-urlencoded");
  1423. ASSERT_TRUE(res);
  1424. ASSERT_EQ(200, res->status);
  1425. res = cli_.Get("/person/john1");
  1426. ASSERT_TRUE(res);
  1427. ASSERT_EQ(200, res->status);
  1428. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1429. ASSERT_EQ("coder", res->body);
  1430. }
  1431. TEST_F(ServerTest, PostMethod2) {
  1432. auto res = cli_.Get("/person/john2");
  1433. ASSERT_TRUE(res);
  1434. ASSERT_EQ(404, res->status);
  1435. Params params;
  1436. params.emplace("name", "john2");
  1437. params.emplace("note", "coder");
  1438. res = cli_.Post("/person", params);
  1439. ASSERT_TRUE(res);
  1440. ASSERT_EQ(200, res->status);
  1441. res = cli_.Get("/person/john2");
  1442. ASSERT_TRUE(res);
  1443. ASSERT_EQ(200, res->status);
  1444. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1445. ASSERT_EQ("coder", res->body);
  1446. }
  1447. TEST_F(ServerTest, PutMethod3) {
  1448. auto res = cli_.Get("/person/john3");
  1449. ASSERT_TRUE(res);
  1450. ASSERT_EQ(404, res->status);
  1451. Params params;
  1452. params.emplace("name", "john3");
  1453. params.emplace("note", "coder");
  1454. res = cli_.Put("/person", params);
  1455. ASSERT_TRUE(res);
  1456. ASSERT_EQ(200, res->status);
  1457. res = cli_.Get("/person/john3");
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(200, res->status);
  1460. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1461. ASSERT_EQ("coder", res->body);
  1462. }
  1463. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1464. Params params;
  1465. params.emplace("json", JSON_DATA);
  1466. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1467. ASSERT_TRUE(res);
  1468. ASSERT_EQ(200, res->status);
  1469. ASSERT_EQ(JSON_DATA, res->body);
  1470. }
  1471. TEST_F(ServerTest, PostEmptyContent) {
  1472. auto res = cli_.Post("/empty", "", "text/plain");
  1473. ASSERT_TRUE(res);
  1474. ASSERT_EQ(200, res->status);
  1475. ASSERT_EQ("empty", res->body);
  1476. }
  1477. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1478. auto res = cli_.Post("/empty-no-content-type");
  1479. ASSERT_TRUE(res);
  1480. ASSERT_EQ(200, res->status);
  1481. ASSERT_EQ("empty-no-content-type", res->body);
  1482. }
  1483. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1484. auto res = cli_.Put("/empty-no-content-type");
  1485. ASSERT_TRUE(res);
  1486. ASSERT_EQ(200, res->status);
  1487. ASSERT_EQ("empty-no-content-type", res->body);
  1488. }
  1489. TEST_F(ServerTest, GetMethodDir) {
  1490. auto res = cli_.Get("/dir/");
  1491. ASSERT_TRUE(res);
  1492. EXPECT_EQ(200, res->status);
  1493. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1494. auto body = R"(<html>
  1495. <head>
  1496. </head>
  1497. <body>
  1498. <a href="/dir/test.html">Test</a>
  1499. <a href="/hi">hi</a>
  1500. </body>
  1501. </html>
  1502. )";
  1503. EXPECT_EQ(body, res->body);
  1504. }
  1505. TEST_F(ServerTest, GetMethodDirTest) {
  1506. auto res = cli_.Get("/dir/test.html");
  1507. ASSERT_TRUE(res);
  1508. EXPECT_EQ(200, res->status);
  1509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1510. EXPECT_EQ("test.html", res->body);
  1511. }
  1512. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1513. auto res = cli_.Get("/dir/../dir/test.html");
  1514. ASSERT_TRUE(res);
  1515. EXPECT_EQ(200, res->status);
  1516. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1517. EXPECT_EQ("test.html", res->body);
  1518. }
  1519. TEST_F(ServerTest, GetMethodInvalidPath) {
  1520. auto res = cli_.Get("/dir/../test.html");
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ(404, res->status);
  1523. }
  1524. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1525. auto res = cli_.Get("/../www/dir/test.html");
  1526. ASSERT_TRUE(res);
  1527. EXPECT_EQ(404, res->status);
  1528. }
  1529. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1530. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1531. ASSERT_TRUE(res);
  1532. EXPECT_EQ(404, res->status);
  1533. }
  1534. TEST_F(ServerTest, GetMethodDirMountTest) {
  1535. auto res = cli_.Get("/mount/dir/test.html");
  1536. ASSERT_TRUE(res);
  1537. EXPECT_EQ(200, res->status);
  1538. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1539. EXPECT_EQ("test.html", res->body);
  1540. }
  1541. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1542. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ(200, res->status);
  1545. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1546. EXPECT_EQ("test.html", res->body);
  1547. }
  1548. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1549. auto res = cli_.Get("/mount/dir/../test.html");
  1550. ASSERT_TRUE(res);
  1551. EXPECT_EQ(404, res->status);
  1552. }
  1553. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1554. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1555. ASSERT_TRUE(res);
  1556. EXPECT_EQ(404, res->status);
  1557. }
  1558. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1559. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1560. ASSERT_TRUE(res);
  1561. EXPECT_EQ(404, res->status);
  1562. }
  1563. TEST_F(ServerTest, PostMethod303) {
  1564. auto res = cli_.Post("/1", "body", "text/plain");
  1565. ASSERT_TRUE(res);
  1566. EXPECT_EQ(303, res->status);
  1567. EXPECT_EQ("/2", res->get_header_value("Location"));
  1568. }
  1569. TEST_F(ServerTest, PostMethod303Redirect) {
  1570. cli_.set_follow_location(true);
  1571. auto res = cli_.Post("/1", "body", "text/plain");
  1572. ASSERT_TRUE(res);
  1573. EXPECT_EQ(200, res->status);
  1574. EXPECT_EQ("redirected.", res->body);
  1575. EXPECT_EQ("/2", res->location);
  1576. }
  1577. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1578. auto res = cli_.Get("/dir/test.abcde");
  1579. ASSERT_TRUE(res);
  1580. EXPECT_EQ(200, res->status);
  1581. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1582. EXPECT_EQ("abcde", res->body);
  1583. }
  1584. TEST_F(ServerTest, StaticFileRange) {
  1585. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1586. ASSERT_TRUE(res);
  1587. EXPECT_EQ(206, res->status);
  1588. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1589. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1590. EXPECT_EQ(true, res->has_header("Content-Range"));
  1591. EXPECT_EQ(std::string("cd"), res->body);
  1592. }
  1593. TEST_F(ServerTest, InvalidBaseDirMount) {
  1594. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1595. }
  1596. TEST_F(ServerTest, Binary) {
  1597. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1598. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1599. "application/octet-stream");
  1600. ASSERT_TRUE(res);
  1601. ASSERT_EQ(200, res->status);
  1602. ASSERT_EQ(4, res->body.size());
  1603. res = cli_.Put("/binary", binary.data(), binary.size(),
  1604. "application/octet-stream");
  1605. ASSERT_TRUE(res);
  1606. ASSERT_EQ(200, res->status);
  1607. ASSERT_EQ(4, res->body.size());
  1608. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1609. "application/octet-stream");
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(200, res->status);
  1612. ASSERT_EQ(4, res->body.size());
  1613. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1614. "application/octet-stream");
  1615. ASSERT_TRUE(res);
  1616. ASSERT_EQ(200, res->status);
  1617. ASSERT_EQ(4, res->body.size());
  1618. }
  1619. TEST_F(ServerTest, BinaryString) {
  1620. auto binary = std::string("\x00\x01\x02\x03", 4);
  1621. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  1622. ASSERT_TRUE(res);
  1623. ASSERT_EQ(200, res->status);
  1624. ASSERT_EQ(4, res->body.size());
  1625. res = cli_.Put("/binary", binary, "application/octet-stream");
  1626. ASSERT_TRUE(res);
  1627. ASSERT_EQ(200, res->status);
  1628. ASSERT_EQ(4, res->body.size());
  1629. res = cli_.Patch("/binary", binary, "application/octet-stream");
  1630. ASSERT_TRUE(res);
  1631. ASSERT_EQ(200, res->status);
  1632. ASSERT_EQ(4, res->body.size());
  1633. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1634. ASSERT_TRUE(res);
  1635. ASSERT_EQ(200, res->status);
  1636. ASSERT_EQ(4, res->body.size());
  1637. }
  1638. TEST_F(ServerTest, EmptyRequest) {
  1639. auto res = cli_.Get("");
  1640. ASSERT_TRUE(!res);
  1641. EXPECT_EQ(Error::Connection, res.error());
  1642. }
  1643. TEST_F(ServerTest, LongRequest) {
  1644. std::string request;
  1645. for (size_t i = 0; i < 545; i++) {
  1646. request += "/TooLongRequest";
  1647. }
  1648. request += "OK";
  1649. auto res = cli_.Get(request.c_str());
  1650. ASSERT_TRUE(res);
  1651. EXPECT_EQ(404, res->status);
  1652. }
  1653. TEST_F(ServerTest, TooLongRequest) {
  1654. std::string request;
  1655. for (size_t i = 0; i < 545; i++) {
  1656. request += "/TooLongRequest";
  1657. }
  1658. request += "_NG";
  1659. auto res = cli_.Get(request.c_str());
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ(414, res->status);
  1662. }
  1663. TEST_F(ServerTest, LongHeader) {
  1664. Request req;
  1665. req.method = "GET";
  1666. req.path = "/hi";
  1667. std::string host_and_port;
  1668. host_and_port += HOST;
  1669. host_and_port += ":";
  1670. host_and_port += std::to_string(PORT);
  1671. req.headers.emplace("Host", host_and_port.c_str());
  1672. req.headers.emplace("Accept", "*/*");
  1673. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1674. req.headers.emplace(
  1675. "Header-Name",
  1676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1704. "@@@@@@@@@@@@@@@@");
  1705. auto res = std::make_shared<Response>();
  1706. auto error = Error::Success;
  1707. auto ret = cli_.send(req, *res, error);
  1708. ASSERT_TRUE(ret);
  1709. EXPECT_EQ(200, res->status);
  1710. }
  1711. TEST_F(ServerTest, LongQueryValue) {
  1712. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(414, res->status);
  1715. }
  1716. TEST_F(ServerTest, TooLongHeader) {
  1717. Request req;
  1718. req.method = "GET";
  1719. req.path = "/hi";
  1720. std::string host_and_port;
  1721. host_and_port += HOST;
  1722. host_and_port += ":";
  1723. host_and_port += std::to_string(PORT);
  1724. req.headers.emplace("Host", host_and_port.c_str());
  1725. req.headers.emplace("Accept", "*/*");
  1726. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1727. req.headers.emplace(
  1728. "Header-Name",
  1729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1757. "@@@@@@@@@@@@@@@@@");
  1758. auto res = std::make_shared<Response>();
  1759. auto error = Error::Success;
  1760. auto ret = cli_.send(req, *res, error);
  1761. ASSERT_TRUE(ret);
  1762. EXPECT_EQ(200, res->status);
  1763. }
  1764. TEST_F(ServerTest, PercentEncoding) {
  1765. auto res = cli_.Get("/e%6edwith%");
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(200, res->status);
  1768. }
  1769. TEST_F(ServerTest, PercentEncodingUnicode) {
  1770. auto res = cli_.Get("/e%u006edwith%");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(200, res->status);
  1773. }
  1774. TEST_F(ServerTest, InvalidPercentEncoding) {
  1775. auto res = cli_.Get("/%endwith%");
  1776. ASSERT_TRUE(res);
  1777. EXPECT_EQ(404, res->status);
  1778. }
  1779. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1780. auto res = cli_.Get("/%uendwith%");
  1781. ASSERT_TRUE(res);
  1782. EXPECT_EQ(404, res->status);
  1783. }
  1784. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1785. auto res = cli_.Get("/hello?aaa=bbb%");
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(404, res->status);
  1788. }
  1789. TEST_F(ServerTest, PlusSignEncoding) {
  1790. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(200, res->status);
  1793. EXPECT_EQ("a +b", res->body);
  1794. }
  1795. TEST_F(ServerTest, MultipartFormData) {
  1796. MultipartFormDataItems items = {
  1797. {"text1", "text default", "", ""},
  1798. {"text2", "aωb", "", ""},
  1799. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1800. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1801. {"file3", "", "", "application/octet-stream"},
  1802. {"file4", "", "", " application/json tmp-string "}};
  1803. auto res = cli_.Post("/multipart", items);
  1804. ASSERT_TRUE(res);
  1805. EXPECT_EQ(200, res->status);
  1806. }
  1807. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1808. auto res = cli_.Get("/hi");
  1809. ASSERT_TRUE(res);
  1810. EXPECT_EQ(200, res->status);
  1811. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1812. EXPECT_EQ("Hello World!", res->body);
  1813. }
  1814. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1815. Request req;
  1816. req.method = "POST";
  1817. req.path = "/chunked";
  1818. std::string host_and_port;
  1819. host_and_port += HOST;
  1820. host_and_port += ":";
  1821. host_and_port += std::to_string(PORT);
  1822. req.headers.emplace("Host", host_and_port.c_str());
  1823. req.headers.emplace("Accept", "*/*");
  1824. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1825. req.headers.emplace("Content-Type", "text/plain");
  1826. req.headers.emplace("Content-Length", "0");
  1827. req.headers.emplace(
  1828. "Transfer-Encoding",
  1829. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1830. // Client does not chunk, so make a chunked body manually.
  1831. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1832. auto res = std::make_shared<Response>();
  1833. auto error = Error::Success;
  1834. auto ret = cli_.send(req, *res, error);
  1835. ASSERT_TRUE(ret);
  1836. EXPECT_EQ(200, res->status);
  1837. }
  1838. TEST_F(ServerTest, GetStreamed2) {
  1839. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(206, res->status);
  1842. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1843. EXPECT_EQ(std::string("ab"), res->body);
  1844. }
  1845. TEST_F(ServerTest, GetStreamed) {
  1846. auto res = cli_.Get("/streamed");
  1847. ASSERT_TRUE(res);
  1848. EXPECT_EQ(200, res->status);
  1849. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1850. EXPECT_EQ(std::string("aaabbb"), res->body);
  1851. }
  1852. TEST_F(ServerTest, GetStreamedWithRange1) {
  1853. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1854. ASSERT_TRUE(res);
  1855. EXPECT_EQ(206, res->status);
  1856. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1857. EXPECT_EQ(true, res->has_header("Content-Range"));
  1858. EXPECT_EQ(std::string("def"), res->body);
  1859. }
  1860. TEST_F(ServerTest, GetStreamedWithRange2) {
  1861. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(206, res->status);
  1864. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1865. EXPECT_EQ(true, res->has_header("Content-Range"));
  1866. EXPECT_EQ(std::string("bcdefg"), res->body);
  1867. }
  1868. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  1869. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  1870. ASSERT_TRUE(res);
  1871. EXPECT_EQ(206, res->status);
  1872. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1873. EXPECT_EQ(true, res->has_header("Content-Range"));
  1874. EXPECT_EQ(std::string("efg"), res->body);
  1875. }
  1876. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  1877. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  1878. ASSERT_TRUE(res);
  1879. EXPECT_EQ(206, res->status);
  1880. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1881. EXPECT_EQ(true, res->has_header("Content-Range"));
  1882. EXPECT_EQ(std::string("abcdefg"), res->body);
  1883. }
  1884. TEST_F(ServerTest, GetStreamedWithRangeError) {
  1885. auto res = cli_.Get("/streamed-with-range",
  1886. {{"Range", "bytes=92233720368547758079223372036854775806-"
  1887. "92233720368547758079223372036854775807"}});
  1888. ASSERT_TRUE(res);
  1889. EXPECT_EQ(416, res->status);
  1890. }
  1891. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  1892. auto res =
  1893. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  1894. EXPECT_EQ(206, res->status);
  1895. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1896. EXPECT_EQ(true, res->has_header("Content-Range"));
  1897. EXPECT_EQ(std::string("abcdefg"), res->body);
  1898. }
  1899. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1900. auto res =
  1901. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(206, res->status);
  1904. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1905. EXPECT_EQ(false, res->has_header("Content-Range"));
  1906. EXPECT_EQ(269, res->body.size());
  1907. }
  1908. TEST_F(ServerTest, GetStreamedEndless) {
  1909. uint64_t offset = 0;
  1910. auto res = cli_.Get("/streamed-cancel",
  1911. [&](const char * /*data*/, uint64_t data_length) {
  1912. if (offset < 100) {
  1913. offset += data_length;
  1914. return true;
  1915. }
  1916. return false;
  1917. });
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Canceled, res.error());
  1920. }
  1921. TEST_F(ServerTest, ClientStop) {
  1922. std::vector<std::thread> threads;
  1923. for (auto i = 0; i < 3; i++) {
  1924. threads.emplace_back(thread([&]() {
  1925. auto res = cli_.Get("/streamed-cancel",
  1926. [&](const char *, uint64_t) { return true; });
  1927. ASSERT_TRUE(!res);
  1928. EXPECT_TRUE(res.error() == Error::Canceled || res.error() == Error::Read);
  1929. }));
  1930. }
  1931. std::this_thread::sleep_for(std::chrono::seconds(2));
  1932. while (cli_.is_socket_open()) {
  1933. cli_.stop();
  1934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1935. }
  1936. for (auto &t : threads) {
  1937. t.join();
  1938. }
  1939. }
  1940. TEST_F(ServerTest, GetWithRange1) {
  1941. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1942. ASSERT_TRUE(res);
  1943. EXPECT_EQ(206, res->status);
  1944. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1945. EXPECT_EQ(true, res->has_header("Content-Range"));
  1946. EXPECT_EQ(std::string("def"), res->body);
  1947. }
  1948. TEST_F(ServerTest, GetWithRange2) {
  1949. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(206, res->status);
  1952. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1953. EXPECT_EQ(true, res->has_header("Content-Range"));
  1954. EXPECT_EQ(std::string("bcdefg"), res->body);
  1955. }
  1956. TEST_F(ServerTest, GetWithRange3) {
  1957. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1958. ASSERT_TRUE(res);
  1959. EXPECT_EQ(206, res->status);
  1960. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1961. EXPECT_EQ(true, res->has_header("Content-Range"));
  1962. EXPECT_EQ(std::string("a"), res->body);
  1963. }
  1964. TEST_F(ServerTest, GetWithRange4) {
  1965. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1966. ASSERT_TRUE(res);
  1967. EXPECT_EQ(206, res->status);
  1968. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1969. EXPECT_EQ(true, res->has_header("Content-Range"));
  1970. EXPECT_EQ(std::string("fg"), res->body);
  1971. }
  1972. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  1973. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(416, res->status);
  1976. }
  1977. TEST_F(ServerTest, GetWithRangeMultipart) {
  1978. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1979. ASSERT_TRUE(res);
  1980. EXPECT_EQ(206, res->status);
  1981. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1982. EXPECT_EQ(false, res->has_header("Content-Range"));
  1983. EXPECT_EQ(269, res->body.size());
  1984. }
  1985. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  1986. auto res =
  1987. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  1988. ASSERT_TRUE(res);
  1989. EXPECT_EQ(416, res->status);
  1990. }
  1991. TEST_F(ServerTest, GetStreamedChunked) {
  1992. auto res = cli_.Get("/streamed-chunked");
  1993. ASSERT_TRUE(res);
  1994. EXPECT_EQ(200, res->status);
  1995. EXPECT_EQ(std::string("123456789"), res->body);
  1996. }
  1997. TEST_F(ServerTest, GetStreamedChunked2) {
  1998. auto res = cli_.Get("/streamed-chunked2");
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(200, res->status);
  2001. EXPECT_EQ(std::string("123456789"), res->body);
  2002. }
  2003. TEST_F(ServerTest, LargeChunkedPost) {
  2004. Request req;
  2005. req.method = "POST";
  2006. req.path = "/large-chunked";
  2007. std::string host_and_port;
  2008. host_and_port += HOST;
  2009. host_and_port += ":";
  2010. host_and_port += std::to_string(PORT);
  2011. req.headers.emplace("Host", host_and_port.c_str());
  2012. req.headers.emplace("Accept", "*/*");
  2013. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2014. req.headers.emplace("Content-Type", "text/plain");
  2015. req.headers.emplace("Content-Length", "0");
  2016. req.headers.emplace("Transfer-Encoding", "chunked");
  2017. std::string long_string(30 * 1024u, 'a');
  2018. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2019. // Attempt to make a large enough post to exceed OS buffers, to test that
  2020. // the server handles short reads if the full chunk data isn't available.
  2021. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2022. auto res = std::make_shared<Response>();
  2023. auto error = Error::Success;
  2024. auto ret = cli_.send(req, *res, error);
  2025. ASSERT_TRUE(ret);
  2026. EXPECT_EQ(200, res->status);
  2027. }
  2028. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2029. auto res = cli_.Get("/remote_addr");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(200, res->status);
  2032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2033. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2034. }
  2035. TEST_F(ServerTest, HTTPResponseSplitting) {
  2036. auto res = cli_.Get("/http_response_splitting");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(200, res->status);
  2039. }
  2040. TEST_F(ServerTest, SlowRequest) {
  2041. request_threads_.push_back(
  2042. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2043. request_threads_.push_back(
  2044. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2045. request_threads_.push_back(
  2046. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2047. }
  2048. TEST_F(ServerTest, SlowPost) {
  2049. char buffer[64 * 1024];
  2050. memset(buffer, 0x42, sizeof(buffer));
  2051. auto res = cli_.Post(
  2052. "/slowpost", 64 * 1024 * 1024,
  2053. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2054. sink.write(buffer, sizeof(buffer));
  2055. return true;
  2056. },
  2057. "text/plain");
  2058. ASSERT_TRUE(res);
  2059. EXPECT_EQ(200, res->status);
  2060. }
  2061. TEST_F(ServerTest, SlowPostFail) {
  2062. char buffer[64 * 1024];
  2063. memset(buffer, 0x42, sizeof(buffer));
  2064. cli_.set_write_timeout(0, 0);
  2065. auto res = cli_.Post(
  2066. "/slowpost", 64 * 1024 * 1024,
  2067. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2068. sink.write(buffer, sizeof(buffer));
  2069. return true;
  2070. },
  2071. "text/plain");
  2072. ASSERT_TRUE(!res);
  2073. EXPECT_EQ(Error::Write, res.error());
  2074. }
  2075. TEST_F(ServerTest, Put) {
  2076. auto res = cli_.Put("/put", "PUT", "text/plain");
  2077. ASSERT_TRUE(res);
  2078. EXPECT_EQ(200, res->status);
  2079. EXPECT_EQ("PUT", res->body);
  2080. }
  2081. TEST_F(ServerTest, PutWithContentProvider) {
  2082. auto res = cli_.Put(
  2083. "/put", 3,
  2084. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2085. EXPECT_TRUE(sink.is_writable());
  2086. sink.os << "PUT";
  2087. return true;
  2088. },
  2089. "text/plain");
  2090. ASSERT_TRUE(res);
  2091. EXPECT_EQ(200, res->status);
  2092. EXPECT_EQ("PUT", res->body);
  2093. }
  2094. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2095. auto res = cli_.Post(
  2096. "/post", 42,
  2097. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2098. return false;
  2099. },
  2100. "text/plain");
  2101. ASSERT_TRUE(!res);
  2102. EXPECT_EQ(Error::Canceled, res.error());
  2103. }
  2104. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2105. auto res = cli_.Put(
  2106. "/put",
  2107. [](size_t /*offset*/, DataSink &sink) {
  2108. EXPECT_TRUE(sink.is_writable());
  2109. sink.os << "PUT";
  2110. sink.done();
  2111. return true;
  2112. },
  2113. "text/plain");
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(200, res->status);
  2116. EXPECT_EQ("PUT", res->body);
  2117. }
  2118. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2119. auto res = cli_.Post(
  2120. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2121. "text/plain");
  2122. ASSERT_TRUE(!res);
  2123. EXPECT_EQ(Error::Canceled, res.error());
  2124. }
  2125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2126. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2127. cli_.set_compress(true);
  2128. auto res = cli_.Put(
  2129. "/put", 3,
  2130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2131. EXPECT_TRUE(sink.is_writable());
  2132. sink.os << "PUT";
  2133. return true;
  2134. },
  2135. "text/plain");
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(200, res->status);
  2138. EXPECT_EQ("PUT", res->body);
  2139. }
  2140. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2141. cli_.set_compress(true);
  2142. auto res = cli_.Post(
  2143. "/post", 42,
  2144. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2145. return false;
  2146. },
  2147. "text/plain");
  2148. ASSERT_TRUE(!res);
  2149. EXPECT_EQ(Error::Canceled, res.error());
  2150. }
  2151. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2152. cli_.set_compress(true);
  2153. auto res = cli_.Put(
  2154. "/put",
  2155. [](size_t /*offset*/, DataSink &sink) {
  2156. EXPECT_TRUE(sink.is_writable());
  2157. sink.os << "PUT";
  2158. sink.done();
  2159. return true;
  2160. },
  2161. "text/plain");
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(200, res->status);
  2164. EXPECT_EQ("PUT", res->body);
  2165. }
  2166. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2167. cli_.set_compress(true);
  2168. auto res = cli_.Post(
  2169. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2170. "text/plain");
  2171. ASSERT_TRUE(!res);
  2172. EXPECT_EQ(Error::Canceled, res.error());
  2173. }
  2174. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2175. cli_.set_compress(true);
  2176. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2177. ASSERT_TRUE(res);
  2178. EXPECT_EQ(200, res->status);
  2179. EXPECT_EQ(LARGE_DATA, res->body);
  2180. }
  2181. TEST_F(ServerTest, PutContentWithDeflate) {
  2182. cli_.set_compress(false);
  2183. Headers headers;
  2184. headers.emplace("Content-Encoding", "deflate");
  2185. // PUT in deflate format:
  2186. auto res = cli_.Put("/put", headers,
  2187. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2188. ASSERT_TRUE(res);
  2189. EXPECT_EQ(200, res->status);
  2190. EXPECT_EQ("PUT", res->body);
  2191. }
  2192. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2193. Headers headers;
  2194. headers.emplace("Accept-Encoding", "gzip, deflate");
  2195. auto res = cli_.Get("/streamed-chunked", headers);
  2196. ASSERT_TRUE(res);
  2197. EXPECT_EQ(200, res->status);
  2198. EXPECT_EQ(std::string("123456789"), res->body);
  2199. }
  2200. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2201. Headers headers;
  2202. headers.emplace("Accept-Encoding", "gzip, deflate");
  2203. auto res = cli_.Get("/streamed-chunked2", headers);
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(200, res->status);
  2206. EXPECT_EQ(std::string("123456789"), res->body);
  2207. }
  2208. TEST(GzipDecompressor, ChunkedDecompression) {
  2209. std::string data;
  2210. for (size_t i = 0; i < 32 * 1024; ++i) {
  2211. data.push_back(static_cast<char>('a' + i % 26));
  2212. }
  2213. std::string compressed_data;
  2214. {
  2215. httplib::detail::gzip_compressor compressor;
  2216. bool result = compressor.compress(
  2217. data.data(), data.size(),
  2218. /*last=*/true, [&](const char *data, size_t size) {
  2219. compressed_data.insert(compressed_data.size(), data, size);
  2220. return true;
  2221. });
  2222. ASSERT_TRUE(result);
  2223. }
  2224. std::string decompressed_data;
  2225. {
  2226. httplib::detail::gzip_decompressor decompressor;
  2227. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2228. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2229. size_t chunk_size = 130;
  2230. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2231. chunk_begin += chunk_size) {
  2232. size_t current_chunk_size =
  2233. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2234. bool result = decompressor.decompress(
  2235. compressed_data.data() + chunk_begin, current_chunk_size,
  2236. [&](const char *data, size_t size) {
  2237. decompressed_data.insert(decompressed_data.size(), data, size);
  2238. return true;
  2239. });
  2240. ASSERT_TRUE(result);
  2241. }
  2242. }
  2243. ASSERT_EQ(data, decompressed_data);
  2244. }
  2245. #endif
  2246. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2247. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2248. Headers headers;
  2249. headers.emplace("Accept-Encoding", "br");
  2250. auto res = cli_.Get("/streamed-chunked", headers);
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ(200, res->status);
  2253. EXPECT_EQ(std::string("123456789"), res->body);
  2254. }
  2255. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2256. Headers headers;
  2257. headers.emplace("Accept-Encoding", "br");
  2258. auto res = cli_.Get("/streamed-chunked2", headers);
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ(200, res->status);
  2261. EXPECT_EQ(std::string("123456789"), res->body);
  2262. }
  2263. #endif
  2264. TEST_F(ServerTest, Patch) {
  2265. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(200, res->status);
  2268. EXPECT_EQ("PATCH", res->body);
  2269. }
  2270. TEST_F(ServerTest, Delete) {
  2271. auto res = cli_.Delete("/delete");
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ(200, res->status);
  2274. EXPECT_EQ("DELETE", res->body);
  2275. }
  2276. TEST_F(ServerTest, DeleteContentReceiver) {
  2277. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2278. ASSERT_TRUE(res);
  2279. EXPECT_EQ(200, res->status);
  2280. EXPECT_EQ("content", res->body);
  2281. }
  2282. TEST_F(ServerTest, Options) {
  2283. auto res = cli_.Options("*");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(200, res->status);
  2286. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2287. EXPECT_TRUE(res->body.empty());
  2288. }
  2289. TEST_F(ServerTest, URL) {
  2290. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2291. ASSERT_TRUE(res);
  2292. EXPECT_EQ(200, res->status);
  2293. }
  2294. TEST_F(ServerTest, ArrayParam) {
  2295. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2296. ASSERT_TRUE(res);
  2297. EXPECT_EQ(200, res->status);
  2298. }
  2299. TEST_F(ServerTest, NoMultipleHeaders) {
  2300. Headers headers = {{"Content-Length", "5"}};
  2301. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2302. "text/plain");
  2303. ASSERT_TRUE(res);
  2304. EXPECT_EQ(200, res->status);
  2305. }
  2306. TEST_F(ServerTest, PostContentReceiver) {
  2307. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2308. ASSERT_TRUE(res);
  2309. ASSERT_EQ(200, res->status);
  2310. ASSERT_EQ("content", res->body);
  2311. }
  2312. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2313. MultipartFormDataItems items = {
  2314. {"text1", "text default", "", ""},
  2315. {"text2", "aωb", "", ""},
  2316. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2317. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2318. {"file3", "", "", "application/octet-stream"},
  2319. };
  2320. auto res = cli_.Post("/content_receiver", items);
  2321. ASSERT_TRUE(res);
  2322. EXPECT_EQ(200, res->status);
  2323. }
  2324. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2325. MultipartFormDataItems items = {
  2326. {"text1", "text default", "", ""},
  2327. {"text2", "aωb", "", ""},
  2328. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2329. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2330. {"file3", "", "", "application/octet-stream"},
  2331. };
  2332. auto boundary = std::string("+++++");
  2333. std::string body;
  2334. for (const auto &item : items) {
  2335. body += "--" + boundary + "\r\n";
  2336. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2337. if (!item.filename.empty()) {
  2338. body += "; filename=\"" + item.filename + "\"";
  2339. }
  2340. body += "\r\n";
  2341. if (!item.content_type.empty()) {
  2342. body += "Content-Type: " + item.content_type + "\r\n";
  2343. }
  2344. body += "\r\n";
  2345. body += item.content + "\r\n";
  2346. }
  2347. body += "--" + boundary + "--\r\n";
  2348. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2349. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(200, res->status);
  2352. }
  2353. TEST_F(ServerTest, PostContentReceiverGzip) {
  2354. cli_.set_compress(true);
  2355. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2356. ASSERT_TRUE(res);
  2357. ASSERT_EQ(200, res->status);
  2358. ASSERT_EQ("content", res->body);
  2359. }
  2360. TEST_F(ServerTest, PutContentReceiver) {
  2361. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2362. ASSERT_TRUE(res);
  2363. ASSERT_EQ(200, res->status);
  2364. ASSERT_EQ("content", res->body);
  2365. }
  2366. TEST_F(ServerTest, PatchContentReceiver) {
  2367. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2368. ASSERT_TRUE(res);
  2369. ASSERT_EQ(200, res->status);
  2370. ASSERT_EQ("content", res->body);
  2371. }
  2372. TEST_F(ServerTest, PostQueryStringAndBody) {
  2373. auto res =
  2374. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2375. ASSERT_TRUE(res);
  2376. ASSERT_EQ(200, res->status);
  2377. }
  2378. TEST_F(ServerTest, HTTP2Magic) {
  2379. Request req;
  2380. req.method = "PRI";
  2381. req.path = "*";
  2382. req.body = "SM";
  2383. auto res = std::make_shared<Response>();
  2384. auto error = Error::Success;
  2385. auto ret = cli_.send(req, *res, error);
  2386. ASSERT_TRUE(ret);
  2387. EXPECT_EQ(400, res->status);
  2388. }
  2389. TEST_F(ServerTest, KeepAlive) {
  2390. auto res = cli_.Get("/hi");
  2391. ASSERT_TRUE(res);
  2392. EXPECT_EQ(200, res->status);
  2393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2394. EXPECT_EQ("Hello World!", res->body);
  2395. res = cli_.Get("/hi");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(200, res->status);
  2398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2399. EXPECT_EQ("Hello World!", res->body);
  2400. res = cli_.Get("/hi");
  2401. ASSERT_TRUE(res);
  2402. EXPECT_EQ(200, res->status);
  2403. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2404. EXPECT_EQ("Hello World!", res->body);
  2405. res = cli_.Get("/not-exist");
  2406. ASSERT_TRUE(res);
  2407. EXPECT_EQ(404, res->status);
  2408. res = cli_.Post("/empty", "", "text/plain");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ(200, res->status);
  2411. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2412. EXPECT_EQ("empty", res->body);
  2413. EXPECT_EQ("close", res->get_header_value("Connection"));
  2414. res = cli_.Post(
  2415. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2416. "text/plain");
  2417. ASSERT_TRUE(res);
  2418. EXPECT_EQ(200, res->status);
  2419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2420. EXPECT_EQ("empty", res->body);
  2421. cli_.set_keep_alive(false);
  2422. res = cli_.Get("/last-request");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(200, res->status);
  2425. EXPECT_EQ("close", res->get_header_value("Connection"));
  2426. }
  2427. TEST_F(ServerTest, TooManyRedirect) {
  2428. cli_.set_follow_location(true);
  2429. auto res = cli_.Get("/redirect/0");
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2432. }
  2433. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2434. TEST_F(ServerTest, Gzip) {
  2435. Headers headers;
  2436. headers.emplace("Accept-Encoding", "gzip, deflate");
  2437. auto res = cli_.Get("/compress", headers);
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2441. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2442. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2443. "7890123456789012345678901234567890",
  2444. res->body);
  2445. EXPECT_EQ(200, res->status);
  2446. }
  2447. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2448. auto res = cli_.Get("/compress");
  2449. ASSERT_TRUE(res);
  2450. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2452. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2453. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2454. "7890123456789012345678901234567890",
  2455. res->body);
  2456. EXPECT_EQ(200, res->status);
  2457. }
  2458. TEST_F(ServerTest, GzipWithContentReceiver) {
  2459. Headers headers;
  2460. headers.emplace("Accept-Encoding", "gzip, deflate");
  2461. std::string body;
  2462. auto res = cli_.Get("/compress", headers,
  2463. [&](const char *data, uint64_t data_length) {
  2464. EXPECT_EQ(data_length, 100);
  2465. body.append(data, data_length);
  2466. return true;
  2467. });
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2470. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2473. "7890123456789012345678901234567890",
  2474. body);
  2475. EXPECT_EQ(200, res->status);
  2476. }
  2477. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2478. Headers headers;
  2479. headers.emplace("Accept-Encoding", "gzip, deflate");
  2480. cli_.set_decompress(false);
  2481. auto res = cli_.Get("/compress", headers);
  2482. ASSERT_TRUE(res);
  2483. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2484. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2485. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2486. EXPECT_EQ(33, res->body.size());
  2487. EXPECT_EQ(200, res->status);
  2488. }
  2489. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2490. std::string body;
  2491. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2492. EXPECT_EQ(data_length, 100);
  2493. body.append(data, data_length);
  2494. return true;
  2495. });
  2496. ASSERT_TRUE(res);
  2497. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2498. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2499. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2500. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2501. "7890123456789012345678901234567890",
  2502. body);
  2503. EXPECT_EQ(200, res->status);
  2504. }
  2505. TEST_F(ServerTest, NoGzip) {
  2506. Headers headers;
  2507. headers.emplace("Accept-Encoding", "gzip, deflate");
  2508. auto res = cli_.Get("/nocompress", headers);
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2511. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2512. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2513. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2514. "7890123456789012345678901234567890",
  2515. res->body);
  2516. EXPECT_EQ(200, res->status);
  2517. }
  2518. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2519. Headers headers;
  2520. headers.emplace("Accept-Encoding", "gzip, deflate");
  2521. std::string body;
  2522. auto res = cli_.Get("/nocompress", headers,
  2523. [&](const char *data, uint64_t data_length) {
  2524. EXPECT_EQ(data_length, 100);
  2525. body.append(data, data_length);
  2526. return true;
  2527. });
  2528. ASSERT_TRUE(res);
  2529. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2530. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2531. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2532. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2533. "7890123456789012345678901234567890",
  2534. body);
  2535. EXPECT_EQ(200, res->status);
  2536. }
  2537. TEST_F(ServerTest, MultipartFormDataGzip) {
  2538. MultipartFormDataItems items = {
  2539. {"key1", "test", "", ""},
  2540. {"key2", "--abcdefg123", "", ""},
  2541. };
  2542. cli_.set_compress(true);
  2543. auto res = cli_.Post("/compress-multipart", items);
  2544. ASSERT_TRUE(res);
  2545. EXPECT_EQ(200, res->status);
  2546. }
  2547. #endif
  2548. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2549. TEST_F(ServerTest, Brotli) {
  2550. Headers headers;
  2551. headers.emplace("Accept-Encoding", "br");
  2552. auto res = cli_.Get("/compress", headers);
  2553. ASSERT_TRUE(res);
  2554. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2556. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2558. "7890123456789012345678901234567890",
  2559. res->body);
  2560. EXPECT_EQ(200, res->status);
  2561. }
  2562. #endif
  2563. // Sends a raw request to a server listening at HOST:PORT.
  2564. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2565. std::string *resp = nullptr) {
  2566. auto error = Error::Success;
  2567. auto client_sock =
  2568. detail::create_client_socket(HOST, PORT, false, nullptr,
  2569. /*timeout_sec=*/5, 0, std::string(), error);
  2570. if (client_sock == INVALID_SOCKET) { return false; }
  2571. auto ret = detail::process_client_socket(
  2572. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2573. if (req.size() !=
  2574. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2575. return false;
  2576. }
  2577. char buf[512];
  2578. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2579. while (line_reader.getline()) {
  2580. if (resp) { *resp += line_reader.ptr(); }
  2581. }
  2582. return true;
  2583. });
  2584. detail::close_socket(client_sock);
  2585. return ret;
  2586. }
  2587. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2588. Server svr;
  2589. std::string header_value;
  2590. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2591. header_value = req.get_header_value("foo");
  2592. res.set_content("ok", "text/plain");
  2593. });
  2594. thread t = thread([&] { svr.listen(HOST, PORT); });
  2595. while (!svr.is_running()) {
  2596. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2597. }
  2598. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2599. // like characters are not treated the same - use vertical tab and escape.
  2600. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2601. "foo: \t \v bar \e\t \r\n"
  2602. "Connection: close\r\n"
  2603. "\r\n";
  2604. ASSERT_TRUE(send_request(5, req));
  2605. svr.stop();
  2606. t.join();
  2607. EXPECT_EQ(header_value, "\v bar \e");
  2608. }
  2609. // Sends a raw request and verifies that there isn't a crash or exception.
  2610. static void test_raw_request(const std::string &req,
  2611. std::string *out = nullptr) {
  2612. Server svr;
  2613. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("ok", "text/plain");
  2615. });
  2616. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("ok", "text/plain");
  2618. });
  2619. // Server read timeout must be longer than the client read timeout for the
  2620. // bug to reproduce, probably to force the server to process a request
  2621. // without a trailing blank line.
  2622. const time_t client_read_timeout_sec = 1;
  2623. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  2624. bool listen_thread_ok = false;
  2625. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2626. while (!svr.is_running()) {
  2627. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2628. }
  2629. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2630. svr.stop();
  2631. t.join();
  2632. EXPECT_TRUE(listen_thread_ok);
  2633. }
  2634. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2635. // A certain header line causes an exception if the header property is parsed
  2636. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2637. test_raw_request(
  2638. "GET /hi HTTP/1.1\r\n"
  2639. " : "
  2640. " "
  2641. " ");
  2642. }
  2643. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2644. // A certain header line causes an exception if the header property *name* is
  2645. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2646. // greedy matcher and requires backtracking when there are a lot of ":"
  2647. // characters.
  2648. // This occurs with libc++ but not libstdc++.
  2649. test_raw_request(
  2650. "GET /hi HTTP/1.1\r\n"
  2651. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2652. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2653. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2654. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2655. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2656. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2657. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2658. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2659. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2660. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2661. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2662. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2663. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2664. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2665. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2666. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2667. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2668. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2669. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2670. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2671. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2672. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2673. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2674. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2675. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2676. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2677. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2678. "&&&%%%");
  2679. }
  2680. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2681. // Make sure this doesn't crash the server.
  2682. // In a previous version of the header line regex, the "\r" rendered the line
  2683. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2684. // a new position where the leading white space ended and the field value
  2685. // began.
  2686. // The crash occurs with libc++ but not libstdc++.
  2687. test_raw_request("GET /hi HTTP/1.1\r\n"
  2688. "a:" +
  2689. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2690. "\r\n"
  2691. "\r\n");
  2692. }
  2693. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2694. std::string out;
  2695. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2696. "Content-Type: text/plain\r\n"
  2697. "Transfer-Encoding: chunked\r\n"
  2698. "\r\n"
  2699. "nothex\r\n",
  2700. &out);
  2701. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2702. }
  2703. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2704. std::string out;
  2705. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2706. "Content-Type: text/plain\r\n"
  2707. "Transfer-Encoding: chunked\r\n"
  2708. "\r\n"
  2709. "3\r\n"
  2710. "xyz\r\n"
  2711. "NaN\r\n",
  2712. &out);
  2713. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2714. }
  2715. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2716. std::string out;
  2717. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2718. "Content-Type: text/plain\r\n"
  2719. "Transfer-Encoding: chunked\r\n"
  2720. "\r\n"
  2721. // Length is too large for 64 bits.
  2722. "1ffffffffffffffff\r\n"
  2723. "xyz\r\n",
  2724. &out);
  2725. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2726. }
  2727. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2728. test_raw_request("GET /hi HTTP/1.1\r\n"
  2729. "Content-Type: text/plain\r\n\r");
  2730. }
  2731. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  2732. std::string out;
  2733. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  2734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2735. }
  2736. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2737. Server svr;
  2738. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2739. res.set_header("Cache-Control", "no-cache");
  2740. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2741. DataSink &sink) {
  2742. char buffer[27];
  2743. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2744. sink.write(buffer, size);
  2745. std::this_thread::sleep_for(std::chrono::seconds(1));
  2746. return true;
  2747. });
  2748. });
  2749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2750. while (!svr.is_running()) {
  2751. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2752. }
  2753. Client client(HOST, PORT);
  2754. const Headers headers = {{"Accept", "text/event-stream"}};
  2755. auto get_thread = std::thread([&client, &headers]() {
  2756. auto res = client.Get(
  2757. "/events", headers,
  2758. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2759. });
  2760. // Give GET time to get a few messages.
  2761. std::this_thread::sleep_for(std::chrono::seconds(2));
  2762. svr.stop();
  2763. listen_thread.join();
  2764. get_thread.join();
  2765. ASSERT_FALSE(svr.is_running());
  2766. }
  2767. TEST(StreamingTest, NoContentLengthStreaming) {
  2768. Server svr;
  2769. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  2770. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  2771. if (offset < 6) {
  2772. sink.os << (offset < 3 ? "a" : "b");
  2773. } else {
  2774. sink.done();
  2775. }
  2776. return true;
  2777. });
  2778. });
  2779. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2780. while (!svr.is_running()) {
  2781. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2782. }
  2783. Client client(HOST, PORT);
  2784. auto get_thread = std::thread([&client]() {
  2785. auto res = client.Get("/stream", [](const char *data, size_t len) -> bool {
  2786. EXPECT_EQ("aaabbb", std::string(data, len));
  2787. return true;
  2788. });
  2789. });
  2790. // Give GET time to get a few messages.
  2791. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2792. svr.stop();
  2793. listen_thread.join();
  2794. get_thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. }
  2797. TEST(MountTest, Unmount) {
  2798. Server svr;
  2799. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2800. while (!svr.is_running()) {
  2801. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2802. }
  2803. // Give GET time to get a few messages.
  2804. std::this_thread::sleep_for(std::chrono::seconds(1));
  2805. Client cli("localhost", PORT);
  2806. svr.set_mount_point("/mount2", "./www2");
  2807. auto res = cli.Get("/");
  2808. ASSERT_TRUE(res);
  2809. EXPECT_EQ(404, res->status);
  2810. res = cli.Get("/mount2/dir/test.html");
  2811. ASSERT_TRUE(res);
  2812. EXPECT_EQ(200, res->status);
  2813. svr.set_mount_point("/", "./www");
  2814. res = cli.Get("/dir/");
  2815. ASSERT_TRUE(res);
  2816. EXPECT_EQ(200, res->status);
  2817. svr.remove_mount_point("/");
  2818. res = cli.Get("/dir/");
  2819. ASSERT_TRUE(res);
  2820. EXPECT_EQ(404, res->status);
  2821. svr.remove_mount_point("/mount2");
  2822. res = cli.Get("/mount2/dir/test.html");
  2823. ASSERT_TRUE(res);
  2824. EXPECT_EQ(404, res->status);
  2825. svr.stop();
  2826. listen_thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. }
  2829. TEST(ExceptionTest, ThrowExceptionInHandler) {
  2830. Server svr;
  2831. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  2832. throw std::runtime_error("exception...");
  2833. // res.set_content("Hello World!", "text/plain");
  2834. });
  2835. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2836. while (!svr.is_running()) {
  2837. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2838. }
  2839. // Give GET time to get a few messages.
  2840. std::this_thread::sleep_for(std::chrono::seconds(1));
  2841. Client cli("localhost", PORT);
  2842. auto res = cli.Get("/hi");
  2843. ASSERT_TRUE(res);
  2844. EXPECT_EQ(500, res->status);
  2845. ASSERT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2846. svr.stop();
  2847. listen_thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. }
  2850. TEST(KeepAliveTest, ReadTimeout) {
  2851. Server svr;
  2852. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2853. std::this_thread::sleep_for(std::chrono::seconds(2));
  2854. res.set_content("a", "text/plain");
  2855. });
  2856. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2857. res.set_content("b", "text/plain");
  2858. });
  2859. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2860. while (!svr.is_running()) {
  2861. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2862. }
  2863. // Give GET time to get a few messages.
  2864. std::this_thread::sleep_for(std::chrono::seconds(1));
  2865. Client cli("localhost", PORT);
  2866. cli.set_keep_alive(true);
  2867. cli.set_read_timeout(1);
  2868. auto resa = cli.Get("/a");
  2869. ASSERT_TRUE(!resa);
  2870. EXPECT_EQ(Error::Read, resa.error());
  2871. auto resb = cli.Get("/b");
  2872. ASSERT_TRUE(resb);
  2873. EXPECT_EQ(200, resb->status);
  2874. EXPECT_EQ("b", resb->body);
  2875. svr.stop();
  2876. listen_thread.join();
  2877. ASSERT_FALSE(svr.is_running());
  2878. }
  2879. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  2880. Server svr;
  2881. svr.set_error_handler([](Request const &, Response &res) -> void {
  2882. res.set_chunked_content_provider(
  2883. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  2884. sink.os << "hello";
  2885. sink.os << "world";
  2886. sink.done();
  2887. return true;
  2888. });
  2889. });
  2890. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2891. while (!svr.is_running()) {
  2892. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2893. }
  2894. // Give GET time to get a few messages.
  2895. std::this_thread::sleep_for(std::chrono::seconds(1));
  2896. Client cli("localhost", PORT);
  2897. auto res = cli.Get("/");
  2898. ASSERT_TRUE(res);
  2899. EXPECT_EQ(404, res->status);
  2900. EXPECT_EQ("helloworld", res->body);
  2901. svr.stop();
  2902. listen_thread.join();
  2903. ASSERT_FALSE(svr.is_running());
  2904. }
  2905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2906. TEST(KeepAliveTest, ReadTimeoutSSL) {
  2907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2908. ASSERT_TRUE(svr.is_valid());
  2909. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2910. std::this_thread::sleep_for(std::chrono::seconds(2));
  2911. res.set_content("a", "text/plain");
  2912. });
  2913. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2914. res.set_content("b", "text/plain");
  2915. });
  2916. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2917. while (!svr.is_running()) {
  2918. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2919. }
  2920. // Give GET time to get a few messages.
  2921. std::this_thread::sleep_for(std::chrono::seconds(1));
  2922. SSLClient cli("localhost", PORT);
  2923. cli.enable_server_certificate_verification(false);
  2924. cli.set_keep_alive(true);
  2925. cli.set_read_timeout(1);
  2926. auto resa = cli.Get("/a");
  2927. ASSERT_TRUE(!resa);
  2928. EXPECT_EQ(Error::Read, resa.error());
  2929. auto resb = cli.Get("/b");
  2930. ASSERT_TRUE(resb);
  2931. EXPECT_EQ(200, resb->status);
  2932. EXPECT_EQ("b", resb->body);
  2933. svr.stop();
  2934. listen_thread.join();
  2935. ASSERT_FALSE(svr.is_running());
  2936. }
  2937. #endif
  2938. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  2939. protected:
  2940. ServerTestWithAI_PASSIVE()
  2941. : cli_(HOST, PORT)
  2942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2943. ,
  2944. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2945. #endif
  2946. {
  2947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2948. cli_.enable_server_certificate_verification(false);
  2949. #endif
  2950. }
  2951. virtual void SetUp() {
  2952. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2953. res.set_content("Hello World!", "text/plain");
  2954. });
  2955. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  2956. while (!svr_.is_running()) {
  2957. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2958. }
  2959. }
  2960. virtual void TearDown() {
  2961. svr_.stop();
  2962. t_.join();
  2963. }
  2964. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2965. SSLClient cli_;
  2966. SSLServer svr_;
  2967. #else
  2968. Client cli_;
  2969. Server svr_;
  2970. #endif
  2971. thread t_;
  2972. };
  2973. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  2974. auto res = cli_.Get("/hi");
  2975. ASSERT_TRUE(res);
  2976. EXPECT_EQ(200, res->status);
  2977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2978. EXPECT_EQ("Hello World!", res->body);
  2979. }
  2980. class ServerUpDownTest : public ::testing::Test {
  2981. protected:
  2982. ServerUpDownTest() : cli_(HOST, PORT) {}
  2983. virtual void SetUp() {
  2984. t_ = thread([&]() {
  2985. svr_.bind_to_any_port(HOST);
  2986. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2987. ASSERT_TRUE(svr_.listen_after_bind());
  2988. });
  2989. while (!svr_.is_running()) {
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2991. }
  2992. }
  2993. virtual void TearDown() {
  2994. svr_.stop();
  2995. t_.join();
  2996. }
  2997. Client cli_;
  2998. Server svr_;
  2999. thread t_;
  3000. };
  3001. TEST_F(ServerUpDownTest, QuickStartStop) {
  3002. // Should not crash, especially when run with
  3003. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3004. }
  3005. class PayloadMaxLengthTest : public ::testing::Test {
  3006. protected:
  3007. PayloadMaxLengthTest()
  3008. : cli_(HOST, PORT)
  3009. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3010. ,
  3011. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3012. #endif
  3013. {
  3014. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3015. cli_.enable_server_certificate_verification(false);
  3016. #endif
  3017. }
  3018. virtual void SetUp() {
  3019. svr_.set_payload_max_length(8);
  3020. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3021. res.set_content("test", "text/plain");
  3022. });
  3023. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3024. while (!svr_.is_running()) {
  3025. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3026. }
  3027. }
  3028. virtual void TearDown() {
  3029. svr_.stop();
  3030. t_.join();
  3031. }
  3032. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3033. SSLClient cli_;
  3034. SSLServer svr_;
  3035. #else
  3036. Client cli_;
  3037. Server svr_;
  3038. #endif
  3039. thread t_;
  3040. };
  3041. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3042. auto res = cli_.Post("/test", "123456789", "text/plain");
  3043. ASSERT_TRUE(res);
  3044. EXPECT_EQ(413, res->status);
  3045. res = cli_.Post("/test", "12345678", "text/plain");
  3046. ASSERT_TRUE(res);
  3047. EXPECT_EQ(200, res->status);
  3048. }
  3049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3050. TEST(SSLClientTest, UpdateCAStore) {
  3051. httplib::SSLClient httplib_client("www.google.com");
  3052. auto ca_store_1 = X509_STORE_new();
  3053. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3054. nullptr);
  3055. httplib_client.set_ca_cert_store(ca_store_1);
  3056. auto ca_store_2 = X509_STORE_new();
  3057. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3058. nullptr);
  3059. httplib_client.set_ca_cert_store(ca_store_2);
  3060. }
  3061. TEST(SSLClientTest, ServerNameIndication) {
  3062. SSLClient cli("httpbin.org", 443);
  3063. auto res = cli.Get("/get");
  3064. ASSERT_TRUE(res);
  3065. ASSERT_EQ(200, res->status);
  3066. }
  3067. TEST(SSLClientTest, ServerCertificateVerification1) {
  3068. SSLClient cli("google.com");
  3069. auto res = cli.Get("/");
  3070. ASSERT_TRUE(res);
  3071. ASSERT_EQ(301, res->status);
  3072. }
  3073. TEST(SSLClientTest, ServerCertificateVerification2) {
  3074. SSLClient cli("google.com");
  3075. cli.enable_server_certificate_verification(true);
  3076. cli.set_ca_cert_path("hello");
  3077. auto res = cli.Get("/");
  3078. ASSERT_TRUE(!res);
  3079. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3080. }
  3081. TEST(SSLClientTest, ServerCertificateVerification3) {
  3082. SSLClient cli("google.com");
  3083. cli.set_ca_cert_path(CA_CERT_FILE);
  3084. auto res = cli.Get("/");
  3085. ASSERT_TRUE(res);
  3086. ASSERT_EQ(301, res->status);
  3087. }
  3088. TEST(SSLClientTest, ServerCertificateVerification4) {
  3089. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3090. ASSERT_TRUE(svr.is_valid());
  3091. svr.Get("/test", [&](const Request &, Response &res) {
  3092. res.set_content("test", "text/plain");
  3093. svr.stop();
  3094. ASSERT_TRUE(true);
  3095. });
  3096. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3097. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3098. SSLClient cli("127.0.0.1", PORT);
  3099. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3100. cli.enable_server_certificate_verification(true);
  3101. cli.set_connection_timeout(30);
  3102. auto res = cli.Get("/test");
  3103. ASSERT_TRUE(res);
  3104. ASSERT_EQ(200, res->status);
  3105. t.join();
  3106. }
  3107. TEST(SSLClientTest, WildcardHostNameMatch) {
  3108. SSLClient cli("www.youtube.com");
  3109. cli.set_ca_cert_path(CA_CERT_FILE);
  3110. cli.enable_server_certificate_verification(true);
  3111. auto res = cli.Get("/");
  3112. ASSERT_TRUE(res);
  3113. ASSERT_EQ(200, res->status);
  3114. }
  3115. TEST(SSLClientServerTest, ClientCertPresent) {
  3116. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3117. CLIENT_CA_CERT_DIR);
  3118. ASSERT_TRUE(svr.is_valid());
  3119. svr.Get("/test", [&](const Request &req, Response &res) {
  3120. res.set_content("test", "text/plain");
  3121. svr.stop();
  3122. ASSERT_TRUE(true);
  3123. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3124. ASSERT_TRUE(peer_cert != nullptr);
  3125. auto subject_name = X509_get_subject_name(peer_cert);
  3126. ASSERT_TRUE(subject_name != nullptr);
  3127. std::string common_name;
  3128. {
  3129. char name[BUFSIZ];
  3130. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3131. name, sizeof(name));
  3132. common_name.assign(name, static_cast<size_t>(name_len));
  3133. }
  3134. EXPECT_EQ("Common Name", common_name);
  3135. X509_free(peer_cert);
  3136. });
  3137. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3138. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3139. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3140. cli.enable_server_certificate_verification(false);
  3141. cli.set_connection_timeout(30);
  3142. auto res = cli.Get("/test");
  3143. ASSERT_TRUE(res);
  3144. ASSERT_EQ(200, res->status);
  3145. t.join();
  3146. }
  3147. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3148. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3149. X509 *server_cert;
  3150. EVP_PKEY *server_private_key;
  3151. X509_STORE *client_ca_cert_store;
  3152. X509 *client_cert;
  3153. EVP_PKEY *client_private_key;
  3154. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3155. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3156. fclose(f);
  3157. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3158. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3159. fclose(f);
  3160. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3161. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3162. client_ca_cert_store = X509_STORE_new();
  3163. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3164. X509_free(client_cert);
  3165. fclose(f);
  3166. f = fopen(CLIENT_CERT_FILE, "r+");
  3167. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3168. fclose(f);
  3169. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3170. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3171. fclose(f);
  3172. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3173. ASSERT_TRUE(svr.is_valid());
  3174. svr.Get("/test", [&](const Request &req, Response &res) {
  3175. res.set_content("test", "text/plain");
  3176. svr.stop();
  3177. ASSERT_TRUE(true);
  3178. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3179. ASSERT_TRUE(peer_cert != nullptr);
  3180. auto subject_name = X509_get_subject_name(peer_cert);
  3181. ASSERT_TRUE(subject_name != nullptr);
  3182. std::string common_name;
  3183. {
  3184. char name[BUFSIZ];
  3185. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3186. name, sizeof(name));
  3187. common_name.assign(name, static_cast<size_t>(name_len));
  3188. }
  3189. EXPECT_EQ("Common Name", common_name);
  3190. X509_free(peer_cert);
  3191. });
  3192. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3193. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3194. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3195. cli.enable_server_certificate_verification(false);
  3196. cli.set_connection_timeout(30);
  3197. auto res = cli.Get("/test");
  3198. ASSERT_TRUE(res);
  3199. ASSERT_EQ(200, res->status);
  3200. X509_free(server_cert);
  3201. EVP_PKEY_free(server_private_key);
  3202. X509_free(client_cert);
  3203. EVP_PKEY_free(client_private_key);
  3204. t.join();
  3205. }
  3206. #endif
  3207. TEST(SSLClientServerTest, ClientCertMissing) {
  3208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3209. CLIENT_CA_CERT_DIR);
  3210. ASSERT_TRUE(svr.is_valid());
  3211. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3212. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3213. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3214. SSLClient cli(HOST, PORT);
  3215. auto res = cli.Get("/test");
  3216. cli.set_connection_timeout(30);
  3217. ASSERT_TRUE(!res);
  3218. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3219. svr.stop();
  3220. t.join();
  3221. }
  3222. TEST(SSLClientServerTest, TrustDirOptional) {
  3223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3224. ASSERT_TRUE(svr.is_valid());
  3225. svr.Get("/test", [&](const Request &, Response &res) {
  3226. res.set_content("test", "text/plain");
  3227. svr.stop();
  3228. });
  3229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3230. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3231. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3232. cli.enable_server_certificate_verification(false);
  3233. cli.set_connection_timeout(30);
  3234. auto res = cli.Get("/test");
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(200, res->status);
  3237. t.join();
  3238. }
  3239. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3240. class NoListenSSLServer : public SSLServer {
  3241. public:
  3242. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3243. const char *client_ca_cert_file_path,
  3244. const char *client_ca_cert_dir_path = nullptr)
  3245. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3246. client_ca_cert_dir_path),
  3247. stop_(false) {}
  3248. bool stop_;
  3249. private:
  3250. bool process_and_close_socket(socket_t /*sock*/) override {
  3251. // Don't create SSL context
  3252. while (!stop_) {
  3253. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3254. }
  3255. return true;
  3256. }
  3257. };
  3258. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3259. CLIENT_CA_CERT_FILE);
  3260. ASSERT_TRUE(svr.is_valid());
  3261. svr.Get("/test", [&](const Request &, Response &res) {
  3262. res.set_content("test", "text/plain");
  3263. });
  3264. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3265. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3266. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3267. cli.enable_server_certificate_verification(false);
  3268. cli.set_connection_timeout(1);
  3269. auto res = cli.Get("/test");
  3270. ASSERT_TRUE(!res);
  3271. EXPECT_EQ(Error::SSLConnection, res.error());
  3272. svr.stop_ = true;
  3273. svr.stop();
  3274. t.join();
  3275. }
  3276. #endif
  3277. #ifdef _WIN32
  3278. TEST(CleanupTest, WSACleanup) {
  3279. int ret = WSACleanup();
  3280. ASSERT_EQ(0, ret);
  3281. }
  3282. #endif
  3283. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3284. TEST(NoSSLSupport, SimpleInterface) {
  3285. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3286. }
  3287. #endif
  3288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3289. TEST(InvalidScheme, SimpleInterface) {
  3290. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3291. }
  3292. TEST(NoScheme, SimpleInterface) {
  3293. Client cli("yahoo.com:80");
  3294. ASSERT_TRUE(cli.is_valid());
  3295. }
  3296. TEST(YahooRedirectTest2, SimpleInterface) {
  3297. Client cli("http://yahoo.com");
  3298. auto res = cli.Get("/");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(301, res->status);
  3301. cli.set_follow_location(true);
  3302. res = cli.Get("/");
  3303. ASSERT_TRUE(res);
  3304. EXPECT_EQ(200, res->status);
  3305. EXPECT_EQ("https://yahoo.com/", res->location);
  3306. }
  3307. TEST(YahooRedirectTest3, SimpleInterface) {
  3308. Client cli("https://yahoo.com");
  3309. auto res = cli.Get("/");
  3310. ASSERT_TRUE(res);
  3311. EXPECT_EQ(301, res->status);
  3312. cli.set_follow_location(true);
  3313. res = cli.Get("/");
  3314. ASSERT_TRUE(res);
  3315. EXPECT_EQ(200, res->status);
  3316. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3317. }
  3318. TEST(YahooRedirectTest3, NewResultInterface) {
  3319. Client cli("https://yahoo.com");
  3320. auto res = cli.Get("/");
  3321. ASSERT_TRUE(res);
  3322. ASSERT_FALSE(!res);
  3323. ASSERT_TRUE(res);
  3324. ASSERT_FALSE(res == nullptr);
  3325. ASSERT_TRUE(res != nullptr);
  3326. EXPECT_EQ(Error::Success, res.error());
  3327. EXPECT_EQ(301, res.value().status);
  3328. EXPECT_EQ(301, (*res).status);
  3329. EXPECT_EQ(301, res->status);
  3330. cli.set_follow_location(true);
  3331. res = cli.Get("/");
  3332. ASSERT_TRUE(res);
  3333. EXPECT_EQ(Error::Success, res.error());
  3334. EXPECT_EQ(200, res.value().status);
  3335. EXPECT_EQ(200, (*res).status);
  3336. EXPECT_EQ(200, res->status);
  3337. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3338. }
  3339. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3340. TEST(DecodeWithChunkedEncoding, BrotliEncoding) {
  3341. Client cli("https://cdnjs.cloudflare.com");
  3342. auto res =
  3343. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3344. ASSERT_TRUE(res);
  3345. EXPECT_EQ(200, res->status);
  3346. EXPECT_EQ(287630, res->body.size());
  3347. EXPECT_EQ("application/javascript; charset=utf-8",
  3348. res->get_header_value("Content-Type"));
  3349. }
  3350. #endif
  3351. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  3352. Client cli("https://nghttp2.org");
  3353. cli.set_follow_location(true);
  3354. auto res =
  3355. cli.Get("/httpbin/"
  3356. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3357. ASSERT_TRUE(res);
  3358. EXPECT_EQ(200, res->status);
  3359. }
  3360. #endif