test.cc 141 KB

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