test.cc 140 KB

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