2
0

test.cc 140 KB

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