test.cc 112 KB

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