test.cc 133 KB

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