test.cc 111 KB

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