test.cc 125 KB

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