test.cc 120 KB

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