test.cc 121 KB

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