2
0

test.cc 110 KB

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