test.cc 144 KB

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