test.cc 164 KB

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