test.cc 139 KB

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