2
0

test.cc 186 KB

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