test.cc 294 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodeURLTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_url(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodeURLTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(TrimTests, TrimStringTests) {
  252. EXPECT_EQ("abc", detail::trim_copy("abc"));
  253. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  254. EXPECT_TRUE(detail::trim_copy("").empty());
  255. }
  256. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  257. // Simple case without quality values
  258. std::vector<std::string> result1;
  259. EXPECT_TRUE(detail::parse_accept_header(
  260. "text/html,application/json,text/plain", result1));
  261. EXPECT_EQ(result1.size(), 3);
  262. EXPECT_EQ(result1[0], "text/html");
  263. EXPECT_EQ(result1[1], "application/json");
  264. EXPECT_EQ(result1[2], "text/plain");
  265. // With quality values
  266. std::vector<std::string> result2;
  267. EXPECT_TRUE(detail::parse_accept_header(
  268. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  269. EXPECT_EQ(result2.size(), 3);
  270. EXPECT_EQ(result2[0], "application/json"); // highest q value
  271. EXPECT_EQ(result2[1], "text/html");
  272. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  273. }
  274. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  275. // Mixed with and without quality values
  276. std::vector<std::string> result;
  277. EXPECT_TRUE(detail::parse_accept_header(
  278. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  279. EXPECT_EQ(result.size(), 3);
  280. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  281. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  282. EXPECT_EQ(result[2], "application/json"); // q=0.5
  283. }
  284. TEST(ParseAcceptHeaderTest, EdgeCases) {
  285. // Empty header
  286. std::vector<std::string> empty_result;
  287. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  288. EXPECT_TRUE(empty_result.empty());
  289. // Single type
  290. std::vector<std::string> single_result;
  291. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  292. EXPECT_EQ(single_result.size(), 1);
  293. EXPECT_EQ(single_result[0], "application/json");
  294. // Wildcard types
  295. std::vector<std::string> wildcard_result;
  296. EXPECT_TRUE(detail::parse_accept_header(
  297. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  298. EXPECT_EQ(wildcard_result.size(), 3);
  299. EXPECT_EQ(wildcard_result[0], "application/json");
  300. EXPECT_EQ(wildcard_result[1], "text/*");
  301. EXPECT_EQ(wildcard_result[2], "*/*");
  302. }
  303. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  304. // Common browser Accept header
  305. std::vector<std::string> browser_result;
  306. EXPECT_TRUE(
  307. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  308. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  309. browser_result));
  310. EXPECT_EQ(browser_result.size(), 6);
  311. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  312. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  313. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  314. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  315. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  316. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  317. // API client header
  318. std::vector<std::string> api_result;
  319. EXPECT_TRUE(detail::parse_accept_header(
  320. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  321. api_result));
  322. EXPECT_EQ(api_result.size(), 3);
  323. EXPECT_EQ(api_result[0], "application/json");
  324. EXPECT_EQ(api_result[1], "application/xml");
  325. EXPECT_EQ(api_result[2], "text/plain");
  326. }
  327. TEST(ParseAcceptHeaderTest, SpecialCases) {
  328. // Quality value with 3 decimal places
  329. std::vector<std::string> decimal_result;
  330. EXPECT_TRUE(detail::parse_accept_header(
  331. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  332. EXPECT_EQ(decimal_result.size(), 2);
  333. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  334. EXPECT_EQ(decimal_result[1], "text/html");
  335. // Zero quality (should still be included but with lowest priority)
  336. std::vector<std::string> zero_q_result;
  337. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  338. zero_q_result));
  339. EXPECT_EQ(zero_q_result.size(), 2);
  340. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  341. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  342. // No spaces around commas
  343. std::vector<std::string> no_space_result;
  344. EXPECT_TRUE(detail::parse_accept_header(
  345. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  346. no_space_result));
  347. EXPECT_EQ(no_space_result.size(), 3);
  348. EXPECT_EQ(no_space_result[0], "text/html");
  349. EXPECT_EQ(no_space_result[1], "application/json");
  350. EXPECT_EQ(no_space_result[2], "text/plain");
  351. }
  352. TEST(ParseAcceptHeaderTest, InvalidCases) {
  353. std::vector<std::string> result;
  354. // Invalid quality value (> 1.0)
  355. EXPECT_FALSE(
  356. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  357. // Invalid quality value (< 0.0)
  358. EXPECT_FALSE(
  359. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  360. // Invalid quality value (not a number)
  361. EXPECT_FALSE(detail::parse_accept_header(
  362. "text/html;q=invalid,application/json", result));
  363. // Empty quality value
  364. EXPECT_FALSE(
  365. detail::parse_accept_header("text/html;q=,application/json", result));
  366. // Invalid media type format (no slash and not wildcard)
  367. EXPECT_FALSE(
  368. detail::parse_accept_header("invalidtype,application/json", result));
  369. // Empty media type
  370. result.clear();
  371. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  372. // Only commas
  373. result.clear();
  374. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  375. // Valid cases should still work
  376. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  377. EXPECT_EQ(result.size(), 1);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1);
  384. EXPECT_EQ(result[0], "text/*");
  385. }
  386. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  387. Server svr;
  388. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  389. EXPECT_EQ(req.accept_content_types.size(), 3);
  390. EXPECT_EQ(req.accept_content_types[0], "application/json");
  391. EXPECT_EQ(req.accept_content_types[1], "text/html");
  392. EXPECT_EQ(req.accept_content_types[2], "*/*");
  393. res.set_content("ok", "text/plain");
  394. });
  395. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  396. EXPECT_TRUE(false);
  397. res.set_content("bad request", "text/plain");
  398. });
  399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  400. auto se = detail::scope_exit([&] {
  401. svr.stop();
  402. listen_thread.join();
  403. ASSERT_FALSE(svr.is_running());
  404. });
  405. svr.wait_until_ready();
  406. Client cli("localhost", PORT);
  407. {
  408. auto res =
  409. cli.Get("/accept_ok",
  410. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ(StatusCode::OK_200, res->status);
  413. }
  414. {
  415. auto res = cli.Get("/accept_bad_request",
  416. {{"Accept", "text/html;q=abc,application/json"}});
  417. ASSERT_TRUE(res);
  418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  419. }
  420. }
  421. TEST(DivideTest, DivideStringTests) {
  422. auto divide = [](const std::string &str, char d) {
  423. std::string lhs;
  424. std::string rhs;
  425. detail::divide(str, d,
  426. [&](const char *lhs_data, std::size_t lhs_size,
  427. const char *rhs_data, std::size_t rhs_size) {
  428. lhs.assign(lhs_data, lhs_size);
  429. rhs.assign(rhs_data, rhs_size);
  430. });
  431. return std::make_pair(std::move(lhs), std::move(rhs));
  432. };
  433. {
  434. const auto res = divide("", '=');
  435. EXPECT_EQ(res.first, "");
  436. EXPECT_EQ(res.second, "");
  437. }
  438. {
  439. const auto res = divide("=", '=');
  440. EXPECT_EQ(res.first, "");
  441. EXPECT_EQ(res.second, "");
  442. }
  443. {
  444. const auto res = divide(" ", '=');
  445. EXPECT_EQ(res.first, " ");
  446. EXPECT_EQ(res.second, "");
  447. }
  448. {
  449. const auto res = divide("a", '=');
  450. EXPECT_EQ(res.first, "a");
  451. EXPECT_EQ(res.second, "");
  452. }
  453. {
  454. const auto res = divide("a=", '=');
  455. EXPECT_EQ(res.first, "a");
  456. EXPECT_EQ(res.second, "");
  457. }
  458. {
  459. const auto res = divide("=b", '=');
  460. EXPECT_EQ(res.first, "");
  461. EXPECT_EQ(res.second, "b");
  462. }
  463. {
  464. const auto res = divide("a=b", '=');
  465. EXPECT_EQ(res.first, "a");
  466. EXPECT_EQ(res.second, "b");
  467. }
  468. {
  469. const auto res = divide("a=b=", '=');
  470. EXPECT_EQ(res.first, "a");
  471. EXPECT_EQ(res.second, "b=");
  472. }
  473. {
  474. const auto res = divide("a=b=c", '=');
  475. EXPECT_EQ(res.first, "a");
  476. EXPECT_EQ(res.second, "b=c");
  477. }
  478. }
  479. TEST(SplitTest, ParseQueryString) {
  480. string s = "key1=val1&key2=val2&key3=val3";
  481. Params dic;
  482. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  483. [&](const char *b, const char *e) {
  484. string key, val;
  485. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  486. if (key.empty()) {
  487. key.assign(b2, e2);
  488. } else {
  489. val.assign(b2, e2);
  490. }
  491. });
  492. dic.emplace(key, val);
  493. });
  494. EXPECT_EQ("val1", dic.find("key1")->second);
  495. EXPECT_EQ("val2", dic.find("key2")->second);
  496. EXPECT_EQ("val3", dic.find("key3")->second);
  497. }
  498. TEST(SplitTest, ParseInvalidQueryTests) {
  499. {
  500. string s = " ";
  501. Params dict;
  502. detail::parse_query_text(s, dict);
  503. EXPECT_TRUE(dict.empty());
  504. }
  505. {
  506. string s = " = =";
  507. Params dict;
  508. detail::parse_query_text(s, dict);
  509. EXPECT_TRUE(dict.empty());
  510. }
  511. }
  512. TEST(ParseQueryTest, ParseQueryString) {
  513. {
  514. std::string s = "key1=val1&key2=val2&key3=val3";
  515. Params dic;
  516. detail::parse_query_text(s, dic);
  517. EXPECT_EQ("val1", dic.find("key1")->second);
  518. EXPECT_EQ("val2", dic.find("key2")->second);
  519. EXPECT_EQ("val3", dic.find("key3")->second);
  520. }
  521. {
  522. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  523. Params dic;
  524. detail::parse_query_text(s, dic);
  525. EXPECT_EQ("", dic.find("key1")->second);
  526. EXPECT_EQ("val1", dic.find("key2")->second);
  527. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  528. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  529. }
  530. }
  531. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  532. Params dic;
  533. EXPECT_EQ(detail::params_to_query_str(dic), "");
  534. dic.emplace("key1", "val1");
  535. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  536. dic.emplace("key2", "val2");
  537. dic.emplace("key3", "val3");
  538. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  539. }
  540. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  541. string content_type = "multipart/form-data; boundary=something";
  542. string boundary;
  543. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  544. EXPECT_TRUE(ret);
  545. EXPECT_EQ(boundary, "something");
  546. }
  547. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  548. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  549. string boundary;
  550. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  551. EXPECT_TRUE(ret);
  552. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  553. }
  554. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  555. string content_type =
  556. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  557. string boundary;
  558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  559. EXPECT_TRUE(ret);
  560. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  561. }
  562. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  563. string content_type =
  564. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  565. string boundary;
  566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  567. EXPECT_TRUE(ret);
  568. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  569. }
  570. TEST(GetHeaderValueTest, DefaultValue) {
  571. Headers headers = {{"Dummy", "Dummy"}};
  572. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  573. EXPECT_STREQ("text/plain", val);
  574. }
  575. TEST(GetHeaderValueTest, DefaultValueInt) {
  576. Headers headers = {{"Dummy", "Dummy"}};
  577. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  578. EXPECT_EQ(100ull, val);
  579. }
  580. TEST(GetHeaderValueTest, RegularValue) {
  581. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  582. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  583. EXPECT_STREQ("text/html", val);
  584. }
  585. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  586. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  587. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  588. EXPECT_STREQ("text/html", val);
  589. }
  590. TEST(GetHeaderValueTest, SetContent) {
  591. Response res;
  592. res.set_content("html", "text/html");
  593. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  594. res.set_content("text", "text/plain");
  595. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  596. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  597. }
  598. TEST(GetHeaderValueTest, RegularValueInt) {
  599. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  600. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  601. EXPECT_EQ(100ull, val);
  602. }
  603. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  604. Headers headers = {{"Content-Length", "x"}};
  605. auto is_invalid_value = false;
  606. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  607. is_invalid_value);
  608. EXPECT_EQ(0ull, val);
  609. EXPECT_TRUE(is_invalid_value);
  610. }
  611. TEST(GetHeaderValueTest, Range) {
  612. {
  613. Headers headers = {make_range_header({{1, -1}})};
  614. auto val = detail::get_header_value(headers, "Range", 0, 0);
  615. EXPECT_STREQ("bytes=1-", val);
  616. }
  617. {
  618. Headers headers = {make_range_header({{-1, 1}})};
  619. auto val = detail::get_header_value(headers, "Range", 0, 0);
  620. EXPECT_STREQ("bytes=-1", val);
  621. }
  622. {
  623. Headers headers = {make_range_header({{1, 10}})};
  624. auto val = detail::get_header_value(headers, "Range", 0, 0);
  625. EXPECT_STREQ("bytes=1-10", val);
  626. }
  627. {
  628. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  629. auto val = detail::get_header_value(headers, "Range", 0, 0);
  630. EXPECT_STREQ("bytes=1-10, 100-", val);
  631. }
  632. {
  633. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  634. auto val = detail::get_header_value(headers, "Range", 0, 0);
  635. EXPECT_STREQ("bytes=1-10, 100-200", val);
  636. }
  637. {
  638. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  639. auto val = detail::get_header_value(headers, "Range", 0, 0);
  640. EXPECT_STREQ("bytes=0-0, -1", val);
  641. }
  642. }
  643. TEST(ParseHeaderValueTest, Range) {
  644. {
  645. Ranges ranges;
  646. auto ret = detail::parse_range_header("bytes=1-", ranges);
  647. EXPECT_TRUE(ret);
  648. EXPECT_EQ(1u, ranges.size());
  649. EXPECT_EQ(1u, ranges[0].first);
  650. EXPECT_EQ(-1, ranges[0].second);
  651. }
  652. {
  653. Ranges ranges;
  654. auto ret = detail::parse_range_header("bytes=-1", ranges);
  655. EXPECT_TRUE(ret);
  656. EXPECT_EQ(1u, ranges.size());
  657. EXPECT_EQ(-1, ranges[0].first);
  658. EXPECT_EQ(1u, ranges[0].second);
  659. }
  660. {
  661. Ranges ranges;
  662. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(1u, ranges.size());
  665. EXPECT_EQ(1u, ranges[0].first);
  666. EXPECT_EQ(10u, ranges[0].second);
  667. }
  668. {
  669. Ranges ranges;
  670. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  671. EXPECT_FALSE(ret);
  672. }
  673. {
  674. Ranges ranges;
  675. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  676. EXPECT_TRUE(ret);
  677. EXPECT_EQ(2u, ranges.size());
  678. EXPECT_EQ(1u, ranges[0].first);
  679. EXPECT_EQ(10u, ranges[0].second);
  680. EXPECT_EQ(100u, ranges[1].first);
  681. EXPECT_EQ(-1, ranges[1].second);
  682. }
  683. {
  684. Ranges ranges;
  685. auto ret =
  686. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  687. EXPECT_TRUE(ret);
  688. EXPECT_EQ(3u, ranges.size());
  689. EXPECT_EQ(1u, ranges[0].first);
  690. EXPECT_EQ(10u, ranges[0].second);
  691. EXPECT_EQ(100u, ranges[1].first);
  692. EXPECT_EQ(200u, ranges[1].second);
  693. EXPECT_EQ(300u, ranges[2].first);
  694. EXPECT_EQ(400u, ranges[2].second);
  695. }
  696. {
  697. Ranges ranges;
  698. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  699. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  700. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  701. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  702. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  703. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  704. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  705. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  706. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  707. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  708. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  709. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  710. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  711. EXPECT_TRUE(ranges.empty());
  712. }
  713. }
  714. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  715. Request req;
  716. req.set_header("Accept-Encoding", "gzip");
  717. Response res;
  718. res.set_header("Content-Type", "text/plain");
  719. auto ret = detail::encoding_type(req, res);
  720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  721. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  722. #else
  723. EXPECT_TRUE(ret == detail::EncodingType::None);
  724. #endif
  725. }
  726. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  727. Request req;
  728. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  729. Response res;
  730. res.set_header("Content-Type", "text/plain");
  731. auto ret = detail::encoding_type(req, res);
  732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  733. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  734. #elif CPPHTTPLIB_ZLIB_SUPPORT
  735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  736. #elif CPPHTTPLIB_ZSTD_SUPPORT
  737. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  738. #else
  739. EXPECT_TRUE(ret == detail::EncodingType::None);
  740. #endif
  741. }
  742. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  743. Request req;
  744. req.set_header("Accept-Encoding",
  745. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  746. Response res;
  747. res.set_header("Content-Type", "text/plain");
  748. auto ret = detail::encoding_type(req, res);
  749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  750. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  751. #elif CPPHTTPLIB_ZLIB_SUPPORT
  752. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  753. #elif CPPHTTPLIB_ZSTD_SUPPORT
  754. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  755. #else
  756. EXPECT_TRUE(ret == detail::EncodingType::None);
  757. #endif
  758. }
  759. TEST(BufferStreamTest, read) {
  760. detail::BufferStream strm1;
  761. Stream &strm = strm1;
  762. EXPECT_EQ(5, strm.write("hello"));
  763. char buf[512];
  764. EXPECT_EQ(2, strm.read(buf, 2));
  765. EXPECT_EQ('h', buf[0]);
  766. EXPECT_EQ('e', buf[1]);
  767. EXPECT_EQ(2, strm.read(buf, 2));
  768. EXPECT_EQ('l', buf[0]);
  769. EXPECT_EQ('l', buf[1]);
  770. EXPECT_EQ(1, strm.read(buf, 1));
  771. EXPECT_EQ('o', buf[0]);
  772. EXPECT_EQ(0, strm.read(buf, 1));
  773. }
  774. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  777. auto port = 443;
  778. SSLClient cli(host, port);
  779. #else
  780. auto port = 80;
  781. Client cli(host, port);
  782. #endif
  783. cli.set_connection_timeout(2);
  784. auto res =
  785. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  786. ASSERT_TRUE(res);
  787. std::string out;
  788. read_file("./image.jpg", out);
  789. EXPECT_EQ(StatusCode::OK_200, res->status);
  790. EXPECT_EQ(out, res->body);
  791. }
  792. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  793. auto host = "www.httpwatch.com";
  794. auto ip = hosted_at(host);
  795. EXPECT_EQ("23.96.13.243", ip);
  796. std::vector<std::string> addrs;
  797. hosted_at(host, addrs);
  798. EXPECT_EQ(1u, addrs.size());
  799. }
  800. #if 0 // It depends on each test environment...
  801. TEST(HostnameToIPConversionTest, YouTube_Online) {
  802. auto host = "www.youtube.com";
  803. std::vector<std::string> addrs;
  804. hosted_at(host, addrs);
  805. EXPECT_EQ(20u, addrs.size());
  806. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  807. EXPECT_TRUE(it != addrs.end());
  808. }
  809. #endif
  810. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  811. auto host = "www.httpwatch.com";
  812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  813. auto port = 443;
  814. SSLClient cli(host, port);
  815. #else
  816. auto port = 80;
  817. Client cli(host, port);
  818. #endif
  819. cli.set_connection_timeout(2);
  820. std::string body;
  821. auto res =
  822. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  823. [&](const char *data, size_t data_length) {
  824. body.append(data, data_length);
  825. return true;
  826. });
  827. ASSERT_TRUE(res);
  828. std::string out;
  829. read_file("./image.jpg", out);
  830. EXPECT_EQ(StatusCode::OK_200, res->status);
  831. EXPECT_EQ(out, body);
  832. }
  833. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  834. auto host = "www.httpwatch.com";
  835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  836. auto port = 443;
  837. SSLClient cli(host, port);
  838. #else
  839. auto port = 80;
  840. Client cli(host, port);
  841. #endif
  842. cli.set_connection_timeout(2);
  843. std::string body;
  844. auto res = cli.Get(
  845. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  846. [&](const Response &response) {
  847. EXPECT_EQ(StatusCode::OK_200, response.status);
  848. return true;
  849. },
  850. [&](const char *data, size_t data_length) {
  851. body.append(data, data_length);
  852. return true;
  853. });
  854. ASSERT_TRUE(res);
  855. std::string out;
  856. read_file("./image.jpg", out);
  857. EXPECT_EQ(StatusCode::OK_200, res->status);
  858. EXPECT_EQ(out, body);
  859. }
  860. TEST(RangeTest, FromHTTPBin_Online) {
  861. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  862. auto host = "httpbin.org";
  863. auto path = std::string{"/range/32"};
  864. #else
  865. auto host = "nghttp2.org";
  866. auto path = std::string{"/httpbin/range/32"};
  867. #endif
  868. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  869. auto port = 443;
  870. SSLClient cli(host, port);
  871. #else
  872. auto port = 80;
  873. Client cli(host, port);
  874. #endif
  875. cli.set_connection_timeout(5);
  876. {
  877. auto res = cli.Get(path);
  878. ASSERT_TRUE(res);
  879. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  880. EXPECT_EQ(StatusCode::OK_200, res->status);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, -1}})};
  884. auto res = cli.Get(path, headers);
  885. ASSERT_TRUE(res);
  886. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  888. }
  889. {
  890. Headers headers = {make_range_header({{1, 10}})};
  891. auto res = cli.Get(path, headers);
  892. ASSERT_TRUE(res);
  893. EXPECT_EQ("bcdefghijk", res->body);
  894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  895. }
  896. {
  897. Headers headers = {make_range_header({{0, 31}})};
  898. auto res = cli.Get(path, headers);
  899. ASSERT_TRUE(res);
  900. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. }
  903. {
  904. Headers headers = {make_range_header({{0, -1}})};
  905. auto res = cli.Get(path, headers);
  906. ASSERT_TRUE(res);
  907. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  908. EXPECT_EQ(StatusCode::OK_200, res->status);
  909. }
  910. {
  911. Headers headers = {make_range_header({{0, 32}})};
  912. auto res = cli.Get(path, headers);
  913. ASSERT_TRUE(res);
  914. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  915. }
  916. }
  917. TEST(ConnectionErrorTest, InvalidHost) {
  918. auto host = "-abcde.com";
  919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  920. auto port = 443;
  921. SSLClient cli(host, port);
  922. #else
  923. auto port = 80;
  924. Client cli(host, port);
  925. #endif
  926. cli.set_connection_timeout(std::chrono::seconds(2));
  927. auto res = cli.Get("/");
  928. ASSERT_TRUE(!res);
  929. EXPECT_EQ(Error::Connection, res.error());
  930. }
  931. TEST(ConnectionErrorTest, InvalidHost2) {
  932. auto host = "httpbin.org/";
  933. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  934. SSLClient cli(host);
  935. #else
  936. Client cli(host);
  937. #endif
  938. cli.set_connection_timeout(std::chrono::seconds(2));
  939. auto res = cli.Get("/");
  940. ASSERT_TRUE(!res);
  941. EXPECT_EQ(Error::Connection, res.error());
  942. }
  943. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  944. auto host = "httpbin.org/";
  945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  946. SSLClient cli(host);
  947. #else
  948. Client cli(host);
  949. #endif
  950. cli.set_connection_timeout(std::chrono::seconds(2));
  951. auto res = cli.Get("/");
  952. ASSERT_TRUE(!res);
  953. stringstream s;
  954. s << "error code: " << res.error();
  955. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  956. }
  957. TEST(ConnectionErrorTest, InvalidPort) {
  958. auto host = "localhost";
  959. auto port = 44380;
  960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  961. SSLClient cli(host, port);
  962. #else
  963. Client cli(host, port);
  964. #endif
  965. cli.set_connection_timeout(std::chrono::seconds(2));
  966. auto res = cli.Get("/");
  967. ASSERT_TRUE(!res);
  968. EXPECT_TRUE(Error::Connection == res.error() ||
  969. Error::ConnectionTimeout == res.error());
  970. }
  971. TEST(ConnectionErrorTest, Timeout_Online) {
  972. auto host = "google.com";
  973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  974. auto port = 44380;
  975. SSLClient cli(host, port);
  976. #else
  977. auto port = 8080;
  978. Client cli(host, port);
  979. #endif
  980. cli.set_connection_timeout(std::chrono::seconds(2));
  981. // only probe one address type so that the error reason
  982. // correlates to the timed-out IPv4, not the unsupported
  983. // IPv6 connection attempt
  984. cli.set_address_family(AF_INET);
  985. auto res = cli.Get("/");
  986. ASSERT_TRUE(!res);
  987. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  988. }
  989. TEST(CancelTest, NoCancel_Online) {
  990. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  991. auto host = "httpbin.org";
  992. auto path = std::string{"/range/32"};
  993. #else
  994. auto host = "nghttp2.org";
  995. auto path = std::string{"/httpbin/range/32"};
  996. #endif
  997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  998. auto port = 443;
  999. SSLClient cli(host, port);
  1000. #else
  1001. auto port = 80;
  1002. Client cli(host, port);
  1003. #endif
  1004. cli.set_connection_timeout(std::chrono::seconds(5));
  1005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1006. ASSERT_TRUE(res);
  1007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1008. EXPECT_EQ(StatusCode::OK_200, res->status);
  1009. }
  1010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1011. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1012. auto host = "httpbin.org";
  1013. auto path = std::string{"/range/32"};
  1014. #else
  1015. auto host = "nghttp2.org";
  1016. auto path = std::string{"/httpbin/range/32"};
  1017. #endif
  1018. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1019. auto port = 443;
  1020. SSLClient cli(host, port);
  1021. #else
  1022. auto port = 80;
  1023. Client cli(host, port);
  1024. #endif
  1025. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1026. cli.set_connection_timeout(std::chrono::seconds(5));
  1027. ASSERT_TRUE(!res);
  1028. EXPECT_EQ(Error::Canceled, res.error());
  1029. }
  1030. TEST(CancelTest, WithCancelLargePayload_Online) {
  1031. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1032. auto host = "httpbin.org";
  1033. auto path = std::string{"/range/65536"};
  1034. #else
  1035. auto host = "nghttp2.org";
  1036. auto path = std::string{"/httpbin/range/65536"};
  1037. #endif
  1038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1039. auto port = 443;
  1040. SSLClient cli(host, port);
  1041. #else
  1042. auto port = 80;
  1043. Client cli(host, port);
  1044. #endif
  1045. cli.set_connection_timeout(std::chrono::seconds(5));
  1046. uint32_t count = 0;
  1047. auto res =
  1048. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1049. ASSERT_TRUE(!res);
  1050. EXPECT_EQ(Error::Canceled, res.error());
  1051. }
  1052. TEST(CancelTest, NoCancelPost) {
  1053. Server svr;
  1054. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1055. res.set_content("Hello World!", "text/plain");
  1056. });
  1057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1058. auto se = detail::scope_exit([&] {
  1059. svr.stop();
  1060. thread.join();
  1061. ASSERT_FALSE(svr.is_running());
  1062. });
  1063. svr.wait_until_ready();
  1064. Client cli(HOST, PORT);
  1065. cli.set_connection_timeout(std::chrono::seconds(5));
  1066. auto res =
  1067. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1068. "application/json", [](uint64_t, uint64_t) { return true; });
  1069. ASSERT_TRUE(res);
  1070. EXPECT_EQ("Hello World!", res->body);
  1071. EXPECT_EQ(StatusCode::OK_200, res->status);
  1072. }
  1073. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1074. Server svr;
  1075. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1076. res.set_content("Hello World!", "text/plain");
  1077. });
  1078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1079. auto se = detail::scope_exit([&] {
  1080. svr.stop();
  1081. thread.join();
  1082. ASSERT_FALSE(svr.is_running());
  1083. });
  1084. svr.wait_until_ready();
  1085. Client cli(HOST, PORT);
  1086. cli.set_connection_timeout(std::chrono::seconds(5));
  1087. auto res =
  1088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1089. "application/json", [](uint64_t, uint64_t) { return false; });
  1090. ASSERT_TRUE(!res);
  1091. EXPECT_EQ(Error::Canceled, res.error());
  1092. }
  1093. TEST(CancelTest, WithCancelLargePayloadPost) {
  1094. Server svr;
  1095. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1096. res.set_content(LARGE_DATA, "text/plain");
  1097. });
  1098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1099. auto se = detail::scope_exit([&] {
  1100. svr.stop();
  1101. thread.join();
  1102. ASSERT_FALSE(svr.is_running());
  1103. });
  1104. svr.wait_until_ready();
  1105. Client cli(HOST, PORT);
  1106. cli.set_connection_timeout(std::chrono::seconds(5));
  1107. auto res =
  1108. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1109. "application/json", [](uint64_t, uint64_t) { return false; });
  1110. ASSERT_TRUE(!res);
  1111. EXPECT_EQ(Error::Canceled, res.error());
  1112. }
  1113. TEST(CancelTest, NoCancelPut) {
  1114. Server svr;
  1115. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1119. auto se = detail::scope_exit([&] {
  1120. svr.stop();
  1121. thread.join();
  1122. ASSERT_FALSE(svr.is_running());
  1123. });
  1124. svr.wait_until_ready();
  1125. Client cli(HOST, PORT);
  1126. cli.set_connection_timeout(std::chrono::seconds(5));
  1127. auto res =
  1128. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1129. "application/json", [](uint64_t, uint64_t) { return true; });
  1130. ASSERT_TRUE(res);
  1131. EXPECT_EQ("Hello World!", res->body);
  1132. EXPECT_EQ(StatusCode::OK_200, res->status);
  1133. }
  1134. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1135. Server svr;
  1136. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1137. res.set_content("Hello World!", "text/plain");
  1138. });
  1139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli(HOST, PORT);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res =
  1149. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1150. "application/json", [](uint64_t, uint64_t) { return false; });
  1151. ASSERT_TRUE(!res);
  1152. EXPECT_EQ(Error::Canceled, res.error());
  1153. }
  1154. TEST(CancelTest, WithCancelLargePayloadPut) {
  1155. Server svr;
  1156. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1157. res.set_content(LARGE_DATA, "text/plain");
  1158. });
  1159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1160. auto se = detail::scope_exit([&] {
  1161. svr.stop();
  1162. thread.join();
  1163. ASSERT_FALSE(svr.is_running());
  1164. });
  1165. svr.wait_until_ready();
  1166. Client cli(HOST, PORT);
  1167. cli.set_connection_timeout(std::chrono::seconds(5));
  1168. auto res =
  1169. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1170. "application/json", [](uint64_t, uint64_t) { return false; });
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Canceled, res.error());
  1173. }
  1174. TEST(CancelTest, NoCancelPatch) {
  1175. Server svr;
  1176. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1177. res.set_content("Hello World!", "text/plain");
  1178. });
  1179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1180. auto se = detail::scope_exit([&] {
  1181. svr.stop();
  1182. thread.join();
  1183. ASSERT_FALSE(svr.is_running());
  1184. });
  1185. svr.wait_until_ready();
  1186. Client cli(HOST, PORT);
  1187. cli.set_connection_timeout(std::chrono::seconds(5));
  1188. auto res =
  1189. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1190. "application/json", [](uint64_t, uint64_t) { return true; });
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("Hello World!", res->body);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. }
  1195. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1196. Server svr;
  1197. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1198. res.set_content("Hello World!", "text/plain");
  1199. });
  1200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1201. auto se = detail::scope_exit([&] {
  1202. svr.stop();
  1203. thread.join();
  1204. ASSERT_FALSE(svr.is_running());
  1205. });
  1206. svr.wait_until_ready();
  1207. Client cli(HOST, PORT);
  1208. cli.set_connection_timeout(std::chrono::seconds(5));
  1209. auto res =
  1210. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1211. "application/json", [](uint64_t, uint64_t) { return false; });
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Canceled, res.error());
  1214. }
  1215. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1216. Server svr;
  1217. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1218. res.set_content(LARGE_DATA, "text/plain");
  1219. });
  1220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1221. auto se = detail::scope_exit([&] {
  1222. svr.stop();
  1223. thread.join();
  1224. ASSERT_FALSE(svr.is_running());
  1225. });
  1226. svr.wait_until_ready();
  1227. Client cli(HOST, PORT);
  1228. cli.set_connection_timeout(std::chrono::seconds(5));
  1229. auto res =
  1230. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1231. "application/json", [](uint64_t, uint64_t) { return false; });
  1232. ASSERT_TRUE(!res);
  1233. EXPECT_EQ(Error::Canceled, res.error());
  1234. }
  1235. TEST(CancelTest, NoCancelDelete) {
  1236. Server svr;
  1237. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1238. res.set_content("Hello World!", "text/plain");
  1239. });
  1240. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. thread.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. Client cli(HOST, PORT);
  1248. cli.set_connection_timeout(std::chrono::seconds(5));
  1249. auto res =
  1250. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1251. "application/json", [](uint64_t, uint64_t) { return true; });
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ("Hello World!", res->body);
  1254. EXPECT_EQ(StatusCode::OK_200, res->status);
  1255. }
  1256. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1257. Server svr;
  1258. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1259. res.set_content("Hello World!", "text/plain");
  1260. });
  1261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1262. auto se = detail::scope_exit([&] {
  1263. svr.stop();
  1264. thread.join();
  1265. ASSERT_FALSE(svr.is_running());
  1266. });
  1267. svr.wait_until_ready();
  1268. Client cli(HOST, PORT);
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. auto res =
  1271. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1272. "application/json", [](uint64_t, uint64_t) { return false; });
  1273. ASSERT_TRUE(!res);
  1274. EXPECT_EQ(Error::Canceled, res.error());
  1275. }
  1276. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1277. Server svr;
  1278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1279. res.set_content(LARGE_DATA, "text/plain");
  1280. });
  1281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1282. auto se = detail::scope_exit([&] {
  1283. svr.stop();
  1284. thread.join();
  1285. ASSERT_FALSE(svr.is_running());
  1286. });
  1287. svr.wait_until_ready();
  1288. Client cli(HOST, PORT);
  1289. cli.set_connection_timeout(std::chrono::seconds(5));
  1290. auto res =
  1291. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1292. "application/json", [](uint64_t, uint64_t) { return false; });
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_EQ(Error::Canceled, res.error());
  1295. }
  1296. static std::string remove_whitespace(const std::string &input) {
  1297. std::string output;
  1298. output.reserve(input.size());
  1299. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1300. [](unsigned char c) { return !std::isspace(c); });
  1301. return output;
  1302. }
  1303. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpbin.org";
  1306. auto path = std::string{"/basic-auth/hello/world"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. {
  1319. auto res = cli.Get(path);
  1320. ASSERT_TRUE(res);
  1321. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1322. }
  1323. {
  1324. auto res =
  1325. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1326. ASSERT_TRUE(res);
  1327. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1328. remove_whitespace(res->body));
  1329. EXPECT_EQ(StatusCode::OK_200, res->status);
  1330. }
  1331. {
  1332. cli.set_basic_auth("hello", "world");
  1333. auto res = cli.Get(path);
  1334. ASSERT_TRUE(res);
  1335. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1336. remove_whitespace(res->body));
  1337. EXPECT_EQ(StatusCode::OK_200, res->status);
  1338. }
  1339. {
  1340. cli.set_basic_auth("hello", "bad");
  1341. auto res = cli.Get(path);
  1342. ASSERT_TRUE(res);
  1343. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1344. }
  1345. {
  1346. cli.set_basic_auth("bad", "world");
  1347. auto res = cli.Get(path);
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1350. }
  1351. }
  1352. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1353. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1354. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1355. auto host = "httpbin.org";
  1356. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1357. auto paths = std::vector<std::string>{
  1358. "/digest-auth/auth/hello/world/MD5",
  1359. "/digest-auth/auth/hello/world/SHA-256",
  1360. "/digest-auth/auth/hello/world/SHA-512",
  1361. "/digest-auth/auth-int/hello/world/MD5",
  1362. };
  1363. #else
  1364. auto host = "nghttp2.org";
  1365. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1366. auto paths = std::vector<std::string>{
  1367. "/httpbin/digest-auth/auth/hello/world/MD5",
  1368. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1369. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1370. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1371. };
  1372. #endif
  1373. auto port = 443;
  1374. SSLClient cli(host, port);
  1375. {
  1376. auto res = cli.Get(unauth_path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. {
  1381. cli.set_digest_auth("hello", "world");
  1382. for (const auto &path : paths) {
  1383. auto res = cli.Get(path.c_str());
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1386. remove_whitespace(res->body));
  1387. EXPECT_EQ(StatusCode::OK_200, res->status);
  1388. }
  1389. cli.set_digest_auth("hello", "bad");
  1390. for (const auto &path : paths) {
  1391. auto res = cli.Get(path.c_str());
  1392. ASSERT_TRUE(res);
  1393. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1394. }
  1395. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1396. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1397. // cli.set_digest_auth("bad", "world");
  1398. // for (const auto& path : paths) {
  1399. // auto res = cli.Get(path.c_str());
  1400. // ASSERT_TRUE(res);
  1401. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1402. // }
  1403. }
  1404. }
  1405. #endif
  1406. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1407. auto host = "google.com";
  1408. auto another_host = "example.com";
  1409. auto wrong_ip = "0.0.0.0";
  1410. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1411. SSLClient cli(host);
  1412. #else
  1413. Client cli(host);
  1414. #endif
  1415. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1416. auto res = cli.Get("/");
  1417. ASSERT_TRUE(res);
  1418. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1419. }
  1420. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1421. auto host = "google.com";
  1422. auto wrong_ip = "0.0.0.0";
  1423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1424. SSLClient cli(host);
  1425. #else
  1426. Client cli(host);
  1427. #endif
  1428. cli.set_hostname_addr_map({{host, wrong_ip}});
  1429. auto res = cli.Get("/");
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Connection, res.error());
  1432. }
  1433. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1434. auto host = "nghttp2.org";
  1435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1436. SSLClient cli(host);
  1437. #else
  1438. Client cli(host);
  1439. #endif
  1440. cli.set_follow_location(true);
  1441. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1442. ASSERT_TRUE(res);
  1443. EXPECT_EQ(StatusCode::OK_200, res->status);
  1444. }
  1445. TEST(RedirectTest, Redirect_Online) {
  1446. auto host = "nghttp2.org";
  1447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1448. SSLClient cli(host);
  1449. #else
  1450. Client cli(host);
  1451. #endif
  1452. cli.set_follow_location(true);
  1453. auto res = cli.Get("/httpbin/redirect/3");
  1454. ASSERT_TRUE(res);
  1455. EXPECT_EQ(StatusCode::OK_200, res->status);
  1456. }
  1457. TEST(RelativeRedirectTest, Redirect_Online) {
  1458. auto host = "nghttp2.org";
  1459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1460. SSLClient cli(host);
  1461. #else
  1462. Client cli(host);
  1463. #endif
  1464. cli.set_follow_location(true);
  1465. auto res = cli.Get("/httpbin/relative-redirect/3");
  1466. ASSERT_TRUE(res);
  1467. EXPECT_EQ(StatusCode::OK_200, res->status);
  1468. }
  1469. TEST(TooManyRedirectTest, Redirect_Online) {
  1470. auto host = "nghttp2.org";
  1471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1472. SSLClient cli(host);
  1473. #else
  1474. Client cli(host);
  1475. #endif
  1476. cli.set_follow_location(true);
  1477. auto res = cli.Get("/httpbin/redirect/21");
  1478. ASSERT_TRUE(!res);
  1479. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1480. }
  1481. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1482. TEST(YahooRedirectTest, Redirect_Online) {
  1483. Client cli("yahoo.com");
  1484. auto res = cli.Get("/");
  1485. ASSERT_TRUE(res);
  1486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1487. cli.set_follow_location(true);
  1488. res = cli.Get("/");
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1492. }
  1493. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1494. #define REDIR_HOST "httpbingo.org"
  1495. #define REDIR_PATH "/redirect-to"
  1496. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1497. SSLClient cli(REDIR_HOST);
  1498. cli.set_follow_location(true);
  1499. auto res =
  1500. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1501. ASSERT_TRUE(res);
  1502. EXPECT_EQ(StatusCode::OK_200, res->status);
  1503. }
  1504. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1505. SSLClient cli(REDIR_HOST);
  1506. cli.set_follow_location(true);
  1507. Params params;
  1508. params.emplace("url", "http://example.com");
  1509. params.emplace("status_code", "302");
  1510. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::OK_200, res->status);
  1513. }
  1514. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1515. SSLClient cli(REDIR_HOST);
  1516. cli.set_follow_location(true);
  1517. Params params;
  1518. params.emplace("url", "http://example.com");
  1519. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1520. ASSERT_TRUE(res);
  1521. EXPECT_EQ(StatusCode::OK_200, res->status);
  1522. }
  1523. TEST(UrlWithSpace, Redirect_Online) {
  1524. SSLClient cli("edge.forgecdn.net");
  1525. cli.set_follow_location(true);
  1526. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1530. }
  1531. #endif
  1532. #if !defined(_WIN32) && !defined(_WIN64)
  1533. TEST(ReceiveSignals, Signal) {
  1534. auto setupSignalHandlers = []() {
  1535. struct sigaction act;
  1536. sigemptyset(&act.sa_mask);
  1537. act.sa_flags = SA_SIGINFO;
  1538. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1539. switch (sig) {
  1540. case SIGINT:
  1541. default: break;
  1542. }
  1543. };
  1544. ::sigaction(SIGINT, &act, nullptr);
  1545. };
  1546. Server svr;
  1547. int port = 0;
  1548. auto thread = std::thread([&]() {
  1549. setupSignalHandlers();
  1550. port = svr.bind_to_any_port("localhost");
  1551. svr.listen_after_bind();
  1552. });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. ASSERT_TRUE(svr.is_running());
  1560. pthread_kill(thread.native_handle(), SIGINT);
  1561. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1562. ASSERT_TRUE(svr.is_running());
  1563. }
  1564. #endif
  1565. TEST(RedirectToDifferentPort, Redirect) {
  1566. Server svr1;
  1567. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1568. res.set_content("Hello World!", "text/plain");
  1569. });
  1570. int svr1_port = 0;
  1571. auto thread1 = std::thread([&]() {
  1572. svr1_port = svr1.bind_to_any_port("localhost");
  1573. svr1.listen_after_bind();
  1574. });
  1575. Server svr2;
  1576. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1577. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1578. });
  1579. int svr2_port = 0;
  1580. auto thread2 = std::thread([&]() {
  1581. svr2_port = svr2.bind_to_any_port("localhost");
  1582. svr2.listen_after_bind();
  1583. });
  1584. auto se = detail::scope_exit([&] {
  1585. svr2.stop();
  1586. thread2.join();
  1587. svr1.stop();
  1588. thread1.join();
  1589. ASSERT_FALSE(svr2.is_running());
  1590. ASSERT_FALSE(svr1.is_running());
  1591. });
  1592. svr1.wait_until_ready();
  1593. svr2.wait_until_ready();
  1594. Client cli("localhost", svr2_port);
  1595. cli.set_follow_location(true);
  1596. auto res = cli.Get("/2");
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ(StatusCode::OK_200, res->status);
  1599. EXPECT_EQ("Hello World!", res->body);
  1600. }
  1601. TEST(RedirectFromPageWithContent, Redirect) {
  1602. Server svr;
  1603. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1604. res.set_content("___", "text/plain");
  1605. res.set_redirect("/2");
  1606. });
  1607. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. th.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. {
  1618. Client cli("localhost", PORT);
  1619. cli.set_follow_location(true);
  1620. std::string body;
  1621. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1622. body.append(data, data_length);
  1623. return true;
  1624. });
  1625. ASSERT_TRUE(res);
  1626. EXPECT_EQ(StatusCode::OK_200, res->status);
  1627. EXPECT_EQ("Hello World!", body);
  1628. }
  1629. {
  1630. Client cli("localhost", PORT);
  1631. std::string body;
  1632. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1633. body.append(data, data_length);
  1634. return true;
  1635. });
  1636. ASSERT_TRUE(res);
  1637. EXPECT_EQ(StatusCode::Found_302, res->status);
  1638. EXPECT_EQ("___", body);
  1639. }
  1640. }
  1641. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1642. Server svr;
  1643. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1644. res.set_content("___", "text/plain");
  1645. // res.set_redirect("/2");
  1646. res.set_redirect("http://[::1]:1234/2");
  1647. });
  1648. svr.Get("/2", [&](const Request &req, Response &res) {
  1649. auto host_header = req.headers.find("Host");
  1650. ASSERT_TRUE(host_header != req.headers.end());
  1651. EXPECT_EQ("[::1]:1234", host_header->second);
  1652. res.set_content("Hello World!", "text/plain");
  1653. });
  1654. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1655. auto se = detail::scope_exit([&] {
  1656. svr.stop();
  1657. th.join();
  1658. ASSERT_FALSE(svr.is_running());
  1659. });
  1660. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1661. // actually starts anything, so the condition !svr.is_running() will
  1662. // always remain true, and the loop never stops.
  1663. // This basically counts how many milliseconds have passed since the
  1664. // call to svr.listen(), and if after 5 seconds nothing started yet
  1665. // aborts the test.
  1666. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1667. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1668. ASSERT_LT(milliseconds, 5000U);
  1669. }
  1670. {
  1671. Client cli("http://[::1]:1234");
  1672. cli.set_follow_location(true);
  1673. std::string body;
  1674. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1675. body.append(data, data_length);
  1676. return true;
  1677. });
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. EXPECT_EQ("Hello World!", body);
  1681. }
  1682. {
  1683. Client cli("http://[::1]:1234");
  1684. std::string body;
  1685. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res);
  1690. EXPECT_EQ(StatusCode::Found_302, res->status);
  1691. EXPECT_EQ("___", body);
  1692. }
  1693. }
  1694. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1695. Server svr;
  1696. svr.Get("/foo", [](const Request &req, Response &res) {
  1697. auto a = req.params.find("a");
  1698. if (a != req.params.end()) {
  1699. res.set_content((*a).second, "text/plain");
  1700. res.status = StatusCode::OK_200;
  1701. } else {
  1702. res.status = StatusCode::BadRequest_400;
  1703. }
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. {
  1713. Client cli(HOST, PORT);
  1714. cli.set_url_encode(false);
  1715. auto res = cli.Get("/foo?a=explicitly+encoded");
  1716. ASSERT_TRUE(res);
  1717. EXPECT_EQ(StatusCode::OK_200, res->status);
  1718. // This expects it back with a space, as the `+` won't have been
  1719. // url-encoded, and server-side the params get decoded turning `+`
  1720. // into spaces.
  1721. EXPECT_EQ("explicitly encoded", res->body);
  1722. }
  1723. }
  1724. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1725. Server svr;
  1726. svr.Get("/", [](const Request &req, Response &) {
  1727. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1728. });
  1729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1730. auto se = detail::scope_exit([&] {
  1731. svr.stop();
  1732. thread.join();
  1733. ASSERT_FALSE(svr.is_running());
  1734. });
  1735. svr.wait_until_ready();
  1736. {
  1737. Client cli(HOST, PORT);
  1738. cli.set_url_encode(false);
  1739. auto res = cli.Get("/?something=%0A");
  1740. ASSERT_TRUE(res);
  1741. EXPECT_EQ(StatusCode::OK_200, res->status);
  1742. }
  1743. }
  1744. TEST(BindServerTest, DISABLED_BindDualStack) {
  1745. Server svr;
  1746. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content("Hello World!", "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. {
  1757. Client cli("127.0.0.1", PORT);
  1758. auto res = cli.Get("/1");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. EXPECT_EQ("Hello World!", res->body);
  1762. }
  1763. {
  1764. Client cli("::1", PORT);
  1765. auto res = cli.Get("/1");
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(StatusCode::OK_200, res->status);
  1768. EXPECT_EQ("Hello World!", res->body);
  1769. }
  1770. }
  1771. TEST(BindServerTest, BindAndListenSeparately) {
  1772. Server svr;
  1773. int port = svr.bind_to_any_port("0.0.0.0");
  1774. ASSERT_TRUE(svr.is_valid());
  1775. ASSERT_TRUE(port > 0);
  1776. svr.stop();
  1777. }
  1778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1779. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1781. CLIENT_CA_CERT_DIR);
  1782. int port = svr.bind_to_any_port("0.0.0.0");
  1783. ASSERT_TRUE(svr.is_valid());
  1784. ASSERT_TRUE(port > 0);
  1785. svr.stop();
  1786. }
  1787. #endif
  1788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1789. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1790. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1791. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1792. int port = svr.bind_to_any_port("0.0.0.0");
  1793. ASSERT_TRUE(svr.is_valid());
  1794. ASSERT_TRUE(port > 0);
  1795. svr.stop();
  1796. }
  1797. #endif
  1798. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1799. X509 *readCertificate(const std::string &strFileName) {
  1800. std::ifstream inStream(strFileName);
  1801. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1802. std::istreambuf_iterator<char>());
  1803. if (strCertPEM.empty()) return (nullptr);
  1804. BIO *pbCert = BIO_new(BIO_s_mem());
  1805. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1806. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1807. BIO_free(pbCert);
  1808. return (pCert);
  1809. }
  1810. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1811. std::ifstream inStream(strFileName);
  1812. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1813. std::istreambuf_iterator<char>());
  1814. if (strPrivateKeyPEM.empty()) return (nullptr);
  1815. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1816. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1817. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1818. BIO_free(pbPrivKey);
  1819. return (pPrivateKey);
  1820. }
  1821. TEST(BindServerTest, UpdateCerts) {
  1822. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1823. int port = svr.bind_to_any_port("0.0.0.0");
  1824. ASSERT_TRUE(svr.is_valid());
  1825. ASSERT_TRUE(port > 0);
  1826. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1827. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1828. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1829. ASSERT_TRUE(cert != nullptr);
  1830. ASSERT_TRUE(ca_cert != nullptr);
  1831. ASSERT_TRUE(key != nullptr);
  1832. X509_STORE *cert_store = X509_STORE_new();
  1833. X509_STORE_add_cert(cert_store, ca_cert);
  1834. svr.update_certs(cert, key, cert_store);
  1835. ASSERT_TRUE(svr.is_valid());
  1836. svr.stop();
  1837. X509_free(cert);
  1838. X509_free(ca_cert);
  1839. EVP_PKEY_free(key);
  1840. }
  1841. #endif
  1842. TEST(ErrorHandlerTest, ContentLength) {
  1843. Server svr;
  1844. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1845. res.status = StatusCode::OK_200;
  1846. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1847. "text/html"); // <= Content-Length still 13
  1848. });
  1849. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!\n", "text/plain");
  1851. res.status = 524;
  1852. });
  1853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. thread.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli(HOST, PORT);
  1862. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::OK_200, res->status);
  1865. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1866. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1867. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1868. }
  1869. }
  1870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1871. TEST(ExceptionTest, WithoutExceptionHandler) {
  1872. Server svr;
  1873. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1874. throw std::runtime_error("exception...");
  1875. });
  1876. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1877. throw std::runtime_error("exception\r\n...");
  1878. });
  1879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. listen_thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. Client cli("localhost", PORT);
  1887. {
  1888. auto res = cli.Get("/exception");
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1891. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1892. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1893. }
  1894. {
  1895. auto res = cli.Get("/unknown");
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1898. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1899. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1900. }
  1901. }
  1902. TEST(ExceptionTest, WithExceptionHandler) {
  1903. Server svr;
  1904. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1905. std::exception_ptr ep) {
  1906. EXPECT_FALSE(ep == nullptr);
  1907. try {
  1908. std::rethrow_exception(ep);
  1909. } catch (std::exception &e) {
  1910. EXPECT_EQ("abc", std::string(e.what()));
  1911. } catch (...) {}
  1912. res.status = StatusCode::InternalServerError_500;
  1913. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1914. "text/html"); // <= Content-Length still 13 at this point
  1915. });
  1916. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1917. res.set_content("Hello World!\n", "text/plain");
  1918. throw std::runtime_error("abc");
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. for (size_t i = 0; i < 10; i++) {
  1928. Client cli(HOST, PORT);
  1929. for (size_t j = 0; j < 100; j++) {
  1930. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1933. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1934. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1935. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1936. }
  1937. cli.set_keep_alive(true);
  1938. for (size_t j = 0; j < 100; j++) {
  1939. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1942. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1943. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1944. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1945. }
  1946. }
  1947. }
  1948. TEST(ExceptionTest, AndErrorHandler) {
  1949. Server svr;
  1950. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1951. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1952. });
  1953. svr.set_exception_handler(
  1954. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1955. EXPECT_FALSE(ep == nullptr);
  1956. try {
  1957. std::rethrow_exception(ep);
  1958. } catch (std::exception &e) {
  1959. res.set_content(e.what(), "text/html");
  1960. } catch (...) {}
  1961. res.status = StatusCode::InternalServerError_500;
  1962. });
  1963. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1964. throw std::runtime_error("EXCEPTION");
  1965. });
  1966. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1967. res.set_content("ERROR", "text/html");
  1968. res.status = StatusCode::InternalServerError_500;
  1969. });
  1970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1971. auto se = detail::scope_exit([&] {
  1972. svr.stop();
  1973. thread.join();
  1974. ASSERT_FALSE(svr.is_running());
  1975. });
  1976. svr.wait_until_ready();
  1977. Client cli(HOST, PORT);
  1978. {
  1979. auto res = cli.Get("/exception");
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1982. EXPECT_EQ("EXCEPTION", res->body);
  1983. }
  1984. {
  1985. auto res = cli.Get("/error");
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1988. EXPECT_EQ("ERROR", res->body);
  1989. }
  1990. {
  1991. auto res = cli.Get("/invalid");
  1992. ASSERT_TRUE(res);
  1993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1994. EXPECT_EQ("NOT_FOUND", res->body);
  1995. }
  1996. }
  1997. #endif
  1998. TEST(NoContentTest, ContentLength) {
  1999. Server svr;
  2000. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2001. res.status = StatusCode::NoContent_204;
  2002. });
  2003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2004. auto se = detail::scope_exit([&] {
  2005. svr.stop();
  2006. thread.join();
  2007. ASSERT_FALSE(svr.is_running());
  2008. });
  2009. svr.wait_until_ready();
  2010. {
  2011. Client cli(HOST, PORT);
  2012. auto res = cli.Get("/hi");
  2013. ASSERT_TRUE(res);
  2014. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2015. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2016. }
  2017. }
  2018. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2019. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2021. ASSERT_TRUE(svr.is_valid());
  2022. #else
  2023. Server svr;
  2024. #endif
  2025. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2026. if (req.path == "/routing_handler") {
  2027. res.set_header("PRE_ROUTING", "on");
  2028. res.set_content("Routing Handler", "text/plain");
  2029. return httplib::Server::HandlerResponse::Handled;
  2030. }
  2031. return httplib::Server::HandlerResponse::Unhandled;
  2032. });
  2033. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2034. res.set_content("Error", "text/html");
  2035. });
  2036. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2037. if (req.path == "/routing_handler") {
  2038. res.set_header("POST_ROUTING", "on");
  2039. }
  2040. });
  2041. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2042. res.set_content("Hello World!\n", "text/plain");
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2053. SSLClient cli(HOST, PORT);
  2054. cli.enable_server_certificate_verification(false);
  2055. #else
  2056. Client cli(HOST, PORT);
  2057. #endif
  2058. auto res = cli.Get("/routing_handler");
  2059. ASSERT_TRUE(res);
  2060. EXPECT_EQ(StatusCode::OK_200, res->status);
  2061. EXPECT_EQ("Routing Handler", res->body);
  2062. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2063. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2064. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2065. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2066. }
  2067. {
  2068. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2069. SSLClient cli(HOST, PORT);
  2070. cli.enable_server_certificate_verification(false);
  2071. #else
  2072. Client cli(HOST, PORT);
  2073. #endif
  2074. auto res = cli.Get("/hi");
  2075. ASSERT_TRUE(res);
  2076. EXPECT_EQ(StatusCode::OK_200, res->status);
  2077. EXPECT_EQ("Hello World!\n", res->body);
  2078. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2079. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2080. }
  2081. {
  2082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2083. SSLClient cli(HOST, PORT);
  2084. cli.enable_server_certificate_verification(false);
  2085. #else
  2086. Client cli(HOST, PORT);
  2087. #endif
  2088. auto res = cli.Get("/aaa");
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2091. EXPECT_EQ("Error", res->body);
  2092. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2093. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2094. }
  2095. }
  2096. TEST(RequestHandlerTest, PreRequestHandler) {
  2097. auto route_path = "/user/:user";
  2098. Server svr;
  2099. svr.Get("/hi", [](const Request &, Response &res) {
  2100. res.set_content("hi", "text/plain");
  2101. });
  2102. svr.Get(route_path, [](const Request &req, Response &res) {
  2103. res.set_content(req.path_params.at("user"), "text/plain");
  2104. });
  2105. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2106. if (req.matched_route == route_path) {
  2107. auto user = req.path_params.at("user");
  2108. if (user != "john") {
  2109. res.status = StatusCode::Forbidden_403;
  2110. res.set_content("error", "text/html");
  2111. return Server::HandlerResponse::Handled;
  2112. }
  2113. }
  2114. return Server::HandlerResponse::Unhandled;
  2115. });
  2116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2117. auto se = detail::scope_exit([&] {
  2118. svr.stop();
  2119. thread.join();
  2120. ASSERT_FALSE(svr.is_running());
  2121. });
  2122. svr.wait_until_ready();
  2123. Client cli(HOST, PORT);
  2124. {
  2125. auto res = cli.Get("/hi");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("hi", res->body);
  2129. }
  2130. {
  2131. auto res = cli.Get("/user/john");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::OK_200, res->status);
  2134. EXPECT_EQ("john", res->body);
  2135. }
  2136. {
  2137. auto res = cli.Get("/user/invalid-user");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2140. EXPECT_EQ("error", res->body);
  2141. }
  2142. }
  2143. TEST(InvalidFormatTest, StatusCode) {
  2144. Server svr;
  2145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2146. res.set_content("Hello World!\n", "text/plain");
  2147. res.status = 9999; // Status should be a three-digit code...
  2148. });
  2149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2150. auto se = detail::scope_exit([&] {
  2151. svr.stop();
  2152. thread.join();
  2153. ASSERT_FALSE(svr.is_running());
  2154. });
  2155. svr.wait_until_ready();
  2156. {
  2157. Client cli(HOST, PORT);
  2158. auto res = cli.Get("/hi");
  2159. ASSERT_FALSE(res);
  2160. }
  2161. }
  2162. TEST(URLFragmentTest, WithFragment) {
  2163. Server svr;
  2164. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2165. EXPECT_TRUE(req.target == "/hi");
  2166. });
  2167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2168. auto se = detail::scope_exit([&] {
  2169. svr.stop();
  2170. thread.join();
  2171. ASSERT_FALSE(svr.is_running());
  2172. });
  2173. svr.wait_until_ready();
  2174. {
  2175. Client cli(HOST, PORT);
  2176. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2177. EXPECT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. res = cli.Get("/hi%23key1=val1=key2=val2");
  2180. EXPECT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2182. }
  2183. }
  2184. TEST(HeaderWriter, SetHeaderWriter) {
  2185. Server svr;
  2186. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2187. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2188. return detail::write_headers(strm, hdrs);
  2189. });
  2190. svr.Get("/hi", [](const Request &req, Response &res) {
  2191. auto it = req.headers.find("CustomClientHeader");
  2192. EXPECT_TRUE(it != req.headers.end());
  2193. EXPECT_EQ(it->second, "CustomClientValue");
  2194. res.set_content("Hello World!\n", "text/plain");
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2206. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2207. return detail::write_headers(strm, hdrs);
  2208. });
  2209. auto res = cli.Get("/hi");
  2210. EXPECT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::OK_200, res->status);
  2212. auto it = res->headers.find("CustomServerHeader");
  2213. EXPECT_TRUE(it != res->headers.end());
  2214. EXPECT_EQ(it->second, "CustomServerValue");
  2215. }
  2216. }
  2217. class ServerTest : public ::testing::Test {
  2218. protected:
  2219. ServerTest()
  2220. : cli_(HOST, PORT)
  2221. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2222. ,
  2223. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2224. #endif
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. cli_.enable_server_certificate_verification(false);
  2228. #endif
  2229. }
  2230. virtual void SetUp() {
  2231. svr_.set_mount_point("/", "./www");
  2232. svr_.set_mount_point("/mount", "./www2");
  2233. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2234. svr_.Get("/hi",
  2235. [&](const Request & /*req*/, Response &res) {
  2236. res.set_content("Hello World!", "text/plain");
  2237. })
  2238. .Get("/file_content",
  2239. [&](const Request & /*req*/, Response &res) {
  2240. res.set_file_content("./www/dir/test.html");
  2241. })
  2242. .Get("/file_content_with_content_type",
  2243. [&](const Request & /*req*/, Response &res) {
  2244. res.set_file_content("./www/file", "text/plain");
  2245. })
  2246. .Get("/invalid_file_content",
  2247. [&](const Request & /*req*/, Response &res) {
  2248. res.set_file_content("./www/dir/invalid_file_path");
  2249. })
  2250. .Get("/http_response_splitting",
  2251. [&](const Request & /*req*/, Response &res) {
  2252. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2253. EXPECT_EQ(0U, res.headers.size());
  2254. EXPECT_FALSE(res.has_header("a"));
  2255. res.set_header("a", "1\nSet-Cookie: a=1");
  2256. EXPECT_EQ(0U, res.headers.size());
  2257. EXPECT_FALSE(res.has_header("a"));
  2258. res.set_header("a", "1\rSet-Cookie: a=1");
  2259. EXPECT_EQ(0U, res.headers.size());
  2260. EXPECT_FALSE(res.has_header("a"));
  2261. res.set_header("a\r\nb", "0");
  2262. EXPECT_EQ(0U, res.headers.size());
  2263. EXPECT_FALSE(res.has_header("a"));
  2264. res.set_header("a\rb", "0");
  2265. EXPECT_EQ(0U, res.headers.size());
  2266. EXPECT_FALSE(res.has_header("a"));
  2267. res.set_header("a\nb", "0");
  2268. EXPECT_EQ(0U, res.headers.size());
  2269. EXPECT_FALSE(res.has_header("a"));
  2270. res.set_redirect("1\r\nSet-Cookie: a=1");
  2271. EXPECT_EQ(0U, res.headers.size());
  2272. EXPECT_FALSE(res.has_header("Location"));
  2273. })
  2274. .Get("/slow",
  2275. [&](const Request & /*req*/, Response &res) {
  2276. std::this_thread::sleep_for(std::chrono::seconds(2));
  2277. res.set_content("slow", "text/plain");
  2278. })
  2279. #if 0
  2280. .Post("/slowpost",
  2281. [&](const Request & /*req*/, Response &res) {
  2282. std::this_thread::sleep_for(std::chrono::seconds(2));
  2283. res.set_content("slow", "text/plain");
  2284. })
  2285. #endif
  2286. .Get("/remote_addr",
  2287. [&](const Request &req, Response &res) {
  2288. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2289. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2290. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2291. EXPECT_EQ(req.remote_port,
  2292. std::stoi(req.get_header_value("REMOTE_PORT")));
  2293. res.set_content(remote_addr.c_str(), "text/plain");
  2294. })
  2295. .Get("/local_addr",
  2296. [&](const Request &req, Response &res) {
  2297. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2298. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2299. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2300. auto local_port = req.get_header_value("LOCAL_PORT");
  2301. EXPECT_EQ(req.local_addr, local_addr);
  2302. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2303. res.set_content(local_addr.append(":").append(local_port),
  2304. "text/plain");
  2305. })
  2306. .Get("/endwith%",
  2307. [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("Hello World!", "text/plain");
  2309. })
  2310. .Get("/a\\+\\+b",
  2311. [&](const Request &req, Response &res) {
  2312. ASSERT_TRUE(req.has_param("a +b"));
  2313. auto val = req.get_param_value("a +b");
  2314. res.set_content(val, "text/plain");
  2315. })
  2316. .Get("/", [&](const Request & /*req*/,
  2317. Response &res) { res.set_redirect("/hi"); })
  2318. .Post("/1",
  2319. [](const Request & /*req*/, Response &res) {
  2320. res.set_redirect("/2", StatusCode::SeeOther_303);
  2321. })
  2322. .Get("/2",
  2323. [](const Request & /*req*/, Response &res) {
  2324. res.set_content("redirected.", "text/plain");
  2325. res.status = StatusCode::OK_200;
  2326. })
  2327. .Post("/person",
  2328. [&](const Request &req, Response &res) {
  2329. if (req.has_param("name") && req.has_param("note")) {
  2330. persons_[req.get_param_value("name")] =
  2331. req.get_param_value("note");
  2332. } else {
  2333. res.status = StatusCode::BadRequest_400;
  2334. }
  2335. })
  2336. .Put("/person",
  2337. [&](const Request &req, Response &res) {
  2338. if (req.has_param("name") && req.has_param("note")) {
  2339. persons_[req.get_param_value("name")] =
  2340. req.get_param_value("note");
  2341. } else {
  2342. res.status = StatusCode::BadRequest_400;
  2343. }
  2344. })
  2345. .Get("/person/(.*)",
  2346. [&](const Request &req, Response &res) {
  2347. string name = req.matches[1];
  2348. if (persons_.find(name) != persons_.end()) {
  2349. auto note = persons_[name];
  2350. res.set_content(note, "text/plain");
  2351. } else {
  2352. res.status = StatusCode::NotFound_404;
  2353. }
  2354. })
  2355. .Delete("/person",
  2356. [&](const Request &req, Response &res) {
  2357. if (req.has_param("name")) {
  2358. string name = req.get_param_value("name");
  2359. if (persons_.find(name) != persons_.end()) {
  2360. persons_.erase(name);
  2361. res.set_content("DELETED", "text/plain");
  2362. } else {
  2363. res.status = StatusCode::NotFound_404;
  2364. }
  2365. } else {
  2366. res.status = StatusCode::BadRequest_400;
  2367. }
  2368. })
  2369. .Post("/x-www-form-urlencoded-json",
  2370. [&](const Request &req, Response &res) {
  2371. auto json = req.get_param_value("json");
  2372. ASSERT_EQ(JSON_DATA, json);
  2373. res.set_content(json, "appliation/json");
  2374. res.status = StatusCode::OK_200;
  2375. })
  2376. .Get("/streamed-chunked",
  2377. [&](const Request & /*req*/, Response &res) {
  2378. res.set_chunked_content_provider(
  2379. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2380. sink.os << "123";
  2381. sink.os << "456";
  2382. sink.os << "789";
  2383. sink.done();
  2384. return true;
  2385. });
  2386. })
  2387. .Get("/streamed-chunked2",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. auto i = new int(0);
  2390. res.set_chunked_content_provider(
  2391. "text/plain",
  2392. [i](size_t /*offset*/, DataSink &sink) {
  2393. switch (*i) {
  2394. case 0: sink.os << "123"; break;
  2395. case 1: sink.os << "456"; break;
  2396. case 2: sink.os << "789"; break;
  2397. case 3: sink.done(); break;
  2398. }
  2399. (*i)++;
  2400. return true;
  2401. },
  2402. [i](bool success) {
  2403. EXPECT_TRUE(success);
  2404. delete i;
  2405. });
  2406. })
  2407. .Get("/streamed-chunked-with-trailer",
  2408. [&](const Request & /*req*/, Response &res) {
  2409. auto i = new int(0);
  2410. res.set_header("Trailer", "Dummy1, Dummy2");
  2411. res.set_chunked_content_provider(
  2412. "text/plain",
  2413. [i](size_t /*offset*/, DataSink &sink) {
  2414. switch (*i) {
  2415. case 0: sink.os << "123"; break;
  2416. case 1: sink.os << "456"; break;
  2417. case 2: sink.os << "789"; break;
  2418. case 3: {
  2419. sink.done_with_trailer(
  2420. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2421. } break;
  2422. }
  2423. (*i)++;
  2424. return true;
  2425. },
  2426. [i](bool success) {
  2427. EXPECT_TRUE(success);
  2428. delete i;
  2429. });
  2430. })
  2431. .Get("/streamed",
  2432. [&](const Request & /*req*/, Response &res) {
  2433. res.set_content_provider(
  2434. 6, "text/plain",
  2435. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2436. sink.os << (offset < 3 ? "a" : "b");
  2437. return true;
  2438. });
  2439. })
  2440. .Get("/streamed-with-range",
  2441. [&](const Request &req, Response &res) {
  2442. auto data = new std::string("abcdefg");
  2443. res.set_content_provider(
  2444. data->size(), "text/plain",
  2445. [data](size_t offset, size_t length, DataSink &sink) {
  2446. size_t DATA_CHUNK_SIZE = 4;
  2447. const auto &d = *data;
  2448. auto out_len =
  2449. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2450. auto ret =
  2451. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2452. EXPECT_TRUE(ret);
  2453. return true;
  2454. },
  2455. [data, &req](bool success) {
  2456. EXPECT_EQ(success, !req.has_param("error"));
  2457. delete data;
  2458. });
  2459. })
  2460. .Get("/streamed-cancel",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. size_t(-1), "text/plain",
  2464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2465. sink.os << "data_chunk";
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/regex-with-delimiter",
  2470. [&](const Request &req, Response & /*res*/) {
  2471. ASSERT_TRUE(req.has_param("key"));
  2472. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2473. })
  2474. .Get("/with-range",
  2475. [&](const Request & /*req*/, Response &res) {
  2476. res.set_content("abcdefg", "text/plain");
  2477. })
  2478. .Get("/with-range-customized-response",
  2479. [&](const Request & /*req*/, Response &res) {
  2480. res.status = StatusCode::BadRequest_400;
  2481. res.set_content(JSON_DATA, "application/json");
  2482. })
  2483. .Post("/chunked",
  2484. [&](const Request &req, Response & /*res*/) {
  2485. EXPECT_EQ(req.body, "dechunked post body");
  2486. })
  2487. .Post("/large-chunked",
  2488. [&](const Request &req, Response & /*res*/) {
  2489. std::string expected(6 * 30 * 1024u, 'a');
  2490. EXPECT_EQ(req.body, expected);
  2491. })
  2492. .Post("/multipart",
  2493. [&](const Request &req, Response & /*res*/) {
  2494. EXPECT_EQ(6u, req.files.size());
  2495. ASSERT_TRUE(!req.has_file("???"));
  2496. ASSERT_TRUE(req.body.empty());
  2497. {
  2498. const auto &file = req.get_file_value("text1");
  2499. EXPECT_TRUE(file.filename.empty());
  2500. EXPECT_EQ("text default", file.content);
  2501. }
  2502. {
  2503. const auto &file = req.get_file_value("text2");
  2504. EXPECT_TRUE(file.filename.empty());
  2505. EXPECT_EQ("aωb", file.content);
  2506. }
  2507. {
  2508. const auto &file = req.get_file_value("file1");
  2509. EXPECT_EQ("hello.txt", file.filename);
  2510. EXPECT_EQ("text/plain", file.content_type);
  2511. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2512. }
  2513. {
  2514. const auto &file = req.get_file_value("file3");
  2515. EXPECT_TRUE(file.filename.empty());
  2516. EXPECT_EQ("application/octet-stream", file.content_type);
  2517. EXPECT_EQ(0u, file.content.size());
  2518. }
  2519. {
  2520. const auto &file = req.get_file_value("file4");
  2521. EXPECT_TRUE(file.filename.empty());
  2522. EXPECT_EQ(0u, file.content.size());
  2523. EXPECT_EQ("application/json tmp-string", file.content_type);
  2524. }
  2525. })
  2526. .Post("/multipart/multi_file_values",
  2527. [&](const Request &req, Response & /*res*/) {
  2528. EXPECT_EQ(5u, req.files.size());
  2529. ASSERT_TRUE(!req.has_file("???"));
  2530. ASSERT_TRUE(req.body.empty());
  2531. {
  2532. const auto &text_value = req.get_file_values("text");
  2533. EXPECT_EQ(1u, text_value.size());
  2534. auto &text = text_value[0];
  2535. EXPECT_TRUE(text.filename.empty());
  2536. EXPECT_EQ("default text", text.content);
  2537. }
  2538. {
  2539. const auto &text1_values = req.get_file_values("multi_text1");
  2540. EXPECT_EQ(2u, text1_values.size());
  2541. EXPECT_EQ("aaaaa", text1_values[0].content);
  2542. EXPECT_EQ("bbbbb", text1_values[1].content);
  2543. }
  2544. {
  2545. const auto &file1_values = req.get_file_values("multi_file1");
  2546. EXPECT_EQ(2u, file1_values.size());
  2547. auto file1 = file1_values[0];
  2548. EXPECT_EQ(file1.filename, "hello.txt");
  2549. EXPECT_EQ(file1.content_type, "text/plain");
  2550. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2551. auto file2 = file1_values[1];
  2552. EXPECT_EQ(file2.filename, "world.json");
  2553. EXPECT_EQ(file2.content_type, "application/json");
  2554. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2555. }
  2556. })
  2557. .Post("/empty",
  2558. [&](const Request &req, Response &res) {
  2559. EXPECT_EQ(req.body, "");
  2560. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2561. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2562. res.set_content("empty", "text/plain");
  2563. })
  2564. .Post("/empty-no-content-type",
  2565. [&](const Request &req, Response &res) {
  2566. EXPECT_EQ(req.body, "");
  2567. EXPECT_FALSE(req.has_header("Content-Type"));
  2568. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2569. res.set_content("empty-no-content-type", "text/plain");
  2570. })
  2571. .Post("/path-only",
  2572. [&](const Request &req, Response &res) {
  2573. EXPECT_EQ(req.body, "");
  2574. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2575. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2576. res.set_content("path-only", "text/plain");
  2577. })
  2578. .Post("/path-headers-only",
  2579. [&](const Request &req, Response &res) {
  2580. EXPECT_EQ(req.body, "");
  2581. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2582. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2583. EXPECT_EQ("world", req.get_header_value("hello"));
  2584. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2585. res.set_content("path-headers-only", "text/plain");
  2586. })
  2587. .Post("/post-large",
  2588. [&](const Request &req, Response &res) {
  2589. EXPECT_EQ(req.body, LARGE_DATA);
  2590. res.set_content(req.body, "text/plain");
  2591. })
  2592. .Put("/empty-no-content-type",
  2593. [&](const Request &req, Response &res) {
  2594. EXPECT_EQ(req.body, "");
  2595. EXPECT_FALSE(req.has_header("Content-Type"));
  2596. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2597. res.set_content("empty-no-content-type", "text/plain");
  2598. })
  2599. .Put("/put",
  2600. [&](const Request &req, Response &res) {
  2601. EXPECT_EQ(req.body, "PUT");
  2602. res.set_content(req.body, "text/plain");
  2603. })
  2604. .Put("/put-large",
  2605. [&](const Request &req, Response &res) {
  2606. EXPECT_EQ(req.body, LARGE_DATA);
  2607. res.set_content(req.body, "text/plain");
  2608. })
  2609. .Patch("/patch",
  2610. [&](const Request &req, Response &res) {
  2611. EXPECT_EQ(req.body, "PATCH");
  2612. res.set_content(req.body, "text/plain");
  2613. })
  2614. .Delete("/delete",
  2615. [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("DELETE", "text/plain");
  2617. })
  2618. .Delete("/delete-body",
  2619. [&](const Request &req, Response &res) {
  2620. EXPECT_EQ(req.body, "content");
  2621. res.set_content(req.body, "text/plain");
  2622. })
  2623. .Options(R"(\*)",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2626. })
  2627. .Get("/request-target",
  2628. [&](const Request &req, Response & /*res*/) {
  2629. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2630. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2631. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2632. })
  2633. .Get("/long-query-value",
  2634. [&](const Request &req, Response & /*res*/) {
  2635. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2636. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2637. })
  2638. .Get("/too-long-query-value",
  2639. [&](const Request &req, Response & /*res*/) {
  2640. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2641. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2642. })
  2643. .Get("/array-param",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2646. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2647. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2648. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2649. })
  2650. .Post("/validate-no-multiple-headers",
  2651. [&](const Request &req, Response & /*res*/) {
  2652. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2653. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2654. })
  2655. .Post("/content_receiver",
  2656. [&](const Request &req, Response &res,
  2657. const ContentReader &content_reader) {
  2658. if (req.is_multipart_form_data()) {
  2659. MultipartFormDataItems files;
  2660. content_reader(
  2661. [&](const MultipartFormData &file) {
  2662. files.push_back(file);
  2663. return true;
  2664. },
  2665. [&](const char *data, size_t data_length) {
  2666. files.back().content.append(data, data_length);
  2667. return true;
  2668. });
  2669. EXPECT_EQ(5u, files.size());
  2670. {
  2671. const auto &file = get_file_value(files, "text1");
  2672. EXPECT_TRUE(file.filename.empty());
  2673. EXPECT_EQ("text default", file.content);
  2674. }
  2675. {
  2676. const auto &file = get_file_value(files, "text2");
  2677. EXPECT_TRUE(file.filename.empty());
  2678. EXPECT_EQ("aωb", file.content);
  2679. }
  2680. {
  2681. const auto &file = get_file_value(files, "file1");
  2682. EXPECT_EQ("hello.txt", file.filename);
  2683. EXPECT_EQ("text/plain", file.content_type);
  2684. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2685. }
  2686. {
  2687. const auto &file = get_file_value(files, "file3");
  2688. EXPECT_TRUE(file.filename.empty());
  2689. EXPECT_EQ("application/octet-stream", file.content_type);
  2690. EXPECT_EQ(0u, file.content.size());
  2691. }
  2692. } else {
  2693. std::string body;
  2694. content_reader([&](const char *data, size_t data_length) {
  2695. EXPECT_EQ(7U, data_length);
  2696. body.append(data, data_length);
  2697. return true;
  2698. });
  2699. EXPECT_EQ(body, "content");
  2700. res.set_content(body, "text/plain");
  2701. }
  2702. })
  2703. .Put("/content_receiver",
  2704. [&](const Request & /*req*/, Response &res,
  2705. const ContentReader &content_reader) {
  2706. std::string body;
  2707. content_reader([&](const char *data, size_t data_length) {
  2708. body.append(data, data_length);
  2709. return true;
  2710. });
  2711. EXPECT_EQ(body, "content");
  2712. res.set_content(body, "text/plain");
  2713. })
  2714. .Patch("/content_receiver",
  2715. [&](const Request & /*req*/, Response &res,
  2716. const ContentReader &content_reader) {
  2717. std::string body;
  2718. content_reader([&](const char *data, size_t data_length) {
  2719. body.append(data, data_length);
  2720. return true;
  2721. });
  2722. EXPECT_EQ(body, "content");
  2723. res.set_content(body, "text/plain");
  2724. })
  2725. .Post("/query-string-and-body",
  2726. [&](const Request &req, Response & /*res*/) {
  2727. ASSERT_TRUE(req.has_param("key"));
  2728. EXPECT_EQ(req.get_param_value("key"), "value");
  2729. EXPECT_EQ(req.body, "content");
  2730. })
  2731. .Get("/last-request",
  2732. [&](const Request &req, Response & /*res*/) {
  2733. EXPECT_EQ("close", req.get_header_value("Connection"));
  2734. })
  2735. .Get(R"(/redirect/(\d+))",
  2736. [&](const Request &req, Response &res) {
  2737. auto num = std::stoi(req.matches[1]) + 1;
  2738. std::string url = "/redirect/" + std::to_string(num);
  2739. res.set_redirect(url);
  2740. })
  2741. .Post("/binary",
  2742. [&](const Request &req, Response &res) {
  2743. EXPECT_EQ(4U, req.body.size());
  2744. EXPECT_EQ("application/octet-stream",
  2745. req.get_header_value("Content-Type"));
  2746. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2747. res.set_content(req.body, "application/octet-stream");
  2748. })
  2749. .Put("/binary",
  2750. [&](const Request &req, Response &res) {
  2751. EXPECT_EQ(4U, req.body.size());
  2752. EXPECT_EQ("application/octet-stream",
  2753. req.get_header_value("Content-Type"));
  2754. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2755. res.set_content(req.body, "application/octet-stream");
  2756. })
  2757. .Patch("/binary",
  2758. [&](const Request &req, Response &res) {
  2759. EXPECT_EQ(4U, req.body.size());
  2760. EXPECT_EQ("application/octet-stream",
  2761. req.get_header_value("Content-Type"));
  2762. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2763. res.set_content(req.body, "application/octet-stream");
  2764. })
  2765. .Delete("/binary",
  2766. [&](const Request &req, Response &res) {
  2767. EXPECT_EQ(4U, req.body.size());
  2768. EXPECT_EQ("application/octet-stream",
  2769. req.get_header_value("Content-Type"));
  2770. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2771. res.set_content(req.body, "application/octet-stream");
  2772. })
  2773. .Get("/issue1772",
  2774. [&](const Request & /*req*/, Response &res) {
  2775. res.status = 401;
  2776. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2777. })
  2778. .Delete("/issue609",
  2779. [](const httplib::Request &, httplib::Response &res,
  2780. const httplib::ContentReader &) {
  2781. res.set_content("ok", "text/plain");
  2782. })
  2783. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2784. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2785. .Get("/compress",
  2786. [&](const Request & /*req*/, Response &res) {
  2787. res.set_content(
  2788. "12345678901234567890123456789012345678901234567890123456789"
  2789. "01234567890123456789012345678901234567890",
  2790. "text/plain");
  2791. })
  2792. .Get("/nocompress",
  2793. [&](const Request & /*req*/, Response &res) {
  2794. res.set_content(
  2795. "12345678901234567890123456789012345678901234567890123456789"
  2796. "01234567890123456789012345678901234567890",
  2797. "application/octet-stream");
  2798. })
  2799. .Post("/compress-multipart",
  2800. [&](const Request &req, Response & /*res*/) {
  2801. EXPECT_EQ(2u, req.files.size());
  2802. ASSERT_TRUE(!req.has_file("???"));
  2803. {
  2804. const auto &file = req.get_file_value("key1");
  2805. EXPECT_TRUE(file.filename.empty());
  2806. EXPECT_EQ("test", file.content);
  2807. }
  2808. {
  2809. const auto &file = req.get_file_value("key2");
  2810. EXPECT_TRUE(file.filename.empty());
  2811. EXPECT_EQ("--abcdefg123", file.content);
  2812. }
  2813. })
  2814. #endif
  2815. ;
  2816. persons_["john"] = "programmer";
  2817. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2818. svr_.wait_until_ready();
  2819. }
  2820. virtual void TearDown() {
  2821. svr_.stop();
  2822. if (!request_threads_.empty()) {
  2823. std::this_thread::sleep_for(std::chrono::seconds(1));
  2824. for (auto &t : request_threads_) {
  2825. t.join();
  2826. }
  2827. }
  2828. t_.join();
  2829. }
  2830. map<string, string> persons_;
  2831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2832. SSLClient cli_;
  2833. SSLServer svr_;
  2834. #else
  2835. Client cli_;
  2836. Server svr_;
  2837. #endif
  2838. thread t_;
  2839. std::vector<thread> request_threads_;
  2840. };
  2841. TEST_F(ServerTest, GetMethod200) {
  2842. auto res = cli_.Get("/hi");
  2843. ASSERT_TRUE(res);
  2844. EXPECT_EQ("HTTP/1.1", res->version);
  2845. EXPECT_EQ(StatusCode::OK_200, res->status);
  2846. EXPECT_EQ("OK", res->reason);
  2847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2848. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2849. EXPECT_EQ("Hello World!", res->body);
  2850. }
  2851. void performance_test(const char *host) {
  2852. auto port = 1234;
  2853. Server svr;
  2854. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2855. res.set_content("Benchmark Response", "text/plain");
  2856. });
  2857. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  2858. auto se = detail::scope_exit([&] {
  2859. svr.stop();
  2860. listen_thread.join();
  2861. ASSERT_FALSE(svr.is_running());
  2862. });
  2863. svr.wait_until_ready();
  2864. Client cli(host, port);
  2865. const int NUM_REQUESTS = 50;
  2866. const int MAX_AVERAGE_MS = 5;
  2867. auto warmup = cli.Get("/benchmark");
  2868. ASSERT_TRUE(warmup);
  2869. auto start = std::chrono::high_resolution_clock::now();
  2870. for (int i = 0; i < NUM_REQUESTS; ++i) {
  2871. auto res = cli.Get("/benchmark");
  2872. ASSERT_TRUE(res) << "Request " << i << " failed";
  2873. EXPECT_EQ(StatusCode::OK_200, res->status);
  2874. }
  2875. auto end = std::chrono::high_resolution_clock::now();
  2876. auto total_ms =
  2877. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2878. .count();
  2879. double avg_ms = static_cast<double>(total_ms) / NUM_REQUESTS;
  2880. std::cout << "Peformance test at \"" << host << "\": " << NUM_REQUESTS
  2881. << " requests in " << total_ms << "ms (avg: " << avg_ms << "ms)"
  2882. << std::endl;
  2883. EXPECT_LE(avg_ms, MAX_AVERAGE_MS)
  2884. << "Performance is too slow: " << avg_ms << "ms (Issue #1777)";
  2885. }
  2886. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  2887. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  2888. TEST_F(ServerTest, GetEmptyFile) {
  2889. auto res = cli_.Get("/empty_file");
  2890. ASSERT_TRUE(res);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2893. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2894. EXPECT_EQ("", res->body);
  2895. }
  2896. TEST_F(ServerTest, GetFileContent) {
  2897. auto res = cli_.Get("/file_content");
  2898. ASSERT_TRUE(res);
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2901. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2902. EXPECT_EQ("test.html", res->body);
  2903. }
  2904. TEST_F(ServerTest, GetFileContentWithRange) {
  2905. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2906. ASSERT_TRUE(res);
  2907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2908. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2909. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2910. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2911. EXPECT_EQ("est", res->body);
  2912. }
  2913. TEST_F(ServerTest, GetFileContentWithContentType) {
  2914. auto res = cli_.Get("/file_content_with_content_type");
  2915. ASSERT_TRUE(res);
  2916. EXPECT_EQ(StatusCode::OK_200, res->status);
  2917. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2918. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2919. EXPECT_EQ("file\n", res->body);
  2920. }
  2921. TEST_F(ServerTest, GetInvalidFileContent) {
  2922. auto res = cli_.Get("/invalid_file_content");
  2923. ASSERT_TRUE(res);
  2924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2925. }
  2926. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2927. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2928. ASSERT_TRUE(res);
  2929. EXPECT_EQ("HTTP/1.1", res->version);
  2930. EXPECT_EQ(StatusCode::OK_200, res->status);
  2931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2932. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2933. EXPECT_EQ("Hello World!", res->body);
  2934. }
  2935. TEST_F(ServerTest, GetMethod302) {
  2936. auto res = cli_.Get("/");
  2937. ASSERT_TRUE(res);
  2938. EXPECT_EQ(StatusCode::Found_302, res->status);
  2939. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2940. }
  2941. TEST_F(ServerTest, GetMethod302Redirect) {
  2942. cli_.set_follow_location(true);
  2943. auto res = cli_.Get("/");
  2944. ASSERT_TRUE(res);
  2945. EXPECT_EQ(StatusCode::OK_200, res->status);
  2946. EXPECT_EQ("Hello World!", res->body);
  2947. EXPECT_EQ("/hi", res->location);
  2948. }
  2949. TEST_F(ServerTest, GetMethod404) {
  2950. auto res = cli_.Get("/invalid");
  2951. ASSERT_TRUE(res);
  2952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2953. }
  2954. TEST_F(ServerTest, HeadMethod200) {
  2955. auto res = cli_.Head("/hi");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2959. EXPECT_TRUE(res->body.empty());
  2960. }
  2961. TEST_F(ServerTest, HeadMethod200Static) {
  2962. auto res = cli_.Head("/mount/dir/index.html");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::OK_200, res->status);
  2965. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2966. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2967. EXPECT_TRUE(res->body.empty());
  2968. }
  2969. TEST_F(ServerTest, HeadMethod404) {
  2970. auto res = cli_.Head("/invalid");
  2971. ASSERT_TRUE(res);
  2972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2973. EXPECT_TRUE(res->body.empty());
  2974. }
  2975. TEST_F(ServerTest, GetMethodPersonJohn) {
  2976. auto res = cli_.Get("/person/john");
  2977. ASSERT_TRUE(res);
  2978. EXPECT_EQ(StatusCode::OK_200, res->status);
  2979. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2980. EXPECT_EQ("programmer", res->body);
  2981. }
  2982. TEST_F(ServerTest, PostMethod1) {
  2983. auto res = cli_.Get("/person/john1");
  2984. ASSERT_TRUE(res);
  2985. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2986. res = cli_.Post("/person", "name=john1&note=coder",
  2987. "application/x-www-form-urlencoded");
  2988. ASSERT_TRUE(res);
  2989. ASSERT_EQ(StatusCode::OK_200, res->status);
  2990. res = cli_.Get("/person/john1");
  2991. ASSERT_TRUE(res);
  2992. ASSERT_EQ(StatusCode::OK_200, res->status);
  2993. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2994. ASSERT_EQ("coder", res->body);
  2995. }
  2996. TEST_F(ServerTest, PostMethod2) {
  2997. auto res = cli_.Get("/person/john2");
  2998. ASSERT_TRUE(res);
  2999. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3000. Params params;
  3001. params.emplace("name", "john2");
  3002. params.emplace("note", "coder");
  3003. res = cli_.Post("/person", params);
  3004. ASSERT_TRUE(res);
  3005. ASSERT_EQ(StatusCode::OK_200, res->status);
  3006. res = cli_.Get("/person/john2");
  3007. ASSERT_TRUE(res);
  3008. ASSERT_EQ(StatusCode::OK_200, res->status);
  3009. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3010. ASSERT_EQ("coder", res->body);
  3011. }
  3012. TEST_F(ServerTest, PutMethod3) {
  3013. auto res = cli_.Get("/person/john3");
  3014. ASSERT_TRUE(res);
  3015. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3016. Params params;
  3017. params.emplace("name", "john3");
  3018. params.emplace("note", "coder");
  3019. res = cli_.Put("/person", params);
  3020. ASSERT_TRUE(res);
  3021. ASSERT_EQ(StatusCode::OK_200, res->status);
  3022. res = cli_.Get("/person/john3");
  3023. ASSERT_TRUE(res);
  3024. ASSERT_EQ(StatusCode::OK_200, res->status);
  3025. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3026. ASSERT_EQ("coder", res->body);
  3027. }
  3028. TEST_F(ServerTest, DeleteMethod1) {
  3029. auto res = cli_.Get("/person/john4");
  3030. ASSERT_TRUE(res);
  3031. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3032. Params params;
  3033. params.emplace("name", "john4");
  3034. params.emplace("note", "coder");
  3035. res = cli_.Post("/person", params);
  3036. ASSERT_TRUE(res);
  3037. ASSERT_EQ(StatusCode::OK_200, res->status);
  3038. res = cli_.Get("/person/john4");
  3039. ASSERT_TRUE(res);
  3040. ASSERT_EQ(StatusCode::OK_200, res->status);
  3041. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3042. ASSERT_EQ("coder", res->body);
  3043. Params delete_params;
  3044. delete_params.emplace("name", "john4");
  3045. res = cli_.Delete("/person", delete_params);
  3046. ASSERT_TRUE(res);
  3047. ASSERT_EQ(StatusCode::OK_200, res->status);
  3048. ASSERT_EQ("DELETED", res->body);
  3049. res = cli_.Get("/person/john4");
  3050. ASSERT_TRUE(res);
  3051. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3052. }
  3053. TEST_F(ServerTest, DeleteMethod2) {
  3054. auto res = cli_.Get("/person/john5");
  3055. ASSERT_TRUE(res);
  3056. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3057. Params params;
  3058. params.emplace("name", "john5");
  3059. params.emplace("note", "developer");
  3060. res = cli_.Post("/person", params);
  3061. ASSERT_TRUE(res);
  3062. ASSERT_EQ(StatusCode::OK_200, res->status);
  3063. res = cli_.Get("/person/john5");
  3064. ASSERT_TRUE(res);
  3065. ASSERT_EQ(StatusCode::OK_200, res->status);
  3066. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3067. ASSERT_EQ("developer", res->body);
  3068. Params delete_params;
  3069. delete_params.emplace("name", "john5");
  3070. Headers headers;
  3071. headers.emplace("Custom-Header", "test-value");
  3072. res = cli_.Delete("/person", headers, delete_params);
  3073. ASSERT_TRUE(res);
  3074. ASSERT_EQ(StatusCode::OK_200, res->status);
  3075. ASSERT_EQ("DELETED", res->body);
  3076. res = cli_.Get("/person/john5");
  3077. ASSERT_TRUE(res);
  3078. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3079. }
  3080. TEST_F(ServerTest, DeleteMethod3) {
  3081. auto res = cli_.Get("/person/john6");
  3082. ASSERT_TRUE(res);
  3083. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3084. Params params;
  3085. params.emplace("name", "john6");
  3086. params.emplace("note", "tester");
  3087. res = cli_.Post("/person", params);
  3088. ASSERT_TRUE(res);
  3089. ASSERT_EQ(StatusCode::OK_200, res->status);
  3090. res = cli_.Get("/person/john6");
  3091. ASSERT_TRUE(res);
  3092. ASSERT_EQ(StatusCode::OK_200, res->status);
  3093. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3094. ASSERT_EQ("tester", res->body);
  3095. Params delete_params;
  3096. delete_params.emplace("name", "john6");
  3097. Headers headers;
  3098. headers.emplace("Custom-Header", "test-value");
  3099. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3100. ASSERT_TRUE(res);
  3101. ASSERT_EQ(StatusCode::OK_200, res->status);
  3102. ASSERT_EQ("DELETED", res->body);
  3103. res = cli_.Get("/person/john6");
  3104. ASSERT_TRUE(res);
  3105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3106. }
  3107. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3108. Params params;
  3109. params.emplace("json", JSON_DATA);
  3110. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3111. ASSERT_TRUE(res);
  3112. ASSERT_EQ(StatusCode::OK_200, res->status);
  3113. ASSERT_EQ(JSON_DATA, res->body);
  3114. }
  3115. TEST_F(ServerTest, PostEmptyContent) {
  3116. auto res = cli_.Post("/empty", "", "text/plain");
  3117. ASSERT_TRUE(res);
  3118. ASSERT_EQ(StatusCode::OK_200, res->status);
  3119. ASSERT_EQ("empty", res->body);
  3120. }
  3121. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3122. auto res = cli_.Post("/empty-no-content-type");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(StatusCode::OK_200, res->status);
  3125. ASSERT_EQ("empty-no-content-type", res->body);
  3126. }
  3127. TEST_F(ServerTest, PostPathOnly) {
  3128. auto res = cli_.Post("/path-only");
  3129. ASSERT_TRUE(res);
  3130. ASSERT_EQ(StatusCode::OK_200, res->status);
  3131. ASSERT_EQ("path-only", res->body);
  3132. }
  3133. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3134. auto res = cli_.Post("/path-headers-only",
  3135. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3136. ASSERT_TRUE(res);
  3137. ASSERT_EQ(StatusCode::OK_200, res->status);
  3138. ASSERT_EQ("path-headers-only", res->body);
  3139. }
  3140. TEST_F(ServerTest, PostLarge) {
  3141. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3142. ASSERT_TRUE(res);
  3143. ASSERT_EQ(StatusCode::OK_200, res->status);
  3144. EXPECT_EQ(LARGE_DATA, res->body);
  3145. }
  3146. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3147. auto res = cli_.Put("/empty-no-content-type");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("empty-no-content-type", res->body);
  3151. }
  3152. TEST_F(ServerTest, GetMethodDir) {
  3153. auto res = cli_.Get("/dir/");
  3154. ASSERT_TRUE(res);
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3157. auto body = R"(<html>
  3158. <head>
  3159. </head>
  3160. <body>
  3161. <a href="/dir/test.html">Test</a>
  3162. <a href="/hi">hi</a>
  3163. </body>
  3164. </html>
  3165. )";
  3166. EXPECT_EQ(body, res->body);
  3167. }
  3168. TEST_F(ServerTest, GetMethodDirTest) {
  3169. auto res = cli_.Get("/dir/test.html");
  3170. ASSERT_TRUE(res);
  3171. EXPECT_EQ(StatusCode::OK_200, res->status);
  3172. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3173. EXPECT_EQ("test.html", res->body);
  3174. }
  3175. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3176. auto res = cli_.Get("/dir/../dir/test.html");
  3177. ASSERT_TRUE(res);
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3180. EXPECT_EQ("test.html", res->body);
  3181. }
  3182. TEST_F(ServerTest, GetMethodInvalidPath) {
  3183. auto res = cli_.Get("/dir/../test.html");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3186. }
  3187. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3188. auto res = cli_.Get("/../www/dir/test.html");
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3191. }
  3192. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3193. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3196. }
  3197. TEST_F(ServerTest, GetMethodDirMountTest) {
  3198. auto res = cli_.Get("/mount/dir/test.html");
  3199. ASSERT_TRUE(res);
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3202. EXPECT_EQ("test.html", res->body);
  3203. }
  3204. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3205. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(StatusCode::OK_200, res->status);
  3208. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3209. EXPECT_EQ("test.html", res->body);
  3210. }
  3211. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3212. auto res = cli_.Get("/mount/dir/../test.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3215. }
  3216. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3217. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3220. }
  3221. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3222. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3223. ASSERT_TRUE(res);
  3224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3225. }
  3226. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3227. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3230. }
  3231. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3232. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3235. }
  3236. TEST_F(ServerTest, PostMethod303) {
  3237. auto res = cli_.Post("/1", "body", "text/plain");
  3238. ASSERT_TRUE(res);
  3239. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3240. EXPECT_EQ("/2", res->get_header_value("Location"));
  3241. }
  3242. TEST_F(ServerTest, PostMethod303Redirect) {
  3243. cli_.set_follow_location(true);
  3244. auto res = cli_.Post("/1", "body", "text/plain");
  3245. ASSERT_TRUE(res);
  3246. EXPECT_EQ(StatusCode::OK_200, res->status);
  3247. EXPECT_EQ("redirected.", res->body);
  3248. EXPECT_EQ("/2", res->location);
  3249. }
  3250. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3251. auto res = cli_.Get("/dir/test.abcde");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::OK_200, res->status);
  3254. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3255. EXPECT_EQ("abcde", res->body);
  3256. }
  3257. TEST_F(ServerTest, StaticFileRange) {
  3258. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3261. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3262. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3263. EXPECT_EQ(true, res->has_header("Content-Range"));
  3264. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3265. EXPECT_EQ(std::string("cd"), res->body);
  3266. }
  3267. TEST_F(ServerTest, StaticFileRanges) {
  3268. auto res =
  3269. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3270. ASSERT_TRUE(res);
  3271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3272. EXPECT_TRUE(
  3273. res->get_header_value("Content-Type")
  3274. .find(
  3275. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3276. 0);
  3277. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3278. }
  3279. TEST_F(ServerTest, StaticFileRangeHead) {
  3280. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3283. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3285. EXPECT_EQ(true, res->has_header("Content-Range"));
  3286. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3287. }
  3288. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3289. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3290. ASSERT_TRUE(res);
  3291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3293. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3294. EXPECT_EQ(true, res->has_header("Content-Range"));
  3295. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3296. res->get_header_value("Content-Range"));
  3297. EXPECT_EQ("LAST\n", res->body);
  3298. }
  3299. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3300. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3301. ASSERT_TRUE(res);
  3302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3304. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3305. EXPECT_EQ(true, res->has_header("Content-Range"));
  3306. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3307. }
  3308. TEST_F(ServerTest, StaticFileBigFile) {
  3309. auto res = cli_.Get("/dir/1MB.txt");
  3310. ASSERT_TRUE(res);
  3311. EXPECT_EQ(StatusCode::OK_200, res->status);
  3312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3313. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3314. }
  3315. TEST_F(ServerTest, InvalidBaseDirMount) {
  3316. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3317. }
  3318. TEST_F(ServerTest, Binary) {
  3319. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3320. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3321. "application/octet-stream");
  3322. ASSERT_TRUE(res);
  3323. ASSERT_EQ(StatusCode::OK_200, res->status);
  3324. ASSERT_EQ(4U, res->body.size());
  3325. res = cli_.Put("/binary", binary.data(), binary.size(),
  3326. "application/octet-stream");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ(4U, res->body.size());
  3330. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3331. "application/octet-stream");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ(4U, res->body.size());
  3335. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3336. "application/octet-stream");
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::OK_200, res->status);
  3339. ASSERT_EQ(4U, res->body.size());
  3340. }
  3341. TEST_F(ServerTest, BinaryString) {
  3342. auto binary = std::string("\x00\x01\x02\x03", 4);
  3343. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ(4U, res->body.size());
  3347. res = cli_.Put("/binary", binary, "application/octet-stream");
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. ASSERT_EQ(4U, res->body.size());
  3351. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. ASSERT_EQ(4U, res->body.size());
  3355. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3356. ASSERT_TRUE(res);
  3357. ASSERT_EQ(StatusCode::OK_200, res->status);
  3358. ASSERT_EQ(4U, res->body.size());
  3359. }
  3360. TEST_F(ServerTest, EmptyRequest) {
  3361. auto res = cli_.Get("");
  3362. ASSERT_TRUE(!res);
  3363. EXPECT_EQ(Error::Connection, res.error());
  3364. }
  3365. TEST_F(ServerTest, LongRequest) {
  3366. std::string request;
  3367. for (size_t i = 0; i < 545; i++) {
  3368. request += "/TooLongRequest";
  3369. }
  3370. request += "OK";
  3371. auto res = cli_.Get(request.c_str());
  3372. ASSERT_TRUE(res);
  3373. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3374. }
  3375. TEST_F(ServerTest, TooLongRequest) {
  3376. std::string request;
  3377. for (size_t i = 0; i < 546; i++) {
  3378. request += "/TooLongRequest";
  3379. }
  3380. request += "_NG";
  3381. auto res = cli_.Get(request.c_str());
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3384. }
  3385. TEST_F(ServerTest, AlmostTooLongRequest) {
  3386. // test for #2046 - URI length check shouldn't include other content on req
  3387. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3388. // leading /, space, HTTP/1.1)
  3389. std::string request =
  3390. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3391. auto res = cli_.Get(request.c_str());
  3392. ASSERT_TRUE(res);
  3393. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3394. }
  3395. TEST_F(ServerTest, LongHeader) {
  3396. Request req;
  3397. req.method = "GET";
  3398. req.path = "/hi";
  3399. std::string host_and_port;
  3400. host_and_port += HOST;
  3401. host_and_port += ":";
  3402. host_and_port += std::to_string(PORT);
  3403. req.headers.emplace("Host", host_and_port.c_str());
  3404. req.headers.emplace("Accept", "*/*");
  3405. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3406. req.headers.emplace(
  3407. "Header-Name",
  3408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3426. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3436. "@@@@@@@@@@@@@@@@");
  3437. auto res = std::make_shared<Response>();
  3438. auto error = Error::Success;
  3439. auto ret = cli_.send(req, *res, error);
  3440. ASSERT_TRUE(ret);
  3441. EXPECT_EQ(StatusCode::OK_200, res->status);
  3442. }
  3443. TEST_F(ServerTest, LongQueryValue) {
  3444. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3445. ASSERT_TRUE(res);
  3446. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3447. }
  3448. TEST_F(ServerTest, TooLongQueryValue) {
  3449. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3450. ASSERT_FALSE(res);
  3451. EXPECT_EQ(Error::Read, res.error());
  3452. }
  3453. TEST_F(ServerTest, TooLongHeader) {
  3454. Request req;
  3455. req.method = "GET";
  3456. req.path = "/hi";
  3457. std::string host_and_port;
  3458. host_and_port += HOST;
  3459. host_and_port += ":";
  3460. host_and_port += std::to_string(PORT);
  3461. req.headers.emplace("Host", host_and_port.c_str());
  3462. req.headers.emplace("Accept", "*/*");
  3463. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3464. req.headers.emplace(
  3465. "Header-Name",
  3466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3473. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3474. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3484. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3494. "@@@@@@@@@@@@@@@@@");
  3495. auto res = std::make_shared<Response>();
  3496. auto error = Error::Success;
  3497. auto ret = cli_.send(req, *res, error);
  3498. ASSERT_TRUE(ret);
  3499. EXPECT_EQ(StatusCode::OK_200, res->status);
  3500. }
  3501. TEST_F(ServerTest, HeaderCountAtLimit) {
  3502. // Test with headers just under the 100 limit
  3503. httplib::Headers headers;
  3504. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3505. // This should keep us just under the 100 header limit
  3506. for (int i = 0; i < 95; i++) {
  3507. std::string name = "X-Test-Header-" + std::to_string(i);
  3508. std::string value = "value" + std::to_string(i);
  3509. headers.emplace(name, value);
  3510. }
  3511. // This should work fine as we're under the limit
  3512. auto res = cli_.Get("/hi", headers);
  3513. EXPECT_TRUE(res);
  3514. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3515. }
  3516. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3517. // Test with many headers to exceed the 100 limit
  3518. httplib::Headers headers;
  3519. // Add 150 headers to definitely exceed the 100 limit
  3520. for (int i = 0; i < 150; i++) {
  3521. std::string name = "X-Test-Header-" + std::to_string(i);
  3522. std::string value = "value" + std::to_string(i);
  3523. headers.emplace(name, value);
  3524. }
  3525. // This should fail due to exceeding header count limit
  3526. auto res = cli_.Get("/hi", headers);
  3527. // The request should either fail or return 400 Bad Request
  3528. if (res) {
  3529. // If we get a response, it should be 400 Bad Request
  3530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3531. } else {
  3532. // Or the request should fail entirely
  3533. EXPECT_FALSE(res);
  3534. }
  3535. }
  3536. TEST_F(ServerTest, PercentEncoding) {
  3537. auto res = cli_.Get("/e%6edwith%");
  3538. ASSERT_TRUE(res);
  3539. EXPECT_EQ(StatusCode::OK_200, res->status);
  3540. }
  3541. TEST_F(ServerTest, PercentEncodingUnicode) {
  3542. auto res = cli_.Get("/e%u006edwith%");
  3543. ASSERT_TRUE(res);
  3544. EXPECT_EQ(StatusCode::OK_200, res->status);
  3545. }
  3546. TEST_F(ServerTest, InvalidPercentEncoding) {
  3547. auto res = cli_.Get("/%endwith%");
  3548. ASSERT_TRUE(res);
  3549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3550. }
  3551. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3552. auto res = cli_.Get("/%uendwith%");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3555. }
  3556. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3557. auto res = cli_.Get("/hello?aaa=bbb%");
  3558. ASSERT_TRUE(res);
  3559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3560. }
  3561. TEST_F(ServerTest, PlusSignEncoding) {
  3562. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. EXPECT_EQ("a +b", res->body);
  3566. }
  3567. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3568. // This test simulates a potential DoS attack using many headers
  3569. // to verify our security fix prevents memory exhaustion
  3570. httplib::Headers attack_headers;
  3571. // Attempt to add many headers like an attacker would (200 headers to far
  3572. // exceed limit)
  3573. for (int i = 0; i < 200; i++) {
  3574. std::string name = "X-Attack-Header-" + std::to_string(i);
  3575. std::string value = "attack_payload_" + std::to_string(i);
  3576. attack_headers.emplace(name, value);
  3577. }
  3578. // Try to POST with excessive headers
  3579. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3580. // Should either fail or return 400 Bad Request due to security limit
  3581. if (res) {
  3582. // If we get a response, it should be 400 Bad Request
  3583. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3584. } else {
  3585. // Request failed, which is the expected behavior for DoS protection
  3586. EXPECT_FALSE(res);
  3587. }
  3588. }
  3589. TEST_F(ServerTest, MultipartFormData) {
  3590. MultipartFormDataItemsForClientInput items = {
  3591. {"text1", "text default", "", ""},
  3592. {"text2", "aωb", "", ""},
  3593. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3594. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3595. {"file3", "", "", "application/octet-stream"},
  3596. {"file4", "", "", " application/json tmp-string "}};
  3597. auto res = cli_.Post("/multipart", items);
  3598. ASSERT_TRUE(res);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. }
  3601. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3602. MultipartFormDataItemsForClientInput items = {
  3603. {"text", "default text", "", ""},
  3604. {"multi_text1", "aaaaa", "", ""},
  3605. {"multi_text1", "bbbbb", "", ""},
  3606. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3607. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3608. "application/json"},
  3609. };
  3610. auto res = cli_.Post("/multipart/multi_file_values", items);
  3611. ASSERT_TRUE(res);
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. }
  3614. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3615. auto res = cli_.Get("/hi");
  3616. ASSERT_TRUE(res);
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3619. EXPECT_EQ("Hello World!", res->body);
  3620. }
  3621. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3622. Request req;
  3623. req.method = "POST";
  3624. req.path = "/chunked";
  3625. std::string host_and_port;
  3626. host_and_port += HOST;
  3627. host_and_port += ":";
  3628. host_and_port += std::to_string(PORT);
  3629. req.headers.emplace("Host", host_and_port.c_str());
  3630. req.headers.emplace("Accept", "*/*");
  3631. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3632. req.headers.emplace("Content-Type", "text/plain");
  3633. req.headers.emplace("Content-Length", "0");
  3634. req.headers.emplace(
  3635. "Transfer-Encoding",
  3636. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3637. // Client does not chunk, so make a chunked body manually.
  3638. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3639. auto res = std::make_shared<Response>();
  3640. auto error = Error::Success;
  3641. auto ret = cli_.send(req, *res, error);
  3642. ASSERT_TRUE(ret);
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. }
  3645. TEST_F(ServerTest, GetStreamed2) {
  3646. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3647. ASSERT_TRUE(res);
  3648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3649. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3650. EXPECT_EQ(true, res->has_header("Content-Range"));
  3651. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3652. EXPECT_EQ(std::string("ab"), res->body);
  3653. }
  3654. TEST_F(ServerTest, GetStreamed) {
  3655. auto res = cli_.Get("/streamed");
  3656. ASSERT_TRUE(res);
  3657. EXPECT_EQ(StatusCode::OK_200, res->status);
  3658. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3659. EXPECT_EQ(std::string("aaabbb"), res->body);
  3660. }
  3661. TEST_F(ServerTest, GetStreamedWithRange1) {
  3662. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3663. ASSERT_TRUE(res);
  3664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3665. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3666. EXPECT_EQ(true, res->has_header("Content-Range"));
  3667. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3668. EXPECT_EQ(std::string("def"), res->body);
  3669. }
  3670. TEST_F(ServerTest, GetStreamedWithRange2) {
  3671. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3672. ASSERT_TRUE(res);
  3673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3674. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3675. EXPECT_EQ(true, res->has_header("Content-Range"));
  3676. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3677. EXPECT_EQ(std::string("bcdefg"), res->body);
  3678. }
  3679. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3680. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3681. ASSERT_TRUE(res);
  3682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3683. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3684. EXPECT_EQ(true, res->has_header("Content-Range"));
  3685. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3686. EXPECT_EQ(std::string("efg"), res->body);
  3687. }
  3688. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3689. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3692. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3693. EXPECT_EQ(false, res->has_header("Content-Range"));
  3694. EXPECT_EQ(0U, res->body.size());
  3695. }
  3696. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3697. auto res = cli_.Get("/streamed-with-range",
  3698. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3699. "92233720368547758079223372036854775807"}});
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3702. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3703. EXPECT_EQ(false, res->has_header("Content-Range"));
  3704. EXPECT_EQ(0U, res->body.size());
  3705. }
  3706. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3707. auto res = cli_.Get(
  3708. "/with-range",
  3709. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3710. {"Accept-Encoding", ""}});
  3711. ASSERT_TRUE(res);
  3712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3713. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3714. EXPECT_EQ(true, res->has_header("Content-Range"));
  3715. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3716. EXPECT_EQ(std::string("abcdefg"), res->body);
  3717. }
  3718. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3719. auto res = cli_.Get("/with-range", {
  3720. {"Range", "bytes=0-"},
  3721. {"Accept-Encoding", ""},
  3722. });
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3725. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3726. EXPECT_EQ(true, res->has_header("Content-Range"));
  3727. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3728. EXPECT_EQ(std::string("abcdefg"), res->body);
  3729. }
  3730. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3731. auto res =
  3732. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3733. ASSERT_TRUE(res);
  3734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3735. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ(false, res->has_header("Content-Range"));
  3737. EXPECT_EQ(267U, res->body.size());
  3738. // Check that both range contents are present
  3739. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3740. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3741. // Check that Content-Range headers are present for both ranges
  3742. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3743. std::string::npos);
  3744. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3745. std::string::npos);
  3746. }
  3747. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3748. Ranges ranges;
  3749. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3750. ranges.emplace_back(0, -1);
  3751. }
  3752. auto res =
  3753. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3756. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3757. EXPECT_EQ(false, res->has_header("Content-Range"));
  3758. EXPECT_EQ(0U, res->body.size());
  3759. }
  3760. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3761. auto res =
  3762. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3763. ASSERT_TRUE(res);
  3764. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3765. EXPECT_EQ(5U, res->body.size());
  3766. // Check that overlapping ranges are coalesced into a single range
  3767. EXPECT_EQ("bcdef", res->body);
  3768. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3769. // Should be single range, not multipart
  3770. EXPECT_TRUE(res->has_header("Content-Range"));
  3771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3772. }
  3773. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3774. auto res =
  3775. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3776. ASSERT_TRUE(res);
  3777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3778. EXPECT_EQ(268U, res->body.size());
  3779. // Check that both range contents are present
  3780. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3781. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3782. // Check that Content-Range headers are present for both ranges
  3783. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3784. std::string::npos);
  3785. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3786. std::string::npos);
  3787. }
  3788. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3789. auto res =
  3790. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3791. ASSERT_TRUE(res);
  3792. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3793. EXPECT_EQ(269U, res->body.size());
  3794. // Check that both duplicate range contents are present
  3795. size_t first_abc = res->body.find("abc\r\n");
  3796. EXPECT_TRUE(first_abc != std::string::npos);
  3797. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3798. EXPECT_TRUE(second_abc != std::string::npos);
  3799. // Check that Content-Range headers are present for both ranges
  3800. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3801. EXPECT_TRUE(first_range != std::string::npos);
  3802. size_t second_range =
  3803. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3804. EXPECT_TRUE(second_range != std::string::npos);
  3805. }
  3806. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3807. auto res = cli_.Get("/streamed-with-range?error",
  3808. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3809. ASSERT_TRUE(res);
  3810. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3811. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3812. EXPECT_EQ(false, res->has_header("Content-Range"));
  3813. EXPECT_EQ(0U, res->body.size());
  3814. }
  3815. TEST_F(ServerTest, GetStreamedEndless) {
  3816. uint64_t offset = 0;
  3817. auto res = cli_.Get("/streamed-cancel",
  3818. [&](const char * /*data*/, uint64_t data_length) {
  3819. if (offset < 100) {
  3820. offset += data_length;
  3821. return true;
  3822. }
  3823. return false;
  3824. });
  3825. ASSERT_TRUE(!res);
  3826. EXPECT_EQ(Error::Canceled, res.error());
  3827. }
  3828. TEST_F(ServerTest, ClientStop) {
  3829. std::atomic_size_t count{4};
  3830. std::vector<std::thread> threads;
  3831. for (auto i = count.load(); i != 0; --i) {
  3832. threads.emplace_back([&]() {
  3833. auto res = cli_.Get("/streamed-cancel",
  3834. [&](const char *, uint64_t) { return true; });
  3835. --count;
  3836. ASSERT_TRUE(!res);
  3837. EXPECT_TRUE(res.error() == Error::Canceled ||
  3838. res.error() == Error::Read || res.error() == Error::Write);
  3839. });
  3840. }
  3841. std::this_thread::sleep_for(std::chrono::seconds(2));
  3842. while (count != 0) {
  3843. cli_.stop();
  3844. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3845. }
  3846. for (auto &t : threads) {
  3847. t.join();
  3848. }
  3849. }
  3850. TEST_F(ServerTest, GetWithRange1) {
  3851. auto res = cli_.Get("/with-range", {
  3852. make_range_header({{3, 5}}),
  3853. {"Accept-Encoding", ""},
  3854. });
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3857. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3858. EXPECT_EQ(true, res->has_header("Content-Range"));
  3859. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3860. EXPECT_EQ(std::string("def"), res->body);
  3861. }
  3862. TEST_F(ServerTest, GetWithRange2) {
  3863. auto res = cli_.Get("/with-range", {
  3864. make_range_header({{1, -1}}),
  3865. {"Accept-Encoding", ""},
  3866. });
  3867. ASSERT_TRUE(res);
  3868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3869. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3870. EXPECT_EQ(true, res->has_header("Content-Range"));
  3871. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3872. EXPECT_EQ(std::string("bcdefg"), res->body);
  3873. }
  3874. TEST_F(ServerTest, GetWithRange3) {
  3875. auto res = cli_.Get("/with-range", {
  3876. make_range_header({{0, 0}}),
  3877. {"Accept-Encoding", ""},
  3878. });
  3879. ASSERT_TRUE(res);
  3880. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3881. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3882. EXPECT_EQ(true, res->has_header("Content-Range"));
  3883. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3884. EXPECT_EQ(std::string("a"), res->body);
  3885. }
  3886. TEST_F(ServerTest, GetWithRange4) {
  3887. auto res = cli_.Get("/with-range", {
  3888. make_range_header({{-1, 2}}),
  3889. {"Accept-Encoding", ""},
  3890. });
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3893. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3894. EXPECT_EQ(true, res->has_header("Content-Range"));
  3895. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3896. EXPECT_EQ(std::string("fg"), res->body);
  3897. }
  3898. TEST_F(ServerTest, GetWithRange5) {
  3899. auto res = cli_.Get("/with-range", {
  3900. make_range_header({{0, 5}}),
  3901. {"Accept-Encoding", ""},
  3902. });
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3905. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3906. EXPECT_EQ(true, res->has_header("Content-Range"));
  3907. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3908. EXPECT_EQ(std::string("abcdef"), res->body);
  3909. }
  3910. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3911. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3914. }
  3915. TEST_F(ServerTest, GetWithRangeMultipart) {
  3916. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3919. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3920. EXPECT_EQ(false, res->has_header("Content-Range"));
  3921. EXPECT_EQ(267U, res->body.size());
  3922. }
  3923. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3924. auto res =
  3925. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3928. }
  3929. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3930. auto res = cli_.Get("/with-range-customized-response",
  3931. {{make_range_header({{1, 2}})}});
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3934. EXPECT_EQ(true, res->has_header("Content-Length"));
  3935. EXPECT_EQ(false, res->has_header("Content-Range"));
  3936. EXPECT_EQ(JSON_DATA, res->body);
  3937. }
  3938. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3939. auto res = cli_.Get("/with-range-customized-response",
  3940. {{make_range_header({{1, 2}, {4, 5}})}});
  3941. ASSERT_TRUE(res);
  3942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3943. EXPECT_EQ(true, res->has_header("Content-Length"));
  3944. EXPECT_EQ(false, res->has_header("Content-Range"));
  3945. EXPECT_EQ(JSON_DATA, res->body);
  3946. }
  3947. TEST_F(ServerTest, Issue1772) {
  3948. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3949. ASSERT_TRUE(res);
  3950. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3951. }
  3952. TEST_F(ServerTest, Issue609) {
  3953. auto res = cli_.Delete("/issue609");
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ(StatusCode::OK_200, res->status);
  3956. EXPECT_EQ(std::string("ok"), res->body);
  3957. }
  3958. TEST_F(ServerTest, GetStreamedChunked) {
  3959. auto res = cli_.Get("/streamed-chunked");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ(std::string("123456789"), res->body);
  3963. }
  3964. TEST_F(ServerTest, GetStreamedChunked2) {
  3965. auto res = cli_.Get("/streamed-chunked2");
  3966. ASSERT_TRUE(res);
  3967. EXPECT_EQ(StatusCode::OK_200, res->status);
  3968. EXPECT_EQ(std::string("123456789"), res->body);
  3969. }
  3970. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3971. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::OK_200, res->status);
  3974. EXPECT_EQ(std::string("123456789"), res->body);
  3975. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3976. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3977. }
  3978. TEST_F(ServerTest, LargeChunkedPost) {
  3979. Request req;
  3980. req.method = "POST";
  3981. req.path = "/large-chunked";
  3982. std::string host_and_port;
  3983. host_and_port += HOST;
  3984. host_and_port += ":";
  3985. host_and_port += std::to_string(PORT);
  3986. req.headers.emplace("Host", host_and_port.c_str());
  3987. req.headers.emplace("Accept", "*/*");
  3988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3989. req.headers.emplace("Content-Type", "text/plain");
  3990. req.headers.emplace("Content-Length", "0");
  3991. req.headers.emplace("Transfer-Encoding", "chunked");
  3992. std::string long_string(30 * 1024u, 'a');
  3993. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3994. // Attempt to make a large enough post to exceed OS buffers, to test that
  3995. // the server handles short reads if the full chunk data isn't available.
  3996. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3997. auto res = std::make_shared<Response>();
  3998. auto error = Error::Success;
  3999. auto ret = cli_.send(req, *res, error);
  4000. ASSERT_TRUE(ret);
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. }
  4003. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4004. auto res = cli_.Get("/remote_addr");
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::OK_200, res->status);
  4007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4008. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4009. }
  4010. TEST_F(ServerTest, GetMethodLocalAddr) {
  4011. auto res = cli_.Get("/local_addr");
  4012. ASSERT_TRUE(res);
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4015. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4016. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4017. }
  4018. TEST_F(ServerTest, HTTPResponseSplitting) {
  4019. auto res = cli_.Get("/http_response_splitting");
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::OK_200, res->status);
  4022. }
  4023. TEST_F(ServerTest, SlowRequest) {
  4024. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4025. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4026. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4027. }
  4028. #if 0
  4029. TEST_F(ServerTest, SlowPost) {
  4030. char buffer[64 * 1024];
  4031. memset(buffer, 0x42, sizeof(buffer));
  4032. auto res = cli_.Post(
  4033. "/slowpost", 64 * 1024 * 1024,
  4034. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4035. auto ret = sink.write(buffer, sizeof(buffer));
  4036. EXPECT_TRUE(ret);
  4037. return true;
  4038. },
  4039. "text/plain");
  4040. ASSERT_TRUE(res);
  4041. EXPECT_EQ(StatusCode::OK_200, res->status);
  4042. }
  4043. TEST_F(ServerTest, SlowPostFail) {
  4044. char buffer[64 * 1024];
  4045. memset(buffer, 0x42, sizeof(buffer));
  4046. cli_.set_write_timeout(std::chrono::seconds(0));
  4047. auto res = cli_.Post(
  4048. "/slowpost", 64 * 1024 * 1024,
  4049. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4050. sink.write(buffer, sizeof(buffer));
  4051. return true;
  4052. },
  4053. "text/plain");
  4054. ASSERT_TRUE(!res);
  4055. EXPECT_EQ(Error::Write, res.error());
  4056. }
  4057. #endif
  4058. TEST_F(ServerTest, Put) {
  4059. auto res = cli_.Put("/put", "PUT", "text/plain");
  4060. ASSERT_TRUE(res);
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. EXPECT_EQ("PUT", res->body);
  4063. }
  4064. TEST_F(ServerTest, PutWithContentProvider) {
  4065. auto res = cli_.Put(
  4066. "/put", 3,
  4067. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4068. sink.os << "PUT";
  4069. return true;
  4070. },
  4071. "text/plain");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. EXPECT_EQ("PUT", res->body);
  4075. }
  4076. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4077. auto res = cli_.Post(
  4078. "/post", 42,
  4079. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4080. return false;
  4081. },
  4082. "text/plain");
  4083. ASSERT_TRUE(!res);
  4084. EXPECT_EQ(Error::Canceled, res.error());
  4085. }
  4086. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4087. auto res = cli_.Put(
  4088. "/put",
  4089. [](size_t /*offset*/, DataSink &sink) {
  4090. sink.os << "PUT";
  4091. sink.done();
  4092. return true;
  4093. },
  4094. "text/plain");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. EXPECT_EQ("PUT", res->body);
  4098. }
  4099. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4100. auto res = cli_.Post(
  4101. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4102. "text/plain");
  4103. ASSERT_TRUE(!res);
  4104. EXPECT_EQ(Error::Canceled, res.error());
  4105. }
  4106. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4107. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4108. cli_.set_compress(true);
  4109. auto res = cli_.Put(
  4110. "/put", 3,
  4111. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4112. sink.os << "PUT";
  4113. return true;
  4114. },
  4115. "text/plain");
  4116. ASSERT_TRUE(res);
  4117. EXPECT_EQ(StatusCode::OK_200, res->status);
  4118. EXPECT_EQ("PUT", res->body);
  4119. }
  4120. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4121. cli_.set_compress(true);
  4122. auto res = cli_.Post(
  4123. "/post", 42,
  4124. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4125. return false;
  4126. },
  4127. "text/plain");
  4128. ASSERT_TRUE(!res);
  4129. EXPECT_EQ(Error::Canceled, res.error());
  4130. }
  4131. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4132. cli_.set_compress(true);
  4133. auto res = cli_.Put(
  4134. "/put",
  4135. [](size_t /*offset*/, DataSink &sink) {
  4136. sink.os << "PUT";
  4137. sink.done();
  4138. return true;
  4139. },
  4140. "text/plain");
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::OK_200, res->status);
  4143. EXPECT_EQ("PUT", res->body);
  4144. }
  4145. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4146. cli_.set_compress(true);
  4147. auto res = cli_.Post(
  4148. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4149. "text/plain");
  4150. ASSERT_TRUE(!res);
  4151. EXPECT_EQ(Error::Canceled, res.error());
  4152. }
  4153. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4154. cli_.set_compress(true);
  4155. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::OK_200, res->status);
  4158. EXPECT_EQ(LARGE_DATA, res->body);
  4159. }
  4160. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4161. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4162. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4163. Client cli(s.c_str());
  4164. cli.enable_server_certificate_verification(false);
  4165. #else
  4166. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4167. Client cli(s.c_str());
  4168. #endif
  4169. cli.set_compress(true);
  4170. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. EXPECT_EQ(LARGE_DATA, res->body);
  4174. // The compressed size should be less than a 10th of the original. May vary
  4175. // depending on the zlib library.
  4176. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4177. static_cast<uint64_t>(10 * 1024 * 1024));
  4178. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4179. }
  4180. TEST_F(ServerTest, PutContentWithDeflate) {
  4181. cli_.set_compress(false);
  4182. Headers headers;
  4183. headers.emplace("Content-Encoding", "deflate");
  4184. // PUT in deflate format:
  4185. auto res = cli_.Put("/put", headers,
  4186. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4187. ASSERT_TRUE(res);
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("PUT", res->body);
  4190. }
  4191. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4192. Headers headers;
  4193. headers.emplace("Accept-Encoding", "gzip, deflate");
  4194. auto res = cli_.Get("/streamed-chunked", headers);
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::OK_200, res->status);
  4197. EXPECT_EQ(std::string("123456789"), res->body);
  4198. }
  4199. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4200. Headers headers;
  4201. headers.emplace("Accept-Encoding", "gzip, deflate");
  4202. auto res = cli_.Get("/streamed-chunked2", headers);
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::OK_200, res->status);
  4205. EXPECT_EQ(std::string("123456789"), res->body);
  4206. }
  4207. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4208. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4209. ASSERT_TRUE(res);
  4210. EXPECT_EQ(StatusCode::OK_200, res->status);
  4211. }
  4212. TEST(GzipDecompressor, ChunkedDecompression) {
  4213. std::string data;
  4214. for (size_t i = 0; i < 32 * 1024; ++i) {
  4215. data.push_back(static_cast<char>('a' + i % 26));
  4216. }
  4217. std::string compressed_data;
  4218. {
  4219. httplib::detail::gzip_compressor compressor;
  4220. bool result = compressor.compress(
  4221. data.data(), data.size(),
  4222. /*last=*/true,
  4223. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4224. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4225. compressed_data_size);
  4226. return true;
  4227. });
  4228. ASSERT_TRUE(result);
  4229. }
  4230. std::string decompressed_data;
  4231. {
  4232. httplib::detail::gzip_decompressor decompressor;
  4233. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4234. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4235. size_t chunk_size = 130;
  4236. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4237. chunk_begin += chunk_size) {
  4238. size_t current_chunk_size =
  4239. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4240. bool result = decompressor.decompress(
  4241. compressed_data.data() + chunk_begin, current_chunk_size,
  4242. [&](const char *decompressed_data_chunk,
  4243. size_t decompressed_data_chunk_size) {
  4244. decompressed_data.insert(decompressed_data.size(),
  4245. decompressed_data_chunk,
  4246. decompressed_data_chunk_size);
  4247. return true;
  4248. });
  4249. ASSERT_TRUE(result);
  4250. }
  4251. }
  4252. ASSERT_EQ(data, decompressed_data);
  4253. }
  4254. TEST(GzipDecompressor, DeflateDecompression) {
  4255. std::string original_text = "Raw deflate without gzip";
  4256. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4257. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4258. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4259. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4260. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4261. std::string decompressed_data;
  4262. {
  4263. httplib::detail::gzip_decompressor decompressor;
  4264. bool result = decompressor.decompress(
  4265. compressed_data.data(), compressed_data.size(),
  4266. [&](const char *decompressed_data_chunk,
  4267. size_t decompressed_data_chunk_size) {
  4268. decompressed_data.insert(decompressed_data.size(),
  4269. decompressed_data_chunk,
  4270. decompressed_data_chunk_size);
  4271. return true;
  4272. });
  4273. ASSERT_TRUE(result);
  4274. }
  4275. ASSERT_EQ(original_text, decompressed_data);
  4276. }
  4277. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4278. std::string original_text = "Raw deflate without gzip";
  4279. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4280. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4281. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4282. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4283. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4284. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4285. std::string decompressed_data;
  4286. {
  4287. httplib::detail::gzip_decompressor decompressor;
  4288. bool result = decompressor.decompress(
  4289. compressed_data.data(), compressed_data.size(),
  4290. [&](const char *decompressed_data_chunk,
  4291. size_t decompressed_data_chunk_size) {
  4292. decompressed_data.insert(decompressed_data.size(),
  4293. decompressed_data_chunk,
  4294. decompressed_data_chunk_size);
  4295. return true;
  4296. });
  4297. ASSERT_TRUE(result);
  4298. }
  4299. ASSERT_EQ(original_text, decompressed_data);
  4300. }
  4301. #ifdef _WIN32
  4302. TEST(GzipDecompressor, LargeRandomData) {
  4303. // prepare large random data that is difficult to be compressed and is
  4304. // expected to have large size even when compressed
  4305. std::random_device seed_gen;
  4306. std::mt19937 random(seed_gen());
  4307. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4308. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4309. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4310. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4311. // compress data over 4GiB
  4312. std::string compressed_data;
  4313. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4314. httplib::detail::gzip_compressor compressor;
  4315. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4316. data.size() * sizeof(std::uint32_t), true,
  4317. [&](const char *data, size_t size) {
  4318. compressed_data.insert(
  4319. compressed_data.size(), data, size);
  4320. return true;
  4321. });
  4322. ASSERT_TRUE(result);
  4323. // FIXME: compressed data size is expected to be greater than 4GiB,
  4324. // but there is no guarantee
  4325. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4326. // decompress data over 4GiB
  4327. std::string decompressed_data;
  4328. decompressed_data.reserve(data_size);
  4329. httplib::detail::gzip_decompressor decompressor;
  4330. result = decompressor.decompress(
  4331. compressed_data.data(), compressed_data.size(),
  4332. [&](const char *data, size_t size) {
  4333. decompressed_data.insert(decompressed_data.size(), data, size);
  4334. return true;
  4335. });
  4336. ASSERT_TRUE(result);
  4337. // compare
  4338. ASSERT_EQ(data_size, decompressed_data.size());
  4339. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4340. 0);
  4341. }
  4342. #endif
  4343. #endif
  4344. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4345. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4346. Headers headers;
  4347. headers.emplace("Accept-Encoding", "br");
  4348. auto res = cli_.Get("/streamed-chunked", headers);
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. EXPECT_EQ(std::string("123456789"), res->body);
  4352. }
  4353. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4354. Headers headers;
  4355. headers.emplace("Accept-Encoding", "br");
  4356. auto res = cli_.Get("/streamed-chunked2", headers);
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. EXPECT_EQ(std::string("123456789"), res->body);
  4360. }
  4361. #endif
  4362. TEST_F(ServerTest, Patch) {
  4363. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4364. ASSERT_TRUE(res);
  4365. EXPECT_EQ(StatusCode::OK_200, res->status);
  4366. EXPECT_EQ("PATCH", res->body);
  4367. }
  4368. TEST_F(ServerTest, Delete) {
  4369. auto res = cli_.Delete("/delete");
  4370. ASSERT_TRUE(res);
  4371. EXPECT_EQ(StatusCode::OK_200, res->status);
  4372. EXPECT_EQ("DELETE", res->body);
  4373. }
  4374. TEST_F(ServerTest, DeleteContentReceiver) {
  4375. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("content", res->body);
  4379. }
  4380. TEST_F(ServerTest, Options) {
  4381. auto res = cli_.Options("*");
  4382. ASSERT_TRUE(res);
  4383. EXPECT_EQ(StatusCode::OK_200, res->status);
  4384. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4385. EXPECT_TRUE(res->body.empty());
  4386. }
  4387. TEST_F(ServerTest, URL) {
  4388. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. }
  4392. TEST_F(ServerTest, ArrayParam) {
  4393. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. }
  4397. TEST_F(ServerTest, NoMultipleHeaders) {
  4398. Headers headers = {{"Content-Length", "5"}};
  4399. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4400. "text/plain");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. }
  4404. TEST_F(ServerTest, PostContentReceiver) {
  4405. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4406. ASSERT_TRUE(res);
  4407. ASSERT_EQ(StatusCode::OK_200, res->status);
  4408. ASSERT_EQ("content", res->body);
  4409. }
  4410. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4411. MultipartFormDataItemsForClientInput items = {
  4412. {"text1", "text default", "", ""},
  4413. {"text2", "aωb", "", ""},
  4414. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4415. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4416. {"file3", "", "", "application/octet-stream"},
  4417. };
  4418. auto res = cli_.Post("/content_receiver", items);
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. }
  4422. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4423. MultipartFormDataItemsForClientInput items = {
  4424. {"text1", "text default", "", ""},
  4425. {"text2", "aωb", "", ""},
  4426. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4427. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4428. {"file3", "", "", "application/octet-stream"},
  4429. };
  4430. auto boundary = std::string("+++++");
  4431. std::string body;
  4432. for (const auto &item : items) {
  4433. body += "--" + boundary + "\r\n";
  4434. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4435. if (!item.filename.empty()) {
  4436. body += "; filename=\"" + item.filename + "\"";
  4437. }
  4438. body += "\r\n";
  4439. if (!item.content_type.empty()) {
  4440. body += "Content-Type: " + item.content_type + "\r\n";
  4441. }
  4442. body += "\r\n";
  4443. body += item.content + "\r\n";
  4444. }
  4445. body += "--" + boundary + "--\r\n";
  4446. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4447. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::OK_200, res->status);
  4450. }
  4451. TEST_F(ServerTest, PostContentReceiverGzip) {
  4452. cli_.set_compress(true);
  4453. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4454. ASSERT_TRUE(res);
  4455. ASSERT_EQ(StatusCode::OK_200, res->status);
  4456. ASSERT_EQ("content", res->body);
  4457. }
  4458. TEST_F(ServerTest, PutContentReceiver) {
  4459. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4460. ASSERT_TRUE(res);
  4461. ASSERT_EQ(StatusCode::OK_200, res->status);
  4462. ASSERT_EQ("content", res->body);
  4463. }
  4464. TEST_F(ServerTest, PatchContentReceiver) {
  4465. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4466. ASSERT_TRUE(res);
  4467. ASSERT_EQ(StatusCode::OK_200, res->status);
  4468. ASSERT_EQ("content", res->body);
  4469. }
  4470. TEST_F(ServerTest, PostQueryStringAndBody) {
  4471. auto res =
  4472. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4473. ASSERT_TRUE(res);
  4474. ASSERT_EQ(StatusCode::OK_200, res->status);
  4475. }
  4476. TEST_F(ServerTest, HTTP2Magic) {
  4477. Request req;
  4478. req.method = "PRI";
  4479. req.path = "*";
  4480. req.body = "SM";
  4481. auto res = std::make_shared<Response>();
  4482. auto error = Error::Success;
  4483. auto ret = cli_.send(req, *res, error);
  4484. ASSERT_TRUE(ret);
  4485. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4486. }
  4487. TEST_F(ServerTest, KeepAlive) {
  4488. auto res = cli_.Get("/hi");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("Hello World!", res->body);
  4493. res = cli_.Get("/hi");
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4497. EXPECT_EQ("Hello World!", res->body);
  4498. res = cli_.Get("/hi");
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::OK_200, res->status);
  4501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4502. EXPECT_EQ("Hello World!", res->body);
  4503. res = cli_.Get("/not-exist");
  4504. ASSERT_TRUE(res);
  4505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4506. res = cli_.Post("/empty", "", "text/plain");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4510. EXPECT_EQ("empty", res->body);
  4511. EXPECT_EQ("close", res->get_header_value("Connection"));
  4512. res = cli_.Post(
  4513. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4514. "text/plain");
  4515. ASSERT_TRUE(res);
  4516. EXPECT_EQ(StatusCode::OK_200, res->status);
  4517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4518. EXPECT_EQ("empty", res->body);
  4519. cli_.set_keep_alive(false);
  4520. res = cli_.Get("/last-request");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("close", res->get_header_value("Connection"));
  4524. }
  4525. TEST_F(ServerTest, TooManyRedirect) {
  4526. cli_.set_follow_location(true);
  4527. auto res = cli_.Get("/redirect/0");
  4528. ASSERT_TRUE(!res);
  4529. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4530. }
  4531. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4532. TEST_F(ServerTest, Gzip) {
  4533. Headers headers;
  4534. headers.emplace("Accept-Encoding", "gzip, deflate");
  4535. auto res = cli_.Get("/compress", headers);
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4539. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4540. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4541. "7890123456789012345678901234567890",
  4542. res->body);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. }
  4545. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4546. Headers headers;
  4547. headers.emplace("Accept-Encoding", "");
  4548. auto res = cli_.Get("/compress", headers);
  4549. ASSERT_TRUE(res);
  4550. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4552. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4553. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4554. "7890123456789012345678901234567890",
  4555. res->body);
  4556. EXPECT_EQ(StatusCode::OK_200, res->status);
  4557. }
  4558. TEST_F(ServerTest, GzipWithContentReceiver) {
  4559. Headers headers;
  4560. headers.emplace("Accept-Encoding", "gzip, deflate");
  4561. std::string body;
  4562. auto res = cli_.Get("/compress", headers,
  4563. [&](const char *data, uint64_t data_length) {
  4564. EXPECT_EQ(100U, data_length);
  4565. body.append(data, data_length);
  4566. return true;
  4567. });
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4571. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4573. "7890123456789012345678901234567890",
  4574. body);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4578. Headers headers;
  4579. headers.emplace("Accept-Encoding", "gzip, deflate");
  4580. cli_.set_decompress(false);
  4581. auto res = cli_.Get("/compress", headers);
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4584. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4585. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4586. EXPECT_EQ(33U, res->body.size());
  4587. EXPECT_EQ(StatusCode::OK_200, res->status);
  4588. }
  4589. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4590. Headers headers;
  4591. headers.emplace("Accept-Encoding", "");
  4592. std::string body;
  4593. auto res = cli_.Get("/compress", headers,
  4594. [&](const char *data, uint64_t data_length) {
  4595. EXPECT_EQ(100U, data_length);
  4596. body.append(data, data_length);
  4597. return true;
  4598. });
  4599. ASSERT_TRUE(res);
  4600. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4602. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4603. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4604. "7890123456789012345678901234567890",
  4605. body);
  4606. EXPECT_EQ(StatusCode::OK_200, res->status);
  4607. }
  4608. TEST_F(ServerTest, NoGzip) {
  4609. Headers headers;
  4610. headers.emplace("Accept-Encoding", "gzip, deflate");
  4611. auto res = cli_.Get("/nocompress", headers);
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4614. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4617. "7890123456789012345678901234567890",
  4618. res->body);
  4619. EXPECT_EQ(StatusCode::OK_200, res->status);
  4620. }
  4621. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4622. Headers headers;
  4623. headers.emplace("Accept-Encoding", "gzip, deflate");
  4624. std::string body;
  4625. auto res = cli_.Get("/nocompress", headers,
  4626. [&](const char *data, uint64_t data_length) {
  4627. EXPECT_EQ(100U, data_length);
  4628. body.append(data, data_length);
  4629. return true;
  4630. });
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4633. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4636. "7890123456789012345678901234567890",
  4637. body);
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. }
  4640. TEST_F(ServerTest, MultipartFormDataGzip) {
  4641. MultipartFormDataItemsForClientInput items = {
  4642. {"key1", "test", "", ""},
  4643. {"key2", "--abcdefg123", "", ""},
  4644. };
  4645. cli_.set_compress(true);
  4646. auto res = cli_.Post("/compress-multipart", items);
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. }
  4650. #endif
  4651. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4652. TEST_F(ServerTest, Brotli) {
  4653. Headers headers;
  4654. headers.emplace("Accept-Encoding", "br");
  4655. auto res = cli_.Get("/compress", headers);
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4658. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4659. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4660. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4661. "7890123456789012345678901234567890",
  4662. res->body);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. }
  4665. #endif
  4666. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4667. TEST_F(ServerTest, Zstd) {
  4668. Headers headers;
  4669. headers.emplace("Accept-Encoding", "zstd");
  4670. auto res = cli_.Get("/compress", headers);
  4671. ASSERT_TRUE(res);
  4672. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4673. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4674. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4675. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4676. "7890123456789012345678901234567890",
  4677. res->body);
  4678. EXPECT_EQ(StatusCode::OK_200, res->status);
  4679. }
  4680. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4681. Headers headers;
  4682. headers.emplace("Accept-Encoding", "");
  4683. auto res = cli_.Get("/compress", headers);
  4684. ASSERT_TRUE(res);
  4685. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4686. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4687. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4688. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4689. "7890123456789012345678901234567890",
  4690. res->body);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. }
  4693. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4694. Headers headers;
  4695. headers.emplace("Accept-Encoding", "zstd");
  4696. std::string body;
  4697. auto res = cli_.Get("/compress", headers,
  4698. [&](const char *data, uint64_t data_length) {
  4699. EXPECT_EQ(100U, data_length);
  4700. body.append(data, data_length);
  4701. return true;
  4702. });
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4706. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4707. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4708. "7890123456789012345678901234567890",
  4709. body);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4713. Headers headers;
  4714. headers.emplace("Accept-Encoding", "zstd");
  4715. cli_.set_decompress(false);
  4716. auto res = cli_.Get("/compress", headers);
  4717. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4718. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4719. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4720. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4721. ASSERT_TRUE(res);
  4722. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4724. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4725. EXPECT_EQ(StatusCode::OK_200, res->status);
  4726. ASSERT_EQ(26U, res->body.size());
  4727. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4728. 0);
  4729. }
  4730. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4731. Headers headers;
  4732. headers.emplace("Accept-Encoding", "");
  4733. std::string body;
  4734. auto res = cli_.Get("/compress", headers,
  4735. [&](const char *data, uint64_t data_length) {
  4736. EXPECT_EQ(100U, data_length);
  4737. body.append(data, data_length);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(res);
  4741. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4743. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4744. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4745. "7890123456789012345678901234567890",
  4746. body);
  4747. EXPECT_EQ(StatusCode::OK_200, res->status);
  4748. }
  4749. TEST_F(ServerTest, NoZstd) {
  4750. Headers headers;
  4751. headers.emplace("Accept-Encoding", "zstd");
  4752. auto res = cli_.Get("/nocompress", headers);
  4753. ASSERT_TRUE(res);
  4754. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4755. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4756. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4757. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4758. "7890123456789012345678901234567890",
  4759. res->body);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. }
  4762. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4763. Headers headers;
  4764. headers.emplace("Accept-Encoding", "zstd");
  4765. std::string body;
  4766. auto res = cli_.Get("/nocompress", headers,
  4767. [&](const char *data, uint64_t data_length) {
  4768. EXPECT_EQ(100U, data_length);
  4769. body.append(data, data_length);
  4770. return true;
  4771. });
  4772. ASSERT_TRUE(res);
  4773. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4774. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4775. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4776. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4777. "7890123456789012345678901234567890",
  4778. body);
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. }
  4781. // TODO: How to enable zstd ??
  4782. TEST_F(ServerTest, MultipartFormDataZstd) {
  4783. MultipartFormDataItemsForClientInput items = {
  4784. {"key1", "test", "", ""},
  4785. {"key2", "--abcdefg123", "", ""},
  4786. };
  4787. Headers headers;
  4788. headers.emplace("Accept-Encoding", "zstd");
  4789. cli_.set_compress(true);
  4790. auto res = cli_.Post("/compress-multipart", headers, items);
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. }
  4794. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4795. Headers headers;
  4796. headers.emplace("Accept-Encoding", "zstd");
  4797. cli_.set_compress(true);
  4798. auto res = cli_.Put(
  4799. "/put", headers, 3,
  4800. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4801. sink.os << "PUT";
  4802. return true;
  4803. },
  4804. "text/plain");
  4805. ASSERT_TRUE(res);
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ("PUT", res->body);
  4808. }
  4809. TEST(ZstdDecompressor, ChunkedDecompression) {
  4810. std::string data;
  4811. for (size_t i = 0; i < 32 * 1024; ++i) {
  4812. data.push_back(static_cast<char>('a' + i % 26));
  4813. }
  4814. std::string compressed_data;
  4815. {
  4816. httplib::detail::zstd_compressor compressor;
  4817. bool result = compressor.compress(
  4818. data.data(), data.size(),
  4819. /*last=*/true,
  4820. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4821. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4822. compressed_data_size);
  4823. return true;
  4824. });
  4825. ASSERT_TRUE(result);
  4826. }
  4827. std::string decompressed_data;
  4828. {
  4829. httplib::detail::zstd_decompressor decompressor;
  4830. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4831. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4832. size_t chunk_size = 130;
  4833. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4834. chunk_begin += chunk_size) {
  4835. size_t current_chunk_size =
  4836. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4837. bool result = decompressor.decompress(
  4838. compressed_data.data() + chunk_begin, current_chunk_size,
  4839. [&](const char *decompressed_data_chunk,
  4840. size_t decompressed_data_chunk_size) {
  4841. decompressed_data.insert(decompressed_data.size(),
  4842. decompressed_data_chunk,
  4843. decompressed_data_chunk_size);
  4844. return true;
  4845. });
  4846. ASSERT_TRUE(result);
  4847. }
  4848. }
  4849. ASSERT_EQ(data, decompressed_data);
  4850. }
  4851. TEST(ZstdDecompressor, Decompress) {
  4852. std::string original_text = "Compressed with ZSTD";
  4853. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4854. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4855. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4856. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4857. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4858. std::string decompressed_data;
  4859. {
  4860. httplib::detail::zstd_decompressor decompressor;
  4861. bool result = decompressor.decompress(
  4862. compressed_data.data(), compressed_data.size(),
  4863. [&](const char *decompressed_data_chunk,
  4864. size_t decompressed_data_chunk_size) {
  4865. decompressed_data.insert(decompressed_data.size(),
  4866. decompressed_data_chunk,
  4867. decompressed_data_chunk_size);
  4868. return true;
  4869. });
  4870. ASSERT_TRUE(result);
  4871. }
  4872. ASSERT_EQ(original_text, decompressed_data);
  4873. }
  4874. #endif
  4875. // Sends a raw request to a server listening at HOST:PORT.
  4876. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4877. std::string *resp = nullptr) {
  4878. auto error = Error::Success;
  4879. auto client_sock = detail::create_client_socket(
  4880. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4881. /*connection_timeout_sec=*/5, 0,
  4882. /*read_timeout_sec=*/5, 0,
  4883. /*write_timeout_sec=*/5, 0, std::string(), error);
  4884. if (client_sock == INVALID_SOCKET) { return false; }
  4885. auto ret = detail::process_client_socket(
  4886. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4887. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4888. if (req.size() !=
  4889. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4890. return false;
  4891. }
  4892. char buf[512];
  4893. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4894. while (line_reader.getline()) {
  4895. if (resp) { *resp += line_reader.ptr(); }
  4896. }
  4897. return true;
  4898. });
  4899. detail::close_socket(client_sock);
  4900. return ret;
  4901. }
  4902. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4903. Server svr;
  4904. std::string header_value;
  4905. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4906. header_value = req.get_header_value("foo");
  4907. res.set_content("ok", "text/plain");
  4908. });
  4909. thread t = thread([&] { svr.listen(HOST, PORT); });
  4910. auto se = detail::scope_exit([&] {
  4911. svr.stop();
  4912. t.join();
  4913. ASSERT_FALSE(svr.is_running());
  4914. });
  4915. svr.wait_until_ready();
  4916. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4917. // like characters are not treated the same - use vertical tab and escape.
  4918. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4919. "foo: \t \v bar \x1B\t \r\n"
  4920. "Connection: close\r\n"
  4921. "\r\n";
  4922. std::string res;
  4923. ASSERT_TRUE(send_request(5, req, &res));
  4924. EXPECT_EQ(header_value, "");
  4925. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4926. }
  4927. // Sends a raw request and verifies that there isn't a crash or exception.
  4928. static void test_raw_request(const std::string &req,
  4929. std::string *out = nullptr) {
  4930. Server svr;
  4931. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4932. res.set_content("ok", "text/plain");
  4933. });
  4934. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4935. res.set_content("ok", "text/plain");
  4936. });
  4937. svr.Get("/header_field_value_check",
  4938. [&](const Request & /*req*/, Response &res) {
  4939. res.set_content("ok", "text/plain");
  4940. });
  4941. // Server read timeout must be longer than the client read timeout for the
  4942. // bug to reproduce, probably to force the server to process a request
  4943. // without a trailing blank line.
  4944. const time_t client_read_timeout_sec = 1;
  4945. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4946. bool listen_thread_ok = false;
  4947. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4948. auto se = detail::scope_exit([&] {
  4949. svr.stop();
  4950. t.join();
  4951. ASSERT_FALSE(svr.is_running());
  4952. EXPECT_TRUE(listen_thread_ok);
  4953. });
  4954. svr.wait_until_ready();
  4955. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4956. }
  4957. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4958. // A certain header line causes an exception if the header property is parsed
  4959. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4960. test_raw_request(
  4961. "GET /hi HTTP/1.1\r\n"
  4962. " : "
  4963. " "
  4964. " ");
  4965. }
  4966. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4967. // A certain header line causes an exception if the header property *name* is
  4968. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4969. // greedy matcher and requires backtracking when there are a lot of ":"
  4970. // characters.
  4971. // This occurs with libc++ but not libstdc++.
  4972. test_raw_request(
  4973. "GET /hi HTTP/1.1\r\n"
  4974. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4975. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4976. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4977. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4978. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4979. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4980. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4981. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4982. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4983. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4984. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4985. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4986. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4987. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4988. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4989. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4990. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4991. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4992. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4993. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4994. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4995. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4996. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4997. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4998. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4999. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5000. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5001. "&&&%%%");
  5002. }
  5003. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5004. // Make sure this doesn't crash the server.
  5005. // In a previous version of the header line regex, the "\r" rendered the line
  5006. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5007. // a new position where the leading white space ended and the field value
  5008. // began.
  5009. // The crash occurs with libc++ but not libstdc++.
  5010. test_raw_request("GET /hi HTTP/1.1\r\n"
  5011. "a:" +
  5012. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5013. "\r\n"
  5014. "\r\n");
  5015. }
  5016. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5017. std::string out;
  5018. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5019. "Content-Type: text/plain\r\n"
  5020. "Transfer-Encoding: chunked\r\n"
  5021. "\r\n"
  5022. "nothex\r\n",
  5023. &out);
  5024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5025. }
  5026. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5027. std::string out;
  5028. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5029. "Content-Type: text/plain\r\n"
  5030. "Transfer-Encoding: chunked\r\n"
  5031. "\r\n"
  5032. "3\r\n"
  5033. "xyz\r\n"
  5034. "NaN\r\n",
  5035. &out);
  5036. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5037. }
  5038. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5039. std::string out;
  5040. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5041. "Content-Type: text/plain\r\n"
  5042. "Transfer-Encoding: chunked\r\n"
  5043. "\r\n"
  5044. // Length is too large for 64 bits.
  5045. "1ffffffffffffffff\r\n"
  5046. "xyz\r\n",
  5047. &out);
  5048. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5049. }
  5050. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5051. test_raw_request("GET /hi HTTP/1.1\r\n"
  5052. "Content-Type: text/plain\r\n\r");
  5053. }
  5054. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5055. std::string out;
  5056. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5057. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5058. }
  5059. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5060. std::string out;
  5061. std::string request(
  5062. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5063. test_raw_request(request, &out);
  5064. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5065. }
  5066. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5067. std::string out;
  5068. std::string request(
  5069. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5070. test_raw_request(request, &out);
  5071. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5072. }
  5073. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5074. std::string out;
  5075. std::string request(
  5076. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5077. test_raw_request(request, &out);
  5078. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5079. }
  5080. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5081. std::string out;
  5082. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5083. "Test: \r\n\r\n",
  5084. &out);
  5085. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5086. }
  5087. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5088. Server svr;
  5089. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5090. res.set_header("Cache-Control", "no-cache");
  5091. res.set_chunked_content_provider(
  5092. "text/event-stream", [](size_t offset, DataSink &sink) {
  5093. std::string s = "data:";
  5094. s += std::to_string(offset);
  5095. s += "\n\n";
  5096. auto ret = sink.write(s.data(), s.size());
  5097. EXPECT_TRUE(ret);
  5098. std::this_thread::sleep_for(std::chrono::seconds(1));
  5099. return true;
  5100. });
  5101. });
  5102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5103. svr.wait_until_ready();
  5104. Client client(HOST, PORT);
  5105. const Headers headers = {{"Accept", "text/event-stream"}};
  5106. auto get_thread = std::thread([&client, &headers]() {
  5107. auto res = client.Get(
  5108. "/events", headers,
  5109. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5110. });
  5111. auto se = detail::scope_exit([&] {
  5112. svr.stop();
  5113. get_thread.join();
  5114. listen_thread.join();
  5115. ASSERT_FALSE(svr.is_running());
  5116. });
  5117. // Give GET time to get a few messages.
  5118. std::this_thread::sleep_for(std::chrono::seconds(2));
  5119. }
  5120. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5121. httplib::Server svr;
  5122. svr.Post("/hi",
  5123. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5124. res.status = StatusCode::OK_200;
  5125. });
  5126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5127. svr.wait_until_ready();
  5128. Client cli(HOST, PORT);
  5129. auto res = cli.Post("/hi", "data", "text/plain");
  5130. ASSERT_TRUE(res);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. svr.stop();
  5133. thread.join();
  5134. ASSERT_FALSE(svr.is_running());
  5135. res = cli.Post("/hi", "data", "text/plain");
  5136. ASSERT_FALSE(res);
  5137. }
  5138. TEST(ServerStopTest, ListenFailure) {
  5139. Server svr;
  5140. auto t = thread([&]() {
  5141. auto ret = svr.listen("????", PORT);
  5142. EXPECT_FALSE(ret);
  5143. });
  5144. svr.wait_until_ready();
  5145. svr.stop();
  5146. t.join();
  5147. }
  5148. TEST(ServerStopTest, Decommision) {
  5149. Server svr;
  5150. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5151. for (int i = 0; i < 4; i++) {
  5152. auto is_even = !(i % 2);
  5153. std::thread t{[&] {
  5154. try {
  5155. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5156. if (is_even) {
  5157. throw std::runtime_error("Some thing that happens to go wrong.");
  5158. }
  5159. svr.listen(HOST, PORT);
  5160. } catch (...) { svr.decommission(); }
  5161. }};
  5162. svr.wait_until_ready();
  5163. // Server is up
  5164. {
  5165. Client cli(HOST, PORT);
  5166. auto res = cli.Get("/hi");
  5167. if (is_even) {
  5168. EXPECT_FALSE(res);
  5169. } else {
  5170. EXPECT_TRUE(res);
  5171. EXPECT_EQ("hi...", res->body);
  5172. }
  5173. }
  5174. svr.stop();
  5175. t.join();
  5176. // Server is down...
  5177. {
  5178. Client cli(HOST, PORT);
  5179. auto res = cli.Get("/hi");
  5180. EXPECT_FALSE(res);
  5181. }
  5182. }
  5183. }
  5184. // Helper function for string body upload progress tests
  5185. template <typename SetupHandler, typename ClientCall>
  5186. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5187. ClientCall &&client_call,
  5188. const string &body) {
  5189. Server svr;
  5190. setup_handler(svr);
  5191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5192. auto se = detail::scope_exit([&] {
  5193. svr.stop();
  5194. t.join();
  5195. });
  5196. svr.wait_until_ready();
  5197. Client cli(HOST, PORT);
  5198. vector<uint64_t> progress_values;
  5199. bool progress_called = false;
  5200. auto res =
  5201. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5202. progress_values.push_back(current);
  5203. progress_called = true;
  5204. return true;
  5205. });
  5206. ASSERT_TRUE(res);
  5207. EXPECT_EQ(200, res->status);
  5208. EXPECT_TRUE(progress_called);
  5209. }
  5210. TEST(UploadProgressTest, PostStringBodyBasic) {
  5211. TestStringBodyUploadProgress(
  5212. [](Server &svr) {
  5213. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5214. res.set_content("received", "text/plain");
  5215. });
  5216. },
  5217. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5218. return cli.Post("/test", body, "text/plain", progress_callback);
  5219. },
  5220. "test data for upload progress");
  5221. }
  5222. TEST(UploadProgressTest, PutStringBodyBasic) {
  5223. TestStringBodyUploadProgress(
  5224. [](Server &svr) {
  5225. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5226. res.set_content("put received", "text/plain");
  5227. });
  5228. },
  5229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5230. return cli.Put("/test", body, "text/plain", progress_callback);
  5231. },
  5232. "put test data for upload progress");
  5233. }
  5234. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5235. TestStringBodyUploadProgress(
  5236. [](Server &svr) {
  5237. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5238. res.set_content("patch received", "text/plain");
  5239. });
  5240. },
  5241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5242. return cli.Patch("/test", body, "text/plain", progress_callback);
  5243. },
  5244. "patch test data for upload progress");
  5245. }
  5246. // Helper function for content provider upload progress tests
  5247. template <typename SetupHandler, typename ClientCall>
  5248. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5249. ClientCall &&client_call) {
  5250. Server svr;
  5251. setup_handler(svr);
  5252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5253. auto se = detail::scope_exit([&] {
  5254. svr.stop();
  5255. t.join();
  5256. });
  5257. svr.wait_until_ready();
  5258. Client cli(HOST, PORT);
  5259. vector<uint64_t> progress_values;
  5260. auto res =
  5261. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5262. progress_values.push_back(current);
  5263. return true;
  5264. });
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(200, res->status);
  5267. EXPECT_FALSE(progress_values.empty());
  5268. }
  5269. TEST(UploadProgressTest, PostContentProviderProgress) {
  5270. TestContentProviderUploadProgress(
  5271. [](Server &svr) {
  5272. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5273. res.set_content("provider received", "text/plain");
  5274. });
  5275. },
  5276. [](Client &cli, UploadProgress progress_callback) {
  5277. return cli.Post(
  5278. "/test", 10,
  5279. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5280. sink.os << "test data";
  5281. return true;
  5282. },
  5283. "text/plain", progress_callback);
  5284. });
  5285. }
  5286. // Helper function for multipart upload progress tests
  5287. template <typename SetupHandler, typename ClientCall>
  5288. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5289. ClientCall &&client_call,
  5290. const string &endpoint) {
  5291. Server svr;
  5292. setup_handler(svr);
  5293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5294. auto se = detail::scope_exit([&] {
  5295. svr.stop();
  5296. t.join();
  5297. });
  5298. svr.wait_until_ready();
  5299. Client cli(HOST, PORT);
  5300. vector<uint64_t> progress_values;
  5301. MultipartFormDataItemsForClientInput items = {
  5302. {"field1", "value1", "", ""},
  5303. {"field2", "longer value for progress tracking test", "", ""},
  5304. {"file1", "file content data for upload progress", "test.txt",
  5305. "text/plain"}};
  5306. auto res = client_call(cli, endpoint, items,
  5307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5308. progress_values.push_back(current);
  5309. return true;
  5310. });
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ(200, res->status);
  5313. EXPECT_FALSE(progress_values.empty());
  5314. }
  5315. TEST(UploadProgressTest, PostMultipartProgress) {
  5316. TestMultipartUploadProgress(
  5317. [](Server &svr) {
  5318. svr.Post("/multipart", [](const Request &req, Response &res) {
  5319. EXPECT_FALSE(req.files.empty());
  5320. res.set_content("multipart received", "text/plain");
  5321. });
  5322. },
  5323. [](Client &cli, const string &endpoint,
  5324. const MultipartFormDataItemsForClientInput &items,
  5325. UploadProgress progress_callback) {
  5326. return cli.Post(endpoint, items, progress_callback);
  5327. },
  5328. "/multipart");
  5329. }
  5330. // Helper function for basic download progress tests
  5331. template <typename SetupHandler, typename ClientCall>
  5332. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5333. ClientCall &&client_call, const string &endpoint,
  5334. size_t expected_content_size) {
  5335. Server svr;
  5336. setup_handler(svr);
  5337. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5338. auto se = detail::scope_exit([&] {
  5339. svr.stop();
  5340. t.join();
  5341. });
  5342. svr.wait_until_ready();
  5343. Client cli(HOST, PORT);
  5344. vector<uint64_t> progress_values;
  5345. auto res = client_call(cli, endpoint,
  5346. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5347. progress_values.push_back(current);
  5348. return true;
  5349. });
  5350. ASSERT_TRUE(res);
  5351. EXPECT_EQ(200, res->status);
  5352. EXPECT_FALSE(progress_values.empty());
  5353. EXPECT_EQ(expected_content_size, res->body.size());
  5354. }
  5355. TEST(DownloadProgressTest, GetBasic) {
  5356. TestBasicDownloadProgress(
  5357. [](Server &svr) {
  5358. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5359. string content(1000, 'D');
  5360. res.set_content(content, "text/plain");
  5361. });
  5362. },
  5363. [](Client &cli, const string &endpoint,
  5364. DownloadProgress progress_callback) {
  5365. return cli.Get(endpoint, progress_callback);
  5366. },
  5367. "/download", 1000u);
  5368. }
  5369. // Helper function for content receiver download progress tests
  5370. template <typename SetupHandler, typename ClientCall>
  5371. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5372. ClientCall &&client_call,
  5373. const string &endpoint,
  5374. size_t expected_content_size) {
  5375. Server svr;
  5376. setup_handler(svr);
  5377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5378. auto se = detail::scope_exit([&] {
  5379. svr.stop();
  5380. t.join();
  5381. });
  5382. svr.wait_until_ready();
  5383. Client cli(HOST, PORT);
  5384. vector<uint64_t> progress_values;
  5385. string received_body;
  5386. auto res = client_call(
  5387. cli, endpoint,
  5388. [&](const char *data, size_t data_length) -> bool {
  5389. received_body.append(data, data_length);
  5390. return true;
  5391. },
  5392. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5393. progress_values.push_back(current);
  5394. return true;
  5395. });
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ(200, res->status);
  5398. EXPECT_FALSE(progress_values.empty());
  5399. EXPECT_EQ(expected_content_size, received_body.size());
  5400. EXPECT_TRUE(res->body.empty());
  5401. }
  5402. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5403. TestContentReceiverDownloadProgress(
  5404. [](Server &svr) {
  5405. svr.Get("/download-receiver",
  5406. [](const Request & /*req*/, Response &res) {
  5407. string content(2000, 'R');
  5408. res.set_content(content, "text/plain");
  5409. });
  5410. },
  5411. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5412. DownloadProgress progress_callback) {
  5413. return cli.Get(endpoint, content_receiver, progress_callback);
  5414. },
  5415. "/download-receiver", 2000u);
  5416. }
  5417. TEST(StreamingTest, NoContentLengthStreaming) {
  5418. Server svr;
  5419. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5420. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5421. if (offset < 6) {
  5422. sink.os << (offset < 3 ? "a" : "b");
  5423. } else {
  5424. sink.done();
  5425. }
  5426. return true;
  5427. });
  5428. });
  5429. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5430. auto listen_se = detail::scope_exit([&] {
  5431. svr.stop();
  5432. listen_thread.join();
  5433. ASSERT_FALSE(svr.is_running());
  5434. });
  5435. svr.wait_until_ready();
  5436. Client client(HOST, PORT);
  5437. auto get_thread = std::thread([&client]() {
  5438. std::string s;
  5439. auto res =
  5440. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5441. s += std::string(data, len);
  5442. return true;
  5443. });
  5444. ASSERT_TRUE(res);
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. EXPECT_EQ("aaabbb", s);
  5447. });
  5448. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5449. // Give GET time to get a few messages.
  5450. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5451. }
  5452. TEST(MountTest, Unmount) {
  5453. Server svr;
  5454. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5455. auto se = detail::scope_exit([&] {
  5456. svr.stop();
  5457. listen_thread.join();
  5458. ASSERT_FALSE(svr.is_running());
  5459. });
  5460. svr.wait_until_ready();
  5461. Client cli("localhost", PORT);
  5462. svr.set_mount_point("/mount2", "./www2");
  5463. auto res = cli.Get("/");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5466. res = cli.Get("/mount2/dir/test.html");
  5467. ASSERT_TRUE(res);
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. svr.set_mount_point("/", "./www");
  5470. res = cli.Get("/dir/");
  5471. ASSERT_TRUE(res);
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. svr.remove_mount_point("/");
  5474. res = cli.Get("/dir/");
  5475. ASSERT_TRUE(res);
  5476. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5477. svr.remove_mount_point("/mount2");
  5478. res = cli.Get("/mount2/dir/test.html");
  5479. ASSERT_TRUE(res);
  5480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5481. }
  5482. TEST(MountTest, Redicect) {
  5483. Server svr;
  5484. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. listen_thread.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. });
  5490. svr.set_mount_point("/", "./www");
  5491. svr.wait_until_ready();
  5492. Client cli("localhost", PORT);
  5493. auto res = cli.Get("/dir/");
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. res = cli.Get("/dir");
  5497. ASSERT_TRUE(res);
  5498. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5499. res = cli.Get("/file");
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. res = cli.Get("/file/");
  5503. ASSERT_TRUE(res);
  5504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5505. cli.set_follow_location(true);
  5506. res = cli.Get("/dir");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. }
  5510. TEST(MountTest, MultibytesPathName) {
  5511. Server svr;
  5512. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5513. auto se = detail::scope_exit([&] {
  5514. svr.stop();
  5515. listen_thread.join();
  5516. ASSERT_FALSE(svr.is_running());
  5517. });
  5518. svr.set_mount_point("/", "./www");
  5519. svr.wait_until_ready();
  5520. Client cli("localhost", PORT);
  5521. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5522. ASSERT_TRUE(res);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5525. }
  5526. TEST(KeepAliveTest, ReadTimeout) {
  5527. Server svr;
  5528. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5529. std::this_thread::sleep_for(std::chrono::seconds(2));
  5530. res.set_content("a", "text/plain");
  5531. });
  5532. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5533. res.set_content("b", "text/plain");
  5534. });
  5535. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5536. auto se = detail::scope_exit([&] {
  5537. svr.stop();
  5538. listen_thread.join();
  5539. ASSERT_FALSE(svr.is_running());
  5540. });
  5541. svr.wait_until_ready();
  5542. Client cli("localhost", PORT);
  5543. cli.set_keep_alive(true);
  5544. cli.set_read_timeout(std::chrono::seconds(1));
  5545. auto resa = cli.Get("/a");
  5546. ASSERT_FALSE(resa);
  5547. EXPECT_EQ(Error::Read, resa.error());
  5548. auto resb = cli.Get("/b");
  5549. ASSERT_TRUE(resb);
  5550. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5551. EXPECT_EQ("b", resb->body);
  5552. }
  5553. TEST(KeepAliveTest, MaxCount) {
  5554. size_t keep_alive_max_count = 3;
  5555. Server svr;
  5556. svr.set_keep_alive_max_count(keep_alive_max_count);
  5557. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5558. res.set_content("Hello World!", "text/plain");
  5559. });
  5560. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5561. auto se = detail::scope_exit([&] {
  5562. svr.stop();
  5563. listen_thread.join();
  5564. ASSERT_FALSE(svr.is_running());
  5565. });
  5566. svr.wait_until_ready();
  5567. Client cli(HOST, PORT);
  5568. cli.set_keep_alive(true);
  5569. for (size_t i = 0; i < 5; i++) {
  5570. auto result = cli.Get("/hi");
  5571. ASSERT_TRUE(result);
  5572. EXPECT_EQ(StatusCode::OK_200, result->status);
  5573. if (i == keep_alive_max_count - 1) {
  5574. EXPECT_EQ("close", result->get_header_value("Connection"));
  5575. } else {
  5576. EXPECT_FALSE(result->has_header("Connection"));
  5577. }
  5578. }
  5579. }
  5580. TEST(KeepAliveTest, Issue1041) {
  5581. Server svr;
  5582. svr.set_keep_alive_timeout(3);
  5583. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5584. res.set_content("Hello World!", "text/plain");
  5585. });
  5586. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5587. auto se = detail::scope_exit([&] {
  5588. svr.stop();
  5589. listen_thread.join();
  5590. ASSERT_FALSE(svr.is_running());
  5591. });
  5592. svr.wait_until_ready();
  5593. Client cli(HOST, PORT);
  5594. cli.set_keep_alive(true);
  5595. auto result = cli.Get("/hi");
  5596. ASSERT_TRUE(result);
  5597. EXPECT_EQ(StatusCode::OK_200, result->status);
  5598. std::this_thread::sleep_for(std::chrono::seconds(5));
  5599. result = cli.Get("/hi");
  5600. ASSERT_TRUE(result);
  5601. EXPECT_EQ(StatusCode::OK_200, result->status);
  5602. }
  5603. TEST(KeepAliveTest, Issue1959) {
  5604. Server svr;
  5605. svr.set_keep_alive_timeout(5);
  5606. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5607. res.set_content("a", "text/plain");
  5608. });
  5609. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5610. auto se = detail::scope_exit([&] {
  5611. if (!svr.is_running()) return;
  5612. svr.stop();
  5613. listen_thread.join();
  5614. ASSERT_FALSE(svr.is_running());
  5615. });
  5616. svr.wait_until_ready();
  5617. Client cli("localhost", PORT);
  5618. cli.set_keep_alive(true);
  5619. using namespace std::chrono;
  5620. auto start = steady_clock::now();
  5621. cli.Get("/a");
  5622. svr.stop();
  5623. listen_thread.join();
  5624. auto end = steady_clock::now();
  5625. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5626. EXPECT_LT(elapsed, 5000);
  5627. }
  5628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5629. TEST(KeepAliveTest, SSLClientReconnection) {
  5630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5631. ASSERT_TRUE(svr.is_valid());
  5632. svr.set_keep_alive_timeout(1);
  5633. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5634. res.set_content("Hello World!", "text/plain");
  5635. });
  5636. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5637. auto se = detail::scope_exit([&] {
  5638. svr.stop();
  5639. listen_thread.join();
  5640. ASSERT_FALSE(svr.is_running());
  5641. });
  5642. svr.wait_until_ready();
  5643. SSLClient cli(HOST, PORT);
  5644. cli.enable_server_certificate_verification(false);
  5645. cli.set_keep_alive(true);
  5646. auto result = cli.Get("/hi");
  5647. ASSERT_TRUE(result);
  5648. EXPECT_EQ(StatusCode::OK_200, result->status);
  5649. result = cli.Get("/hi");
  5650. ASSERT_TRUE(result);
  5651. EXPECT_EQ(StatusCode::OK_200, result->status);
  5652. std::this_thread::sleep_for(std::chrono::seconds(2));
  5653. // Recoonect
  5654. result = cli.Get("/hi");
  5655. ASSERT_TRUE(result);
  5656. EXPECT_EQ(StatusCode::OK_200, result->status);
  5657. result = cli.Get("/hi");
  5658. ASSERT_TRUE(result);
  5659. EXPECT_EQ(StatusCode::OK_200, result->status);
  5660. }
  5661. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5663. ASSERT_TRUE(svr.is_valid());
  5664. svr.set_keep_alive_timeout(1);
  5665. std::string content = "reconnect";
  5666. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5667. res.set_content("Hello World!", "text/plain");
  5668. });
  5669. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5670. auto se = detail::scope_exit([&] {
  5671. svr.stop();
  5672. listen_thread.join();
  5673. ASSERT_FALSE(svr.is_running());
  5674. });
  5675. svr.wait_until_ready();
  5676. SSLClient cli(HOST, PORT);
  5677. cli.enable_server_certificate_verification(false);
  5678. cli.set_keep_alive(true);
  5679. auto result = cli.Post(
  5680. "/hi", content.size(),
  5681. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5682. sink.write(content.c_str(), content.size());
  5683. return true;
  5684. },
  5685. "text/plain");
  5686. ASSERT_TRUE(result);
  5687. EXPECT_EQ(200, result->status);
  5688. std::this_thread::sleep_for(std::chrono::seconds(2));
  5689. // Recoonect
  5690. result = cli.Post(
  5691. "/hi", content.size(),
  5692. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5693. sink.write(content.c_str(), content.size());
  5694. return true;
  5695. },
  5696. "text/plain");
  5697. ASSERT_TRUE(result);
  5698. EXPECT_EQ(200, result->status);
  5699. result = cli.Post(
  5700. "/hi", content.size(),
  5701. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5702. sink.write(content.c_str(), content.size());
  5703. return true;
  5704. },
  5705. "text/plain");
  5706. ASSERT_TRUE(result);
  5707. EXPECT_EQ(200, result->status);
  5708. }
  5709. #endif
  5710. TEST(ClientProblemDetectionTest, ContentProvider) {
  5711. Server svr;
  5712. size_t content_length = 1024 * 1024;
  5713. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5714. res.set_content_provider(
  5715. content_length, "text/plain",
  5716. [&](size_t offset, size_t length, DataSink &sink) {
  5717. auto out_len = std::min(length, static_cast<size_t>(1024));
  5718. std::string out(out_len, '@');
  5719. sink.write(out.data(), out_len);
  5720. return offset < 4096;
  5721. },
  5722. [](bool success) { ASSERT_FALSE(success); });
  5723. });
  5724. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5725. res.set_content_provider(
  5726. 0, "text/plain",
  5727. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5728. EXPECT_TRUE(false);
  5729. return true;
  5730. },
  5731. [](bool success) { ASSERT_FALSE(success); });
  5732. });
  5733. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5734. auto se = detail::scope_exit([&] {
  5735. svr.stop();
  5736. listen_thread.join();
  5737. ASSERT_FALSE(svr.is_running());
  5738. });
  5739. svr.wait_until_ready();
  5740. Client cli("localhost", PORT);
  5741. {
  5742. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5743. size_t /*data_length*/) { return false; });
  5744. ASSERT_FALSE(res);
  5745. }
  5746. {
  5747. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5748. size_t /*data_length*/) { return false; });
  5749. ASSERT_TRUE(res);
  5750. }
  5751. }
  5752. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5753. Server svr;
  5754. svr.set_error_handler([](Request const &, Response &res) -> void {
  5755. res.set_chunked_content_provider(
  5756. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5757. sink.os << "hello";
  5758. sink.os << "world";
  5759. sink.done();
  5760. return true;
  5761. });
  5762. });
  5763. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5764. auto se = detail::scope_exit([&] {
  5765. svr.stop();
  5766. listen_thread.join();
  5767. ASSERT_FALSE(svr.is_running());
  5768. });
  5769. svr.wait_until_ready();
  5770. Client cli("localhost", PORT);
  5771. auto res = cli.Get("/");
  5772. ASSERT_TRUE(res);
  5773. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5774. EXPECT_EQ("helloworld", res->body);
  5775. }
  5776. TEST(LongPollingTest, ClientCloseDetection) {
  5777. Server svr;
  5778. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5779. res.set_chunked_content_provider(
  5780. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5781. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5782. sink.os << "hello";
  5783. auto count = 10;
  5784. while (count > 0 && sink.is_writable()) {
  5785. this_thread::sleep_for(chrono::milliseconds(10));
  5786. count--;
  5787. }
  5788. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5789. return true;
  5790. });
  5791. });
  5792. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5793. auto se = detail::scope_exit([&] {
  5794. svr.stop();
  5795. listen_thread.join();
  5796. ASSERT_FALSE(svr.is_running());
  5797. });
  5798. svr.wait_until_ready();
  5799. Client cli("localhost", PORT);
  5800. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5801. EXPECT_EQ("hello", string(data, data_length));
  5802. return false; // close the socket immediately.
  5803. });
  5804. ASSERT_FALSE(res);
  5805. }
  5806. TEST(GetWithParametersTest, GetWithParameters) {
  5807. Server svr;
  5808. svr.Get("/", [&](const Request &req, Response &) {
  5809. EXPECT_EQ("world", req.get_param_value("hello"));
  5810. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5811. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5812. });
  5813. svr.Get("/params", [&](const Request &req, Response &) {
  5814. EXPECT_EQ("world", req.get_param_value("hello"));
  5815. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5816. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5817. });
  5818. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5819. EXPECT_EQ("resource-id", req.matches[1]);
  5820. EXPECT_EQ("foo", req.get_param_value("param1"));
  5821. EXPECT_EQ("bar", req.get_param_value("param2"));
  5822. });
  5823. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5824. EXPECT_EQ("user-id", req.path_params.at("id"));
  5825. EXPECT_EQ("foo", req.get_param_value("param1"));
  5826. EXPECT_EQ("bar", req.get_param_value("param2"));
  5827. });
  5828. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5829. auto se = detail::scope_exit([&] {
  5830. svr.stop();
  5831. listen_thread.join();
  5832. ASSERT_FALSE(svr.is_running());
  5833. });
  5834. svr.wait_until_ready();
  5835. {
  5836. Client cli(HOST, PORT);
  5837. Params params;
  5838. params.emplace("hello", "world");
  5839. params.emplace("hello2", "world2");
  5840. params.emplace("hello3", "world3");
  5841. auto res = cli.Get("/", params, Headers{});
  5842. ASSERT_TRUE(res);
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. }
  5845. {
  5846. Client cli(HOST, PORT);
  5847. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5848. ASSERT_TRUE(res);
  5849. EXPECT_EQ(StatusCode::OK_200, res->status);
  5850. }
  5851. {
  5852. Client cli(HOST, PORT);
  5853. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5854. ASSERT_TRUE(res);
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. {
  5858. Client cli(HOST, PORT);
  5859. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5860. ASSERT_TRUE(res);
  5861. EXPECT_EQ(StatusCode::OK_200, res->status);
  5862. }
  5863. }
  5864. TEST(GetWithParametersTest, GetWithParameters2) {
  5865. Server svr;
  5866. svr.Get("/", [&](const Request &req, Response &res) {
  5867. auto text = req.get_param_value("hello");
  5868. res.set_content(text, "text/plain");
  5869. });
  5870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5871. auto se = detail::scope_exit([&] {
  5872. svr.stop();
  5873. listen_thread.join();
  5874. ASSERT_FALSE(svr.is_running());
  5875. });
  5876. svr.wait_until_ready();
  5877. Client cli("localhost", PORT);
  5878. Params params;
  5879. params.emplace("hello", "world");
  5880. std::string body;
  5881. auto res = cli.Get("/", params, Headers{},
  5882. [&](const char *data, size_t data_length) {
  5883. body.append(data, data_length);
  5884. return true;
  5885. });
  5886. ASSERT_TRUE(res);
  5887. EXPECT_EQ(StatusCode::OK_200, res->status);
  5888. EXPECT_EQ("world", body);
  5889. }
  5890. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5891. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5892. auto host = "httpbin.org";
  5893. auto path = std::string{"/range/32"};
  5894. #else
  5895. auto host = "nghttp2.org";
  5896. auto path = std::string{"/httpbin/range/32"};
  5897. #endif
  5898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5899. SSLClient cli(host);
  5900. #else
  5901. Client cli(host);
  5902. #endif
  5903. cli.set_default_headers({make_range_header({{1, 10}})});
  5904. cli.set_connection_timeout(5);
  5905. {
  5906. auto res = cli.Get(path);
  5907. ASSERT_TRUE(res);
  5908. EXPECT_EQ("bcdefghijk", res->body);
  5909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5910. }
  5911. {
  5912. auto res = cli.Get(path);
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ("bcdefghijk", res->body);
  5915. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5916. }
  5917. }
  5918. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5919. Server svr;
  5920. svr.set_default_headers({{"Hello", "World"}});
  5921. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5922. res.set_content("ok", "text/plain");
  5923. });
  5924. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5925. auto se = detail::scope_exit([&] {
  5926. svr.stop();
  5927. listen_thread.join();
  5928. ASSERT_FALSE(svr.is_running());
  5929. });
  5930. svr.wait_until_ready();
  5931. Client cli("localhost", PORT);
  5932. auto res = cli.Get("/");
  5933. ASSERT_TRUE(res);
  5934. EXPECT_EQ(StatusCode::OK_200, res->status);
  5935. EXPECT_EQ("ok", res->body);
  5936. EXPECT_EQ("World", res->get_header_value("Hello"));
  5937. }
  5938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5939. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5941. ASSERT_TRUE(svr.is_valid());
  5942. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5943. std::this_thread::sleep_for(std::chrono::seconds(2));
  5944. res.set_content("a", "text/plain");
  5945. });
  5946. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5947. res.set_content("b", "text/plain");
  5948. });
  5949. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5950. auto se = detail::scope_exit([&] {
  5951. svr.stop();
  5952. listen_thread.join();
  5953. ASSERT_FALSE(svr.is_running());
  5954. });
  5955. svr.wait_until_ready();
  5956. SSLClient cli("localhost", PORT);
  5957. cli.enable_server_certificate_verification(false);
  5958. cli.set_keep_alive(true);
  5959. cli.set_read_timeout(std::chrono::seconds(1));
  5960. auto resa = cli.Get("/a");
  5961. ASSERT_TRUE(!resa);
  5962. EXPECT_EQ(Error::Read, resa.error());
  5963. auto resb = cli.Get("/b");
  5964. ASSERT_TRUE(resb);
  5965. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5966. EXPECT_EQ("b", resb->body);
  5967. }
  5968. #endif
  5969. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5970. protected:
  5971. ServerTestWithAI_PASSIVE()
  5972. : cli_(HOST, PORT)
  5973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5974. ,
  5975. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5976. #endif
  5977. {
  5978. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5979. cli_.enable_server_certificate_verification(false);
  5980. #endif
  5981. }
  5982. virtual void SetUp() {
  5983. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5984. res.set_content("Hello World!", "text/plain");
  5985. });
  5986. t_ = thread(
  5987. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5988. svr_.wait_until_ready();
  5989. }
  5990. virtual void TearDown() {
  5991. svr_.stop();
  5992. t_.join();
  5993. }
  5994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5995. SSLClient cli_;
  5996. SSLServer svr_;
  5997. #else
  5998. Client cli_;
  5999. Server svr_;
  6000. #endif
  6001. thread t_;
  6002. };
  6003. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6004. auto res = cli_.Get("/hi");
  6005. ASSERT_TRUE(res);
  6006. EXPECT_EQ(StatusCode::OK_200, res->status);
  6007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6008. EXPECT_EQ("Hello World!", res->body);
  6009. }
  6010. class ServerUpDownTest : public ::testing::Test {
  6011. protected:
  6012. ServerUpDownTest() : cli_(HOST, PORT) {}
  6013. virtual void SetUp() {
  6014. t_ = thread([&]() {
  6015. svr_.bind_to_any_port(HOST);
  6016. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6017. ASSERT_TRUE(svr_.listen_after_bind());
  6018. });
  6019. svr_.wait_until_ready();
  6020. }
  6021. virtual void TearDown() {
  6022. svr_.stop();
  6023. t_.join();
  6024. }
  6025. Client cli_;
  6026. Server svr_;
  6027. thread t_;
  6028. };
  6029. TEST_F(ServerUpDownTest, QuickStartStop) {
  6030. // Should not crash, especially when run with
  6031. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6032. }
  6033. class PayloadMaxLengthTest : public ::testing::Test {
  6034. protected:
  6035. PayloadMaxLengthTest()
  6036. : cli_(HOST, PORT)
  6037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6038. ,
  6039. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6040. #endif
  6041. {
  6042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6043. cli_.enable_server_certificate_verification(false);
  6044. #endif
  6045. }
  6046. virtual void SetUp() {
  6047. svr_.set_payload_max_length(8);
  6048. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6049. res.set_content("test", "text/plain");
  6050. });
  6051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6052. svr_.wait_until_ready();
  6053. }
  6054. virtual void TearDown() {
  6055. svr_.stop();
  6056. t_.join();
  6057. }
  6058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6059. SSLClient cli_;
  6060. SSLServer svr_;
  6061. #else
  6062. Client cli_;
  6063. Server svr_;
  6064. #endif
  6065. thread t_;
  6066. };
  6067. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6068. auto res = cli_.Post("/test", "123456789", "text/plain");
  6069. ASSERT_TRUE(res);
  6070. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6071. res = cli_.Post("/test", "12345678", "text/plain");
  6072. ASSERT_TRUE(res);
  6073. EXPECT_EQ(StatusCode::OK_200, res->status);
  6074. }
  6075. TEST(HostAndPortPropertiesTest, NoSSL) {
  6076. httplib::Client cli("www.google.com", 1234);
  6077. ASSERT_EQ("www.google.com", cli.host());
  6078. ASSERT_EQ(1234, cli.port());
  6079. }
  6080. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6081. httplib::Client cli("www.google.com:1234");
  6082. ASSERT_EQ("www.google.com", cli.host());
  6083. ASSERT_EQ(1234, cli.port());
  6084. }
  6085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6086. TEST(HostAndPortPropertiesTest, SSL) {
  6087. httplib::SSLClient cli("www.google.com");
  6088. ASSERT_EQ("www.google.com", cli.host());
  6089. ASSERT_EQ(443, cli.port());
  6090. }
  6091. #endif
  6092. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6093. TEST(SSLClientTest, UpdateCAStore) {
  6094. httplib::SSLClient httplib_client("www.google.com");
  6095. auto ca_store_1 = X509_STORE_new();
  6096. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6097. nullptr);
  6098. httplib_client.set_ca_cert_store(ca_store_1);
  6099. auto ca_store_2 = X509_STORE_new();
  6100. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6101. nullptr);
  6102. httplib_client.set_ca_cert_store(ca_store_2);
  6103. }
  6104. TEST(SSLClientTest, ServerNameIndication_Online) {
  6105. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6106. auto host = "httpbin.org";
  6107. auto path = std::string{"/get"};
  6108. #else
  6109. auto host = "nghttp2.org";
  6110. auto path = std::string{"/httpbin/get"};
  6111. #endif
  6112. SSLClient cli(host, 443);
  6113. auto res = cli.Get(path);
  6114. ASSERT_TRUE(res);
  6115. ASSERT_EQ(StatusCode::OK_200, res->status);
  6116. }
  6117. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6118. Client cli("https://google.com");
  6119. auto res = cli.Get("/");
  6120. ASSERT_TRUE(res);
  6121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6122. }
  6123. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6124. SSLClient cli("google.com");
  6125. cli.enable_server_certificate_verification(true);
  6126. cli.set_ca_cert_path("hello");
  6127. auto res = cli.Get("/");
  6128. ASSERT_TRUE(!res);
  6129. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6130. }
  6131. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6132. SSLClient cli("google.com");
  6133. cli.set_ca_cert_path(CA_CERT_FILE);
  6134. auto res = cli.Get("/");
  6135. ASSERT_TRUE(res);
  6136. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6137. }
  6138. TEST(SSLClientTest, ServerCertificateVerification4) {
  6139. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6140. ASSERT_TRUE(svr.is_valid());
  6141. svr.Get("/test", [&](const Request &, Response &res) {
  6142. res.set_content("test", "text/plain");
  6143. svr.stop();
  6144. ASSERT_TRUE(true);
  6145. });
  6146. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6147. auto se = detail::scope_exit([&] {
  6148. t.join();
  6149. ASSERT_FALSE(svr.is_running());
  6150. });
  6151. svr.wait_until_ready();
  6152. SSLClient cli("127.0.0.1", PORT);
  6153. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6154. cli.enable_server_certificate_verification(true);
  6155. cli.set_connection_timeout(30);
  6156. auto res = cli.Get("/test");
  6157. ASSERT_TRUE(res);
  6158. ASSERT_EQ(StatusCode::OK_200, res->status);
  6159. }
  6160. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6161. std::string cert;
  6162. read_file(CA_CERT_FILE, cert);
  6163. SSLClient cli("google.com");
  6164. cli.load_ca_cert_store(cert.data(), cert.size());
  6165. const auto res = cli.Get("/");
  6166. ASSERT_TRUE(res);
  6167. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6168. }
  6169. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6170. // clang-format off
  6171. static constexpr char cert[] =
  6172. "GlobalSign Root CA\n"
  6173. "==================\n"
  6174. "-----BEGIN CERTIFICATE-----\n"
  6175. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6176. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6177. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6178. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6179. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6180. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6181. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6182. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6183. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6184. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6185. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6186. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6187. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6188. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6189. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6190. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6191. "-----END CERTIFICATE-----\n";
  6192. // clang-format on
  6193. SSLClient cli("google.com");
  6194. cli.load_ca_cert_store(cert, sizeof(cert));
  6195. const auto res = cli.Get("/");
  6196. ASSERT_TRUE(res);
  6197. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6198. }
  6199. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6200. SSLClient cli("www.youtube.com");
  6201. cli.set_ca_cert_path(CA_CERT_FILE);
  6202. cli.enable_server_certificate_verification(true);
  6203. cli.set_follow_location(true);
  6204. auto res = cli.Get("/");
  6205. ASSERT_TRUE(res);
  6206. ASSERT_EQ(StatusCode::OK_200, res->status);
  6207. }
  6208. TEST(SSLClientTest, Issue2004_Online) {
  6209. Client client("https://google.com");
  6210. client.set_follow_location(true);
  6211. auto res = client.Get("/");
  6212. ASSERT_TRUE(res);
  6213. ASSERT_EQ(StatusCode::OK_200, res->status);
  6214. auto body = res->body;
  6215. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6216. }
  6217. #if 0
  6218. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6219. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6220. ASSERT_TRUE(cli != nullptr);
  6221. cli->set_address_family(AF_INET6);
  6222. cli->set_interface("en0");
  6223. auto res = cli->Get("/get");
  6224. ASSERT_TRUE(res);
  6225. ASSERT_EQ(StatusCode::OK_200, res->status);
  6226. }
  6227. #endif
  6228. void ClientCertPresent(
  6229. const std::string &client_cert_file,
  6230. const std::string &client_private_key_file,
  6231. const std::string &client_encrypted_private_key_pass = std::string()) {
  6232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6233. CLIENT_CA_CERT_DIR);
  6234. ASSERT_TRUE(svr.is_valid());
  6235. svr.Get("/test", [&](const Request &req, Response &res) {
  6236. res.set_content("test", "text/plain");
  6237. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6238. ASSERT_TRUE(peer_cert != nullptr);
  6239. auto subject_name = X509_get_subject_name(peer_cert);
  6240. ASSERT_TRUE(subject_name != nullptr);
  6241. std::string common_name;
  6242. {
  6243. char name[BUFSIZ];
  6244. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6245. name, sizeof(name));
  6246. common_name.assign(name, static_cast<size_t>(name_len));
  6247. }
  6248. EXPECT_EQ("Common Name", common_name);
  6249. X509_free(peer_cert);
  6250. });
  6251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6252. auto se = detail::scope_exit([&] {
  6253. svr.stop();
  6254. t.join();
  6255. ASSERT_FALSE(svr.is_running());
  6256. });
  6257. svr.wait_until_ready();
  6258. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6259. client_encrypted_private_key_pass);
  6260. cli.enable_server_certificate_verification(false);
  6261. cli.set_connection_timeout(30);
  6262. auto res = cli.Get("/test");
  6263. ASSERT_TRUE(res);
  6264. ASSERT_EQ(StatusCode::OK_200, res->status);
  6265. }
  6266. TEST(SSLClientServerTest, ClientCertPresent) {
  6267. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6268. }
  6269. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6270. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6271. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6272. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6273. }
  6274. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6275. void MemoryClientCertPresent(
  6276. const std::string &client_cert_file,
  6277. const std::string &client_private_key_file,
  6278. const std::string &client_encrypted_private_key_pass = std::string()) {
  6279. auto f = fopen(SERVER_CERT_FILE, "r+");
  6280. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6281. fclose(f);
  6282. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6283. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6284. fclose(f);
  6285. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6286. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6287. auto client_ca_cert_store = X509_STORE_new();
  6288. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6289. X509_free(client_cert);
  6290. fclose(f);
  6291. f = fopen(client_cert_file.c_str(), "r+");
  6292. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6293. fclose(f);
  6294. f = fopen(client_private_key_file.c_str(), "r+");
  6295. auto client_private_key = PEM_read_PrivateKey(
  6296. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6297. fclose(f);
  6298. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6299. ASSERT_TRUE(svr.is_valid());
  6300. svr.Get("/test", [&](const Request &req, Response &res) {
  6301. res.set_content("test", "text/plain");
  6302. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6303. ASSERT_TRUE(peer_cert != nullptr);
  6304. auto subject_name = X509_get_subject_name(peer_cert);
  6305. ASSERT_TRUE(subject_name != nullptr);
  6306. std::string common_name;
  6307. {
  6308. char name[BUFSIZ];
  6309. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6310. name, sizeof(name));
  6311. common_name.assign(name, static_cast<size_t>(name_len));
  6312. }
  6313. EXPECT_EQ("Common Name", common_name);
  6314. X509_free(peer_cert);
  6315. });
  6316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. t.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6324. client_encrypted_private_key_pass);
  6325. cli.enable_server_certificate_verification(false);
  6326. cli.set_connection_timeout(30);
  6327. auto res = cli.Get("/test");
  6328. ASSERT_TRUE(res);
  6329. ASSERT_EQ(StatusCode::OK_200, res->status);
  6330. X509_free(server_cert);
  6331. EVP_PKEY_free(server_private_key);
  6332. X509_free(client_cert);
  6333. EVP_PKEY_free(client_private_key);
  6334. }
  6335. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6336. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6337. }
  6338. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6339. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6340. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6341. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6342. }
  6343. #endif
  6344. TEST(SSLClientServerTest, ClientCertMissing) {
  6345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6346. CLIENT_CA_CERT_DIR);
  6347. ASSERT_TRUE(svr.is_valid());
  6348. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6350. auto se = detail::scope_exit([&] {
  6351. svr.stop();
  6352. t.join();
  6353. ASSERT_FALSE(svr.is_running());
  6354. });
  6355. svr.wait_until_ready();
  6356. SSLClient cli(HOST, PORT);
  6357. auto res = cli.Get("/test");
  6358. cli.set_connection_timeout(30);
  6359. ASSERT_TRUE(!res);
  6360. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6361. }
  6362. TEST(SSLClientServerTest, TrustDirOptional) {
  6363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6364. ASSERT_TRUE(svr.is_valid());
  6365. svr.Get("/test", [&](const Request &, Response &res) {
  6366. res.set_content("test", "text/plain");
  6367. });
  6368. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6369. auto se = detail::scope_exit([&] {
  6370. svr.stop();
  6371. t.join();
  6372. ASSERT_FALSE(svr.is_running());
  6373. });
  6374. svr.wait_until_ready();
  6375. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6376. cli.enable_server_certificate_verification(false);
  6377. cli.set_connection_timeout(30);
  6378. auto res = cli.Get("/test");
  6379. ASSERT_TRUE(res);
  6380. ASSERT_EQ(StatusCode::OK_200, res->status);
  6381. }
  6382. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6383. class NoListenSSLServer : public SSLServer {
  6384. public:
  6385. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6386. const char *client_ca_cert_file_path,
  6387. const char *client_ca_cert_dir_path = nullptr)
  6388. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6389. client_ca_cert_dir_path),
  6390. stop_(false) {}
  6391. std::atomic_bool stop_;
  6392. private:
  6393. bool process_and_close_socket(socket_t /*sock*/) override {
  6394. // Don't create SSL context
  6395. while (!stop_.load()) {
  6396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6397. }
  6398. return true;
  6399. }
  6400. };
  6401. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6402. CLIENT_CA_CERT_FILE);
  6403. ASSERT_TRUE(svr.is_valid());
  6404. svr.Get("/test", [&](const Request &, Response &res) {
  6405. res.set_content("test", "text/plain");
  6406. });
  6407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop_ = true;
  6410. svr.stop();
  6411. t.join();
  6412. ASSERT_FALSE(svr.is_running());
  6413. });
  6414. svr.wait_until_ready();
  6415. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6416. cli.enable_server_certificate_verification(false);
  6417. cli.set_connection_timeout(1);
  6418. auto res = cli.Get("/test");
  6419. ASSERT_TRUE(!res);
  6420. EXPECT_EQ(Error::SSLConnection, res.error());
  6421. }
  6422. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6423. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6424. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6425. SSL_CTX_set_options(&ssl_ctx,
  6426. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6427. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6428. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6429. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6430. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6431. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6432. "ECDHE-DSS-AES128-SHA256:"
  6433. "ECDHE-RSA-AES256-SHA256:"
  6434. "ECDHE-DSS-AES256-SHA256:";
  6435. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6436. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6437. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6438. SSL_FILETYPE_PEM) != 1) {
  6439. return false;
  6440. }
  6441. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6442. CLIENT_CA_CERT_DIR);
  6443. SSL_CTX_set_verify(
  6444. &ssl_ctx,
  6445. SSL_VERIFY_PEER |
  6446. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6447. nullptr);
  6448. return true;
  6449. };
  6450. SSLServer svr(setup_ssl_ctx_callback);
  6451. ASSERT_TRUE(svr.is_valid());
  6452. svr.Get("/test", [&](const Request &req, Response &res) {
  6453. res.set_content("test", "text/plain");
  6454. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6455. ASSERT_TRUE(peer_cert != nullptr);
  6456. auto subject_name = X509_get_subject_name(peer_cert);
  6457. ASSERT_TRUE(subject_name != nullptr);
  6458. std::string common_name;
  6459. {
  6460. char name[BUFSIZ];
  6461. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6462. name, sizeof(name));
  6463. common_name.assign(name, static_cast<size_t>(name_len));
  6464. }
  6465. EXPECT_EQ("Common Name", common_name);
  6466. X509_free(peer_cert);
  6467. });
  6468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6469. auto se = detail::scope_exit([&] {
  6470. svr.stop();
  6471. t.join();
  6472. ASSERT_FALSE(svr.is_running());
  6473. });
  6474. svr.wait_until_ready();
  6475. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6476. cli.enable_server_certificate_verification(false);
  6477. cli.set_connection_timeout(30);
  6478. auto res = cli.Get("/test");
  6479. ASSERT_TRUE(res);
  6480. ASSERT_EQ(StatusCode::OK_200, res->status);
  6481. }
  6482. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6483. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6484. // prepare large data
  6485. std::random_device seed_gen;
  6486. std::mt19937 random(seed_gen());
  6487. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6488. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6489. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6490. // server
  6491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6492. ASSERT_TRUE(svr.is_valid());
  6493. svr.Post("/binary", [&](const Request &req, Response &res) {
  6494. EXPECT_EQ(large_size_byte, req.body.size());
  6495. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6496. res.set_content(req.body, "application/octet-stream");
  6497. });
  6498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6499. auto se = detail::scope_exit([&] {
  6500. svr.stop();
  6501. listen_thread.join();
  6502. ASSERT_FALSE(svr.is_running());
  6503. });
  6504. svr.wait_until_ready();
  6505. // client POST
  6506. SSLClient cli("localhost", PORT);
  6507. cli.enable_server_certificate_verification(false);
  6508. cli.set_read_timeout(std::chrono::seconds(100));
  6509. cli.set_write_timeout(std::chrono::seconds(100));
  6510. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6511. large_size_byte, "application/octet-stream");
  6512. // compare
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ(large_size_byte, res->body.size());
  6515. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6516. }
  6517. #endif
  6518. #ifdef _WIN32
  6519. TEST(CleanupTest, WSACleanup) {
  6520. int ret = WSACleanup();
  6521. ASSERT_EQ(0, ret);
  6522. }
  6523. #endif
  6524. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6525. TEST(NoSSLSupport, SimpleInterface) {
  6526. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6527. }
  6528. #endif
  6529. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6530. TEST(InvalidScheme, SimpleInterface) {
  6531. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6532. }
  6533. #endif
  6534. TEST(NoScheme, SimpleInterface) {
  6535. Client cli("yahoo.com:80");
  6536. ASSERT_TRUE(cli.is_valid());
  6537. }
  6538. TEST(SendAPI, SimpleInterface_Online) {
  6539. Client cli("http://yahoo.com");
  6540. Request req;
  6541. req.method = "GET";
  6542. req.path = "/";
  6543. auto res = cli.send(req);
  6544. ASSERT_TRUE(res);
  6545. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6546. }
  6547. TEST(SendAPI, WithParamsInRequest) {
  6548. Server svr;
  6549. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6550. EXPECT_TRUE(req.has_param("test"));
  6551. EXPECT_EQ("test_value", req.get_param_value("test"));
  6552. });
  6553. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6554. auto se = detail::scope_exit([&] {
  6555. svr.stop();
  6556. t.join();
  6557. ASSERT_FALSE(svr.is_running());
  6558. });
  6559. svr.wait_until_ready();
  6560. Client cli(HOST, PORT);
  6561. {
  6562. Request req;
  6563. req.method = "GET";
  6564. req.path = "/";
  6565. req.params.emplace("test", "test_value");
  6566. auto res = cli.send(req);
  6567. ASSERT_TRUE(res);
  6568. }
  6569. {
  6570. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6571. ASSERT_TRUE(res);
  6572. }
  6573. }
  6574. TEST(ClientImplMethods, GetSocketTest) {
  6575. httplib::Server svr;
  6576. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6577. res.status = StatusCode::OK_200;
  6578. });
  6579. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6580. auto se = detail::scope_exit([&] {
  6581. svr.stop();
  6582. thread.join();
  6583. ASSERT_FALSE(svr.is_running());
  6584. });
  6585. svr.wait_until_ready();
  6586. {
  6587. httplib::Client cli("http://127.0.0.1:3333");
  6588. cli.set_keep_alive(true);
  6589. // Use the behavior of cpp-httplib of opening the connection
  6590. // only when the first request happens. If that changes,
  6591. // this test would be obsolete.
  6592. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6593. // This also implicitly tests the server. But other tests would fail much
  6594. // earlier than this one to be considered.
  6595. auto res = cli.Get("/");
  6596. ASSERT_TRUE(res);
  6597. EXPECT_EQ(StatusCode::OK_200, res->status);
  6598. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6599. }
  6600. }
  6601. // Disabled due to out-of-memory problem on GitHub Actions
  6602. #ifdef _WIN64
  6603. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6604. // allocate content size larger than 2GB in memory
  6605. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6606. char *content = (char *)malloc(content_size);
  6607. ASSERT_TRUE(content);
  6608. Server svr;
  6609. svr.Get("/foo",
  6610. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6611. res.set_content(content, content_size, "application/octet-stream");
  6612. });
  6613. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6614. auto se = detail::scope_exit([&] {
  6615. svr.stop();
  6616. listen_thread.join();
  6617. if (content) free(content);
  6618. ASSERT_FALSE(svr.is_running());
  6619. });
  6620. svr.wait_until_ready();
  6621. Client cli(HOST, PORT);
  6622. auto res = cli.Get("/foo");
  6623. ASSERT_TRUE(res);
  6624. EXPECT_EQ(StatusCode::OK_200, res->status);
  6625. EXPECT_EQ(content_size, res->body.length());
  6626. }
  6627. #endif
  6628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6629. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6630. Client cli("http://yahoo.com");
  6631. auto res = cli.Get("/");
  6632. ASSERT_TRUE(res);
  6633. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6634. cli.set_follow_location(true);
  6635. res = cli.Get("/");
  6636. ASSERT_TRUE(res);
  6637. EXPECT_EQ(StatusCode::OK_200, res->status);
  6638. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6639. }
  6640. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6641. Client cli("https://yahoo.com");
  6642. auto res = cli.Get("/");
  6643. ASSERT_TRUE(res);
  6644. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6645. cli.set_follow_location(true);
  6646. res = cli.Get("/");
  6647. ASSERT_TRUE(res);
  6648. EXPECT_EQ(StatusCode::OK_200, res->status);
  6649. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6650. }
  6651. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6652. Client cli("https://yahoo.com");
  6653. auto res = cli.Get("/");
  6654. ASSERT_TRUE(res);
  6655. ASSERT_FALSE(!res);
  6656. ASSERT_TRUE(res);
  6657. ASSERT_FALSE(res == nullptr);
  6658. ASSERT_TRUE(res != nullptr);
  6659. EXPECT_EQ(Error::Success, res.error());
  6660. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6661. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6662. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6663. cli.set_follow_location(true);
  6664. res = cli.Get("/");
  6665. ASSERT_TRUE(res);
  6666. EXPECT_EQ(Error::Success, res.error());
  6667. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6668. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6671. }
  6672. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6673. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6674. Client cli("https://cdnjs.cloudflare.com");
  6675. auto res =
  6676. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6677. ASSERT_TRUE(res);
  6678. EXPECT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ(287630U, res->body.size());
  6680. EXPECT_EQ("application/javascript; charset=utf-8",
  6681. res->get_header_value("Content-Type"));
  6682. }
  6683. #endif
  6684. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6685. #undef REDIR_HOST // Silence compiler warning
  6686. #define REDIR_HOST "https://httpbingo.org"
  6687. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6688. Client cli(REDIR_HOST);
  6689. cli.set_follow_location(true);
  6690. auto res =
  6691. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6692. ASSERT_TRUE(res);
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6696. Client cli(REDIR_HOST);
  6697. cli.set_follow_location(true);
  6698. Params params;
  6699. params.emplace("url", "http://example.com");
  6700. params.emplace("status_code", "302");
  6701. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6702. ASSERT_TRUE(res);
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. }
  6705. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6706. Client cli(REDIR_HOST);
  6707. cli.set_follow_location(true);
  6708. Params params;
  6709. params.emplace("url", "http://example.com");
  6710. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6711. ASSERT_TRUE(res);
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. }
  6714. TEST(HttpToHttpsRedirectTest, CertFile) {
  6715. Server svr;
  6716. ASSERT_TRUE(svr.is_valid());
  6717. svr.Get("/index", [&](const Request &, Response &res) {
  6718. res.set_redirect("https://127.0.0.1:1235/index");
  6719. svr.stop();
  6720. });
  6721. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6722. ASSERT_TRUE(ssl_svr.is_valid());
  6723. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6724. res.set_content("test", "text/plain");
  6725. ssl_svr.stop();
  6726. });
  6727. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6728. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6729. auto se = detail::scope_exit([&] {
  6730. t2.join();
  6731. t.join();
  6732. ASSERT_FALSE(svr.is_running());
  6733. });
  6734. svr.wait_until_ready();
  6735. ssl_svr.wait_until_ready();
  6736. Client cli("127.0.0.1", PORT);
  6737. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6738. cli.enable_server_certificate_verification(true);
  6739. cli.set_follow_location(true);
  6740. cli.set_connection_timeout(30);
  6741. auto res = cli.Get("/index");
  6742. ASSERT_TRUE(res);
  6743. ASSERT_EQ(StatusCode::OK_200, res->status);
  6744. }
  6745. TEST(MultipartFormDataTest, LargeData) {
  6746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6747. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6748. const ContentReader &content_reader) {
  6749. if (req.is_multipart_form_data()) {
  6750. MultipartFormDataItems files;
  6751. content_reader(
  6752. [&](const MultipartFormData &file) {
  6753. files.push_back(file);
  6754. return true;
  6755. },
  6756. [&](const char *data, size_t data_length) {
  6757. files.back().content.append(data, data_length);
  6758. return true;
  6759. });
  6760. EXPECT_TRUE(std::string(files[0].name) == "document");
  6761. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6762. EXPECT_TRUE(files[0].filename == "2MB_data");
  6763. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6764. EXPECT_TRUE(files[1].name == "hello");
  6765. EXPECT_TRUE(files[1].content == "world");
  6766. EXPECT_TRUE(files[1].filename == "");
  6767. EXPECT_TRUE(files[1].content_type == "");
  6768. } else {
  6769. std::string body;
  6770. content_reader([&](const char *data, size_t data_length) {
  6771. body.append(data, data_length);
  6772. return true;
  6773. });
  6774. }
  6775. });
  6776. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6777. auto se = detail::scope_exit([&] {
  6778. svr.stop();
  6779. t.join();
  6780. ASSERT_FALSE(svr.is_running());
  6781. });
  6782. svr.wait_until_ready();
  6783. {
  6784. std::string data(1024 * 1024 * 2, '.');
  6785. std::stringstream buffer;
  6786. buffer << data;
  6787. Client cli("https://localhost:8080");
  6788. cli.enable_server_certificate_verification(false);
  6789. MultipartFormDataItemsForClientInput items{
  6790. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6791. {"hello", "world", "", ""},
  6792. };
  6793. auto res = cli.Post("/post", items);
  6794. ASSERT_TRUE(res);
  6795. ASSERT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. }
  6798. TEST(MultipartFormDataTest, DataProviderItems) {
  6799. std::random_device seed_gen;
  6800. std::mt19937 random(seed_gen());
  6801. std::string rand1;
  6802. rand1.resize(1000);
  6803. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6804. std::string rand2;
  6805. rand2.resize(3000);
  6806. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6808. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6809. const ContentReader &content_reader) {
  6810. ASSERT_FALSE(req.is_multipart_form_data());
  6811. std::string body;
  6812. content_reader([&](const char *data, size_t data_length) {
  6813. body.append(data, data_length);
  6814. return true;
  6815. });
  6816. EXPECT_EQ(body, "");
  6817. });
  6818. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6819. const ContentReader &content_reader) {
  6820. ASSERT_TRUE(req.is_multipart_form_data());
  6821. MultipartFormDataItems files;
  6822. content_reader(
  6823. [&](const MultipartFormData &file) {
  6824. files.push_back(file);
  6825. return true;
  6826. },
  6827. [&](const char *data, size_t data_length) {
  6828. files.back().content.append(data, data_length);
  6829. return true;
  6830. });
  6831. ASSERT_TRUE(files.size() == 2);
  6832. EXPECT_EQ(std::string(files[0].name), "name1");
  6833. EXPECT_EQ(files[0].content, "Testing123");
  6834. EXPECT_EQ(files[0].filename, "filename1");
  6835. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6836. EXPECT_EQ(files[1].name, "name2");
  6837. EXPECT_EQ(files[1].content, "Testing456");
  6838. EXPECT_EQ(files[1].filename, "");
  6839. EXPECT_EQ(files[1].content_type, "");
  6840. });
  6841. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6842. const ContentReader &content_reader) {
  6843. ASSERT_TRUE(req.is_multipart_form_data());
  6844. MultipartFormDataItems files;
  6845. content_reader(
  6846. [&](const MultipartFormData &file) {
  6847. files.push_back(file);
  6848. return true;
  6849. },
  6850. [&](const char *data, size_t data_length) {
  6851. files.back().content.append(data, data_length);
  6852. return true;
  6853. });
  6854. ASSERT_TRUE(files.size() == 2);
  6855. EXPECT_EQ(files[0].name, "name3");
  6856. EXPECT_EQ(files[0].content, rand1);
  6857. EXPECT_EQ(files[0].filename, "filename3");
  6858. EXPECT_EQ(files[0].content_type, "");
  6859. EXPECT_EQ(files[1].name, "name4");
  6860. EXPECT_EQ(files[1].content, rand2);
  6861. EXPECT_EQ(files[1].filename, "filename4");
  6862. EXPECT_EQ(files[1].content_type, "");
  6863. });
  6864. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6865. const ContentReader &content_reader) {
  6866. ASSERT_TRUE(req.is_multipart_form_data());
  6867. MultipartFormDataItems files;
  6868. content_reader(
  6869. [&](const MultipartFormData &file) {
  6870. files.push_back(file);
  6871. return true;
  6872. },
  6873. [&](const char *data, size_t data_length) {
  6874. files.back().content.append(data, data_length);
  6875. return true;
  6876. });
  6877. ASSERT_TRUE(files.size() == 4);
  6878. EXPECT_EQ(std::string(files[0].name), "name1");
  6879. EXPECT_EQ(files[0].content, "Testing123");
  6880. EXPECT_EQ(files[0].filename, "filename1");
  6881. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6882. EXPECT_EQ(files[1].name, "name2");
  6883. EXPECT_EQ(files[1].content, "Testing456");
  6884. EXPECT_EQ(files[1].filename, "");
  6885. EXPECT_EQ(files[1].content_type, "");
  6886. EXPECT_EQ(files[2].name, "name3");
  6887. EXPECT_EQ(files[2].content, rand1);
  6888. EXPECT_EQ(files[2].filename, "filename3");
  6889. EXPECT_EQ(files[2].content_type, "");
  6890. EXPECT_EQ(files[3].name, "name4");
  6891. EXPECT_EQ(files[3].content, rand2);
  6892. EXPECT_EQ(files[3].filename, "filename4");
  6893. EXPECT_EQ(files[3].content_type, "");
  6894. });
  6895. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6896. auto se = detail::scope_exit([&] {
  6897. svr.stop();
  6898. t.join();
  6899. ASSERT_FALSE(svr.is_running());
  6900. });
  6901. svr.wait_until_ready();
  6902. {
  6903. Client cli("https://localhost:8080");
  6904. cli.enable_server_certificate_verification(false);
  6905. MultipartFormDataItemsForClientInput items{
  6906. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6907. {"name2", "Testing456", "", ""}, // not a file
  6908. };
  6909. {
  6910. auto res = cli.Post("/post-none", {}, {}, {});
  6911. ASSERT_TRUE(res);
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. }
  6914. MultipartFormDataProviderItems providers;
  6915. {
  6916. auto res =
  6917. cli.Post("/post-items", {}, items, providers); // empty providers
  6918. ASSERT_TRUE(res);
  6919. ASSERT_EQ(StatusCode::OK_200, res->status);
  6920. }
  6921. providers.push_back({"name3",
  6922. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6923. // test the offset is given correctly at each step
  6924. if (!offset)
  6925. sink.os.write(rand1.data(), 30);
  6926. else if (offset == 30)
  6927. sink.os.write(rand1.data() + 30, 300);
  6928. else if (offset == 330)
  6929. sink.os.write(rand1.data() + 330, 670);
  6930. else if (offset == rand1.size())
  6931. sink.done();
  6932. return true;
  6933. },
  6934. "filename3",
  6935. {}});
  6936. providers.push_back({"name4",
  6937. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6938. // test the offset is given correctly at each step
  6939. if (!offset)
  6940. sink.os.write(rand2.data(), 2000);
  6941. else if (offset == 2000)
  6942. sink.os.write(rand2.data() + 2000, 1);
  6943. else if (offset == 2001)
  6944. sink.os.write(rand2.data() + 2001, 999);
  6945. else if (offset == rand2.size())
  6946. sink.done();
  6947. return true;
  6948. },
  6949. "filename4",
  6950. {}});
  6951. {
  6952. auto res = cli.Post("/post-providers", {}, {}, providers);
  6953. ASSERT_TRUE(res);
  6954. ASSERT_EQ(StatusCode::OK_200, res->status);
  6955. }
  6956. {
  6957. auto res = cli.Post("/post-both", {}, items, providers);
  6958. ASSERT_TRUE(res);
  6959. ASSERT_EQ(StatusCode::OK_200, res->status);
  6960. }
  6961. }
  6962. }
  6963. TEST(MultipartFormDataTest, BadHeader) {
  6964. Server svr;
  6965. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6966. res.set_content("ok", "text/plain");
  6967. });
  6968. thread t = thread([&] { svr.listen(HOST, PORT); });
  6969. auto se = detail::scope_exit([&] {
  6970. svr.stop();
  6971. t.join();
  6972. ASSERT_FALSE(svr.is_running());
  6973. });
  6974. svr.wait_until_ready();
  6975. const std::string body =
  6976. "This is the preamble. It is to be ignored, though it\r\n"
  6977. "is a handy place for composition agents to include an\r\n"
  6978. "explanatory note to non-MIME conformant readers.\r\n"
  6979. "\r\n"
  6980. "\r\n"
  6981. "--simple boundary\r\n"
  6982. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6983. ": BAD...\r\n"
  6984. "\r\n"
  6985. "value1\r\n"
  6986. "--simple boundary\r\n"
  6987. "Content-Disposition: form-data; name=\"field2\"; "
  6988. "filename=\"example.txt\"\r\n"
  6989. "\r\n"
  6990. "value2\r\n"
  6991. "--simple boundary--\r\n"
  6992. "This is the epilogue. It is also to be ignored.\r\n";
  6993. std::string content_type =
  6994. R"(multipart/form-data; boundary="simple boundary")";
  6995. Client cli(HOST, PORT);
  6996. auto res = cli.Post("/post", body, content_type.c_str());
  6997. ASSERT_TRUE(res);
  6998. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6999. }
  7000. TEST(MultipartFormDataTest, WithPreamble) {
  7001. Server svr;
  7002. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7003. res.set_content("ok", "text/plain");
  7004. });
  7005. thread t = thread([&] { svr.listen(HOST, PORT); });
  7006. auto se = detail::scope_exit([&] {
  7007. svr.stop();
  7008. t.join();
  7009. ASSERT_FALSE(svr.is_running());
  7010. });
  7011. svr.wait_until_ready();
  7012. const std::string body =
  7013. "This is the preamble. It is to be ignored, though it\r\n"
  7014. "is a handy place for composition agents to include an\r\n"
  7015. "explanatory note to non-MIME conformant readers.\r\n"
  7016. "\r\n"
  7017. "\r\n"
  7018. "--simple boundary\r\n"
  7019. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7020. "\r\n"
  7021. "value1\r\n"
  7022. "--simple boundary\r\n"
  7023. "Content-Disposition: form-data; name=\"field2\"; "
  7024. "filename=\"example.txt\"\r\n"
  7025. "\r\n"
  7026. "value2\r\n"
  7027. "--simple boundary--\r\n"
  7028. "This is the epilogue. It is also to be ignored.\r\n";
  7029. std::string content_type =
  7030. R"(multipart/form-data; boundary="simple boundary")";
  7031. Client cli(HOST, PORT);
  7032. auto res = cli.Post("/post", body, content_type.c_str());
  7033. ASSERT_TRUE(res);
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. }
  7036. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7038. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7039. const ContentReader &content_reader) {
  7040. if (req.is_multipart_form_data()) {
  7041. MultipartFormDataItems files;
  7042. content_reader(
  7043. [&](const MultipartFormData &file) {
  7044. files.push_back(file);
  7045. return true;
  7046. },
  7047. [&](const char *data, size_t data_length) {
  7048. files.back().content.append(data, data_length);
  7049. return true;
  7050. });
  7051. EXPECT_TRUE(std::string(files[0].name) == "document");
  7052. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7053. EXPECT_TRUE(files[0].filename == "2MB_data");
  7054. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7055. EXPECT_TRUE(files[1].name == "hello");
  7056. EXPECT_TRUE(files[1].content == "world");
  7057. EXPECT_TRUE(files[1].filename == "");
  7058. EXPECT_TRUE(files[1].content_type == "");
  7059. } else {
  7060. std::string body;
  7061. content_reader([&](const char *data, size_t data_length) {
  7062. body.append(data, data_length);
  7063. return true;
  7064. });
  7065. }
  7066. });
  7067. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7068. auto se = detail::scope_exit([&] {
  7069. svr.stop();
  7070. t.join();
  7071. ASSERT_FALSE(svr.is_running());
  7072. });
  7073. svr.wait_until_ready();
  7074. {
  7075. std::string data(1024 * 1024 * 2, '.');
  7076. std::stringstream buffer;
  7077. buffer << data;
  7078. Client cli("https://localhost:8080");
  7079. cli.enable_server_certificate_verification(false);
  7080. MultipartFormDataItemsForClientInput items{
  7081. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7082. {"hello", "world", "", ""},
  7083. };
  7084. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7085. ASSERT_TRUE(res);
  7086. ASSERT_EQ(StatusCode::OK_200, res->status);
  7087. }
  7088. }
  7089. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7090. std::string data(1024 * 1024 * 2, '&');
  7091. std::stringstream buffer;
  7092. buffer << data;
  7093. Client cli("https://localhost:8080");
  7094. MultipartFormDataItemsForClientInput items{
  7095. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7096. {"hello", "world", "", ""},
  7097. };
  7098. for (const char &c : " \t\r\n") {
  7099. auto res =
  7100. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7101. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7102. ASSERT_FALSE(res);
  7103. }
  7104. }
  7105. TEST(MultipartFormDataTest, PutFormData) {
  7106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7107. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7108. const ContentReader &content_reader) {
  7109. if (req.is_multipart_form_data()) {
  7110. MultipartFormDataItems files;
  7111. content_reader(
  7112. [&](const MultipartFormData &file) {
  7113. files.push_back(file);
  7114. return true;
  7115. },
  7116. [&](const char *data, size_t data_length) {
  7117. files.back().content.append(data, data_length);
  7118. return true;
  7119. });
  7120. EXPECT_TRUE(std::string(files[0].name) == "document");
  7121. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7122. EXPECT_TRUE(files[0].filename == "2MB_data");
  7123. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7124. EXPECT_TRUE(files[1].name == "hello");
  7125. EXPECT_TRUE(files[1].content == "world");
  7126. EXPECT_TRUE(files[1].filename == "");
  7127. EXPECT_TRUE(files[1].content_type == "");
  7128. } else {
  7129. std::string body;
  7130. content_reader([&](const char *data, size_t data_length) {
  7131. body.append(data, data_length);
  7132. return true;
  7133. });
  7134. }
  7135. });
  7136. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7137. auto se = detail::scope_exit([&] {
  7138. svr.stop();
  7139. t.join();
  7140. ASSERT_FALSE(svr.is_running());
  7141. });
  7142. svr.wait_until_ready();
  7143. {
  7144. std::string data(1024 * 1024 * 2, '&');
  7145. std::stringstream buffer;
  7146. buffer << data;
  7147. Client cli("https://localhost:8080");
  7148. cli.enable_server_certificate_verification(false);
  7149. MultipartFormDataItemsForClientInput items{
  7150. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7151. {"hello", "world", "", ""},
  7152. };
  7153. auto res = cli.Put("/put", items);
  7154. ASSERT_TRUE(res);
  7155. ASSERT_EQ(StatusCode::OK_200, res->status);
  7156. }
  7157. }
  7158. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7159. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7160. svr.Put("/put_customboundary",
  7161. [&](const Request &req, const Response & /*res*/,
  7162. const ContentReader &content_reader) {
  7163. if (req.is_multipart_form_data()) {
  7164. MultipartFormDataItems files;
  7165. content_reader(
  7166. [&](const MultipartFormData &file) {
  7167. files.push_back(file);
  7168. return true;
  7169. },
  7170. [&](const char *data, size_t data_length) {
  7171. files.back().content.append(data, data_length);
  7172. return true;
  7173. });
  7174. EXPECT_TRUE(std::string(files[0].name) == "document");
  7175. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7176. EXPECT_TRUE(files[0].filename == "2MB_data");
  7177. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7178. EXPECT_TRUE(files[1].name == "hello");
  7179. EXPECT_TRUE(files[1].content == "world");
  7180. EXPECT_TRUE(files[1].filename == "");
  7181. EXPECT_TRUE(files[1].content_type == "");
  7182. } else {
  7183. std::string body;
  7184. content_reader([&](const char *data, size_t data_length) {
  7185. body.append(data, data_length);
  7186. return true;
  7187. });
  7188. }
  7189. });
  7190. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7191. auto se = detail::scope_exit([&] {
  7192. svr.stop();
  7193. t.join();
  7194. ASSERT_FALSE(svr.is_running());
  7195. });
  7196. svr.wait_until_ready();
  7197. {
  7198. std::string data(1024 * 1024 * 2, '&');
  7199. std::stringstream buffer;
  7200. buffer << data;
  7201. Client cli("https://localhost:8080");
  7202. cli.enable_server_certificate_verification(false);
  7203. MultipartFormDataItemsForClientInput items{
  7204. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7205. {"hello", "world", "", ""},
  7206. };
  7207. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7208. ASSERT_TRUE(res);
  7209. ASSERT_EQ(StatusCode::OK_200, res->status);
  7210. }
  7211. }
  7212. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7213. std::string data(1024 * 1024 * 2, '&');
  7214. std::stringstream buffer;
  7215. buffer << data;
  7216. Client cli("https://localhost:8080");
  7217. cli.enable_server_certificate_verification(false);
  7218. MultipartFormDataItemsForClientInput items{
  7219. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7220. {"hello", "world", "", ""},
  7221. };
  7222. for (const char &c : " \t\r\n") {
  7223. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7224. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7225. ASSERT_FALSE(res);
  7226. }
  7227. }
  7228. TEST(MultipartFormDataTest, AlternateFilename) {
  7229. auto handled = false;
  7230. Server svr;
  7231. svr.Post("/test", [&](const Request &req, Response &res) {
  7232. ASSERT_EQ(3u, req.files.size());
  7233. auto it = req.files.begin();
  7234. ASSERT_EQ("file1", it->second.name);
  7235. ASSERT_EQ("A.txt", it->second.filename);
  7236. ASSERT_EQ("text/plain", it->second.content_type);
  7237. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7238. ++it;
  7239. ASSERT_EQ("file2", it->second.name);
  7240. ASSERT_EQ("a.html", it->second.filename);
  7241. ASSERT_EQ("text/html", it->second.content_type);
  7242. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7243. it->second.content);
  7244. ++it;
  7245. ASSERT_EQ("text", it->second.name);
  7246. ASSERT_EQ("", it->second.filename);
  7247. ASSERT_EQ("", it->second.content_type);
  7248. ASSERT_EQ("text default", it->second.content);
  7249. res.set_content("ok", "text/plain");
  7250. handled = true;
  7251. });
  7252. thread t = thread([&] { svr.listen(HOST, PORT); });
  7253. auto se = detail::scope_exit([&] {
  7254. svr.stop();
  7255. t.join();
  7256. ASSERT_FALSE(svr.is_running());
  7257. ASSERT_TRUE(handled);
  7258. });
  7259. svr.wait_until_ready();
  7260. auto req = "POST /test HTTP/1.1\r\n"
  7261. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7262. "Content-Length: 399\r\n"
  7263. "\r\n"
  7264. "----------\r\n"
  7265. "Content-Disposition: form-data; name=\"text\"\r\n"
  7266. "\r\n"
  7267. "text default\r\n"
  7268. "----------\r\n"
  7269. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7270. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7271. "Content-Type: text/plain\r\n"
  7272. "\r\n"
  7273. "Content of a.txt.\r\n"
  7274. "\r\n"
  7275. "----------\r\n"
  7276. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7277. "\"a.html\"\r\n"
  7278. "Content-Type: text/html\r\n"
  7279. "\r\n"
  7280. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7281. "\r\n"
  7282. "------------\r\n";
  7283. ASSERT_TRUE(send_request(1, req));
  7284. }
  7285. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7286. auto handled = false;
  7287. Server svr;
  7288. svr.Post("/test", [&](const Request &req, Response &) {
  7289. ASSERT_EQ(2u, req.files.size());
  7290. auto it = req.files.begin();
  7291. ASSERT_EQ("text1", it->second.name);
  7292. ASSERT_EQ("text1", it->second.content);
  7293. ++it;
  7294. ASSERT_EQ("text2", it->second.name);
  7295. ASSERT_EQ("text2", it->second.content);
  7296. handled = true;
  7297. });
  7298. thread t = thread([&] { svr.listen(HOST, PORT); });
  7299. auto se = detail::scope_exit([&] {
  7300. svr.stop();
  7301. t.join();
  7302. ASSERT_FALSE(svr.is_running());
  7303. ASSERT_TRUE(handled);
  7304. });
  7305. svr.wait_until_ready();
  7306. auto req = "POST /test HTTP/1.1\r\n"
  7307. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7308. "Content-Length: 146\r\n"
  7309. "\r\n----------\r\n"
  7310. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7311. "\r\n"
  7312. "text1"
  7313. "\r\n----------\r\n"
  7314. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7315. "\r\n"
  7316. "text2"
  7317. "\r\n------------";
  7318. std::string response;
  7319. ASSERT_TRUE(send_request(1, req, &response));
  7320. ASSERT_EQ("200", response.substr(9, 3));
  7321. }
  7322. TEST(MultipartFormDataTest, ContentLength) {
  7323. auto handled = false;
  7324. Server svr;
  7325. svr.Post("/test", [&](const Request &req, Response &) {
  7326. ASSERT_EQ(2u, req.files.size());
  7327. auto it = req.files.begin();
  7328. ASSERT_EQ("text1", it->second.name);
  7329. ASSERT_EQ("text1", it->second.content);
  7330. ++it;
  7331. ASSERT_EQ("text2", it->second.name);
  7332. ASSERT_EQ("text2", it->second.content);
  7333. handled = true;
  7334. });
  7335. thread t = thread([&] { svr.listen(HOST, PORT); });
  7336. auto se = detail::scope_exit([&] {
  7337. svr.stop();
  7338. t.join();
  7339. ASSERT_FALSE(svr.is_running());
  7340. ASSERT_TRUE(handled);
  7341. });
  7342. svr.wait_until_ready();
  7343. auto req = "POST /test HTTP/1.1\r\n"
  7344. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7345. "Content-Length: 167\r\n"
  7346. "\r\n----------\r\n"
  7347. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7348. "Content-Length: 5\r\n"
  7349. "\r\n"
  7350. "text1"
  7351. "\r\n----------\r\n"
  7352. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7353. "\r\n"
  7354. "text2"
  7355. "\r\n------------\r\n";
  7356. std::string response;
  7357. ASSERT_TRUE(send_request(1, req, &response));
  7358. ASSERT_EQ("200", response.substr(9, 3));
  7359. }
  7360. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7361. auto handled = false;
  7362. Server svr;
  7363. svr.Post("/test", [&](const Request &req, Response &) {
  7364. ASSERT_EQ(2u, req.files.size());
  7365. auto it = req.files.begin();
  7366. ASSERT_EQ("text1", it->second.name);
  7367. ASSERT_EQ("text1", it->second.content);
  7368. ASSERT_EQ(1, it->second.headers.count("Content-Length"));
  7369. auto content_length = it->second.headers.find("CONTENT-length");
  7370. ASSERT_EQ("5", content_length->second);
  7371. ASSERT_EQ(3, it->second.headers.size());
  7372. ++it;
  7373. ASSERT_EQ("text2", it->second.name);
  7374. ASSERT_EQ("text2", it->second.content);
  7375. auto &headers = it->second.headers;
  7376. ASSERT_EQ(3, headers.size());
  7377. auto custom_header = headers.find("x-whatever");
  7378. ASSERT_TRUE(custom_header != headers.end());
  7379. ASSERT_NE("customvalue", custom_header->second);
  7380. ASSERT_EQ("CustomValue", custom_header->second);
  7381. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7382. handled = true;
  7383. });
  7384. thread t = thread([&] { svr.listen(HOST, PORT); });
  7385. auto se = detail::scope_exit([&] {
  7386. svr.stop();
  7387. t.join();
  7388. ASSERT_FALSE(svr.is_running());
  7389. ASSERT_TRUE(handled);
  7390. });
  7391. svr.wait_until_ready();
  7392. auto req = "POST /test HTTP/1.1\r\n"
  7393. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7394. "Content-Length: 232\r\n"
  7395. "\r\n----------\r\n"
  7396. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7397. "Content-Length: 5\r\n"
  7398. "X-Test: 1\r\n"
  7399. "\r\n"
  7400. "text1"
  7401. "\r\n----------\r\n"
  7402. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7403. "Content-Type: text/plain\r\n"
  7404. "X-Whatever: CustomValue\r\n"
  7405. "\r\n"
  7406. "text2"
  7407. "\r\n------------\r\n"
  7408. "That should be disregarded. Not even read";
  7409. std::string response;
  7410. ASSERT_TRUE(send_request(1, req, &response));
  7411. ASSERT_EQ("200", response.substr(9, 3));
  7412. }
  7413. #endif
  7414. TEST(MultipartFormDataTest, LargeHeader) {
  7415. auto handled = false;
  7416. Server svr;
  7417. svr.Post("/test", [&](const Request &req, Response &) {
  7418. ASSERT_EQ(1u, req.files.size());
  7419. auto it = req.files.begin();
  7420. ASSERT_EQ("name1", it->second.name);
  7421. ASSERT_EQ("text1", it->second.content);
  7422. handled = true;
  7423. });
  7424. thread t = thread([&] { svr.listen(HOST, PORT); });
  7425. auto se = detail::scope_exit([&] {
  7426. svr.stop();
  7427. t.join();
  7428. ASSERT_FALSE(svr.is_running());
  7429. ASSERT_TRUE(handled);
  7430. });
  7431. svr.wait_until_ready();
  7432. auto boundary = std::string("cpp-httplib-multipart-data");
  7433. std::string content = "--" + boundary +
  7434. "\r\n"
  7435. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7436. "\r\n"
  7437. "text1\r\n"
  7438. "--" +
  7439. boundary + "--\r\n";
  7440. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7441. "Content-Type: multipart/form-data;boundary=" +
  7442. boundary +
  7443. "\r\n"
  7444. "Content-Length: " +
  7445. std::to_string(content.size()) +
  7446. "\r\n"
  7447. "Dummy-Header: ";
  7448. std::string header_suffix = "\r\n"
  7449. "\r\n";
  7450. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7451. size_t header_dummy_size =
  7452. read_buff_size -
  7453. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7454. auto header_dummy = std::string(header_dummy_size, '@');
  7455. auto req = header_prefix + header_dummy + header_suffix + content;
  7456. std::string response;
  7457. ASSERT_TRUE(send_request(1, req, &response));
  7458. ASSERT_EQ("200", response.substr(9, 3));
  7459. }
  7460. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7461. static constexpr unsigned int number_of_tasks{1000000};
  7462. std::atomic_uint count{0};
  7463. std::unique_ptr<TaskQueue> task_queue{
  7464. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7465. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7466. auto queued = task_queue->enqueue(
  7467. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7468. EXPECT_TRUE(queued);
  7469. }
  7470. EXPECT_NO_THROW(task_queue->shutdown());
  7471. EXPECT_EQ(number_of_tasks, count.load());
  7472. }
  7473. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7474. static constexpr unsigned int number_of_tasks{1000000};
  7475. static constexpr unsigned int qlimit{2};
  7476. unsigned int queued_count{0};
  7477. std::atomic_uint count{0};
  7478. std::unique_ptr<TaskQueue> task_queue{
  7479. new ThreadPool{/*num_threads=*/1, qlimit}};
  7480. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7481. if (task_queue->enqueue(
  7482. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7483. queued_count++;
  7484. }
  7485. }
  7486. EXPECT_NO_THROW(task_queue->shutdown());
  7487. EXPECT_EQ(queued_count, count.load());
  7488. EXPECT_TRUE(queued_count <= number_of_tasks);
  7489. EXPECT_TRUE(queued_count >= qlimit);
  7490. }
  7491. TEST(TaskQueueTest, MaxQueuedRequests) {
  7492. static constexpr unsigned int qlimit{3};
  7493. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7494. std::condition_variable sem_cv;
  7495. std::mutex sem_mtx;
  7496. int credits = 0;
  7497. bool queued;
  7498. /* Fill up the queue with tasks that will block until we give them credits to
  7499. * complete. */
  7500. for (unsigned int n = 0; n <= qlimit;) {
  7501. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7502. std::unique_lock<std::mutex> lock(sem_mtx);
  7503. while (credits <= 0) {
  7504. sem_cv.wait(lock);
  7505. }
  7506. /* Consume the credit and signal the test code if they are all gone. */
  7507. if (--credits == 0) { sem_cv.notify_one(); }
  7508. });
  7509. if (n < qlimit) {
  7510. /* The first qlimit enqueues must succeed. */
  7511. EXPECT_TRUE(queued);
  7512. } else {
  7513. /* The last one will succeed only when the worker thread
  7514. * starts and dequeues the first blocking task. Although
  7515. * not necessary for the correctness of this test, we sleep for
  7516. * a short while to avoid busy waiting. */
  7517. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7518. }
  7519. if (queued) { n++; }
  7520. }
  7521. /* Further enqueues must fail since the queue is full. */
  7522. for (auto i = 0; i < 4; i++) {
  7523. queued = task_queue->enqueue([] {});
  7524. EXPECT_FALSE(queued);
  7525. }
  7526. /* Give the credits to allow the previous tasks to complete. */
  7527. {
  7528. std::unique_lock<std::mutex> lock(sem_mtx);
  7529. credits += qlimit + 1;
  7530. }
  7531. sem_cv.notify_all();
  7532. /* Wait for all the credits to be consumed. */
  7533. {
  7534. std::unique_lock<std::mutex> lock(sem_mtx);
  7535. while (credits > 0) {
  7536. sem_cv.wait(lock);
  7537. }
  7538. }
  7539. /* Check that we are able again to enqueue at least qlimit tasks. */
  7540. for (unsigned int i = 0; i < qlimit; i++) {
  7541. queued = task_queue->enqueue([] {});
  7542. EXPECT_TRUE(queued);
  7543. }
  7544. EXPECT_NO_THROW(task_queue->shutdown());
  7545. }
  7546. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7547. Server svr;
  7548. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7549. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7550. });
  7551. svr.Get("/hello", [](const Request &req, Response &res) {
  7552. res.set_content(req.get_param_value("key"), "text/plain");
  7553. });
  7554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7555. auto se = detail::scope_exit([&] {
  7556. svr.stop();
  7557. thread.join();
  7558. ASSERT_FALSE(svr.is_running());
  7559. });
  7560. svr.wait_until_ready();
  7561. {
  7562. Client cli(HOST, PORT);
  7563. cli.set_follow_location(true);
  7564. auto res = cli.Get("/");
  7565. ASSERT_TRUE(res);
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. EXPECT_EQ("val&key2=val2", res->body);
  7568. }
  7569. }
  7570. TEST(VulnerabilityTest, CRLFInjection) {
  7571. Server svr;
  7572. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7573. res.set_content("Hello 1", "text/plain");
  7574. });
  7575. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7576. res.set_content("Hello 2", "text/plain");
  7577. });
  7578. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7579. res.set_content("Hello 3", "text/plain");
  7580. });
  7581. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7582. res.set_content("Hello 4", "text/plain");
  7583. });
  7584. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7585. for (const auto &x : req.headers) {
  7586. auto key = x.first;
  7587. EXPECT_STRNE("evil", key.c_str());
  7588. }
  7589. });
  7590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7591. auto se = detail::scope_exit([&] {
  7592. svr.stop();
  7593. thread.join();
  7594. ASSERT_FALSE(svr.is_running());
  7595. });
  7596. svr.wait_until_ready();
  7597. {
  7598. Client cli(HOST, PORT);
  7599. cli.Post("/test1", "A=B",
  7600. "application/x-www-form-urlencoded\r\nevil: hello1");
  7601. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7602. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7603. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7604. }
  7605. }
  7606. TEST(PathParamsTest, StaticMatch) {
  7607. const auto pattern = "/users/all";
  7608. detail::PathParamsMatcher matcher(pattern);
  7609. Request request;
  7610. request.path = "/users/all";
  7611. ASSERT_TRUE(matcher.match(request));
  7612. std::unordered_map<std::string, std::string> expected_params = {};
  7613. EXPECT_EQ(request.path_params, expected_params);
  7614. }
  7615. TEST(PathParamsTest, StaticMismatch) {
  7616. const auto pattern = "/users/all";
  7617. detail::PathParamsMatcher matcher(pattern);
  7618. Request request;
  7619. request.path = "/users/1";
  7620. ASSERT_FALSE(matcher.match(request));
  7621. }
  7622. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7623. const auto pattern = "/users/:id/subscriptions";
  7624. detail::PathParamsMatcher matcher(pattern);
  7625. Request request;
  7626. request.path = "/users/42/subscriptions";
  7627. ASSERT_TRUE(matcher.match(request));
  7628. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7629. EXPECT_EQ(request.path_params, expected_params);
  7630. }
  7631. TEST(PathParamsTest, SingleParamInTheEnd) {
  7632. const auto pattern = "/users/:id";
  7633. detail::PathParamsMatcher matcher(pattern);
  7634. Request request;
  7635. request.path = "/users/24";
  7636. ASSERT_TRUE(matcher.match(request));
  7637. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7638. EXPECT_EQ(request.path_params, expected_params);
  7639. }
  7640. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7641. const auto pattern = "/users/:id/";
  7642. detail::PathParamsMatcher matcher(pattern);
  7643. Request request;
  7644. request.path = "/users/42/";
  7645. ASSERT_TRUE(matcher.match(request));
  7646. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7647. EXPECT_EQ(request.path_params, expected_params);
  7648. }
  7649. TEST(PathParamsTest, EmptyParam) {
  7650. const auto pattern = "/users/:id/";
  7651. detail::PathParamsMatcher matcher(pattern);
  7652. Request request;
  7653. request.path = "/users//";
  7654. ASSERT_TRUE(matcher.match(request));
  7655. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  7656. EXPECT_EQ(request.path_params, expected_params);
  7657. }
  7658. TEST(PathParamsTest, FragmentMismatch) {
  7659. const auto pattern = "/users/:id/";
  7660. detail::PathParamsMatcher matcher(pattern);
  7661. Request request;
  7662. request.path = "/admins/24/";
  7663. ASSERT_FALSE(matcher.match(request));
  7664. }
  7665. TEST(PathParamsTest, ExtraFragments) {
  7666. const auto pattern = "/users/:id";
  7667. detail::PathParamsMatcher matcher(pattern);
  7668. Request request;
  7669. request.path = "/users/42/subscriptions";
  7670. ASSERT_FALSE(matcher.match(request));
  7671. }
  7672. TEST(PathParamsTest, MissingTrailingParam) {
  7673. const auto pattern = "/users/:id";
  7674. detail::PathParamsMatcher matcher(pattern);
  7675. Request request;
  7676. request.path = "/users";
  7677. ASSERT_FALSE(matcher.match(request));
  7678. }
  7679. TEST(PathParamsTest, MissingParamInTheMiddle) {
  7680. const auto pattern = "/users/:id/subscriptions";
  7681. detail::PathParamsMatcher matcher(pattern);
  7682. Request request;
  7683. request.path = "/users/subscriptions";
  7684. ASSERT_FALSE(matcher.match(request));
  7685. }
  7686. TEST(PathParamsTest, MultipleParams) {
  7687. const auto pattern = "/users/:userid/subscriptions/:subid";
  7688. detail::PathParamsMatcher matcher(pattern);
  7689. Request request;
  7690. request.path = "/users/42/subscriptions/2";
  7691. ASSERT_TRUE(matcher.match(request));
  7692. std::unordered_map<std::string, std::string> expected_params = {
  7693. {"userid", "42"}, {"subid", "2"}};
  7694. EXPECT_EQ(request.path_params, expected_params);
  7695. }
  7696. TEST(PathParamsTest, SequenceOfParams) {
  7697. const auto pattern = "/values/:x/:y/:z";
  7698. detail::PathParamsMatcher matcher(pattern);
  7699. Request request;
  7700. request.path = "/values/1/2/3";
  7701. ASSERT_TRUE(matcher.match(request));
  7702. std::unordered_map<std::string, std::string> expected_params = {
  7703. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  7704. EXPECT_EQ(request.path_params, expected_params);
  7705. }
  7706. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  7707. const auto pattern = "/prefix:suffix";
  7708. detail::PathParamsMatcher matcher(pattern);
  7709. Request request;
  7710. request.path = "/prefix:suffix";
  7711. ASSERT_TRUE(matcher.match(request));
  7712. const std::unordered_map<std::string, std::string> expected_params = {};
  7713. EXPECT_EQ(request.path_params, expected_params);
  7714. }
  7715. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  7716. // If ipv6 regex working, regex match codepath is taken.
  7717. // else port will default to 80 in Client impl
  7718. int clientImplMagicPort = 80;
  7719. int port = 4321;
  7720. // above ports must be different to avoid false negative
  7721. EXPECT_NE(clientImplMagicPort, port);
  7722. std::string ipV6TestURL = "http://[ff06::c3]";
  7723. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  7724. CLIENT_PRIVATE_KEY_FILE);
  7725. EXPECT_EQ(cli.port(), port);
  7726. }
  7727. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  7728. auto file_path = "./www/dir/index.html";
  7729. auto dir_path = "./www/dir";
  7730. detail::FileStat stat_file(file_path);
  7731. EXPECT_TRUE(stat_file.is_file());
  7732. EXPECT_FALSE(stat_file.is_dir());
  7733. detail::FileStat stat_dir(dir_path);
  7734. EXPECT_FALSE(stat_dir.is_file());
  7735. EXPECT_TRUE(stat_dir.is_dir());
  7736. }
  7737. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  7738. Server svr;
  7739. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7740. EXPECT_EQ(res.status, 400);
  7741. });
  7742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. thread.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. Client cli(HOST, PORT);
  7750. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  7751. }
  7752. TEST(InvalidHeaderCharsTest, is_field_name) {
  7753. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  7754. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  7755. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  7756. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  7757. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  7758. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  7759. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  7760. EXPECT_FALSE(detail::fields::is_field_name(""));
  7761. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  7762. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  7763. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  7764. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  7765. }
  7766. TEST(InvalidHeaderCharsTest, is_field_value) {
  7767. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  7768. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  7769. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  7770. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  7771. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  7772. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  7773. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  7774. EXPECT_TRUE(detail::fields::is_field_value(""));
  7775. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  7776. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  7777. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  7778. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  7779. EXPECT_TRUE(detail::fields::is_field_value("0"));
  7780. }
  7781. TEST(InvalidHeaderCharsTest, OnServer) {
  7782. Server svr;
  7783. svr.Get("/test_name", [&](const Request &req, Response &res) {
  7784. std::string header = "Not Set";
  7785. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7786. res.set_header(header, "value");
  7787. res.set_content("Page Content Page Content", "text/plain");
  7788. });
  7789. svr.Get("/test_value", [&](const Request &req, Response &res) {
  7790. std::string header = "Not Set";
  7791. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7792. res.set_header("X-Test", header);
  7793. res.set_content("Page Content Page Content", "text/plain");
  7794. });
  7795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7796. auto se = detail::scope_exit([&] {
  7797. svr.stop();
  7798. thread.join();
  7799. ASSERT_FALSE(svr.is_running());
  7800. });
  7801. svr.wait_until_ready();
  7802. Client cli(HOST, PORT);
  7803. {
  7804. auto res = cli.Get(
  7805. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ("Page Content Page Content", res->body);
  7808. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7809. }
  7810. {
  7811. auto res = cli.Get(
  7812. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7813. ASSERT_TRUE(res);
  7814. EXPECT_EQ("Page Content Page Content", res->body);
  7815. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7816. }
  7817. }
  7818. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  7819. auto handled = false;
  7820. Server svr;
  7821. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  7822. thread t = thread([&] { svr.listen(HOST, PORT); });
  7823. auto se = detail::scope_exit([&] {
  7824. svr.stop();
  7825. t.join();
  7826. ASSERT_FALSE(svr.is_running());
  7827. ASSERT_FALSE(handled);
  7828. });
  7829. svr.wait_until_ready();
  7830. auto req = "POST /test HTTP/1.1\r\n"
  7831. "Content-Length: x\r\n"
  7832. "\r\n";
  7833. std::string response;
  7834. ASSERT_TRUE(send_request(1, req, &response));
  7835. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7836. response.substr(0, response.find("\r\n")));
  7837. }
  7838. #ifndef _WIN32
  7839. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7840. static constexpr char reject[] = "Unauthorized";
  7841. static constexpr char accept[] = "Upload accepted";
  7842. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7843. Server svr;
  7844. svr.set_expect_100_continue_handler(
  7845. [](const Request & /*req*/, Response &res) {
  7846. res.status = StatusCode::Unauthorized_401;
  7847. res.set_content(reject, "text/plain");
  7848. return res.status;
  7849. });
  7850. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7851. res.set_content(accept, "text/plain");
  7852. });
  7853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7854. auto se = detail::scope_exit([&] {
  7855. svr.stop();
  7856. thread.join();
  7857. ASSERT_FALSE(svr.is_running());
  7858. });
  7859. svr.wait_until_ready();
  7860. {
  7861. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7862. curl_easy_init(), &curl_easy_cleanup};
  7863. ASSERT_NE(curl, nullptr);
  7864. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7865. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7866. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7867. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7868. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7869. &curl_slist_free_all};
  7870. ASSERT_NE(list, nullptr);
  7871. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7872. struct read_data {
  7873. size_t read_size;
  7874. size_t total_size;
  7875. } data = {0, total_size};
  7876. using read_callback_t =
  7877. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7878. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7879. void *userdata) -> size_t {
  7880. read_data *data = (read_data *)userdata;
  7881. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7882. std::fill_n(ptr, size * nmemb, 'A');
  7883. data->read_size += size * nmemb;
  7884. return size * nmemb;
  7885. };
  7886. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7887. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7888. std::vector<char> buffer;
  7889. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7890. using write_callback_t =
  7891. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7892. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7893. void *userdata) -> size_t {
  7894. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7895. buffer->reserve(buffer->size() + size * nmemb + 1);
  7896. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7897. return size * nmemb;
  7898. };
  7899. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7900. {
  7901. const auto res = curl_easy_perform(curl.get());
  7902. ASSERT_EQ(res, CURLE_OK);
  7903. }
  7904. {
  7905. auto response_code = long{};
  7906. const auto res =
  7907. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7908. ASSERT_EQ(res, CURLE_OK);
  7909. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7910. }
  7911. {
  7912. auto dl = curl_off_t{};
  7913. const auto res =
  7914. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7915. ASSERT_EQ(res, CURLE_OK);
  7916. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7917. }
  7918. {
  7919. buffer.push_back('\0');
  7920. ASSERT_STRCASEEQ(buffer.data(), reject);
  7921. }
  7922. }
  7923. }
  7924. #endif
  7925. template <typename S, typename C>
  7926. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7927. svr.Get("/stream", [&](const Request &, Response &res) {
  7928. auto data = new std::string("01234567890123456789");
  7929. res.set_content_provider(
  7930. data->size(), "text/plain",
  7931. [&, data](size_t offset, size_t length, DataSink &sink) {
  7932. const size_t DATA_CHUNK_SIZE = 4;
  7933. const auto &d = *data;
  7934. std::this_thread::sleep_for(std::chrono::seconds(1));
  7935. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7936. return true;
  7937. },
  7938. [data](bool success) {
  7939. EXPECT_FALSE(success);
  7940. delete data;
  7941. });
  7942. });
  7943. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7944. auto i = new size_t(0);
  7945. res.set_content_provider(
  7946. "text/plain",
  7947. [i](size_t, DataSink &sink) {
  7948. if (*i < 5) {
  7949. std::this_thread::sleep_for(std::chrono::seconds(1));
  7950. sink.write("abcd", 4);
  7951. (*i)++;
  7952. } else {
  7953. sink.done();
  7954. }
  7955. return true;
  7956. },
  7957. [i](bool success) {
  7958. EXPECT_FALSE(success);
  7959. delete i;
  7960. });
  7961. });
  7962. svr.Get("/chunked", [&](const Request &, Response &res) {
  7963. auto i = new size_t(0);
  7964. res.set_chunked_content_provider(
  7965. "text/plain",
  7966. [i](size_t, DataSink &sink) {
  7967. if (*i < 5) {
  7968. std::this_thread::sleep_for(std::chrono::seconds(1));
  7969. sink.os << "abcd";
  7970. (*i)++;
  7971. } else {
  7972. sink.done();
  7973. }
  7974. return true;
  7975. },
  7976. [i](bool success) {
  7977. EXPECT_FALSE(success);
  7978. delete i;
  7979. });
  7980. });
  7981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7982. auto se = detail::scope_exit([&] {
  7983. svr.stop();
  7984. listen_thread.join();
  7985. ASSERT_FALSE(svr.is_running());
  7986. });
  7987. svr.wait_until_ready();
  7988. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7989. {
  7990. auto start = std::chrono::steady_clock::now();
  7991. auto res = cli.Get("/stream");
  7992. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7993. std::chrono::steady_clock::now() - start)
  7994. .count();
  7995. ASSERT_FALSE(res);
  7996. EXPECT_EQ(Error::Read, res.error());
  7997. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7998. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7999. }
  8000. {
  8001. auto start = std::chrono::steady_clock::now();
  8002. auto res = cli.Get("/stream_without_length");
  8003. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8004. std::chrono::steady_clock::now() - start)
  8005. .count();
  8006. ASSERT_FALSE(res);
  8007. EXPECT_EQ(Error::Read, res.error());
  8008. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8009. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8010. }
  8011. {
  8012. auto start = std::chrono::steady_clock::now();
  8013. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8014. EXPECT_EQ("abcd", string(data, data_length));
  8015. return true;
  8016. });
  8017. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8018. std::chrono::steady_clock::now() - start)
  8019. .count();
  8020. ASSERT_FALSE(res);
  8021. EXPECT_EQ(Error::Read, res.error());
  8022. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8023. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8024. }
  8025. }
  8026. TEST(MaxTimeoutTest, ContentStream) {
  8027. time_t timeout = 2000;
  8028. time_t threshold = 200;
  8029. Server svr;
  8030. Client cli("localhost", PORT);
  8031. max_timeout_test(svr, cli, timeout, threshold);
  8032. }
  8033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8034. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8035. time_t timeout = 2000;
  8036. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8038. SSLClient cli("localhost", PORT);
  8039. cli.enable_server_certificate_verification(false);
  8040. max_timeout_test(svr, cli, timeout, threshold);
  8041. }
  8042. #endif
  8043. class EventDispatcher {
  8044. public:
  8045. EventDispatcher() {}
  8046. void wait_event(DataSink *sink) {
  8047. unique_lock<mutex> lk(m_);
  8048. int id = id_;
  8049. cv_.wait(lk, [&] { return cid_ == id; });
  8050. sink->write(message_.data(), message_.size());
  8051. }
  8052. void send_event(const string &message) {
  8053. lock_guard<mutex> lk(m_);
  8054. cid_ = id_++;
  8055. message_ = message;
  8056. cv_.notify_all();
  8057. }
  8058. private:
  8059. mutex m_;
  8060. condition_variable cv_;
  8061. atomic_int id_{0};
  8062. atomic_int cid_{-1};
  8063. string message_;
  8064. };
  8065. TEST(ClientInThreadTest, Issue2068) {
  8066. EventDispatcher ed;
  8067. Server svr;
  8068. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8069. res.set_chunked_content_provider("text/event-stream",
  8070. [&](size_t /*offset*/, DataSink &sink) {
  8071. ed.wait_event(&sink);
  8072. return true;
  8073. });
  8074. });
  8075. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8076. svr.wait_until_ready();
  8077. thread event_thread([&] {
  8078. int id = 0;
  8079. while (svr.is_running()) {
  8080. this_thread::sleep_for(chrono::milliseconds(500));
  8081. std::stringstream ss;
  8082. ss << "data: " << id << "\n\n";
  8083. ed.send_event(ss.str());
  8084. id++;
  8085. }
  8086. });
  8087. auto se = detail::scope_exit([&] {
  8088. svr.stop();
  8089. listen_thread.join();
  8090. event_thread.join();
  8091. ASSERT_FALSE(svr.is_running());
  8092. });
  8093. {
  8094. auto client = detail::make_unique<Client>(HOST, PORT);
  8095. client->set_read_timeout(std::chrono::minutes(10));
  8096. std::atomic<bool> stop{false};
  8097. std::thread t([&] {
  8098. client->Get("/event1",
  8099. [&](const char *, size_t) -> bool { return !stop; });
  8100. });
  8101. std::this_thread::sleep_for(std::chrono::seconds(2));
  8102. stop = true;
  8103. client->stop();
  8104. client.reset();
  8105. t.join();
  8106. }
  8107. }