test.cc 141 KB

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