test.cc 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031
  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 *b2, const char *e2) {
  90. if (key.empty()) {
  91. key.assign(b2, e2);
  92. } else {
  93. val.assign(b2, e2);
  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_ptr ep) {
  1017. EXPECT_FALSE(ep == nullptr);
  1018. try{
  1019. std::rethrow_exception(ep);
  1020. }catch(std::exception& e){
  1021. EXPECT_EQ("abc", std::string(e.what()));
  1022. }
  1023. res.status = 500;
  1024. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1025. "text/html"); // <= Content-Length still 13 at this point
  1026. });
  1027. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1028. res.set_content("Hello World!\n", "text/plain");
  1029. throw std::runtime_error("abc");
  1030. });
  1031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1032. // Give GET time to get a few messages.
  1033. std::this_thread::sleep_for(std::chrono::seconds(1));
  1034. for (size_t i = 0; i < 10; i++) {
  1035. Client cli(HOST, PORT);
  1036. for (size_t j = 0; j < 100; j++) {
  1037. auto res = cli.Get("/hi");
  1038. ASSERT_TRUE(res);
  1039. EXPECT_EQ(500, res->status);
  1040. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1042. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1043. }
  1044. cli.set_keep_alive(true);
  1045. for (size_t j = 0; j < 100; j++) {
  1046. auto res = cli.Get("/hi");
  1047. ASSERT_TRUE(res);
  1048. EXPECT_EQ(500, res->status);
  1049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1050. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1051. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1052. }
  1053. }
  1054. svr.stop();
  1055. thread.join();
  1056. ASSERT_FALSE(svr.is_running());
  1057. }
  1058. #endif
  1059. TEST(NoContentTest, ContentLength) {
  1060. Server svr;
  1061. svr.Get("/hi",
  1062. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1064. // Give GET time to get a few messages.
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. {
  1067. Client cli(HOST, PORT);
  1068. auto res = cli.Get("/hi");
  1069. ASSERT_TRUE(res);
  1070. EXPECT_EQ(204, res->status);
  1071. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1072. }
  1073. svr.stop();
  1074. thread.join();
  1075. ASSERT_FALSE(svr.is_running());
  1076. }
  1077. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1078. Server svr;
  1079. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1080. if (req.path == "/routing_handler") {
  1081. res.set_header("PRE_ROUTING", "on");
  1082. res.set_content("Routing Handler", "text/plain");
  1083. return httplib::Server::HandlerResponse::Handled;
  1084. }
  1085. return httplib::Server::HandlerResponse::Unhandled;
  1086. });
  1087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1088. res.set_content("Error", "text/html");
  1089. });
  1090. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1091. if (req.path == "/routing_handler") {
  1092. res.set_header("POST_ROUTING", "on");
  1093. }
  1094. });
  1095. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1096. res.set_content("Hello World!\n", "text/plain");
  1097. });
  1098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1099. // Give GET time to get a few messages.
  1100. std::this_thread::sleep_for(std::chrono::seconds(1));
  1101. {
  1102. Client cli(HOST, PORT);
  1103. auto res = cli.Get("/routing_handler");
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ(200, res->status);
  1106. EXPECT_EQ("Routing Handler", res->body);
  1107. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1108. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1109. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1110. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1111. }
  1112. {
  1113. Client cli(HOST, PORT);
  1114. auto res = cli.Get("/hi");
  1115. ASSERT_TRUE(res);
  1116. EXPECT_EQ(200, res->status);
  1117. EXPECT_EQ("Hello World!\n", res->body);
  1118. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1119. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1120. }
  1121. {
  1122. Client cli(HOST, PORT);
  1123. auto res = cli.Get("/aaa");
  1124. ASSERT_TRUE(res);
  1125. EXPECT_EQ(404, res->status);
  1126. EXPECT_EQ("Error", res->body);
  1127. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1128. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1129. }
  1130. svr.stop();
  1131. thread.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. }
  1134. TEST(InvalidFormatTest, StatusCode) {
  1135. Server svr;
  1136. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1137. res.set_content("Hello World!\n", "text/plain");
  1138. res.status = 9999; // Status should be a three-digit code...
  1139. });
  1140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1141. // Give GET time to get a few messages.
  1142. std::this_thread::sleep_for(std::chrono::seconds(1));
  1143. {
  1144. Client cli(HOST, PORT);
  1145. auto res = cli.Get("/hi");
  1146. ASSERT_FALSE(res);
  1147. }
  1148. svr.stop();
  1149. thread.join();
  1150. ASSERT_FALSE(svr.is_running());
  1151. }
  1152. TEST(URLFragmentTest, WithFragment) {
  1153. Server svr;
  1154. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1155. EXPECT_TRUE(req.target == "/hi");
  1156. });
  1157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1158. std::this_thread::sleep_for(std::chrono::seconds(1));
  1159. {
  1160. Client cli(HOST, PORT);
  1161. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1162. EXPECT_TRUE(res);
  1163. EXPECT_EQ(200, res->status);
  1164. res = cli.Get("/hi%23key1=val1=key2=val2");
  1165. EXPECT_TRUE(res);
  1166. EXPECT_EQ(404, res->status);
  1167. }
  1168. svr.stop();
  1169. thread.join();
  1170. ASSERT_FALSE(svr.is_running());
  1171. }
  1172. class ServerTest : public ::testing::Test {
  1173. protected:
  1174. ServerTest()
  1175. : cli_(HOST, PORT)
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. ,
  1178. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1179. #endif
  1180. {
  1181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1182. cli_.enable_server_certificate_verification(false);
  1183. #endif
  1184. }
  1185. virtual void SetUp() {
  1186. svr_.set_mount_point("/", "./www");
  1187. svr_.set_mount_point("/mount", "./www2");
  1188. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1189. svr_.Get("/hi",
  1190. [&](const Request & /*req*/, Response &res) {
  1191. res.set_content("Hello World!", "text/plain");
  1192. })
  1193. .Get("/http_response_splitting",
  1194. [&](const Request & /*req*/, Response &res) {
  1195. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1196. EXPECT_EQ(0U, res.headers.size());
  1197. EXPECT_FALSE(res.has_header("a"));
  1198. res.set_header("a", "1\nSet-Cookie: a=1");
  1199. EXPECT_EQ(0U, res.headers.size());
  1200. EXPECT_FALSE(res.has_header("a"));
  1201. res.set_header("a", "1\rSet-Cookie: a=1");
  1202. EXPECT_EQ(0U, res.headers.size());
  1203. EXPECT_FALSE(res.has_header("a"));
  1204. res.set_header("a\r\nb", "0");
  1205. EXPECT_EQ(0U, res.headers.size());
  1206. EXPECT_FALSE(res.has_header("a"));
  1207. res.set_header("a\rb", "0");
  1208. EXPECT_EQ(0U, res.headers.size());
  1209. EXPECT_FALSE(res.has_header("a"));
  1210. res.set_header("a\nb", "0");
  1211. EXPECT_EQ(0U, res.headers.size());
  1212. EXPECT_FALSE(res.has_header("a"));
  1213. res.set_redirect("1\r\nSet-Cookie: a=1");
  1214. EXPECT_EQ(0U, res.headers.size());
  1215. EXPECT_FALSE(res.has_header("Location"));
  1216. })
  1217. .Get("/slow",
  1218. [&](const Request & /*req*/, Response &res) {
  1219. std::this_thread::sleep_for(std::chrono::seconds(2));
  1220. res.set_content("slow", "text/plain");
  1221. })
  1222. #if 0
  1223. .Post("/slowpost",
  1224. [&](const Request & /*req*/, Response &res) {
  1225. std::this_thread::sleep_for(std::chrono::seconds(2));
  1226. res.set_content("slow", "text/plain");
  1227. })
  1228. #endif
  1229. .Get("/remote_addr",
  1230. [&](const Request &req, Response &res) {
  1231. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1232. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1233. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1234. EXPECT_EQ(req.remote_port,
  1235. std::stoi(req.get_header_value("REMOTE_PORT")));
  1236. res.set_content(remote_addr.c_str(), "text/plain");
  1237. })
  1238. .Get("/endwith%",
  1239. [&](const Request & /*req*/, Response &res) {
  1240. res.set_content("Hello World!", "text/plain");
  1241. })
  1242. .Get("/a\\+\\+b",
  1243. [&](const Request &req, Response &res) {
  1244. ASSERT_TRUE(req.has_param("a +b"));
  1245. auto val = req.get_param_value("a +b");
  1246. res.set_content(val, "text/plain");
  1247. })
  1248. .Get("/", [&](const Request & /*req*/,
  1249. Response &res) { res.set_redirect("/hi"); })
  1250. .Post("/1", [](const Request & /*req*/,
  1251. Response &res) { res.set_redirect("/2", 303); })
  1252. .Get("/2",
  1253. [](const Request & /*req*/, Response &res) {
  1254. res.set_content("redirected.", "text/plain");
  1255. res.status = 200;
  1256. })
  1257. .Post("/person",
  1258. [&](const Request &req, Response &res) {
  1259. if (req.has_param("name") && req.has_param("note")) {
  1260. persons_[req.get_param_value("name")] =
  1261. req.get_param_value("note");
  1262. } else {
  1263. res.status = 400;
  1264. }
  1265. })
  1266. .Put("/person",
  1267. [&](const Request &req, Response &res) {
  1268. if (req.has_param("name") && req.has_param("note")) {
  1269. persons_[req.get_param_value("name")] =
  1270. req.get_param_value("note");
  1271. } else {
  1272. res.status = 400;
  1273. }
  1274. })
  1275. .Get("/person/(.*)",
  1276. [&](const Request &req, Response &res) {
  1277. string name = req.matches[1];
  1278. if (persons_.find(name) != persons_.end()) {
  1279. auto note = persons_[name];
  1280. res.set_content(note, "text/plain");
  1281. } else {
  1282. res.status = 404;
  1283. }
  1284. })
  1285. .Post("/x-www-form-urlencoded-json",
  1286. [&](const Request &req, Response &res) {
  1287. auto json = req.get_param_value("json");
  1288. ASSERT_EQ(JSON_DATA, json);
  1289. res.set_content(json, "appliation/json");
  1290. res.status = 200;
  1291. })
  1292. .Get("/streamed-chunked",
  1293. [&](const Request & /*req*/, Response &res) {
  1294. res.set_chunked_content_provider(
  1295. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1296. EXPECT_TRUE(sink.is_writable());
  1297. sink.os << "123";
  1298. sink.os << "456";
  1299. sink.os << "789";
  1300. sink.done();
  1301. return true;
  1302. });
  1303. })
  1304. .Get("/streamed-chunked2",
  1305. [&](const Request & /*req*/, Response &res) {
  1306. auto i = new int(0);
  1307. res.set_chunked_content_provider(
  1308. "text/plain",
  1309. [i](size_t /*offset*/, DataSink &sink) {
  1310. EXPECT_TRUE(sink.is_writable());
  1311. switch (*i) {
  1312. case 0: sink.os << "123"; break;
  1313. case 1: sink.os << "456"; break;
  1314. case 2: sink.os << "789"; break;
  1315. case 3: sink.done(); break;
  1316. }
  1317. (*i)++;
  1318. return true;
  1319. },
  1320. [i](bool success) {
  1321. EXPECT_TRUE(success);
  1322. delete i;
  1323. });
  1324. })
  1325. .Get("/streamed",
  1326. [&](const Request & /*req*/, Response &res) {
  1327. res.set_content_provider(
  1328. 6, "text/plain",
  1329. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1330. sink.os << (offset < 3 ? "a" : "b");
  1331. return true;
  1332. });
  1333. })
  1334. .Get("/streamed-with-range",
  1335. [&](const Request & /*req*/, Response &res) {
  1336. auto data = new std::string("abcdefg");
  1337. res.set_content_provider(
  1338. data->size(), "text/plain",
  1339. [data](size_t offset, size_t length, DataSink &sink) {
  1340. EXPECT_TRUE(sink.is_writable());
  1341. size_t DATA_CHUNK_SIZE = 4;
  1342. const auto &d = *data;
  1343. auto out_len =
  1344. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1345. auto ret =
  1346. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1347. EXPECT_TRUE(ret);
  1348. return true;
  1349. },
  1350. [data](bool success) {
  1351. EXPECT_TRUE(success);
  1352. delete data;
  1353. });
  1354. })
  1355. .Get("/streamed-cancel",
  1356. [&](const Request & /*req*/, Response &res) {
  1357. res.set_content_provider(
  1358. size_t(-1), "text/plain",
  1359. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1360. EXPECT_TRUE(sink.is_writable());
  1361. sink.os << "data_chunk";
  1362. return true;
  1363. });
  1364. })
  1365. .Get("/with-range",
  1366. [&](const Request & /*req*/, Response &res) {
  1367. res.set_content("abcdefg", "text/plain");
  1368. })
  1369. .Post("/chunked",
  1370. [&](const Request &req, Response & /*res*/) {
  1371. EXPECT_EQ(req.body, "dechunked post body");
  1372. })
  1373. .Post("/large-chunked",
  1374. [&](const Request &req, Response & /*res*/) {
  1375. std::string expected(6 * 30 * 1024u, 'a');
  1376. EXPECT_EQ(req.body, expected);
  1377. })
  1378. .Post("/multipart",
  1379. [&](const Request &req, Response & /*res*/) {
  1380. EXPECT_EQ(6u, req.files.size());
  1381. ASSERT_TRUE(!req.has_file("???"));
  1382. ASSERT_TRUE(req.body.empty());
  1383. {
  1384. const auto &file = req.get_file_value("text1");
  1385. EXPECT_TRUE(file.filename.empty());
  1386. EXPECT_EQ("text default", file.content);
  1387. }
  1388. {
  1389. const auto &file = req.get_file_value("text2");
  1390. EXPECT_TRUE(file.filename.empty());
  1391. EXPECT_EQ("aωb", file.content);
  1392. }
  1393. {
  1394. const auto &file = req.get_file_value("file1");
  1395. EXPECT_EQ("hello.txt", file.filename);
  1396. EXPECT_EQ("text/plain", file.content_type);
  1397. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1398. }
  1399. {
  1400. const auto &file = req.get_file_value("file3");
  1401. EXPECT_TRUE(file.filename.empty());
  1402. EXPECT_EQ("application/octet-stream", file.content_type);
  1403. EXPECT_EQ(0u, file.content.size());
  1404. }
  1405. {
  1406. const auto &file = req.get_file_value("file4");
  1407. EXPECT_TRUE(file.filename.empty());
  1408. EXPECT_EQ(0u, file.content.size());
  1409. EXPECT_EQ("application/json tmp-string", file.content_type);
  1410. }
  1411. })
  1412. .Post("/empty",
  1413. [&](const Request &req, Response &res) {
  1414. EXPECT_EQ(req.body, "");
  1415. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1416. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1417. res.set_content("empty", "text/plain");
  1418. })
  1419. .Post("/empty-no-content-type",
  1420. [&](const Request &req, Response &res) {
  1421. EXPECT_EQ(req.body, "");
  1422. EXPECT_FALSE(req.has_header("Content-Type"));
  1423. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1424. res.set_content("empty-no-content-type", "text/plain");
  1425. })
  1426. .Post("/post-large",
  1427. [&](const Request &req, Response &res) {
  1428. EXPECT_EQ(req.body, LARGE_DATA);
  1429. res.set_content(req.body, "text/plain");
  1430. })
  1431. .Put("/empty-no-content-type",
  1432. [&](const Request &req, Response &res) {
  1433. EXPECT_EQ(req.body, "");
  1434. EXPECT_FALSE(req.has_header("Content-Type"));
  1435. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1436. res.set_content("empty-no-content-type", "text/plain");
  1437. })
  1438. .Put("/put",
  1439. [&](const Request &req, Response &res) {
  1440. EXPECT_EQ(req.body, "PUT");
  1441. res.set_content(req.body, "text/plain");
  1442. })
  1443. .Put("/put-large",
  1444. [&](const Request &req, Response &res) {
  1445. EXPECT_EQ(req.body, LARGE_DATA);
  1446. res.set_content(req.body, "text/plain");
  1447. })
  1448. .Patch("/patch",
  1449. [&](const Request &req, Response &res) {
  1450. EXPECT_EQ(req.body, "PATCH");
  1451. res.set_content(req.body, "text/plain");
  1452. })
  1453. .Delete("/delete",
  1454. [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("DELETE", "text/plain");
  1456. })
  1457. .Delete("/delete-body",
  1458. [&](const Request &req, Response &res) {
  1459. EXPECT_EQ(req.body, "content");
  1460. res.set_content(req.body, "text/plain");
  1461. })
  1462. .Options(R"(\*)",
  1463. [&](const Request & /*req*/, Response &res) {
  1464. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1465. })
  1466. .Get("/request-target",
  1467. [&](const Request &req, Response & /*res*/) {
  1468. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1469. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1470. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1471. })
  1472. .Get("/long-query-value",
  1473. [&](const Request &req, Response & /*res*/) {
  1474. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1475. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1476. })
  1477. .Get("/array-param",
  1478. [&](const Request &req, Response & /*res*/) {
  1479. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1480. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1481. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1482. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1483. })
  1484. .Post("/validate-no-multiple-headers",
  1485. [&](const Request &req, Response & /*res*/) {
  1486. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1487. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1488. })
  1489. .Post("/content_receiver",
  1490. [&](const Request &req, Response &res,
  1491. const ContentReader &content_reader) {
  1492. if (req.is_multipart_form_data()) {
  1493. MultipartFormDataItems files;
  1494. content_reader(
  1495. [&](const MultipartFormData &file) {
  1496. files.push_back(file);
  1497. return true;
  1498. },
  1499. [&](const char *data, size_t data_length) {
  1500. files.back().content.append(data, data_length);
  1501. return true;
  1502. });
  1503. EXPECT_EQ(5u, files.size());
  1504. {
  1505. const auto &file = get_file_value(files, "text1");
  1506. EXPECT_TRUE(file.filename.empty());
  1507. EXPECT_EQ("text default", file.content);
  1508. }
  1509. {
  1510. const auto &file = get_file_value(files, "text2");
  1511. EXPECT_TRUE(file.filename.empty());
  1512. EXPECT_EQ("aωb", file.content);
  1513. }
  1514. {
  1515. const auto &file = get_file_value(files, "file1");
  1516. EXPECT_EQ("hello.txt", file.filename);
  1517. EXPECT_EQ("text/plain", file.content_type);
  1518. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1519. }
  1520. {
  1521. const auto &file = get_file_value(files, "file3");
  1522. EXPECT_TRUE(file.filename.empty());
  1523. EXPECT_EQ("application/octet-stream", file.content_type);
  1524. EXPECT_EQ(0u, file.content.size());
  1525. }
  1526. } else {
  1527. std::string body;
  1528. content_reader([&](const char *data, size_t data_length) {
  1529. EXPECT_EQ(7U, data_length);
  1530. body.append(data, data_length);
  1531. return true;
  1532. });
  1533. EXPECT_EQ(body, "content");
  1534. res.set_content(body, "text/plain");
  1535. }
  1536. })
  1537. .Put("/content_receiver",
  1538. [&](const Request & /*req*/, Response &res,
  1539. const ContentReader &content_reader) {
  1540. std::string body;
  1541. content_reader([&](const char *data, size_t data_length) {
  1542. body.append(data, data_length);
  1543. return true;
  1544. });
  1545. EXPECT_EQ(body, "content");
  1546. res.set_content(body, "text/plain");
  1547. })
  1548. .Patch("/content_receiver",
  1549. [&](const Request & /*req*/, Response &res,
  1550. const ContentReader &content_reader) {
  1551. std::string body;
  1552. content_reader([&](const char *data, size_t data_length) {
  1553. body.append(data, data_length);
  1554. return true;
  1555. });
  1556. EXPECT_EQ(body, "content");
  1557. res.set_content(body, "text/plain");
  1558. })
  1559. .Post("/query-string-and-body",
  1560. [&](const Request &req, Response & /*res*/) {
  1561. ASSERT_TRUE(req.has_param("key"));
  1562. EXPECT_EQ(req.get_param_value("key"), "value");
  1563. EXPECT_EQ(req.body, "content");
  1564. })
  1565. .Get("/last-request",
  1566. [&](const Request &req, Response & /*res*/) {
  1567. EXPECT_EQ("close", req.get_header_value("Connection"));
  1568. })
  1569. .Get(R"(/redirect/(\d+))",
  1570. [&](const Request &req, Response &res) {
  1571. auto num = std::stoi(req.matches[1]) + 1;
  1572. std::string url = "/redirect/" + std::to_string(num);
  1573. res.set_redirect(url);
  1574. })
  1575. .Post("/binary",
  1576. [&](const Request &req, Response &res) {
  1577. EXPECT_EQ(4U, req.body.size());
  1578. EXPECT_EQ("application/octet-stream",
  1579. req.get_header_value("Content-Type"));
  1580. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1581. res.set_content(req.body, "application/octet-stream");
  1582. })
  1583. .Put("/binary",
  1584. [&](const Request &req, Response &res) {
  1585. EXPECT_EQ(4U, req.body.size());
  1586. EXPECT_EQ("application/octet-stream",
  1587. req.get_header_value("Content-Type"));
  1588. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1589. res.set_content(req.body, "application/octet-stream");
  1590. })
  1591. .Patch("/binary",
  1592. [&](const Request &req, Response &res) {
  1593. EXPECT_EQ(4U, req.body.size());
  1594. EXPECT_EQ("application/octet-stream",
  1595. req.get_header_value("Content-Type"));
  1596. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1597. res.set_content(req.body, "application/octet-stream");
  1598. })
  1599. .Delete("/binary",
  1600. [&](const Request &req, Response &res) {
  1601. EXPECT_EQ(4U, req.body.size());
  1602. EXPECT_EQ("application/octet-stream",
  1603. req.get_header_value("Content-Type"));
  1604. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1605. res.set_content(req.body, "application/octet-stream");
  1606. })
  1607. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1608. .Get("/compress",
  1609. [&](const Request & /*req*/, Response &res) {
  1610. res.set_content(
  1611. "12345678901234567890123456789012345678901234567890123456789"
  1612. "01234567890123456789012345678901234567890",
  1613. "text/plain");
  1614. })
  1615. .Get("/nocompress",
  1616. [&](const Request & /*req*/, Response &res) {
  1617. res.set_content(
  1618. "12345678901234567890123456789012345678901234567890123456789"
  1619. "01234567890123456789012345678901234567890",
  1620. "application/octet-stream");
  1621. })
  1622. .Post("/compress-multipart",
  1623. [&](const Request &req, Response & /*res*/) {
  1624. EXPECT_EQ(2u, req.files.size());
  1625. ASSERT_TRUE(!req.has_file("???"));
  1626. {
  1627. const auto &file = req.get_file_value("key1");
  1628. EXPECT_TRUE(file.filename.empty());
  1629. EXPECT_EQ("test", file.content);
  1630. }
  1631. {
  1632. const auto &file = req.get_file_value("key2");
  1633. EXPECT_TRUE(file.filename.empty());
  1634. EXPECT_EQ("--abcdefg123", file.content);
  1635. }
  1636. })
  1637. #endif
  1638. ;
  1639. persons_["john"] = "programmer";
  1640. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1641. while (!svr_.is_running()) {
  1642. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1643. }
  1644. }
  1645. virtual void TearDown() {
  1646. svr_.stop();
  1647. if (!request_threads_.empty()) {
  1648. std::this_thread::sleep_for(std::chrono::seconds(1));
  1649. for (auto &t : request_threads_) {
  1650. t.join();
  1651. }
  1652. }
  1653. t_.join();
  1654. }
  1655. map<string, string> persons_;
  1656. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1657. SSLClient cli_;
  1658. SSLServer svr_;
  1659. #else
  1660. Client cli_;
  1661. Server svr_;
  1662. #endif
  1663. thread t_;
  1664. std::vector<thread> request_threads_;
  1665. };
  1666. TEST_F(ServerTest, GetMethod200) {
  1667. auto res = cli_.Get("/hi");
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ("HTTP/1.1", res->version);
  1670. EXPECT_EQ(200, res->status);
  1671. EXPECT_EQ("OK", res->reason);
  1672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1673. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1674. EXPECT_EQ("Hello World!", res->body);
  1675. }
  1676. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1677. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ("HTTP/1.1", res->version);
  1680. EXPECT_EQ(200, res->status);
  1681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1682. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1683. EXPECT_EQ("Hello World!", res->body);
  1684. }
  1685. TEST_F(ServerTest, GetMethod302) {
  1686. auto res = cli_.Get("/");
  1687. ASSERT_TRUE(res);
  1688. EXPECT_EQ(302, res->status);
  1689. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1690. }
  1691. TEST_F(ServerTest, GetMethod302Redirect) {
  1692. cli_.set_follow_location(true);
  1693. auto res = cli_.Get("/");
  1694. ASSERT_TRUE(res);
  1695. EXPECT_EQ(200, res->status);
  1696. EXPECT_EQ("Hello World!", res->body);
  1697. EXPECT_EQ("/hi", res->location);
  1698. }
  1699. TEST_F(ServerTest, GetMethod404) {
  1700. auto res = cli_.Get("/invalid");
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(404, res->status);
  1703. }
  1704. TEST_F(ServerTest, HeadMethod200) {
  1705. auto res = cli_.Head("/hi");
  1706. ASSERT_TRUE(res);
  1707. EXPECT_EQ(200, res->status);
  1708. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1709. EXPECT_TRUE(res->body.empty());
  1710. }
  1711. TEST_F(ServerTest, HeadMethod200Static) {
  1712. auto res = cli_.Head("/mount/dir/index.html");
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(200, res->status);
  1715. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1716. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1717. EXPECT_TRUE(res->body.empty());
  1718. }
  1719. TEST_F(ServerTest, HeadMethod404) {
  1720. auto res = cli_.Head("/invalid");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(404, res->status);
  1723. EXPECT_TRUE(res->body.empty());
  1724. }
  1725. TEST_F(ServerTest, GetMethodPersonJohn) {
  1726. auto res = cli_.Get("/person/john");
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(200, res->status);
  1729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1730. EXPECT_EQ("programmer", res->body);
  1731. }
  1732. TEST_F(ServerTest, PostMethod1) {
  1733. auto res = cli_.Get("/person/john1");
  1734. ASSERT_TRUE(res);
  1735. ASSERT_EQ(404, res->status);
  1736. res = cli_.Post("/person", "name=john1&note=coder",
  1737. "application/x-www-form-urlencoded");
  1738. ASSERT_TRUE(res);
  1739. ASSERT_EQ(200, res->status);
  1740. res = cli_.Get("/person/john1");
  1741. ASSERT_TRUE(res);
  1742. ASSERT_EQ(200, res->status);
  1743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1744. ASSERT_EQ("coder", res->body);
  1745. }
  1746. TEST_F(ServerTest, PostMethod2) {
  1747. auto res = cli_.Get("/person/john2");
  1748. ASSERT_TRUE(res);
  1749. ASSERT_EQ(404, res->status);
  1750. Params params;
  1751. params.emplace("name", "john2");
  1752. params.emplace("note", "coder");
  1753. res = cli_.Post("/person", params);
  1754. ASSERT_TRUE(res);
  1755. ASSERT_EQ(200, res->status);
  1756. res = cli_.Get("/person/john2");
  1757. ASSERT_TRUE(res);
  1758. ASSERT_EQ(200, res->status);
  1759. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1760. ASSERT_EQ("coder", res->body);
  1761. }
  1762. TEST_F(ServerTest, PutMethod3) {
  1763. auto res = cli_.Get("/person/john3");
  1764. ASSERT_TRUE(res);
  1765. ASSERT_EQ(404, res->status);
  1766. Params params;
  1767. params.emplace("name", "john3");
  1768. params.emplace("note", "coder");
  1769. res = cli_.Put("/person", params);
  1770. ASSERT_TRUE(res);
  1771. ASSERT_EQ(200, res->status);
  1772. res = cli_.Get("/person/john3");
  1773. ASSERT_TRUE(res);
  1774. ASSERT_EQ(200, res->status);
  1775. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1776. ASSERT_EQ("coder", res->body);
  1777. }
  1778. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1779. Params params;
  1780. params.emplace("json", JSON_DATA);
  1781. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1782. ASSERT_TRUE(res);
  1783. ASSERT_EQ(200, res->status);
  1784. ASSERT_EQ(JSON_DATA, res->body);
  1785. }
  1786. TEST_F(ServerTest, PostEmptyContent) {
  1787. auto res = cli_.Post("/empty", "", "text/plain");
  1788. ASSERT_TRUE(res);
  1789. ASSERT_EQ(200, res->status);
  1790. ASSERT_EQ("empty", res->body);
  1791. }
  1792. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1793. auto res = cli_.Post("/empty-no-content-type");
  1794. ASSERT_TRUE(res);
  1795. ASSERT_EQ(200, res->status);
  1796. ASSERT_EQ("empty-no-content-type", res->body);
  1797. }
  1798. TEST_F(ServerTest, PostLarge) {
  1799. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1800. ASSERT_TRUE(res);
  1801. ASSERT_EQ(200, res->status);
  1802. EXPECT_EQ(LARGE_DATA, res->body);
  1803. }
  1804. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1805. auto res = cli_.Put("/empty-no-content-type");
  1806. ASSERT_TRUE(res);
  1807. ASSERT_EQ(200, res->status);
  1808. ASSERT_EQ("empty-no-content-type", res->body);
  1809. }
  1810. TEST_F(ServerTest, GetMethodDir) {
  1811. auto res = cli_.Get("/dir/");
  1812. ASSERT_TRUE(res);
  1813. EXPECT_EQ(200, res->status);
  1814. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1815. auto body = R"(<html>
  1816. <head>
  1817. </head>
  1818. <body>
  1819. <a href="/dir/test.html">Test</a>
  1820. <a href="/hi">hi</a>
  1821. </body>
  1822. </html>
  1823. )";
  1824. EXPECT_EQ(body, res->body);
  1825. }
  1826. TEST_F(ServerTest, GetMethodDirTest) {
  1827. auto res = cli_.Get("/dir/test.html");
  1828. ASSERT_TRUE(res);
  1829. EXPECT_EQ(200, res->status);
  1830. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1831. EXPECT_EQ("test.html", res->body);
  1832. }
  1833. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1834. auto res = cli_.Get("/dir/../dir/test.html");
  1835. ASSERT_TRUE(res);
  1836. EXPECT_EQ(200, res->status);
  1837. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1838. EXPECT_EQ("test.html", res->body);
  1839. }
  1840. TEST_F(ServerTest, GetMethodInvalidPath) {
  1841. auto res = cli_.Get("/dir/../test.html");
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(404, res->status);
  1844. }
  1845. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1846. auto res = cli_.Get("/../www/dir/test.html");
  1847. ASSERT_TRUE(res);
  1848. EXPECT_EQ(404, res->status);
  1849. }
  1850. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1851. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(404, res->status);
  1854. }
  1855. TEST_F(ServerTest, GetMethodDirMountTest) {
  1856. auto res = cli_.Get("/mount/dir/test.html");
  1857. ASSERT_TRUE(res);
  1858. EXPECT_EQ(200, res->status);
  1859. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1860. EXPECT_EQ("test.html", res->body);
  1861. }
  1862. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1863. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(200, res->status);
  1866. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1867. EXPECT_EQ("test.html", res->body);
  1868. }
  1869. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1870. auto res = cli_.Get("/mount/dir/../test.html");
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(404, res->status);
  1873. }
  1874. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1875. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(404, res->status);
  1878. }
  1879. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1880. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(404, res->status);
  1883. }
  1884. TEST_F(ServerTest, PostMethod303) {
  1885. auto res = cli_.Post("/1", "body", "text/plain");
  1886. ASSERT_TRUE(res);
  1887. EXPECT_EQ(303, res->status);
  1888. EXPECT_EQ("/2", res->get_header_value("Location"));
  1889. }
  1890. TEST_F(ServerTest, PostMethod303Redirect) {
  1891. cli_.set_follow_location(true);
  1892. auto res = cli_.Post("/1", "body", "text/plain");
  1893. ASSERT_TRUE(res);
  1894. EXPECT_EQ(200, res->status);
  1895. EXPECT_EQ("redirected.", res->body);
  1896. EXPECT_EQ("/2", res->location);
  1897. }
  1898. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1899. auto res = cli_.Get("/dir/test.abcde");
  1900. ASSERT_TRUE(res);
  1901. EXPECT_EQ(200, res->status);
  1902. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1903. EXPECT_EQ("abcde", res->body);
  1904. }
  1905. TEST_F(ServerTest, StaticFileRange) {
  1906. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(206, res->status);
  1909. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1910. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1911. EXPECT_EQ(true, res->has_header("Content-Range"));
  1912. EXPECT_EQ(std::string("cd"), res->body);
  1913. }
  1914. TEST_F(ServerTest, InvalidBaseDirMount) {
  1915. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1916. }
  1917. TEST_F(ServerTest, Binary) {
  1918. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1919. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1920. "application/octet-stream");
  1921. ASSERT_TRUE(res);
  1922. ASSERT_EQ(200, res->status);
  1923. ASSERT_EQ(4U, res->body.size());
  1924. res = cli_.Put("/binary", binary.data(), binary.size(),
  1925. "application/octet-stream");
  1926. ASSERT_TRUE(res);
  1927. ASSERT_EQ(200, res->status);
  1928. ASSERT_EQ(4U, res->body.size());
  1929. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1930. "application/octet-stream");
  1931. ASSERT_TRUE(res);
  1932. ASSERT_EQ(200, res->status);
  1933. ASSERT_EQ(4U, res->body.size());
  1934. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1935. "application/octet-stream");
  1936. ASSERT_TRUE(res);
  1937. ASSERT_EQ(200, res->status);
  1938. ASSERT_EQ(4U, res->body.size());
  1939. }
  1940. TEST_F(ServerTest, BinaryString) {
  1941. auto binary = std::string("\x00\x01\x02\x03", 4);
  1942. auto res = cli_.Post("/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_.Put("/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_.Patch("/binary", binary, "application/octet-stream");
  1951. ASSERT_TRUE(res);
  1952. ASSERT_EQ(200, res->status);
  1953. ASSERT_EQ(4U, res->body.size());
  1954. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1955. ASSERT_TRUE(res);
  1956. ASSERT_EQ(200, res->status);
  1957. ASSERT_EQ(4U, res->body.size());
  1958. }
  1959. TEST_F(ServerTest, EmptyRequest) {
  1960. auto res = cli_.Get("");
  1961. ASSERT_TRUE(!res);
  1962. EXPECT_EQ(Error::Connection, res.error());
  1963. }
  1964. TEST_F(ServerTest, LongRequest) {
  1965. std::string request;
  1966. for (size_t i = 0; i < 545; i++) {
  1967. request += "/TooLongRequest";
  1968. }
  1969. request += "OK";
  1970. auto res = cli_.Get(request.c_str());
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(404, res->status);
  1973. }
  1974. TEST_F(ServerTest, TooLongRequest) {
  1975. std::string request;
  1976. for (size_t i = 0; i < 545; i++) {
  1977. request += "/TooLongRequest";
  1978. }
  1979. request += "_NG";
  1980. auto res = cli_.Get(request.c_str());
  1981. ASSERT_TRUE(res);
  1982. EXPECT_EQ(414, res->status);
  1983. }
  1984. TEST_F(ServerTest, LongHeader) {
  1985. Request req;
  1986. req.method = "GET";
  1987. req.path = "/hi";
  1988. std::string host_and_port;
  1989. host_and_port += HOST;
  1990. host_and_port += ":";
  1991. host_and_port += std::to_string(PORT);
  1992. req.headers.emplace("Host", host_and_port.c_str());
  1993. req.headers.emplace("Accept", "*/*");
  1994. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1995. req.headers.emplace(
  1996. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2025. "@@@@@@@@@@@@@@@@");
  2026. auto res = std::make_shared<Response>();
  2027. auto error = Error::Success;
  2028. auto ret = cli_.send(req, *res, error);
  2029. ASSERT_TRUE(ret);
  2030. EXPECT_EQ(200, res->status);
  2031. }
  2032. TEST_F(ServerTest, LongQueryValue) {
  2033. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2034. ASSERT_TRUE(res);
  2035. EXPECT_EQ(414, res->status);
  2036. }
  2037. TEST_F(ServerTest, TooLongHeader) {
  2038. Request req;
  2039. req.method = "GET";
  2040. req.path = "/hi";
  2041. std::string host_and_port;
  2042. host_and_port += HOST;
  2043. host_and_port += ":";
  2044. host_and_port += std::to_string(PORT);
  2045. req.headers.emplace("Host", host_and_port.c_str());
  2046. req.headers.emplace("Accept", "*/*");
  2047. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2048. req.headers.emplace(
  2049. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2078. "@@@@@@@@@@@@@@@@@");
  2079. auto res = std::make_shared<Response>();
  2080. auto error = Error::Success;
  2081. auto ret = cli_.send(req, *res, error);
  2082. ASSERT_TRUE(ret);
  2083. EXPECT_EQ(200, res->status);
  2084. }
  2085. TEST_F(ServerTest, PercentEncoding) {
  2086. auto res = cli_.Get("/e%6edwith%");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(200, res->status);
  2089. }
  2090. TEST_F(ServerTest, PercentEncodingUnicode) {
  2091. auto res = cli_.Get("/e%u006edwith%");
  2092. ASSERT_TRUE(res);
  2093. EXPECT_EQ(200, res->status);
  2094. }
  2095. TEST_F(ServerTest, InvalidPercentEncoding) {
  2096. auto res = cli_.Get("/%endwith%");
  2097. ASSERT_TRUE(res);
  2098. EXPECT_EQ(404, res->status);
  2099. }
  2100. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2101. auto res = cli_.Get("/%uendwith%");
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(404, res->status);
  2104. }
  2105. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2106. auto res = cli_.Get("/hello?aaa=bbb%");
  2107. ASSERT_TRUE(res);
  2108. EXPECT_EQ(404, res->status);
  2109. }
  2110. TEST_F(ServerTest, PlusSignEncoding) {
  2111. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2112. ASSERT_TRUE(res);
  2113. EXPECT_EQ(200, res->status);
  2114. EXPECT_EQ("a +b", res->body);
  2115. }
  2116. TEST_F(ServerTest, MultipartFormData) {
  2117. MultipartFormDataItems items = {
  2118. {"text1", "text default", "", ""},
  2119. {"text2", "aωb", "", ""},
  2120. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2121. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2122. {"file3", "", "", "application/octet-stream"},
  2123. {"file4", "", "", " application/json tmp-string "}};
  2124. auto res = cli_.Post("/multipart", items);
  2125. ASSERT_TRUE(res);
  2126. EXPECT_EQ(200, res->status);
  2127. }
  2128. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2129. auto res = cli_.Get("/hi");
  2130. ASSERT_TRUE(res);
  2131. EXPECT_EQ(200, res->status);
  2132. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2133. EXPECT_EQ("Hello World!", res->body);
  2134. }
  2135. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2136. Request req;
  2137. req.method = "POST";
  2138. req.path = "/chunked";
  2139. std::string host_and_port;
  2140. host_and_port += HOST;
  2141. host_and_port += ":";
  2142. host_and_port += std::to_string(PORT);
  2143. req.headers.emplace("Host", host_and_port.c_str());
  2144. req.headers.emplace("Accept", "*/*");
  2145. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2146. req.headers.emplace("Content-Type", "text/plain");
  2147. req.headers.emplace("Content-Length", "0");
  2148. req.headers.emplace(
  2149. "Transfer-Encoding",
  2150. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2151. // Client does not chunk, so make a chunked body manually.
  2152. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2153. auto res = std::make_shared<Response>();
  2154. auto error = Error::Success;
  2155. auto ret = cli_.send(req, *res, error);
  2156. ASSERT_TRUE(ret);
  2157. EXPECT_EQ(200, res->status);
  2158. }
  2159. TEST_F(ServerTest, GetStreamed2) {
  2160. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(206, res->status);
  2163. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2164. EXPECT_EQ(std::string("ab"), res->body);
  2165. }
  2166. TEST_F(ServerTest, GetStreamed) {
  2167. auto res = cli_.Get("/streamed");
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(200, res->status);
  2170. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2171. EXPECT_EQ(std::string("aaabbb"), res->body);
  2172. }
  2173. TEST_F(ServerTest, GetStreamedWithRange1) {
  2174. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(206, res->status);
  2177. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ(true, res->has_header("Content-Range"));
  2179. EXPECT_EQ(std::string("def"), res->body);
  2180. }
  2181. TEST_F(ServerTest, GetStreamedWithRange2) {
  2182. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(206, res->status);
  2185. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2186. EXPECT_EQ(true, res->has_header("Content-Range"));
  2187. EXPECT_EQ(std::string("bcdefg"), res->body);
  2188. }
  2189. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2190. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2191. ASSERT_TRUE(res);
  2192. EXPECT_EQ(206, res->status);
  2193. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2194. EXPECT_EQ(true, res->has_header("Content-Range"));
  2195. EXPECT_EQ(std::string("efg"), res->body);
  2196. }
  2197. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2198. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2199. ASSERT_TRUE(res);
  2200. EXPECT_EQ(206, res->status);
  2201. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2202. EXPECT_EQ(true, res->has_header("Content-Range"));
  2203. EXPECT_EQ(std::string("abcdefg"), res->body);
  2204. }
  2205. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2206. auto res = cli_.Get("/streamed-with-range",
  2207. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2208. "92233720368547758079223372036854775807"}});
  2209. ASSERT_TRUE(res);
  2210. EXPECT_EQ(416, res->status);
  2211. }
  2212. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2213. auto res =
  2214. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2215. EXPECT_EQ(206, res->status);
  2216. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2217. EXPECT_EQ(true, res->has_header("Content-Range"));
  2218. EXPECT_EQ(std::string("abcdefg"), res->body);
  2219. }
  2220. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2221. auto res =
  2222. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ(206, res->status);
  2225. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2226. EXPECT_EQ(false, res->has_header("Content-Range"));
  2227. EXPECT_EQ(269U, res->body.size());
  2228. }
  2229. TEST_F(ServerTest, GetStreamedEndless) {
  2230. uint64_t offset = 0;
  2231. auto res = cli_.Get("/streamed-cancel",
  2232. [&](const char * /*data*/, uint64_t data_length) {
  2233. if (offset < 100) {
  2234. offset += data_length;
  2235. return true;
  2236. }
  2237. return false;
  2238. });
  2239. ASSERT_TRUE(!res);
  2240. EXPECT_EQ(Error::Canceled, res.error());
  2241. }
  2242. TEST_F(ServerTest, ClientStop) {
  2243. std::vector<std::thread> threads;
  2244. for (auto i = 0; i < 3; i++) {
  2245. threads.emplace_back(thread([&]() {
  2246. auto res = cli_.Get("/streamed-cancel",
  2247. [&](const char *, uint64_t) { return true; });
  2248. ASSERT_TRUE(!res);
  2249. EXPECT_TRUE(res.error() == Error::Canceled ||
  2250. res.error() == Error::Read || res.error() == Error::Write);
  2251. }));
  2252. }
  2253. std::this_thread::sleep_for(std::chrono::seconds(2));
  2254. while (cli_.is_socket_open()) {
  2255. cli_.stop();
  2256. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2257. }
  2258. for (auto &t : threads) {
  2259. t.join();
  2260. }
  2261. }
  2262. TEST_F(ServerTest, GetWithRange1) {
  2263. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(206, res->status);
  2266. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2267. EXPECT_EQ(true, res->has_header("Content-Range"));
  2268. EXPECT_EQ(std::string("def"), res->body);
  2269. }
  2270. TEST_F(ServerTest, GetWithRange2) {
  2271. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ(206, res->status);
  2274. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2275. EXPECT_EQ(true, res->has_header("Content-Range"));
  2276. EXPECT_EQ(std::string("bcdefg"), res->body);
  2277. }
  2278. TEST_F(ServerTest, GetWithRange3) {
  2279. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(206, res->status);
  2282. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2283. EXPECT_EQ(true, res->has_header("Content-Range"));
  2284. EXPECT_EQ(std::string("a"), res->body);
  2285. }
  2286. TEST_F(ServerTest, GetWithRange4) {
  2287. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(206, res->status);
  2290. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2291. EXPECT_EQ(true, res->has_header("Content-Range"));
  2292. EXPECT_EQ(std::string("fg"), res->body);
  2293. }
  2294. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2295. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2296. ASSERT_TRUE(res);
  2297. EXPECT_EQ(416, res->status);
  2298. }
  2299. TEST_F(ServerTest, GetWithRangeMultipart) {
  2300. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(206, res->status);
  2303. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2304. EXPECT_EQ(false, res->has_header("Content-Range"));
  2305. EXPECT_EQ(269U, res->body.size());
  2306. }
  2307. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2308. auto res =
  2309. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(416, res->status);
  2312. }
  2313. TEST_F(ServerTest, GetStreamedChunked) {
  2314. auto res = cli_.Get("/streamed-chunked");
  2315. ASSERT_TRUE(res);
  2316. EXPECT_EQ(200, res->status);
  2317. EXPECT_EQ(std::string("123456789"), res->body);
  2318. }
  2319. TEST_F(ServerTest, GetStreamedChunked2) {
  2320. auto res = cli_.Get("/streamed-chunked2");
  2321. ASSERT_TRUE(res);
  2322. EXPECT_EQ(200, res->status);
  2323. EXPECT_EQ(std::string("123456789"), res->body);
  2324. }
  2325. TEST_F(ServerTest, LargeChunkedPost) {
  2326. Request req;
  2327. req.method = "POST";
  2328. req.path = "/large-chunked";
  2329. std::string host_and_port;
  2330. host_and_port += HOST;
  2331. host_and_port += ":";
  2332. host_and_port += std::to_string(PORT);
  2333. req.headers.emplace("Host", host_and_port.c_str());
  2334. req.headers.emplace("Accept", "*/*");
  2335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2336. req.headers.emplace("Content-Type", "text/plain");
  2337. req.headers.emplace("Content-Length", "0");
  2338. req.headers.emplace("Transfer-Encoding", "chunked");
  2339. std::string long_string(30 * 1024u, 'a');
  2340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2341. // Attempt to make a large enough post to exceed OS buffers, to test that
  2342. // the server handles short reads if the full chunk data isn't available.
  2343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2344. auto res = std::make_shared<Response>();
  2345. auto error = Error::Success;
  2346. auto ret = cli_.send(req, *res, error);
  2347. ASSERT_TRUE(ret);
  2348. EXPECT_EQ(200, res->status);
  2349. }
  2350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2351. auto res = cli_.Get("/remote_addr");
  2352. ASSERT_TRUE(res);
  2353. EXPECT_EQ(200, res->status);
  2354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2356. }
  2357. TEST_F(ServerTest, HTTPResponseSplitting) {
  2358. auto res = cli_.Get("/http_response_splitting");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ(200, res->status);
  2361. }
  2362. TEST_F(ServerTest, SlowRequest) {
  2363. request_threads_.push_back(
  2364. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2365. request_threads_.push_back(
  2366. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2367. request_threads_.push_back(
  2368. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2369. }
  2370. #if 0
  2371. TEST_F(ServerTest, SlowPost) {
  2372. char buffer[64 * 1024];
  2373. memset(buffer, 0x42, sizeof(buffer));
  2374. auto res = cli_.Post(
  2375. "/slowpost", 64 * 1024 * 1024,
  2376. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2377. auto ret = sink.write(buffer, sizeof(buffer));
  2378. EXPECT_TRUE(ret);
  2379. return true;
  2380. },
  2381. "text/plain");
  2382. ASSERT_TRUE(res);
  2383. EXPECT_EQ(200, res->status);
  2384. }
  2385. TEST_F(ServerTest, SlowPostFail) {
  2386. char buffer[64 * 1024];
  2387. memset(buffer, 0x42, sizeof(buffer));
  2388. cli_.set_write_timeout(std::chrono::seconds(0));
  2389. auto res = cli_.Post(
  2390. "/slowpost", 64 * 1024 * 1024,
  2391. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2392. sink.write(buffer, sizeof(buffer));
  2393. return true;
  2394. },
  2395. "text/plain");
  2396. ASSERT_TRUE(!res);
  2397. EXPECT_EQ(Error::Write, res.error());
  2398. }
  2399. #endif
  2400. TEST_F(ServerTest, Put) {
  2401. auto res = cli_.Put("/put", "PUT", "text/plain");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(200, res->status);
  2404. EXPECT_EQ("PUT", res->body);
  2405. }
  2406. TEST_F(ServerTest, PutWithContentProvider) {
  2407. auto res = cli_.Put(
  2408. "/put", 3,
  2409. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2410. EXPECT_TRUE(sink.is_writable());
  2411. sink.os << "PUT";
  2412. return true;
  2413. },
  2414. "text/plain");
  2415. ASSERT_TRUE(res);
  2416. EXPECT_EQ(200, res->status);
  2417. EXPECT_EQ("PUT", res->body);
  2418. }
  2419. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2420. auto res = cli_.Post(
  2421. "/post", 42,
  2422. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2423. return false;
  2424. },
  2425. "text/plain");
  2426. ASSERT_TRUE(!res);
  2427. EXPECT_EQ(Error::Canceled, res.error());
  2428. }
  2429. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2430. auto res = cli_.Put(
  2431. "/put",
  2432. [](size_t /*offset*/, DataSink &sink) {
  2433. EXPECT_TRUE(sink.is_writable());
  2434. sink.os << "PUT";
  2435. sink.done();
  2436. return true;
  2437. },
  2438. "text/plain");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(200, res->status);
  2441. EXPECT_EQ("PUT", res->body);
  2442. }
  2443. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2444. auto res = cli_.Post(
  2445. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2446. "text/plain");
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Canceled, res.error());
  2449. }
  2450. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2451. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2452. cli_.set_compress(true);
  2453. auto res = cli_.Put(
  2454. "/put", 3,
  2455. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2456. EXPECT_TRUE(sink.is_writable());
  2457. sink.os << "PUT";
  2458. return true;
  2459. },
  2460. "text/plain");
  2461. ASSERT_TRUE(res);
  2462. EXPECT_EQ(200, res->status);
  2463. EXPECT_EQ("PUT", res->body);
  2464. }
  2465. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2466. cli_.set_compress(true);
  2467. auto res = cli_.Post(
  2468. "/post", 42,
  2469. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2470. return false;
  2471. },
  2472. "text/plain");
  2473. ASSERT_TRUE(!res);
  2474. EXPECT_EQ(Error::Canceled, res.error());
  2475. }
  2476. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2477. cli_.set_compress(true);
  2478. auto res = cli_.Put(
  2479. "/put",
  2480. [](size_t /*offset*/, DataSink &sink) {
  2481. EXPECT_TRUE(sink.is_writable());
  2482. sink.os << "PUT";
  2483. sink.done();
  2484. return true;
  2485. },
  2486. "text/plain");
  2487. ASSERT_TRUE(res);
  2488. EXPECT_EQ(200, res->status);
  2489. EXPECT_EQ("PUT", res->body);
  2490. }
  2491. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2492. cli_.set_compress(true);
  2493. auto res = cli_.Post(
  2494. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2495. "text/plain");
  2496. ASSERT_TRUE(!res);
  2497. EXPECT_EQ(Error::Canceled, res.error());
  2498. }
  2499. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2500. cli_.set_compress(true);
  2501. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2502. ASSERT_TRUE(res);
  2503. EXPECT_EQ(200, res->status);
  2504. EXPECT_EQ(LARGE_DATA, res->body);
  2505. }
  2506. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2507. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2508. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2509. Client cli(s.c_str());
  2510. cli.enable_server_certificate_verification(false);
  2511. #else
  2512. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2513. Client cli(s.c_str());
  2514. #endif
  2515. cli.set_compress(true);
  2516. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(200, res->status);
  2519. EXPECT_EQ(LARGE_DATA, res->body);
  2520. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2521. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2522. }
  2523. TEST_F(ServerTest, PutContentWithDeflate) {
  2524. cli_.set_compress(false);
  2525. Headers headers;
  2526. headers.emplace("Content-Encoding", "deflate");
  2527. // PUT in deflate format:
  2528. auto res = cli_.Put("/put", headers,
  2529. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2530. ASSERT_TRUE(res);
  2531. EXPECT_EQ(200, res->status);
  2532. EXPECT_EQ("PUT", res->body);
  2533. }
  2534. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2535. Headers headers;
  2536. headers.emplace("Accept-Encoding", "gzip, deflate");
  2537. auto res = cli_.Get("/streamed-chunked", headers);
  2538. ASSERT_TRUE(res);
  2539. EXPECT_EQ(200, res->status);
  2540. EXPECT_EQ(std::string("123456789"), res->body);
  2541. }
  2542. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2543. Headers headers;
  2544. headers.emplace("Accept-Encoding", "gzip, deflate");
  2545. auto res = cli_.Get("/streamed-chunked2", headers);
  2546. ASSERT_TRUE(res);
  2547. EXPECT_EQ(200, res->status);
  2548. EXPECT_EQ(std::string("123456789"), res->body);
  2549. }
  2550. TEST(GzipDecompressor, ChunkedDecompression) {
  2551. std::string data;
  2552. for (size_t i = 0; i < 32 * 1024; ++i) {
  2553. data.push_back(static_cast<char>('a' + i % 26));
  2554. }
  2555. std::string compressed_data;
  2556. {
  2557. httplib::detail::gzip_compressor compressor;
  2558. bool result = compressor.compress(
  2559. data.data(), data.size(),
  2560. /*last=*/true,
  2561. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2562. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2563. compressed_data_size);
  2564. return true;
  2565. });
  2566. ASSERT_TRUE(result);
  2567. }
  2568. std::string decompressed_data;
  2569. {
  2570. httplib::detail::gzip_decompressor decompressor;
  2571. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2572. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2573. size_t chunk_size = 130;
  2574. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2575. chunk_begin += chunk_size) {
  2576. size_t current_chunk_size =
  2577. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2578. bool result = decompressor.decompress(
  2579. compressed_data.data() + chunk_begin, current_chunk_size,
  2580. [&](const char *decompressed_data_chunk,
  2581. size_t decompressed_data_chunk_size) {
  2582. decompressed_data.insert(decompressed_data.size(),
  2583. decompressed_data_chunk,
  2584. decompressed_data_chunk_size);
  2585. return true;
  2586. });
  2587. ASSERT_TRUE(result);
  2588. }
  2589. }
  2590. ASSERT_EQ(data, decompressed_data);
  2591. }
  2592. #ifdef _WIN32
  2593. TEST(GzipDecompressor, LargeRandomData) {
  2594. // prepare large random data that is difficult to be compressed and is
  2595. // expected to have large size even when compressed
  2596. std::random_device seed_gen;
  2597. std::mt19937 random(seed_gen());
  2598. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2599. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2600. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2601. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2602. // compress data over 4GiB
  2603. std::string compressed_data;
  2604. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2605. httplib::detail::gzip_compressor compressor;
  2606. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2607. data.size() * sizeof(std::uint32_t), true,
  2608. [&](const char *data, size_t size) {
  2609. compressed_data.insert(
  2610. compressed_data.size(), data, size);
  2611. return true;
  2612. });
  2613. ASSERT_TRUE(result);
  2614. // FIXME: compressed data size is expected to be greater than 4GiB,
  2615. // but there is no guarantee
  2616. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2617. // decompress data over 4GiB
  2618. std::string decompressed_data;
  2619. decompressed_data.reserve(data_size);
  2620. httplib::detail::gzip_decompressor decompressor;
  2621. result = decompressor.decompress(
  2622. compressed_data.data(), compressed_data.size(),
  2623. [&](const char *data, size_t size) {
  2624. decompressed_data.insert(decompressed_data.size(), data, size);
  2625. return true;
  2626. });
  2627. ASSERT_TRUE(result);
  2628. // compare
  2629. ASSERT_EQ(data_size, decompressed_data.size());
  2630. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2631. 0);
  2632. }
  2633. #endif
  2634. #endif
  2635. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2636. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2637. Headers headers;
  2638. headers.emplace("Accept-Encoding", "br");
  2639. auto res = cli_.Get("/streamed-chunked", headers);
  2640. ASSERT_TRUE(res);
  2641. EXPECT_EQ(200, res->status);
  2642. EXPECT_EQ(std::string("123456789"), res->body);
  2643. }
  2644. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2645. Headers headers;
  2646. headers.emplace("Accept-Encoding", "br");
  2647. auto res = cli_.Get("/streamed-chunked2", headers);
  2648. ASSERT_TRUE(res);
  2649. EXPECT_EQ(200, res->status);
  2650. EXPECT_EQ(std::string("123456789"), res->body);
  2651. }
  2652. #endif
  2653. TEST_F(ServerTest, Patch) {
  2654. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2655. ASSERT_TRUE(res);
  2656. EXPECT_EQ(200, res->status);
  2657. EXPECT_EQ("PATCH", res->body);
  2658. }
  2659. TEST_F(ServerTest, Delete) {
  2660. auto res = cli_.Delete("/delete");
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(200, res->status);
  2663. EXPECT_EQ("DELETE", res->body);
  2664. }
  2665. TEST_F(ServerTest, DeleteContentReceiver) {
  2666. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2667. ASSERT_TRUE(res);
  2668. EXPECT_EQ(200, res->status);
  2669. EXPECT_EQ("content", res->body);
  2670. }
  2671. TEST_F(ServerTest, Options) {
  2672. auto res = cli_.Options("*");
  2673. ASSERT_TRUE(res);
  2674. EXPECT_EQ(200, res->status);
  2675. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2676. EXPECT_TRUE(res->body.empty());
  2677. }
  2678. TEST_F(ServerTest, URL) {
  2679. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2680. ASSERT_TRUE(res);
  2681. EXPECT_EQ(200, res->status);
  2682. }
  2683. TEST_F(ServerTest, ArrayParam) {
  2684. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2685. ASSERT_TRUE(res);
  2686. EXPECT_EQ(200, res->status);
  2687. }
  2688. TEST_F(ServerTest, NoMultipleHeaders) {
  2689. Headers headers = {{"Content-Length", "5"}};
  2690. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2691. "text/plain");
  2692. ASSERT_TRUE(res);
  2693. EXPECT_EQ(200, res->status);
  2694. }
  2695. TEST_F(ServerTest, PostContentReceiver) {
  2696. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2697. ASSERT_TRUE(res);
  2698. ASSERT_EQ(200, res->status);
  2699. ASSERT_EQ("content", res->body);
  2700. }
  2701. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2702. MultipartFormDataItems items = {
  2703. {"text1", "text default", "", ""},
  2704. {"text2", "aωb", "", ""},
  2705. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2706. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2707. {"file3", "", "", "application/octet-stream"},
  2708. };
  2709. auto res = cli_.Post("/content_receiver", items);
  2710. ASSERT_TRUE(res);
  2711. EXPECT_EQ(200, res->status);
  2712. }
  2713. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2714. MultipartFormDataItems items = {
  2715. {"text1", "text default", "", ""},
  2716. {"text2", "aωb", "", ""},
  2717. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2718. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2719. {"file3", "", "", "application/octet-stream"},
  2720. };
  2721. auto boundary = std::string("+++++");
  2722. std::string body;
  2723. for (const auto &item : items) {
  2724. body += "--" + boundary + "\r\n";
  2725. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2726. if (!item.filename.empty()) {
  2727. body += "; filename=\"" + item.filename + "\"";
  2728. }
  2729. body += "\r\n";
  2730. if (!item.content_type.empty()) {
  2731. body += "Content-Type: " + item.content_type + "\r\n";
  2732. }
  2733. body += "\r\n";
  2734. body += item.content + "\r\n";
  2735. }
  2736. body += "--" + boundary + "--\r\n";
  2737. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2738. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ(200, res->status);
  2741. }
  2742. TEST_F(ServerTest, PostContentReceiverGzip) {
  2743. cli_.set_compress(true);
  2744. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2745. ASSERT_TRUE(res);
  2746. ASSERT_EQ(200, res->status);
  2747. ASSERT_EQ("content", res->body);
  2748. }
  2749. TEST_F(ServerTest, PutContentReceiver) {
  2750. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2751. ASSERT_TRUE(res);
  2752. ASSERT_EQ(200, res->status);
  2753. ASSERT_EQ("content", res->body);
  2754. }
  2755. TEST_F(ServerTest, PatchContentReceiver) {
  2756. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2757. ASSERT_TRUE(res);
  2758. ASSERT_EQ(200, res->status);
  2759. ASSERT_EQ("content", res->body);
  2760. }
  2761. TEST_F(ServerTest, PostQueryStringAndBody) {
  2762. auto res =
  2763. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2764. ASSERT_TRUE(res);
  2765. ASSERT_EQ(200, res->status);
  2766. }
  2767. TEST_F(ServerTest, HTTP2Magic) {
  2768. Request req;
  2769. req.method = "PRI";
  2770. req.path = "*";
  2771. req.body = "SM";
  2772. auto res = std::make_shared<Response>();
  2773. auto error = Error::Success;
  2774. auto ret = cli_.send(req, *res, error);
  2775. ASSERT_TRUE(ret);
  2776. EXPECT_EQ(400, res->status);
  2777. }
  2778. TEST_F(ServerTest, KeepAlive) {
  2779. auto res = cli_.Get("/hi");
  2780. ASSERT_TRUE(res);
  2781. EXPECT_EQ(200, res->status);
  2782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2783. EXPECT_EQ("Hello World!", res->body);
  2784. res = cli_.Get("/hi");
  2785. ASSERT_TRUE(res);
  2786. EXPECT_EQ(200, res->status);
  2787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2788. EXPECT_EQ("Hello World!", res->body);
  2789. res = cli_.Get("/hi");
  2790. ASSERT_TRUE(res);
  2791. EXPECT_EQ(200, res->status);
  2792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2793. EXPECT_EQ("Hello World!", res->body);
  2794. res = cli_.Get("/not-exist");
  2795. ASSERT_TRUE(res);
  2796. EXPECT_EQ(404, res->status);
  2797. res = cli_.Post("/empty", "", "text/plain");
  2798. ASSERT_TRUE(res);
  2799. EXPECT_EQ(200, res->status);
  2800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2801. EXPECT_EQ("empty", res->body);
  2802. EXPECT_EQ("close", res->get_header_value("Connection"));
  2803. res = cli_.Post(
  2804. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2805. "text/plain");
  2806. ASSERT_TRUE(res);
  2807. EXPECT_EQ(200, res->status);
  2808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2809. EXPECT_EQ("empty", res->body);
  2810. cli_.set_keep_alive(false);
  2811. res = cli_.Get("/last-request");
  2812. ASSERT_TRUE(res);
  2813. EXPECT_EQ(200, res->status);
  2814. EXPECT_EQ("close", res->get_header_value("Connection"));
  2815. }
  2816. TEST_F(ServerTest, TooManyRedirect) {
  2817. cli_.set_follow_location(true);
  2818. auto res = cli_.Get("/redirect/0");
  2819. ASSERT_TRUE(!res);
  2820. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2821. }
  2822. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2823. TEST_F(ServerTest, Gzip) {
  2824. Headers headers;
  2825. headers.emplace("Accept-Encoding", "gzip, deflate");
  2826. auto res = cli_.Get("/compress", headers);
  2827. ASSERT_TRUE(res);
  2828. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2830. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2831. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2832. "7890123456789012345678901234567890",
  2833. res->body);
  2834. EXPECT_EQ(200, res->status);
  2835. }
  2836. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2837. auto res = cli_.Get("/compress");
  2838. ASSERT_TRUE(res);
  2839. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2841. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2842. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2843. "7890123456789012345678901234567890",
  2844. res->body);
  2845. EXPECT_EQ(200, res->status);
  2846. }
  2847. TEST_F(ServerTest, GzipWithContentReceiver) {
  2848. Headers headers;
  2849. headers.emplace("Accept-Encoding", "gzip, deflate");
  2850. std::string body;
  2851. auto res = cli_.Get("/compress", headers,
  2852. [&](const char *data, uint64_t data_length) {
  2853. EXPECT_EQ(100U, data_length);
  2854. body.append(data, data_length);
  2855. return true;
  2856. });
  2857. ASSERT_TRUE(res);
  2858. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2860. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2862. "7890123456789012345678901234567890",
  2863. body);
  2864. EXPECT_EQ(200, res->status);
  2865. }
  2866. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2867. Headers headers;
  2868. headers.emplace("Accept-Encoding", "gzip, deflate");
  2869. cli_.set_decompress(false);
  2870. auto res = cli_.Get("/compress", headers);
  2871. ASSERT_TRUE(res);
  2872. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2873. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2874. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2875. EXPECT_EQ(33U, res->body.size());
  2876. EXPECT_EQ(200, res->status);
  2877. }
  2878. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2879. std::string body;
  2880. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2881. EXPECT_EQ(100U, data_length);
  2882. body.append(data, data_length);
  2883. return true;
  2884. });
  2885. ASSERT_TRUE(res);
  2886. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2888. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2889. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2890. "7890123456789012345678901234567890",
  2891. body);
  2892. EXPECT_EQ(200, res->status);
  2893. }
  2894. TEST_F(ServerTest, NoGzip) {
  2895. Headers headers;
  2896. headers.emplace("Accept-Encoding", "gzip, deflate");
  2897. auto res = cli_.Get("/nocompress", headers);
  2898. ASSERT_TRUE(res);
  2899. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2900. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2901. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2902. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2903. "7890123456789012345678901234567890",
  2904. res->body);
  2905. EXPECT_EQ(200, res->status);
  2906. }
  2907. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2908. Headers headers;
  2909. headers.emplace("Accept-Encoding", "gzip, deflate");
  2910. std::string body;
  2911. auto res = cli_.Get("/nocompress", headers,
  2912. [&](const char *data, uint64_t data_length) {
  2913. EXPECT_EQ(100U, data_length);
  2914. body.append(data, data_length);
  2915. return true;
  2916. });
  2917. ASSERT_TRUE(res);
  2918. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2919. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2920. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2921. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2922. "7890123456789012345678901234567890",
  2923. body);
  2924. EXPECT_EQ(200, res->status);
  2925. }
  2926. TEST_F(ServerTest, MultipartFormDataGzip) {
  2927. MultipartFormDataItems items = {
  2928. {"key1", "test", "", ""},
  2929. {"key2", "--abcdefg123", "", ""},
  2930. };
  2931. cli_.set_compress(true);
  2932. auto res = cli_.Post("/compress-multipart", items);
  2933. ASSERT_TRUE(res);
  2934. EXPECT_EQ(200, res->status);
  2935. }
  2936. #endif
  2937. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2938. TEST_F(ServerTest, Brotli) {
  2939. Headers headers;
  2940. headers.emplace("Accept-Encoding", "br");
  2941. auto res = cli_.Get("/compress", headers);
  2942. ASSERT_TRUE(res);
  2943. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2945. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2946. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2947. "7890123456789012345678901234567890",
  2948. res->body);
  2949. EXPECT_EQ(200, res->status);
  2950. }
  2951. #endif
  2952. // Sends a raw request to a server listening at HOST:PORT.
  2953. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2954. std::string *resp = nullptr) {
  2955. auto error = Error::Success;
  2956. auto client_sock = detail::create_client_socket(
  2957. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  2958. /*connection_timeout_sec=*/5, 0,
  2959. /*read_timeout_sec=*/5, 0,
  2960. /*write_timeout_sec=*/5, 0, std::string(), error);
  2961. if (client_sock == INVALID_SOCKET) { return false; }
  2962. auto ret = detail::process_client_socket(
  2963. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2964. if (req.size() !=
  2965. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2966. return false;
  2967. }
  2968. char buf[512];
  2969. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2970. while (line_reader.getline()) {
  2971. if (resp) { *resp += line_reader.ptr(); }
  2972. }
  2973. return true;
  2974. });
  2975. detail::close_socket(client_sock);
  2976. return ret;
  2977. }
  2978. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2979. Server svr;
  2980. std::string header_value;
  2981. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2982. header_value = req.get_header_value("foo");
  2983. res.set_content("ok", "text/plain");
  2984. });
  2985. thread t = thread([&] { svr.listen(HOST, PORT); });
  2986. while (!svr.is_running()) {
  2987. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2988. }
  2989. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2990. // like characters are not treated the same - use vertical tab and escape.
  2991. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2992. "foo: \t \v bar \x1B\t \r\n"
  2993. "Connection: close\r\n"
  2994. "\r\n";
  2995. ASSERT_TRUE(send_request(5, req));
  2996. svr.stop();
  2997. t.join();
  2998. EXPECT_EQ(header_value, "\v bar \x1B");
  2999. }
  3000. // Sends a raw request and verifies that there isn't a crash or exception.
  3001. static void test_raw_request(const std::string &req,
  3002. std::string *out = nullptr) {
  3003. Server svr;
  3004. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3005. res.set_content("ok", "text/plain");
  3006. });
  3007. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3008. res.set_content("ok", "text/plain");
  3009. });
  3010. // Server read timeout must be longer than the client read timeout for the
  3011. // bug to reproduce, probably to force the server to process a request
  3012. // without a trailing blank line.
  3013. const time_t client_read_timeout_sec = 1;
  3014. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3015. bool listen_thread_ok = false;
  3016. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3017. while (!svr.is_running()) {
  3018. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3019. }
  3020. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3021. svr.stop();
  3022. t.join();
  3023. EXPECT_TRUE(listen_thread_ok);
  3024. }
  3025. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3026. // A certain header line causes an exception if the header property is parsed
  3027. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3028. test_raw_request(
  3029. "GET /hi HTTP/1.1\r\n"
  3030. " : "
  3031. " "
  3032. " ");
  3033. }
  3034. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3035. // A certain header line causes an exception if the header property *name* is
  3036. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3037. // greedy matcher and requires backtracking when there are a lot of ":"
  3038. // characters.
  3039. // This occurs with libc++ but not libstdc++.
  3040. test_raw_request(
  3041. "GET /hi HTTP/1.1\r\n"
  3042. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3043. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3044. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3045. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3046. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3047. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3048. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3049. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3050. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3051. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3052. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3053. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3054. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3055. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3056. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3057. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3058. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3059. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3060. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3061. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3062. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3063. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3064. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3065. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3066. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3067. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3068. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3069. "&&&%%%");
  3070. }
  3071. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  3072. // Make sure this doesn't crash the server.
  3073. // In a previous version of the header line regex, the "\r" rendered the line
  3074. // unparseable and the regex engine repeatedly backtracked, trying to look for
  3075. // a new position where the leading white space ended and the field value
  3076. // began.
  3077. // The crash occurs with libc++ but not libstdc++.
  3078. test_raw_request("GET /hi HTTP/1.1\r\n"
  3079. "a:" +
  3080. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3081. "\r\n"
  3082. "\r\n");
  3083. }
  3084. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3085. std::string out;
  3086. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3087. "Content-Type: text/plain\r\n"
  3088. "Transfer-Encoding: chunked\r\n"
  3089. "\r\n"
  3090. "nothex\r\n",
  3091. &out);
  3092. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3093. }
  3094. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3095. std::string out;
  3096. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3097. "Content-Type: text/plain\r\n"
  3098. "Transfer-Encoding: chunked\r\n"
  3099. "\r\n"
  3100. "3\r\n"
  3101. "xyz\r\n"
  3102. "NaN\r\n",
  3103. &out);
  3104. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3105. }
  3106. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3107. std::string out;
  3108. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3109. "Content-Type: text/plain\r\n"
  3110. "Transfer-Encoding: chunked\r\n"
  3111. "\r\n"
  3112. // Length is too large for 64 bits.
  3113. "1ffffffffffffffff\r\n"
  3114. "xyz\r\n",
  3115. &out);
  3116. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3117. }
  3118. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3119. test_raw_request("GET /hi HTTP/1.1\r\n"
  3120. "Content-Type: text/plain\r\n\r");
  3121. }
  3122. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3123. std::string out;
  3124. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3125. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3126. }
  3127. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3128. Server svr;
  3129. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3130. res.set_header("Cache-Control", "no-cache");
  3131. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3132. DataSink &sink) {
  3133. char buffer[27];
  3134. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3135. auto ret = sink.write(buffer, size);
  3136. EXPECT_TRUE(ret);
  3137. std::this_thread::sleep_for(std::chrono::seconds(1));
  3138. return true;
  3139. });
  3140. });
  3141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3142. while (!svr.is_running()) {
  3143. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3144. }
  3145. Client client(HOST, PORT);
  3146. const Headers headers = {{"Accept", "text/event-stream"}};
  3147. auto get_thread = std::thread([&client, &headers]() {
  3148. auto res = client.Get(
  3149. "/events", headers,
  3150. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3151. });
  3152. // Give GET time to get a few messages.
  3153. std::this_thread::sleep_for(std::chrono::seconds(2));
  3154. svr.stop();
  3155. listen_thread.join();
  3156. get_thread.join();
  3157. ASSERT_FALSE(svr.is_running());
  3158. }
  3159. TEST(StreamingTest, NoContentLengthStreaming) {
  3160. Server svr;
  3161. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3162. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3163. if (offset < 6) {
  3164. sink.os << (offset < 3 ? "a" : "b");
  3165. } else {
  3166. sink.done();
  3167. }
  3168. return true;
  3169. });
  3170. });
  3171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3172. while (!svr.is_running()) {
  3173. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3174. }
  3175. Client client(HOST, PORT);
  3176. auto get_thread = std::thread([&client]() {
  3177. std::string s;
  3178. auto res =
  3179. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3180. s += std::string(data, len);
  3181. return true;
  3182. });
  3183. EXPECT_EQ("aaabbb", s);
  3184. });
  3185. // Give GET time to get a few messages.
  3186. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3187. svr.stop();
  3188. listen_thread.join();
  3189. get_thread.join();
  3190. ASSERT_FALSE(svr.is_running());
  3191. }
  3192. TEST(MountTest, Unmount) {
  3193. Server svr;
  3194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3195. while (!svr.is_running()) {
  3196. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3197. }
  3198. // Give GET time to get a few messages.
  3199. std::this_thread::sleep_for(std::chrono::seconds(1));
  3200. Client cli("localhost", PORT);
  3201. svr.set_mount_point("/mount2", "./www2");
  3202. auto res = cli.Get("/");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(404, res->status);
  3205. res = cli.Get("/mount2/dir/test.html");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(200, res->status);
  3208. svr.set_mount_point("/", "./www");
  3209. res = cli.Get("/dir/");
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(200, res->status);
  3212. svr.remove_mount_point("/");
  3213. res = cli.Get("/dir/");
  3214. ASSERT_TRUE(res);
  3215. EXPECT_EQ(404, res->status);
  3216. svr.remove_mount_point("/mount2");
  3217. res = cli.Get("/mount2/dir/test.html");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(404, res->status);
  3220. svr.stop();
  3221. listen_thread.join();
  3222. ASSERT_FALSE(svr.is_running());
  3223. }
  3224. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3225. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3226. Server svr;
  3227. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  3228. throw std::runtime_error("exception...");
  3229. // res.set_content("Hello World!", "text/plain");
  3230. });
  3231. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3232. while (!svr.is_running()) {
  3233. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3234. }
  3235. // Give GET time to get a few messages.
  3236. std::this_thread::sleep_for(std::chrono::seconds(1));
  3237. Client cli("localhost", PORT);
  3238. auto res = cli.Get("/hi");
  3239. ASSERT_TRUE(res);
  3240. EXPECT_EQ(500, res->status);
  3241. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3242. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3243. svr.stop();
  3244. listen_thread.join();
  3245. ASSERT_FALSE(svr.is_running());
  3246. }
  3247. #endif
  3248. TEST(KeepAliveTest, ReadTimeout) {
  3249. Server svr;
  3250. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3251. std::this_thread::sleep_for(std::chrono::seconds(2));
  3252. res.set_content("a", "text/plain");
  3253. });
  3254. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3255. res.set_content("b", "text/plain");
  3256. });
  3257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3258. while (!svr.is_running()) {
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3260. }
  3261. // Give GET time to get a few messages.
  3262. std::this_thread::sleep_for(std::chrono::seconds(1));
  3263. Client cli("localhost", PORT);
  3264. cli.set_keep_alive(true);
  3265. cli.set_read_timeout(std::chrono::seconds(1));
  3266. auto resa = cli.Get("/a");
  3267. ASSERT_TRUE(!resa);
  3268. EXPECT_EQ(Error::Read, resa.error());
  3269. auto resb = cli.Get("/b");
  3270. ASSERT_TRUE(resb);
  3271. EXPECT_EQ(200, resb->status);
  3272. EXPECT_EQ("b", resb->body);
  3273. svr.stop();
  3274. listen_thread.join();
  3275. ASSERT_FALSE(svr.is_running());
  3276. }
  3277. TEST(KeepAliveTest, Issue1041) {
  3278. const auto resourcePath = "/hi";
  3279. Server svr;
  3280. svr.set_keep_alive_timeout(3);
  3281. svr.Get(resourcePath, [](const httplib::Request &, httplib::Response &res) {
  3282. res.set_content("Hello World!", "text/plain");
  3283. });
  3284. auto a2 = std::async(std::launch::async, [&svr] { svr.listen(HOST, PORT); });
  3285. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3286. Client cli(HOST, PORT);
  3287. cli.set_keep_alive(true);
  3288. auto result = cli.Get(resourcePath);
  3289. ASSERT_TRUE(result);
  3290. EXPECT_EQ(200, result->status);
  3291. std::this_thread::sleep_for(std::chrono::seconds(5));
  3292. result = cli.Get(resourcePath);
  3293. ASSERT_TRUE(result);
  3294. EXPECT_EQ(200, result->status);
  3295. svr.stop();
  3296. a2.wait();
  3297. }
  3298. TEST(ClientProblemDetectionTest, ContentProvider) {
  3299. Server svr;
  3300. size_t content_length = 1024 * 1024;
  3301. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content_provider(
  3303. content_length, "text/plain",
  3304. [&](size_t offset, size_t length, DataSink &sink) {
  3305. auto out_len = std::min(length, static_cast<size_t>(1024));
  3306. std::string out(out_len, '@');
  3307. sink.write(out.data(), out_len);
  3308. return offset < 4096;
  3309. },
  3310. [](bool success) { ASSERT_FALSE(success); });
  3311. });
  3312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3313. while (!svr.is_running()) {
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3315. }
  3316. // Give GET time to get a few messages.
  3317. std::this_thread::sleep_for(std::chrono::seconds(1));
  3318. Client cli("localhost", PORT);
  3319. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3320. return false;
  3321. });
  3322. ASSERT_FALSE(res);
  3323. svr.stop();
  3324. listen_thread.join();
  3325. ASSERT_FALSE(svr.is_running());
  3326. }
  3327. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3328. Server svr;
  3329. svr.set_error_handler([](Request const &, Response &res) -> void {
  3330. res.set_chunked_content_provider(
  3331. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3332. sink.os << "hello";
  3333. sink.os << "world";
  3334. sink.done();
  3335. return true;
  3336. });
  3337. });
  3338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3339. while (!svr.is_running()) {
  3340. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3341. }
  3342. // Give GET time to get a few messages.
  3343. std::this_thread::sleep_for(std::chrono::seconds(1));
  3344. Client cli("localhost", PORT);
  3345. auto res = cli.Get("/");
  3346. ASSERT_TRUE(res);
  3347. EXPECT_EQ(404, res->status);
  3348. EXPECT_EQ("helloworld", res->body);
  3349. svr.stop();
  3350. listen_thread.join();
  3351. ASSERT_FALSE(svr.is_running());
  3352. }
  3353. TEST(GetWithParametersTest, GetWithParameters) {
  3354. Server svr;
  3355. svr.Get("/", [&](const Request &req, Response &) {
  3356. EXPECT_EQ("world", req.get_param_value("hello"));
  3357. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3358. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3359. });
  3360. svr.Get("/params", [&](const Request &req, Response &) {
  3361. EXPECT_EQ("world", req.get_param_value("hello"));
  3362. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3363. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3364. });
  3365. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3366. EXPECT_EQ("resource-id", req.matches[1]);
  3367. EXPECT_EQ("foo", req.get_param_value("param1"));
  3368. EXPECT_EQ("bar", req.get_param_value("param2"));
  3369. });
  3370. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3371. while (!svr.is_running()) {
  3372. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3373. }
  3374. std::this_thread::sleep_for(std::chrono::seconds(1));
  3375. {
  3376. Client cli(HOST, PORT);
  3377. Params params;
  3378. params.emplace("hello", "world");
  3379. params.emplace("hello2", "world2");
  3380. params.emplace("hello3", "world3");
  3381. auto res = cli.Get("/", params, Headers{});
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(200, res->status);
  3384. }
  3385. {
  3386. Client cli(HOST, PORT);
  3387. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3388. ASSERT_TRUE(res);
  3389. EXPECT_EQ(200, res->status);
  3390. }
  3391. {
  3392. Client cli(HOST, PORT);
  3393. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3394. ASSERT_TRUE(res);
  3395. EXPECT_EQ(200, res->status);
  3396. }
  3397. svr.stop();
  3398. listen_thread.join();
  3399. ASSERT_FALSE(svr.is_running());
  3400. }
  3401. TEST(GetWithParametersTest, GetWithParameters2) {
  3402. Server svr;
  3403. svr.Get("/", [&](const Request &req, Response &res) {
  3404. auto text = req.get_param_value("hello");
  3405. res.set_content(text, "text/plain");
  3406. });
  3407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3408. while (!svr.is_running()) {
  3409. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3410. }
  3411. std::this_thread::sleep_for(std::chrono::seconds(1));
  3412. Client cli("localhost", PORT);
  3413. Params params;
  3414. params.emplace("hello", "world");
  3415. std::string body;
  3416. auto res = cli.Get("/", params, Headers{},
  3417. [&](const char *data, size_t data_length) {
  3418. body.append(data, data_length);
  3419. return true;
  3420. });
  3421. ASSERT_TRUE(res);
  3422. EXPECT_EQ(200, res->status);
  3423. EXPECT_EQ("world", body);
  3424. svr.stop();
  3425. listen_thread.join();
  3426. ASSERT_FALSE(svr.is_running());
  3427. }
  3428. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3429. Client cli("httpbin.org");
  3430. cli.set_default_headers({make_range_header({{1, 10}})});
  3431. cli.set_connection_timeout(5);
  3432. {
  3433. auto res = cli.Get("/range/32");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ("bcdefghijk", res->body);
  3436. EXPECT_EQ(206, res->status);
  3437. }
  3438. {
  3439. auto res = cli.Get("/range/32");
  3440. ASSERT_TRUE(res);
  3441. EXPECT_EQ("bcdefghijk", res->body);
  3442. EXPECT_EQ(206, res->status);
  3443. }
  3444. }
  3445. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3446. Server svr;
  3447. svr.set_default_headers({{"Hello", "World"}});
  3448. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3449. res.set_content("ok", "text/plain");
  3450. });
  3451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3452. while (!svr.is_running()) {
  3453. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3454. }
  3455. std::this_thread::sleep_for(std::chrono::seconds(1));
  3456. Client cli("localhost", PORT);
  3457. auto res = cli.Get("/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(200, res->status);
  3460. EXPECT_EQ("ok", res->body);
  3461. EXPECT_EQ("World", res->get_header_value("Hello"));
  3462. svr.stop();
  3463. listen_thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. }
  3466. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3467. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3469. ASSERT_TRUE(svr.is_valid());
  3470. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3471. std::this_thread::sleep_for(std::chrono::seconds(2));
  3472. res.set_content("a", "text/plain");
  3473. });
  3474. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3475. res.set_content("b", "text/plain");
  3476. });
  3477. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3478. while (!svr.is_running()) {
  3479. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3480. }
  3481. // Give GET time to get a few messages.
  3482. std::this_thread::sleep_for(std::chrono::seconds(1));
  3483. SSLClient cli("localhost", PORT);
  3484. cli.enable_server_certificate_verification(false);
  3485. cli.set_keep_alive(true);
  3486. cli.set_read_timeout(std::chrono::seconds(1));
  3487. auto resa = cli.Get("/a");
  3488. ASSERT_TRUE(!resa);
  3489. EXPECT_EQ(Error::Read, resa.error());
  3490. auto resb = cli.Get("/b");
  3491. ASSERT_TRUE(resb);
  3492. EXPECT_EQ(200, resb->status);
  3493. EXPECT_EQ("b", resb->body);
  3494. svr.stop();
  3495. listen_thread.join();
  3496. ASSERT_FALSE(svr.is_running());
  3497. }
  3498. #endif
  3499. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3500. protected:
  3501. ServerTestWithAI_PASSIVE()
  3502. : cli_(HOST, PORT)
  3503. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3504. ,
  3505. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3506. #endif
  3507. {
  3508. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3509. cli_.enable_server_certificate_verification(false);
  3510. #endif
  3511. }
  3512. virtual void SetUp() {
  3513. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3514. res.set_content("Hello World!", "text/plain");
  3515. });
  3516. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  3517. while (!svr_.is_running()) {
  3518. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3519. }
  3520. }
  3521. virtual void TearDown() {
  3522. svr_.stop();
  3523. t_.join();
  3524. }
  3525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3526. SSLClient cli_;
  3527. SSLServer svr_;
  3528. #else
  3529. Client cli_;
  3530. Server svr_;
  3531. #endif
  3532. thread t_;
  3533. };
  3534. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3535. auto res = cli_.Get("/hi");
  3536. ASSERT_TRUE(res);
  3537. EXPECT_EQ(200, res->status);
  3538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. EXPECT_EQ("Hello World!", res->body);
  3540. }
  3541. class ServerUpDownTest : public ::testing::Test {
  3542. protected:
  3543. ServerUpDownTest() : cli_(HOST, PORT) {}
  3544. virtual void SetUp() {
  3545. t_ = thread([&]() {
  3546. svr_.bind_to_any_port(HOST);
  3547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3548. ASSERT_TRUE(svr_.listen_after_bind());
  3549. });
  3550. while (!svr_.is_running()) {
  3551. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3552. }
  3553. }
  3554. virtual void TearDown() {
  3555. svr_.stop();
  3556. t_.join();
  3557. }
  3558. Client cli_;
  3559. Server svr_;
  3560. thread t_;
  3561. };
  3562. TEST_F(ServerUpDownTest, QuickStartStop) {
  3563. // Should not crash, especially when run with
  3564. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3565. }
  3566. class PayloadMaxLengthTest : public ::testing::Test {
  3567. protected:
  3568. PayloadMaxLengthTest()
  3569. : cli_(HOST, PORT)
  3570. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3571. ,
  3572. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3573. #endif
  3574. {
  3575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3576. cli_.enable_server_certificate_verification(false);
  3577. #endif
  3578. }
  3579. virtual void SetUp() {
  3580. svr_.set_payload_max_length(8);
  3581. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3582. res.set_content("test", "text/plain");
  3583. });
  3584. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3585. while (!svr_.is_running()) {
  3586. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3587. }
  3588. }
  3589. virtual void TearDown() {
  3590. svr_.stop();
  3591. t_.join();
  3592. }
  3593. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3594. SSLClient cli_;
  3595. SSLServer svr_;
  3596. #else
  3597. Client cli_;
  3598. Server svr_;
  3599. #endif
  3600. thread t_;
  3601. };
  3602. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3603. auto res = cli_.Post("/test", "123456789", "text/plain");
  3604. ASSERT_TRUE(res);
  3605. EXPECT_EQ(413, res->status);
  3606. res = cli_.Post("/test", "12345678", "text/plain");
  3607. ASSERT_TRUE(res);
  3608. EXPECT_EQ(200, res->status);
  3609. }
  3610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3611. TEST(SSLClientTest, UpdateCAStore) {
  3612. httplib::SSLClient httplib_client("www.google.com");
  3613. auto ca_store_1 = X509_STORE_new();
  3614. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3615. nullptr);
  3616. httplib_client.set_ca_cert_store(ca_store_1);
  3617. auto ca_store_2 = X509_STORE_new();
  3618. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3619. nullptr);
  3620. httplib_client.set_ca_cert_store(ca_store_2);
  3621. }
  3622. TEST(SSLClientTest, ServerNameIndication_Online) {
  3623. SSLClient cli("httpbin.org", 443);
  3624. auto res = cli.Get("/get");
  3625. ASSERT_TRUE(res);
  3626. ASSERT_EQ(200, res->status);
  3627. }
  3628. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3629. SSLClient cli("google.com");
  3630. auto res = cli.Get("/");
  3631. ASSERT_TRUE(res);
  3632. ASSERT_EQ(301, res->status);
  3633. }
  3634. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3635. SSLClient cli("google.com");
  3636. cli.enable_server_certificate_verification(true);
  3637. cli.set_ca_cert_path("hello");
  3638. auto res = cli.Get("/");
  3639. ASSERT_TRUE(!res);
  3640. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3641. }
  3642. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3643. SSLClient cli("google.com");
  3644. cli.set_ca_cert_path(CA_CERT_FILE);
  3645. auto res = cli.Get("/");
  3646. ASSERT_TRUE(res);
  3647. ASSERT_EQ(301, res->status);
  3648. }
  3649. TEST(SSLClientTest, ServerCertificateVerification4) {
  3650. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3651. ASSERT_TRUE(svr.is_valid());
  3652. svr.Get("/test", [&](const Request &, Response &res) {
  3653. res.set_content("test", "text/plain");
  3654. svr.stop();
  3655. ASSERT_TRUE(true);
  3656. });
  3657. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3658. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3659. SSLClient cli("127.0.0.1", PORT);
  3660. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3661. cli.enable_server_certificate_verification(true);
  3662. cli.set_connection_timeout(30);
  3663. auto res = cli.Get("/test");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(200, res->status);
  3666. t.join();
  3667. }
  3668. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3669. SSLClient cli("www.youtube.com");
  3670. cli.set_ca_cert_path(CA_CERT_FILE);
  3671. cli.enable_server_certificate_verification(true);
  3672. cli.set_follow_location(true);
  3673. auto res = cli.Get("/");
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(200, res->status);
  3676. }
  3677. #if 0
  3678. TEST(SSLClientTest, SetInterfaceWithINET6) {
  3679. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  3680. ASSERT_TRUE(cli != nullptr);
  3681. cli->set_address_family(AF_INET6);
  3682. cli->set_interface("en0");
  3683. auto res = cli->Get("/get");
  3684. ASSERT_TRUE(res);
  3685. ASSERT_EQ(200, res->status);
  3686. }
  3687. #endif
  3688. TEST(SSLClientServerTest, ClientCertPresent) {
  3689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3690. CLIENT_CA_CERT_DIR);
  3691. ASSERT_TRUE(svr.is_valid());
  3692. svr.Get("/test", [&](const Request &req, Response &res) {
  3693. res.set_content("test", "text/plain");
  3694. svr.stop();
  3695. ASSERT_TRUE(true);
  3696. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3697. ASSERT_TRUE(peer_cert != nullptr);
  3698. auto subject_name = X509_get_subject_name(peer_cert);
  3699. ASSERT_TRUE(subject_name != nullptr);
  3700. std::string common_name;
  3701. {
  3702. char name[BUFSIZ];
  3703. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3704. name, sizeof(name));
  3705. common_name.assign(name, static_cast<size_t>(name_len));
  3706. }
  3707. EXPECT_EQ("Common Name", common_name);
  3708. X509_free(peer_cert);
  3709. });
  3710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3711. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3712. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3713. cli.enable_server_certificate_verification(false);
  3714. cli.set_connection_timeout(30);
  3715. auto res = cli.Get("/test");
  3716. ASSERT_TRUE(res);
  3717. ASSERT_EQ(200, res->status);
  3718. t.join();
  3719. }
  3720. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3721. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3722. X509 *server_cert;
  3723. EVP_PKEY *server_private_key;
  3724. X509_STORE *client_ca_cert_store;
  3725. X509 *client_cert;
  3726. EVP_PKEY *client_private_key;
  3727. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3728. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3729. fclose(f);
  3730. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3731. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3732. fclose(f);
  3733. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3734. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3735. client_ca_cert_store = X509_STORE_new();
  3736. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3737. X509_free(client_cert);
  3738. fclose(f);
  3739. f = fopen(CLIENT_CERT_FILE, "r+");
  3740. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3741. fclose(f);
  3742. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3743. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3744. fclose(f);
  3745. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3746. ASSERT_TRUE(svr.is_valid());
  3747. svr.Get("/test", [&](const Request &req, Response &res) {
  3748. res.set_content("test", "text/plain");
  3749. svr.stop();
  3750. ASSERT_TRUE(true);
  3751. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3752. ASSERT_TRUE(peer_cert != nullptr);
  3753. auto subject_name = X509_get_subject_name(peer_cert);
  3754. ASSERT_TRUE(subject_name != nullptr);
  3755. std::string common_name;
  3756. {
  3757. char name[BUFSIZ];
  3758. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3759. name, sizeof(name));
  3760. common_name.assign(name, static_cast<size_t>(name_len));
  3761. }
  3762. EXPECT_EQ("Common Name", common_name);
  3763. X509_free(peer_cert);
  3764. });
  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, client_cert, client_private_key);
  3768. cli.enable_server_certificate_verification(false);
  3769. cli.set_connection_timeout(30);
  3770. auto res = cli.Get("/test");
  3771. ASSERT_TRUE(res);
  3772. ASSERT_EQ(200, res->status);
  3773. X509_free(server_cert);
  3774. EVP_PKEY_free(server_private_key);
  3775. X509_free(client_cert);
  3776. EVP_PKEY_free(client_private_key);
  3777. t.join();
  3778. }
  3779. #endif
  3780. TEST(SSLClientServerTest, ClientCertMissing) {
  3781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3782. CLIENT_CA_CERT_DIR);
  3783. ASSERT_TRUE(svr.is_valid());
  3784. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3785. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3786. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3787. SSLClient cli(HOST, PORT);
  3788. auto res = cli.Get("/test");
  3789. cli.set_connection_timeout(30);
  3790. ASSERT_TRUE(!res);
  3791. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3792. svr.stop();
  3793. t.join();
  3794. }
  3795. TEST(SSLClientServerTest, TrustDirOptional) {
  3796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3797. ASSERT_TRUE(svr.is_valid());
  3798. svr.Get("/test", [&](const Request &, Response &res) {
  3799. res.set_content("test", "text/plain");
  3800. svr.stop();
  3801. });
  3802. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3803. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3804. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3805. cli.enable_server_certificate_verification(false);
  3806. cli.set_connection_timeout(30);
  3807. auto res = cli.Get("/test");
  3808. ASSERT_TRUE(res);
  3809. ASSERT_EQ(200, res->status);
  3810. t.join();
  3811. }
  3812. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3813. class NoListenSSLServer : public SSLServer {
  3814. public:
  3815. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3816. const char *client_ca_cert_file_path,
  3817. const char *client_ca_cert_dir_path = nullptr)
  3818. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3819. client_ca_cert_dir_path),
  3820. stop_(false) {}
  3821. bool stop_;
  3822. private:
  3823. bool process_and_close_socket(socket_t /*sock*/) override {
  3824. // Don't create SSL context
  3825. while (!stop_) {
  3826. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3827. }
  3828. return true;
  3829. }
  3830. };
  3831. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3832. CLIENT_CA_CERT_FILE);
  3833. ASSERT_TRUE(svr.is_valid());
  3834. svr.Get("/test", [&](const Request &, Response &res) {
  3835. res.set_content("test", "text/plain");
  3836. });
  3837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3838. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3839. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3840. cli.enable_server_certificate_verification(false);
  3841. cli.set_connection_timeout(1);
  3842. auto res = cli.Get("/test");
  3843. ASSERT_TRUE(!res);
  3844. EXPECT_EQ(Error::SSLConnection, res.error());
  3845. svr.stop_ = true;
  3846. svr.stop();
  3847. t.join();
  3848. }
  3849. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  3850. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  3851. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  3852. SSL_CTX_set_options(&ssl_ctx,
  3853. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3854. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  3855. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  3856. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  3857. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  3858. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  3859. "ECDHE-DSS-AES128-SHA256:"
  3860. "ECDHE-RSA-AES256-SHA256:"
  3861. "ECDHE-DSS-AES256-SHA256:";
  3862. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  3863. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  3864. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  3865. SSL_FILETYPE_PEM) != 1) {
  3866. return false;
  3867. }
  3868. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  3869. CLIENT_CA_CERT_DIR);
  3870. SSL_CTX_set_verify(
  3871. &ssl_ctx,
  3872. SSL_VERIFY_PEER |
  3873. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3874. nullptr);
  3875. return true;
  3876. };
  3877. SSLServer svr(setup_ssl_ctx_callback);
  3878. ASSERT_TRUE(svr.is_valid());
  3879. svr.Get("/test", [&](const Request &req, Response &res) {
  3880. res.set_content("test", "text/plain");
  3881. svr.stop();
  3882. ASSERT_TRUE(true);
  3883. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3884. ASSERT_TRUE(peer_cert != nullptr);
  3885. auto subject_name = X509_get_subject_name(peer_cert);
  3886. ASSERT_TRUE(subject_name != nullptr);
  3887. std::string common_name;
  3888. {
  3889. char name[BUFSIZ];
  3890. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3891. name, sizeof(name));
  3892. common_name.assign(name, static_cast<size_t>(name_len));
  3893. }
  3894. EXPECT_EQ("Common Name", common_name);
  3895. X509_free(peer_cert);
  3896. });
  3897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3898. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3899. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3900. cli.enable_server_certificate_verification(false);
  3901. cli.set_connection_timeout(30);
  3902. auto res = cli.Get("/test");
  3903. ASSERT_TRUE(res);
  3904. ASSERT_EQ(200, res->status);
  3905. t.join();
  3906. }
  3907. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  3908. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  3909. // prepare large data
  3910. std::random_device seed_gen;
  3911. std::mt19937 random(seed_gen());
  3912. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  3913. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  3914. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  3915. // server
  3916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3917. ASSERT_TRUE(svr.is_valid());
  3918. svr.Post("/binary", [&](const Request &req, Response &res) {
  3919. EXPECT_EQ(large_size_byte, req.body.size());
  3920. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  3921. res.set_content(req.body, "application/octet-stream");
  3922. });
  3923. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3924. while (!svr.is_running()) {
  3925. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3926. }
  3927. // client POST
  3928. SSLClient cli("localhost", PORT);
  3929. cli.enable_server_certificate_verification(false);
  3930. cli.set_read_timeout(std::chrono::seconds(100));
  3931. cli.set_write_timeout(std::chrono::seconds(100));
  3932. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  3933. large_size_byte, "application/octet-stream");
  3934. // compare
  3935. EXPECT_EQ(200, res->status);
  3936. EXPECT_EQ(large_size_byte, res->body.size());
  3937. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  3938. // cleanup
  3939. svr.stop();
  3940. listen_thread.join();
  3941. ASSERT_FALSE(svr.is_running());
  3942. }
  3943. #endif
  3944. #ifdef _WIN32
  3945. TEST(CleanupTest, WSACleanup) {
  3946. int ret = WSACleanup();
  3947. ASSERT_EQ(0, ret);
  3948. }
  3949. #endif
  3950. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3951. TEST(NoSSLSupport, SimpleInterface) {
  3952. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3953. }
  3954. #endif
  3955. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3956. TEST(InvalidScheme, SimpleInterface) {
  3957. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3958. }
  3959. #endif
  3960. TEST(NoScheme, SimpleInterface) {
  3961. Client cli("yahoo.com:80");
  3962. ASSERT_TRUE(cli.is_valid());
  3963. }
  3964. TEST(SendAPI, SimpleInterface_Online) {
  3965. Client cli("http://yahoo.com");
  3966. Request req;
  3967. req.method = "GET";
  3968. req.path = "/";
  3969. auto res = cli.send(req);
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(301, res->status);
  3972. }
  3973. // Disabled due to out-of-memory problem on GitHub Actions
  3974. #ifdef _WIN64
  3975. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  3976. // allocate content size larger than 2GB in memory
  3977. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  3978. char *content = (char *)malloc(content_size);
  3979. ASSERT_TRUE(content);
  3980. Server svr;
  3981. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  3982. resp.set_content(content, content_size, "application/octet-stream");
  3983. });
  3984. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3985. while (!svr.is_running()) {
  3986. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3987. }
  3988. // Give GET time to get a few messages.
  3989. std::this_thread::sleep_for(std::chrono::seconds(1));
  3990. Client cli(HOST, PORT);
  3991. auto res = cli.Get("/foo");
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(200, res->status);
  3994. EXPECT_EQ(content_size, res->body.length());
  3995. free(content);
  3996. svr.stop();
  3997. listen_thread.join();
  3998. ASSERT_FALSE(svr.is_running());
  3999. }
  4000. #endif
  4001. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4002. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4003. Client cli("http://yahoo.com");
  4004. auto res = cli.Get("/");
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(301, res->status);
  4007. cli.set_follow_location(true);
  4008. res = cli.Get("/");
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(200, res->status);
  4011. EXPECT_EQ("https://yahoo.com/", res->location);
  4012. }
  4013. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4014. Client cli("https://yahoo.com");
  4015. auto res = cli.Get("/");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(301, res->status);
  4018. cli.set_follow_location(true);
  4019. res = cli.Get("/");
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(200, res->status);
  4022. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4023. }
  4024. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4025. Client cli("https://yahoo.com");
  4026. auto res = cli.Get("/");
  4027. ASSERT_TRUE(res);
  4028. ASSERT_FALSE(!res);
  4029. ASSERT_TRUE(res);
  4030. ASSERT_FALSE(res == nullptr);
  4031. ASSERT_TRUE(res != nullptr);
  4032. EXPECT_EQ(Error::Success, res.error());
  4033. EXPECT_EQ(301, res.value().status);
  4034. EXPECT_EQ(301, (*res).status);
  4035. EXPECT_EQ(301, res->status);
  4036. cli.set_follow_location(true);
  4037. res = cli.Get("/");
  4038. ASSERT_TRUE(res);
  4039. EXPECT_EQ(Error::Success, res.error());
  4040. EXPECT_EQ(200, res.value().status);
  4041. EXPECT_EQ(200, (*res).status);
  4042. EXPECT_EQ(200, res->status);
  4043. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4044. }
  4045. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4046. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4047. Client cli("https://cdnjs.cloudflare.com");
  4048. auto res =
  4049. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4050. ASSERT_TRUE(res);
  4051. EXPECT_EQ(200, res->status);
  4052. EXPECT_EQ(287630U, res->body.size());
  4053. EXPECT_EQ("application/javascript; charset=utf-8",
  4054. res->get_header_value("Content-Type"));
  4055. }
  4056. #endif
  4057. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4058. Client cli("https://nghttp2.org");
  4059. cli.set_follow_location(true);
  4060. auto res =
  4061. cli.Get("/httpbin/"
  4062. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(200, res->status);
  4065. }
  4066. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4067. Client cli("https://nghttp2.org");
  4068. cli.set_follow_location(true);
  4069. Params params;
  4070. params.emplace("url", "http://www.google.com");
  4071. params.emplace("status_code", "302");
  4072. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4073. ASSERT_TRUE(res);
  4074. EXPECT_EQ(200, res->status);
  4075. }
  4076. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4077. Client cli("https://nghttp2.org");
  4078. cli.set_follow_location(true);
  4079. Params params;
  4080. params.emplace("url", "http://www.google.com");
  4081. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(200, res->status);
  4084. }
  4085. TEST(HttpToHttpsRedirectTest, CertFile) {
  4086. Server svr;
  4087. ASSERT_TRUE(svr.is_valid());
  4088. svr.Get("/index", [&](const Request &, Response &res) {
  4089. res.set_redirect("https://127.0.0.1:1235/index");
  4090. svr.stop();
  4091. });
  4092. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4093. ASSERT_TRUE(ssl_svr.is_valid());
  4094. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4095. res.set_content("test", "text/plain");
  4096. ssl_svr.stop();
  4097. });
  4098. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4099. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4100. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4101. Client cli("127.0.0.1", PORT);
  4102. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4103. cli.enable_server_certificate_verification(true);
  4104. cli.set_follow_location(true);
  4105. cli.set_connection_timeout(30);
  4106. auto res = cli.Get("/index");
  4107. ASSERT_TRUE(res);
  4108. ASSERT_EQ(200, res->status);
  4109. t.join();
  4110. t2.join();
  4111. }
  4112. TEST(MultipartFormDataTest, LargeData) {
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4114. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4115. const ContentReader &content_reader) {
  4116. if (req.is_multipart_form_data()) {
  4117. MultipartFormDataItems files;
  4118. content_reader(
  4119. [&](const MultipartFormData &file) {
  4120. files.push_back(file);
  4121. return true;
  4122. },
  4123. [&](const char *data, size_t data_length) {
  4124. files.back().content.append(data, data_length);
  4125. return true;
  4126. });
  4127. EXPECT_TRUE(std::string(files[0].name) == "document");
  4128. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4129. EXPECT_TRUE(files[0].filename == "2MB_data");
  4130. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4131. EXPECT_TRUE(files[1].name == "hello");
  4132. EXPECT_TRUE(files[1].content == "world");
  4133. EXPECT_TRUE(files[1].filename == "");
  4134. EXPECT_TRUE(files[1].content_type == "");
  4135. } else {
  4136. std::string body;
  4137. content_reader([&](const char *data, size_t data_length) {
  4138. body.append(data, data_length);
  4139. return true;
  4140. });
  4141. }
  4142. });
  4143. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4144. while (!svr.is_running()) {
  4145. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4146. }
  4147. std::this_thread::sleep_for(std::chrono::seconds(1));
  4148. {
  4149. std::string data(1024 * 1024 * 2, '.');
  4150. std::stringstream buffer;
  4151. buffer << data;
  4152. Client cli("https://localhost:8080");
  4153. cli.enable_server_certificate_verification(false);
  4154. MultipartFormDataItems items{
  4155. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4156. {"hello", "world", "", ""},
  4157. };
  4158. auto res = cli.Post("/post", items);
  4159. ASSERT_TRUE(res);
  4160. ASSERT_EQ(200, res->status);
  4161. }
  4162. svr.stop();
  4163. t.join();
  4164. }
  4165. TEST(MultipartFormDataTest, WithPreamble) {
  4166. Server svr;
  4167. svr.Post("/post", [&](const Request &req, Response &res) {
  4168. res.set_content("ok", "text/plain");
  4169. });
  4170. thread t = thread([&] { svr.listen(HOST, PORT); });
  4171. while (!svr.is_running()) {
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4173. }
  4174. const std::string body =
  4175. "This is the preamble. It is to be ignored, though it\r\n"
  4176. "is a handy place for composition agents to include an\r\n"
  4177. "explanatory note to non-MIME conformant readers.\r\n"
  4178. "\r\n"
  4179. "\r\n"
  4180. "--simple boundary\r\n"
  4181. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4182. "\r\n"
  4183. "value1\r\n"
  4184. "--simple boundary\r\n"
  4185. "Content-Disposition: form-data; name=\"field2\"; "
  4186. "filename=\"example.txt\"\r\n"
  4187. "\r\n"
  4188. "value2\r\n"
  4189. "--simple boundary--\r\n"
  4190. "This is the epilogue. It is also to be ignored.\r\n";
  4191. std::string content_type =
  4192. R"(multipart/form-data; boundary="simple boundary")";
  4193. Client cli(HOST, PORT);
  4194. auto res = cli.Post("/post", body, content_type.c_str());
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(200, res->status);
  4197. svr.stop();
  4198. t.join();
  4199. }
  4200. #endif