test.cc 134 KB

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