test.cc 138 KB

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