test.cc 134 KB

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