test.cc 137 KB

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