test.cc 176 KB

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