test.cc 138 KB

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