test.cc 209 KB

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