test.cc 138 KB

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