test.cc 294 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733
  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(), 3U);
  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(), 3U);
  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(), 3U);
  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(), 1U);
  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(), 3U);
  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(), 6U);
  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(), 3U);
  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(), 2U);
  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(), 2U);
  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(), 3U);
  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(), 1U);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1U);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1U);
  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(), 3U);
  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(HostnameToIPConversionTest, HTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. auto ip = hosted_at(host);
  777. EXPECT_EQ("23.96.13.243", ip);
  778. std::vector<std::string> addrs;
  779. hosted_at(host, addrs);
  780. EXPECT_EQ(1u, addrs.size());
  781. }
  782. #if 0 // It depends on each test environment...
  783. TEST(HostnameToIPConversionTest, YouTube_Online) {
  784. auto host = "www.youtube.com";
  785. std::vector<std::string> addrs;
  786. hosted_at(host, addrs);
  787. EXPECT_EQ(20u, addrs.size());
  788. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  789. EXPECT_TRUE(it != addrs.end());
  790. }
  791. #endif
  792. class ChunkedEncodingTest : public ::testing::Test {
  793. protected:
  794. ChunkedEncodingTest()
  795. : cli_(HOST, PORT)
  796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  797. ,
  798. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  799. #endif
  800. {
  801. cli_.set_connection_timeout(2);
  802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  803. cli_.enable_server_certificate_verification(false);
  804. #endif
  805. }
  806. virtual void SetUp() {
  807. read_file("./image.jpg", image_data_);
  808. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  809. res.set_content("Hello World!", "text/plain");
  810. });
  811. svr_.Get(
  812. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  813. res.set_chunked_content_provider(
  814. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  815. size_t remaining = image_data_.size() - offset;
  816. if (remaining == 0) {
  817. sink.done();
  818. } else {
  819. constexpr size_t CHUNK_SIZE = 1024;
  820. size_t send_size = std::min(CHUNK_SIZE, remaining);
  821. sink.write(&image_data_[offset], send_size);
  822. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  823. }
  824. return true;
  825. });
  826. });
  827. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  828. svr_.wait_until_ready();
  829. }
  830. virtual void TearDown() {
  831. svr_.stop();
  832. if (!request_threads_.empty()) {
  833. std::this_thread::sleep_for(std::chrono::seconds(1));
  834. for (auto &t : request_threads_) {
  835. t.join();
  836. }
  837. }
  838. t_.join();
  839. }
  840. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  841. SSLClient cli_;
  842. SSLServer svr_;
  843. #else
  844. Client cli_;
  845. Server svr_;
  846. #endif
  847. thread t_;
  848. std::vector<thread> request_threads_;
  849. std::string image_data_;
  850. };
  851. TEST_F(ChunkedEncodingTest, NormalGet) {
  852. auto res = cli_.Get("/chunked");
  853. ASSERT_TRUE(res);
  854. std::string out;
  855. read_file("./image.jpg", out);
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. EXPECT_EQ(out, res->body);
  858. }
  859. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  860. std::string body;
  861. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  862. body.append(data, data_length);
  863. return true;
  864. });
  865. ASSERT_TRUE(res);
  866. std::string out;
  867. read_file("./image.jpg", out);
  868. EXPECT_EQ(StatusCode::OK_200, res->status);
  869. EXPECT_EQ(out, body);
  870. }
  871. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  872. std::string body;
  873. auto res = cli_.Get(
  874. "/chunked",
  875. [&](const Response &response) {
  876. EXPECT_EQ(StatusCode::OK_200, response.status);
  877. return true;
  878. },
  879. [&](const char *data, size_t data_length) {
  880. body.append(data, data_length);
  881. return true;
  882. });
  883. ASSERT_TRUE(res);
  884. std::string out;
  885. read_file("./image.jpg", out);
  886. EXPECT_EQ(StatusCode::OK_200, res->status);
  887. EXPECT_EQ(out, body);
  888. }
  889. TEST(RangeTest, FromHTTPBin_Online) {
  890. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  891. auto host = "httpbin.org";
  892. auto path = std::string{"/range/32"};
  893. #else
  894. auto host = "nghttp2.org";
  895. auto path = std::string{"/httpbin/range/32"};
  896. #endif
  897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  898. auto port = 443;
  899. SSLClient cli(host, port);
  900. #else
  901. auto port = 80;
  902. Client cli(host, port);
  903. #endif
  904. cli.set_connection_timeout(5);
  905. {
  906. auto res = cli.Get(path);
  907. ASSERT_TRUE(res);
  908. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  909. EXPECT_EQ(StatusCode::OK_200, res->status);
  910. }
  911. {
  912. Headers headers = {make_range_header({{1, -1}})};
  913. auto res = cli.Get(path, headers);
  914. ASSERT_TRUE(res);
  915. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  917. }
  918. {
  919. Headers headers = {make_range_header({{1, 10}})};
  920. auto res = cli.Get(path, headers);
  921. ASSERT_TRUE(res);
  922. EXPECT_EQ("bcdefghijk", res->body);
  923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  924. }
  925. {
  926. Headers headers = {make_range_header({{0, 31}})};
  927. auto res = cli.Get(path, headers);
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  930. EXPECT_EQ(StatusCode::OK_200, res->status);
  931. }
  932. {
  933. Headers headers = {make_range_header({{0, -1}})};
  934. auto res = cli.Get(path, headers);
  935. ASSERT_TRUE(res);
  936. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  937. EXPECT_EQ(StatusCode::OK_200, res->status);
  938. }
  939. {
  940. Headers headers = {make_range_header({{0, 32}})};
  941. auto res = cli.Get(path, headers);
  942. ASSERT_TRUE(res);
  943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  944. }
  945. }
  946. TEST(ConnectionErrorTest, InvalidHost) {
  947. auto host = "-abcde.com";
  948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  949. auto port = 443;
  950. SSLClient cli(host, port);
  951. #else
  952. auto port = 80;
  953. Client cli(host, port);
  954. #endif
  955. cli.set_connection_timeout(std::chrono::seconds(2));
  956. auto res = cli.Get("/");
  957. ASSERT_TRUE(!res);
  958. EXPECT_EQ(Error::Connection, res.error());
  959. }
  960. TEST(ConnectionErrorTest, InvalidHost2) {
  961. auto host = "httpbin.org/";
  962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  963. SSLClient cli(host);
  964. #else
  965. Client cli(host);
  966. #endif
  967. cli.set_connection_timeout(std::chrono::seconds(2));
  968. auto res = cli.Get("/");
  969. ASSERT_TRUE(!res);
  970. EXPECT_EQ(Error::Connection, res.error());
  971. }
  972. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  973. auto host = "httpbin.org/";
  974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  975. SSLClient cli(host);
  976. #else
  977. Client cli(host);
  978. #endif
  979. cli.set_connection_timeout(std::chrono::seconds(2));
  980. auto res = cli.Get("/");
  981. ASSERT_TRUE(!res);
  982. stringstream s;
  983. s << "error code: " << res.error();
  984. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  985. }
  986. TEST(ConnectionErrorTest, InvalidPort) {
  987. auto host = "localhost";
  988. auto port = 44380;
  989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  990. SSLClient cli(host, port);
  991. #else
  992. Client cli(host, port);
  993. #endif
  994. cli.set_connection_timeout(std::chrono::seconds(2));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(!res);
  997. EXPECT_TRUE(Error::Connection == res.error() ||
  998. Error::ConnectionTimeout == res.error());
  999. }
  1000. TEST(ConnectionErrorTest, Timeout_Online) {
  1001. auto host = "google.com";
  1002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1003. auto port = 44380;
  1004. SSLClient cli(host, port);
  1005. #else
  1006. auto port = 8080;
  1007. Client cli(host, port);
  1008. #endif
  1009. cli.set_connection_timeout(std::chrono::seconds(2));
  1010. // only probe one address type so that the error reason
  1011. // correlates to the timed-out IPv4, not the unsupported
  1012. // IPv6 connection attempt
  1013. cli.set_address_family(AF_INET);
  1014. auto res = cli.Get("/");
  1015. ASSERT_TRUE(!res);
  1016. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1017. }
  1018. TEST(CancelTest, NoCancel_Online) {
  1019. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1020. auto host = "httpbin.org";
  1021. auto path = std::string{"/range/32"};
  1022. #else
  1023. auto host = "nghttp2.org";
  1024. auto path = std::string{"/httpbin/range/32"};
  1025. #endif
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. auto port = 443;
  1028. SSLClient cli(host, port);
  1029. #else
  1030. auto port = 80;
  1031. Client cli(host, port);
  1032. #endif
  1033. cli.set_connection_timeout(std::chrono::seconds(5));
  1034. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1035. ASSERT_TRUE(res);
  1036. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1037. EXPECT_EQ(StatusCode::OK_200, res->status);
  1038. }
  1039. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1040. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1041. auto host = "httpbin.org";
  1042. auto path = std::string{"/range/32"};
  1043. #else
  1044. auto host = "nghttp2.org";
  1045. auto path = std::string{"/httpbin/range/32"};
  1046. #endif
  1047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1048. auto port = 443;
  1049. SSLClient cli(host, port);
  1050. #else
  1051. auto port = 80;
  1052. Client cli(host, port);
  1053. #endif
  1054. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1055. cli.set_connection_timeout(std::chrono::seconds(5));
  1056. ASSERT_TRUE(!res);
  1057. EXPECT_EQ(Error::Canceled, res.error());
  1058. }
  1059. TEST(CancelTest, WithCancelLargePayload_Online) {
  1060. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1061. auto host = "httpbin.org";
  1062. auto path = std::string{"/range/65536"};
  1063. #else
  1064. auto host = "nghttp2.org";
  1065. auto path = std::string{"/httpbin/range/65536"};
  1066. #endif
  1067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1068. auto port = 443;
  1069. SSLClient cli(host, port);
  1070. #else
  1071. auto port = 80;
  1072. Client cli(host, port);
  1073. #endif
  1074. cli.set_connection_timeout(std::chrono::seconds(5));
  1075. uint32_t count = 0;
  1076. auto res =
  1077. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1078. ASSERT_TRUE(!res);
  1079. EXPECT_EQ(Error::Canceled, res.error());
  1080. }
  1081. TEST(CancelTest, NoCancelPost) {
  1082. Server svr;
  1083. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1084. res.set_content("Hello World!", "text/plain");
  1085. });
  1086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1087. auto se = detail::scope_exit([&] {
  1088. svr.stop();
  1089. thread.join();
  1090. ASSERT_FALSE(svr.is_running());
  1091. });
  1092. svr.wait_until_ready();
  1093. Client cli(HOST, PORT);
  1094. cli.set_connection_timeout(std::chrono::seconds(5));
  1095. auto res =
  1096. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1097. "application/json", [](uint64_t, uint64_t) { return true; });
  1098. ASSERT_TRUE(res);
  1099. EXPECT_EQ("Hello World!", res->body);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. }
  1102. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1103. Server svr;
  1104. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1108. auto se = detail::scope_exit([&] {
  1109. svr.stop();
  1110. thread.join();
  1111. ASSERT_FALSE(svr.is_running());
  1112. });
  1113. svr.wait_until_ready();
  1114. Client cli(HOST, PORT);
  1115. cli.set_connection_timeout(std::chrono::seconds(5));
  1116. auto res =
  1117. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1118. "application/json", [](uint64_t, uint64_t) { return false; });
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Canceled, res.error());
  1121. }
  1122. TEST(CancelTest, WithCancelLargePayloadPost) {
  1123. Server svr;
  1124. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1125. res.set_content(LARGE_DATA, "text/plain");
  1126. });
  1127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1128. auto se = detail::scope_exit([&] {
  1129. svr.stop();
  1130. thread.join();
  1131. ASSERT_FALSE(svr.is_running());
  1132. });
  1133. svr.wait_until_ready();
  1134. Client cli(HOST, PORT);
  1135. cli.set_connection_timeout(std::chrono::seconds(5));
  1136. auto res =
  1137. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1138. "application/json", [](uint64_t, uint64_t) { return false; });
  1139. ASSERT_TRUE(!res);
  1140. EXPECT_EQ(Error::Canceled, res.error());
  1141. }
  1142. TEST(CancelTest, NoCancelPut) {
  1143. Server svr;
  1144. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1145. res.set_content("Hello World!", "text/plain");
  1146. });
  1147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1148. auto se = detail::scope_exit([&] {
  1149. svr.stop();
  1150. thread.join();
  1151. ASSERT_FALSE(svr.is_running());
  1152. });
  1153. svr.wait_until_ready();
  1154. Client cli(HOST, PORT);
  1155. cli.set_connection_timeout(std::chrono::seconds(5));
  1156. auto res =
  1157. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1158. "application/json", [](uint64_t, uint64_t) { return true; });
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("Hello World!", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1164. Server svr;
  1165. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1166. res.set_content("Hello World!", "text/plain");
  1167. });
  1168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. thread.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. Client cli(HOST, PORT);
  1176. cli.set_connection_timeout(std::chrono::seconds(5));
  1177. auto res =
  1178. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1179. "application/json", [](uint64_t, uint64_t) { return false; });
  1180. ASSERT_TRUE(!res);
  1181. EXPECT_EQ(Error::Canceled, res.error());
  1182. }
  1183. TEST(CancelTest, WithCancelLargePayloadPut) {
  1184. Server svr;
  1185. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1186. res.set_content(LARGE_DATA, "text/plain");
  1187. });
  1188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1189. auto se = detail::scope_exit([&] {
  1190. svr.stop();
  1191. thread.join();
  1192. ASSERT_FALSE(svr.is_running());
  1193. });
  1194. svr.wait_until_ready();
  1195. Client cli(HOST, PORT);
  1196. cli.set_connection_timeout(std::chrono::seconds(5));
  1197. auto res =
  1198. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1199. "application/json", [](uint64_t, uint64_t) { return false; });
  1200. ASSERT_TRUE(!res);
  1201. EXPECT_EQ(Error::Canceled, res.error());
  1202. }
  1203. TEST(CancelTest, NoCancelPatch) {
  1204. Server svr;
  1205. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1206. res.set_content("Hello World!", "text/plain");
  1207. });
  1208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. thread.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. Client cli(HOST, PORT);
  1216. cli.set_connection_timeout(std::chrono::seconds(5));
  1217. auto res =
  1218. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1219. "application/json", [](uint64_t, uint64_t) { return true; });
  1220. ASSERT_TRUE(res);
  1221. EXPECT_EQ("Hello World!", res->body);
  1222. EXPECT_EQ(StatusCode::OK_200, res->status);
  1223. }
  1224. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1225. Server svr;
  1226. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1227. res.set_content("Hello World!", "text/plain");
  1228. });
  1229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1230. auto se = detail::scope_exit([&] {
  1231. svr.stop();
  1232. thread.join();
  1233. ASSERT_FALSE(svr.is_running());
  1234. });
  1235. svr.wait_until_ready();
  1236. Client cli(HOST, PORT);
  1237. cli.set_connection_timeout(std::chrono::seconds(5));
  1238. auto res =
  1239. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1240. "application/json", [](uint64_t, uint64_t) { return false; });
  1241. ASSERT_TRUE(!res);
  1242. EXPECT_EQ(Error::Canceled, res.error());
  1243. }
  1244. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1245. Server svr;
  1246. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1247. res.set_content(LARGE_DATA, "text/plain");
  1248. });
  1249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1250. auto se = detail::scope_exit([&] {
  1251. svr.stop();
  1252. thread.join();
  1253. ASSERT_FALSE(svr.is_running());
  1254. });
  1255. svr.wait_until_ready();
  1256. Client cli(HOST, PORT);
  1257. cli.set_connection_timeout(std::chrono::seconds(5));
  1258. auto res =
  1259. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1260. "application/json", [](uint64_t, uint64_t) { return false; });
  1261. ASSERT_TRUE(!res);
  1262. EXPECT_EQ(Error::Canceled, res.error());
  1263. }
  1264. TEST(CancelTest, NoCancelDelete) {
  1265. Server svr;
  1266. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return true; });
  1281. ASSERT_TRUE(res);
  1282. EXPECT_EQ("Hello World!", res->body);
  1283. EXPECT_EQ(StatusCode::OK_200, res->status);
  1284. }
  1285. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1286. Server svr;
  1287. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1288. res.set_content("Hello World!", "text/plain");
  1289. });
  1290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1291. auto se = detail::scope_exit([&] {
  1292. svr.stop();
  1293. thread.join();
  1294. ASSERT_FALSE(svr.is_running());
  1295. });
  1296. svr.wait_until_ready();
  1297. Client cli(HOST, PORT);
  1298. cli.set_connection_timeout(std::chrono::seconds(5));
  1299. auto res =
  1300. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1301. "application/json", [](uint64_t, uint64_t) { return false; });
  1302. ASSERT_TRUE(!res);
  1303. EXPECT_EQ(Error::Canceled, res.error());
  1304. }
  1305. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1306. Server svr;
  1307. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1308. res.set_content(LARGE_DATA, "text/plain");
  1309. });
  1310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1311. auto se = detail::scope_exit([&] {
  1312. svr.stop();
  1313. thread.join();
  1314. ASSERT_FALSE(svr.is_running());
  1315. });
  1316. svr.wait_until_ready();
  1317. Client cli(HOST, PORT);
  1318. cli.set_connection_timeout(std::chrono::seconds(5));
  1319. auto res =
  1320. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1321. "application/json", [](uint64_t, uint64_t) { return false; });
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_EQ(Error::Canceled, res.error());
  1324. }
  1325. static std::string remove_whitespace(const std::string &input) {
  1326. std::string output;
  1327. output.reserve(input.size());
  1328. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1329. [](unsigned char c) { return !std::isspace(c); });
  1330. return output;
  1331. }
  1332. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1333. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1334. auto host = "httpbin.org";
  1335. auto path = std::string{"/basic-auth/hello/world"};
  1336. #else
  1337. auto host = "nghttp2.org";
  1338. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1339. #endif
  1340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1341. auto port = 443;
  1342. SSLClient cli(host, port);
  1343. #else
  1344. auto port = 80;
  1345. Client cli(host, port);
  1346. #endif
  1347. {
  1348. auto res = cli.Get(path);
  1349. ASSERT_TRUE(res);
  1350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1351. }
  1352. {
  1353. auto res =
  1354. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1355. ASSERT_TRUE(res);
  1356. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1357. remove_whitespace(res->body));
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. {
  1361. cli.set_basic_auth("hello", "world");
  1362. auto res = cli.Get(path);
  1363. ASSERT_TRUE(res);
  1364. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1365. remove_whitespace(res->body));
  1366. EXPECT_EQ(StatusCode::OK_200, res->status);
  1367. }
  1368. {
  1369. cli.set_basic_auth("hello", "bad");
  1370. auto res = cli.Get(path);
  1371. ASSERT_TRUE(res);
  1372. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1373. }
  1374. {
  1375. cli.set_basic_auth("bad", "world");
  1376. auto res = cli.Get(path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. }
  1381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1382. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1383. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1384. auto host = "httpbin.org";
  1385. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1386. auto paths = std::vector<std::string>{
  1387. "/digest-auth/auth/hello/world/MD5",
  1388. "/digest-auth/auth/hello/world/SHA-256",
  1389. "/digest-auth/auth/hello/world/SHA-512",
  1390. "/digest-auth/auth-int/hello/world/MD5",
  1391. };
  1392. #else
  1393. auto host = "nghttp2.org";
  1394. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1395. auto paths = std::vector<std::string>{
  1396. "/httpbin/digest-auth/auth/hello/world/MD5",
  1397. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1398. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1399. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1400. };
  1401. #endif
  1402. auto port = 443;
  1403. SSLClient cli(host, port);
  1404. {
  1405. auto res = cli.Get(unauth_path);
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1408. }
  1409. {
  1410. cli.set_digest_auth("hello", "world");
  1411. for (const auto &path : paths) {
  1412. auto res = cli.Get(path.c_str());
  1413. ASSERT_TRUE(res);
  1414. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1415. remove_whitespace(res->body));
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. cli.set_digest_auth("hello", "bad");
  1419. for (const auto &path : paths) {
  1420. auto res = cli.Get(path.c_str());
  1421. ASSERT_TRUE(res);
  1422. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1423. }
  1424. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1425. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1426. // cli.set_digest_auth("bad", "world");
  1427. // for (const auto& path : paths) {
  1428. // auto res = cli.Get(path.c_str());
  1429. // ASSERT_TRUE(res);
  1430. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1431. // }
  1432. }
  1433. }
  1434. #endif
  1435. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1436. auto host = "google.com";
  1437. auto another_host = "example.com";
  1438. auto wrong_ip = "0.0.0.0";
  1439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1440. SSLClient cli(host);
  1441. #else
  1442. Client cli(host);
  1443. #endif
  1444. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1445. auto res = cli.Get("/");
  1446. ASSERT_TRUE(res);
  1447. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1448. }
  1449. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1450. auto host = "google.com";
  1451. auto wrong_ip = "0.0.0.0";
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. SSLClient cli(host);
  1454. #else
  1455. Client cli(host);
  1456. #endif
  1457. cli.set_hostname_addr_map({{host, wrong_ip}});
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::Connection, res.error());
  1461. }
  1462. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1463. auto host = "nghttp2.org";
  1464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1465. SSLClient cli(host);
  1466. #else
  1467. Client cli(host);
  1468. #endif
  1469. cli.set_follow_location(true);
  1470. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ(StatusCode::OK_200, res->status);
  1473. }
  1474. TEST(RedirectTest, Redirect_Online) {
  1475. auto host = "nghttp2.org";
  1476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1477. SSLClient cli(host);
  1478. #else
  1479. Client cli(host);
  1480. #endif
  1481. cli.set_follow_location(true);
  1482. auto res = cli.Get("/httpbin/redirect/3");
  1483. ASSERT_TRUE(res);
  1484. EXPECT_EQ(StatusCode::OK_200, res->status);
  1485. }
  1486. TEST(RelativeRedirectTest, Redirect_Online) {
  1487. auto host = "nghttp2.org";
  1488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1489. SSLClient cli(host);
  1490. #else
  1491. Client cli(host);
  1492. #endif
  1493. cli.set_follow_location(true);
  1494. auto res = cli.Get("/httpbin/relative-redirect/3");
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ(StatusCode::OK_200, res->status);
  1497. }
  1498. TEST(TooManyRedirectTest, Redirect_Online) {
  1499. auto host = "nghttp2.org";
  1500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1501. SSLClient cli(host);
  1502. #else
  1503. Client cli(host);
  1504. #endif
  1505. cli.set_follow_location(true);
  1506. auto res = cli.Get("/httpbin/redirect/21");
  1507. ASSERT_TRUE(!res);
  1508. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1509. }
  1510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1511. TEST(YahooRedirectTest, Redirect_Online) {
  1512. Client cli("yahoo.com");
  1513. auto res = cli.Get("/");
  1514. ASSERT_TRUE(res);
  1515. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1516. cli.set_follow_location(true);
  1517. res = cli.Get("/");
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ(StatusCode::OK_200, res->status);
  1520. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1521. }
  1522. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1523. #define REDIR_HOST "httpbingo.org"
  1524. #define REDIR_PATH "/redirect-to"
  1525. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1526. SSLClient cli(REDIR_HOST);
  1527. cli.set_follow_location(true);
  1528. auto res =
  1529. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ(StatusCode::OK_200, res->status);
  1532. }
  1533. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1534. SSLClient cli(REDIR_HOST);
  1535. cli.set_follow_location(true);
  1536. Params params;
  1537. params.emplace("url", "http://example.com");
  1538. params.emplace("status_code", "302");
  1539. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1540. ASSERT_TRUE(res);
  1541. EXPECT_EQ(StatusCode::OK_200, res->status);
  1542. }
  1543. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1544. SSLClient cli(REDIR_HOST);
  1545. cli.set_follow_location(true);
  1546. Params params;
  1547. params.emplace("url", "http://example.com");
  1548. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1549. ASSERT_TRUE(res);
  1550. EXPECT_EQ(StatusCode::OK_200, res->status);
  1551. }
  1552. TEST(UrlWithSpace, Redirect_Online) {
  1553. SSLClient cli("edge.forgecdn.net");
  1554. cli.set_follow_location(true);
  1555. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1556. ASSERT_TRUE(res);
  1557. EXPECT_EQ(StatusCode::OK_200, res->status);
  1558. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1559. }
  1560. #endif
  1561. #if !defined(_WIN32) && !defined(_WIN64)
  1562. TEST(ReceiveSignals, Signal) {
  1563. auto setupSignalHandlers = []() {
  1564. struct sigaction act;
  1565. sigemptyset(&act.sa_mask);
  1566. act.sa_flags = SA_SIGINFO;
  1567. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1568. switch (sig) {
  1569. case SIGINT:
  1570. default: break;
  1571. }
  1572. };
  1573. ::sigaction(SIGINT, &act, nullptr);
  1574. };
  1575. Server svr;
  1576. int port = 0;
  1577. auto thread = std::thread([&]() {
  1578. setupSignalHandlers();
  1579. port = svr.bind_to_any_port("localhost");
  1580. svr.listen_after_bind();
  1581. });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. ASSERT_TRUE(svr.is_running());
  1589. pthread_kill(thread.native_handle(), SIGINT);
  1590. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1591. ASSERT_TRUE(svr.is_running());
  1592. }
  1593. #endif
  1594. TEST(RedirectToDifferentPort, Redirect) {
  1595. Server svr1;
  1596. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1597. res.set_content("Hello World!", "text/plain");
  1598. });
  1599. int svr1_port = 0;
  1600. auto thread1 = std::thread([&]() {
  1601. svr1_port = svr1.bind_to_any_port("localhost");
  1602. svr1.listen_after_bind();
  1603. });
  1604. Server svr2;
  1605. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1606. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1607. });
  1608. int svr2_port = 0;
  1609. auto thread2 = std::thread([&]() {
  1610. svr2_port = svr2.bind_to_any_port("localhost");
  1611. svr2.listen_after_bind();
  1612. });
  1613. auto se = detail::scope_exit([&] {
  1614. svr2.stop();
  1615. thread2.join();
  1616. svr1.stop();
  1617. thread1.join();
  1618. ASSERT_FALSE(svr2.is_running());
  1619. ASSERT_FALSE(svr1.is_running());
  1620. });
  1621. svr1.wait_until_ready();
  1622. svr2.wait_until_ready();
  1623. Client cli("localhost", svr2_port);
  1624. cli.set_follow_location(true);
  1625. auto res = cli.Get("/2");
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::OK_200, res->status);
  1628. EXPECT_EQ("Hello World!", res->body);
  1629. }
  1630. TEST(RedirectFromPageWithContent, Redirect) {
  1631. Server svr;
  1632. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("___", "text/plain");
  1634. res.set_redirect("/2");
  1635. });
  1636. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1637. res.set_content("Hello World!", "text/plain");
  1638. });
  1639. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. th.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. {
  1647. Client cli("localhost", PORT);
  1648. cli.set_follow_location(true);
  1649. std::string body;
  1650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1651. body.append(data, data_length);
  1652. return true;
  1653. });
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::OK_200, res->status);
  1656. EXPECT_EQ("Hello World!", body);
  1657. }
  1658. {
  1659. Client cli("localhost", PORT);
  1660. std::string body;
  1661. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1662. body.append(data, data_length);
  1663. return true;
  1664. });
  1665. ASSERT_TRUE(res);
  1666. EXPECT_EQ(StatusCode::Found_302, res->status);
  1667. EXPECT_EQ("___", body);
  1668. }
  1669. }
  1670. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1671. Server svr;
  1672. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1673. res.set_content("___", "text/plain");
  1674. // res.set_redirect("/2");
  1675. res.set_redirect("http://[::1]:1234/2");
  1676. });
  1677. svr.Get("/2", [&](const Request &req, Response &res) {
  1678. auto host_header = req.headers.find("Host");
  1679. ASSERT_TRUE(host_header != req.headers.end());
  1680. EXPECT_EQ("[::1]:1234", host_header->second);
  1681. res.set_content("Hello World!", "text/plain");
  1682. });
  1683. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1684. auto se = detail::scope_exit([&] {
  1685. svr.stop();
  1686. th.join();
  1687. ASSERT_FALSE(svr.is_running());
  1688. });
  1689. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1690. // actually starts anything, so the condition !svr.is_running() will
  1691. // always remain true, and the loop never stops.
  1692. // This basically counts how many milliseconds have passed since the
  1693. // call to svr.listen(), and if after 5 seconds nothing started yet
  1694. // aborts the test.
  1695. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1696. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1697. ASSERT_LT(milliseconds, 5000U);
  1698. }
  1699. {
  1700. Client cli("http://[::1]:1234");
  1701. cli.set_follow_location(true);
  1702. std::string body;
  1703. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res);
  1708. EXPECT_EQ(StatusCode::OK_200, res->status);
  1709. EXPECT_EQ("Hello World!", body);
  1710. }
  1711. {
  1712. Client cli("http://[::1]:1234");
  1713. std::string body;
  1714. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1715. body.append(data, data_length);
  1716. return true;
  1717. });
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::Found_302, res->status);
  1720. EXPECT_EQ("___", body);
  1721. }
  1722. }
  1723. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1724. Server svr;
  1725. svr.Get("/foo", [](const Request &req, Response &res) {
  1726. auto a = req.params.find("a");
  1727. if (a != req.params.end()) {
  1728. res.set_content((*a).second, "text/plain");
  1729. res.status = StatusCode::OK_200;
  1730. } else {
  1731. res.status = StatusCode::BadRequest_400;
  1732. }
  1733. });
  1734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1735. auto se = detail::scope_exit([&] {
  1736. svr.stop();
  1737. thread.join();
  1738. ASSERT_FALSE(svr.is_running());
  1739. });
  1740. svr.wait_until_ready();
  1741. {
  1742. Client cli(HOST, PORT);
  1743. cli.set_url_encode(false);
  1744. auto res = cli.Get("/foo?a=explicitly+encoded");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. // This expects it back with a space, as the `+` won't have been
  1748. // url-encoded, and server-side the params get decoded turning `+`
  1749. // into spaces.
  1750. EXPECT_EQ("explicitly encoded", res->body);
  1751. }
  1752. }
  1753. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1754. Server svr;
  1755. svr.Get("/", [](const Request &req, Response &) {
  1756. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1757. });
  1758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1759. auto se = detail::scope_exit([&] {
  1760. svr.stop();
  1761. thread.join();
  1762. ASSERT_FALSE(svr.is_running());
  1763. });
  1764. svr.wait_until_ready();
  1765. {
  1766. Client cli(HOST, PORT);
  1767. cli.set_url_encode(false);
  1768. auto res = cli.Get("/?something=%0A");
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ(StatusCode::OK_200, res->status);
  1771. }
  1772. }
  1773. TEST(BindServerTest, DISABLED_BindDualStack) {
  1774. Server svr;
  1775. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content("Hello World!", "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. {
  1786. Client cli("127.0.0.1", PORT);
  1787. auto res = cli.Get("/1");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. {
  1793. Client cli("::1", PORT);
  1794. auto res = cli.Get("/1");
  1795. ASSERT_TRUE(res);
  1796. EXPECT_EQ(StatusCode::OK_200, res->status);
  1797. EXPECT_EQ("Hello World!", res->body);
  1798. }
  1799. }
  1800. TEST(BindServerTest, BindAndListenSeparately) {
  1801. Server svr;
  1802. int port = svr.bind_to_any_port("0.0.0.0");
  1803. ASSERT_TRUE(svr.is_valid());
  1804. ASSERT_TRUE(port > 0);
  1805. svr.stop();
  1806. }
  1807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1808. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1810. CLIENT_CA_CERT_DIR);
  1811. int port = svr.bind_to_any_port("0.0.0.0");
  1812. ASSERT_TRUE(svr.is_valid());
  1813. ASSERT_TRUE(port > 0);
  1814. svr.stop();
  1815. }
  1816. #endif
  1817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1818. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1819. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1820. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1821. int port = svr.bind_to_any_port("0.0.0.0");
  1822. ASSERT_TRUE(svr.is_valid());
  1823. ASSERT_TRUE(port > 0);
  1824. svr.stop();
  1825. }
  1826. #endif
  1827. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1828. X509 *readCertificate(const std::string &strFileName) {
  1829. std::ifstream inStream(strFileName);
  1830. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1831. std::istreambuf_iterator<char>());
  1832. if (strCertPEM.empty()) return (nullptr);
  1833. BIO *pbCert = BIO_new(BIO_s_mem());
  1834. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1835. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1836. BIO_free(pbCert);
  1837. return (pCert);
  1838. }
  1839. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1840. std::ifstream inStream(strFileName);
  1841. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1842. std::istreambuf_iterator<char>());
  1843. if (strPrivateKeyPEM.empty()) return (nullptr);
  1844. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1845. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1846. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1847. BIO_free(pbPrivKey);
  1848. return (pPrivateKey);
  1849. }
  1850. TEST(BindServerTest, UpdateCerts) {
  1851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1852. int port = svr.bind_to_any_port("0.0.0.0");
  1853. ASSERT_TRUE(svr.is_valid());
  1854. ASSERT_TRUE(port > 0);
  1855. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1856. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1857. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1858. ASSERT_TRUE(cert != nullptr);
  1859. ASSERT_TRUE(ca_cert != nullptr);
  1860. ASSERT_TRUE(key != nullptr);
  1861. X509_STORE *cert_store = X509_STORE_new();
  1862. X509_STORE_add_cert(cert_store, ca_cert);
  1863. svr.update_certs(cert, key, cert_store);
  1864. ASSERT_TRUE(svr.is_valid());
  1865. svr.stop();
  1866. X509_free(cert);
  1867. X509_free(ca_cert);
  1868. EVP_PKEY_free(key);
  1869. }
  1870. #endif
  1871. TEST(ErrorHandlerTest, ContentLength) {
  1872. Server svr;
  1873. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1874. res.status = StatusCode::OK_200;
  1875. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1876. "text/html"); // <= Content-Length still 13
  1877. });
  1878. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!\n", "text/plain");
  1880. res.status = 524;
  1881. });
  1882. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1883. auto se = detail::scope_exit([&] {
  1884. svr.stop();
  1885. thread.join();
  1886. ASSERT_FALSE(svr.is_running());
  1887. });
  1888. svr.wait_until_ready();
  1889. {
  1890. Client cli(HOST, PORT);
  1891. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1892. ASSERT_TRUE(res);
  1893. EXPECT_EQ(StatusCode::OK_200, res->status);
  1894. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1895. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1896. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1897. }
  1898. }
  1899. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1900. TEST(ExceptionTest, WithoutExceptionHandler) {
  1901. Server svr;
  1902. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1903. throw std::runtime_error("exception...");
  1904. });
  1905. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1906. throw std::runtime_error("exception\r\n...");
  1907. });
  1908. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1909. auto se = detail::scope_exit([&] {
  1910. svr.stop();
  1911. listen_thread.join();
  1912. ASSERT_FALSE(svr.is_running());
  1913. });
  1914. svr.wait_until_ready();
  1915. Client cli("localhost", PORT);
  1916. {
  1917. auto res = cli.Get("/exception");
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1920. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1921. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1922. }
  1923. {
  1924. auto res = cli.Get("/unknown");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1927. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1928. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1929. }
  1930. }
  1931. TEST(ExceptionTest, WithExceptionHandler) {
  1932. Server svr;
  1933. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1934. std::exception_ptr ep) {
  1935. EXPECT_FALSE(ep == nullptr);
  1936. try {
  1937. std::rethrow_exception(ep);
  1938. } catch (std::exception &e) {
  1939. EXPECT_EQ("abc", std::string(e.what()));
  1940. } catch (...) {}
  1941. res.status = StatusCode::InternalServerError_500;
  1942. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1943. "text/html"); // <= Content-Length still 13 at this point
  1944. });
  1945. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1946. res.set_content("Hello World!\n", "text/plain");
  1947. throw std::runtime_error("abc");
  1948. });
  1949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1950. auto se = detail::scope_exit([&] {
  1951. svr.stop();
  1952. thread.join();
  1953. ASSERT_FALSE(svr.is_running());
  1954. });
  1955. svr.wait_until_ready();
  1956. for (size_t i = 0; i < 10; i++) {
  1957. Client cli(HOST, PORT);
  1958. for (size_t j = 0; j < 100; j++) {
  1959. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1962. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1963. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1964. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1965. }
  1966. cli.set_keep_alive(true);
  1967. for (size_t j = 0; j < 100; j++) {
  1968. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1969. ASSERT_TRUE(res);
  1970. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1971. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1972. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1973. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1974. }
  1975. }
  1976. }
  1977. TEST(ExceptionTest, AndErrorHandler) {
  1978. Server svr;
  1979. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1980. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1981. });
  1982. svr.set_exception_handler(
  1983. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1984. EXPECT_FALSE(ep == nullptr);
  1985. try {
  1986. std::rethrow_exception(ep);
  1987. } catch (std::exception &e) {
  1988. res.set_content(e.what(), "text/html");
  1989. } catch (...) {}
  1990. res.status = StatusCode::InternalServerError_500;
  1991. });
  1992. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1993. throw std::runtime_error("EXCEPTION");
  1994. });
  1995. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1996. res.set_content("ERROR", "text/html");
  1997. res.status = StatusCode::InternalServerError_500;
  1998. });
  1999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2000. auto se = detail::scope_exit([&] {
  2001. svr.stop();
  2002. thread.join();
  2003. ASSERT_FALSE(svr.is_running());
  2004. });
  2005. svr.wait_until_ready();
  2006. Client cli(HOST, PORT);
  2007. {
  2008. auto res = cli.Get("/exception");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2011. EXPECT_EQ("EXCEPTION", res->body);
  2012. }
  2013. {
  2014. auto res = cli.Get("/error");
  2015. ASSERT_TRUE(res);
  2016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2017. EXPECT_EQ("ERROR", res->body);
  2018. }
  2019. {
  2020. auto res = cli.Get("/invalid");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2023. EXPECT_EQ("NOT_FOUND", res->body);
  2024. }
  2025. }
  2026. #endif
  2027. TEST(NoContentTest, ContentLength) {
  2028. Server svr;
  2029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2030. res.status = StatusCode::NoContent_204;
  2031. });
  2032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2033. auto se = detail::scope_exit([&] {
  2034. svr.stop();
  2035. thread.join();
  2036. ASSERT_FALSE(svr.is_running());
  2037. });
  2038. svr.wait_until_ready();
  2039. {
  2040. Client cli(HOST, PORT);
  2041. auto res = cli.Get("/hi");
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2044. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2045. }
  2046. }
  2047. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2050. ASSERT_TRUE(svr.is_valid());
  2051. #else
  2052. Server svr;
  2053. #endif
  2054. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2055. if (req.path == "/routing_handler") {
  2056. res.set_header("PRE_ROUTING", "on");
  2057. res.set_content("Routing Handler", "text/plain");
  2058. return httplib::Server::HandlerResponse::Handled;
  2059. }
  2060. return httplib::Server::HandlerResponse::Unhandled;
  2061. });
  2062. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2063. res.set_content("Error", "text/html");
  2064. });
  2065. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2066. if (req.path == "/routing_handler") {
  2067. res.set_header("POST_ROUTING", "on");
  2068. }
  2069. });
  2070. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2071. res.set_content("Hello World!\n", "text/plain");
  2072. });
  2073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2074. auto se = detail::scope_exit([&] {
  2075. svr.stop();
  2076. thread.join();
  2077. ASSERT_FALSE(svr.is_running());
  2078. });
  2079. svr.wait_until_ready();
  2080. {
  2081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2082. SSLClient cli(HOST, PORT);
  2083. cli.enable_server_certificate_verification(false);
  2084. #else
  2085. Client cli(HOST, PORT);
  2086. #endif
  2087. auto res = cli.Get("/routing_handler");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. EXPECT_EQ("Routing Handler", res->body);
  2091. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2092. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2093. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2094. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2095. }
  2096. {
  2097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2098. SSLClient cli(HOST, PORT);
  2099. cli.enable_server_certificate_verification(false);
  2100. #else
  2101. Client cli(HOST, PORT);
  2102. #endif
  2103. auto res = cli.Get("/hi");
  2104. ASSERT_TRUE(res);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. EXPECT_EQ("Hello World!\n", res->body);
  2107. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2108. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2109. }
  2110. {
  2111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2112. SSLClient cli(HOST, PORT);
  2113. cli.enable_server_certificate_verification(false);
  2114. #else
  2115. Client cli(HOST, PORT);
  2116. #endif
  2117. auto res = cli.Get("/aaa");
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2120. EXPECT_EQ("Error", res->body);
  2121. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2122. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2123. }
  2124. }
  2125. TEST(RequestHandlerTest, PreRequestHandler) {
  2126. auto route_path = "/user/:user";
  2127. Server svr;
  2128. svr.Get("/hi", [](const Request &, Response &res) {
  2129. res.set_content("hi", "text/plain");
  2130. });
  2131. svr.Get(route_path, [](const Request &req, Response &res) {
  2132. res.set_content(req.path_params.at("user"), "text/plain");
  2133. });
  2134. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2135. if (req.matched_route == route_path) {
  2136. auto user = req.path_params.at("user");
  2137. if (user != "john") {
  2138. res.status = StatusCode::Forbidden_403;
  2139. res.set_content("error", "text/html");
  2140. return Server::HandlerResponse::Handled;
  2141. }
  2142. }
  2143. return Server::HandlerResponse::Unhandled;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. Client cli(HOST, PORT);
  2153. {
  2154. auto res = cli.Get("/hi");
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::OK_200, res->status);
  2157. EXPECT_EQ("hi", res->body);
  2158. }
  2159. {
  2160. auto res = cli.Get("/user/john");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::OK_200, res->status);
  2163. EXPECT_EQ("john", res->body);
  2164. }
  2165. {
  2166. auto res = cli.Get("/user/invalid-user");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2169. EXPECT_EQ("error", res->body);
  2170. }
  2171. }
  2172. TEST(InvalidFormatTest, StatusCode) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.set_content("Hello World!\n", "text/plain");
  2176. res.status = 9999; // Status should be a three-digit code...
  2177. });
  2178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2179. auto se = detail::scope_exit([&] {
  2180. svr.stop();
  2181. thread.join();
  2182. ASSERT_FALSE(svr.is_running());
  2183. });
  2184. svr.wait_until_ready();
  2185. {
  2186. Client cli(HOST, PORT);
  2187. auto res = cli.Get("/hi");
  2188. ASSERT_FALSE(res);
  2189. }
  2190. }
  2191. TEST(URLFragmentTest, WithFragment) {
  2192. Server svr;
  2193. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2194. EXPECT_TRUE(req.target == "/hi");
  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. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2206. EXPECT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::OK_200, res->status);
  2208. res = cli.Get("/hi%23key1=val1=key2=val2");
  2209. EXPECT_TRUE(res);
  2210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2211. }
  2212. }
  2213. TEST(HeaderWriter, SetHeaderWriter) {
  2214. Server svr;
  2215. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2216. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2217. return detail::write_headers(strm, hdrs);
  2218. });
  2219. svr.Get("/hi", [](const Request &req, Response &res) {
  2220. auto it = req.headers.find("CustomClientHeader");
  2221. EXPECT_TRUE(it != req.headers.end());
  2222. EXPECT_EQ(it->second, "CustomClientValue");
  2223. res.set_content("Hello World!\n", "text/plain");
  2224. });
  2225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2226. auto se = detail::scope_exit([&] {
  2227. svr.stop();
  2228. thread.join();
  2229. ASSERT_FALSE(svr.is_running());
  2230. });
  2231. svr.wait_until_ready();
  2232. {
  2233. Client cli(HOST, PORT);
  2234. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2235. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2236. return detail::write_headers(strm, hdrs);
  2237. });
  2238. auto res = cli.Get("/hi");
  2239. EXPECT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. auto it = res->headers.find("CustomServerHeader");
  2242. EXPECT_TRUE(it != res->headers.end());
  2243. EXPECT_EQ(it->second, "CustomServerValue");
  2244. }
  2245. }
  2246. class ServerTest : public ::testing::Test {
  2247. protected:
  2248. ServerTest()
  2249. : cli_(HOST, PORT)
  2250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2251. ,
  2252. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2253. #endif
  2254. {
  2255. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2256. cli_.enable_server_certificate_verification(false);
  2257. #endif
  2258. }
  2259. virtual void SetUp() {
  2260. svr_.set_mount_point("/", "./www");
  2261. svr_.set_mount_point("/mount", "./www2");
  2262. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2263. svr_.Get("/hi",
  2264. [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. })
  2267. .Get("/file_content",
  2268. [&](const Request & /*req*/, Response &res) {
  2269. res.set_file_content("./www/dir/test.html");
  2270. })
  2271. .Get("/file_content_with_content_type",
  2272. [&](const Request & /*req*/, Response &res) {
  2273. res.set_file_content("./www/file", "text/plain");
  2274. })
  2275. .Get("/invalid_file_content",
  2276. [&](const Request & /*req*/, Response &res) {
  2277. res.set_file_content("./www/dir/invalid_file_path");
  2278. })
  2279. .Get("/http_response_splitting",
  2280. [&](const Request & /*req*/, Response &res) {
  2281. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2282. EXPECT_EQ(0U, res.headers.size());
  2283. EXPECT_FALSE(res.has_header("a"));
  2284. res.set_header("a", "1\nSet-Cookie: a=1");
  2285. EXPECT_EQ(0U, res.headers.size());
  2286. EXPECT_FALSE(res.has_header("a"));
  2287. res.set_header("a", "1\rSet-Cookie: a=1");
  2288. EXPECT_EQ(0U, res.headers.size());
  2289. EXPECT_FALSE(res.has_header("a"));
  2290. res.set_header("a\r\nb", "0");
  2291. EXPECT_EQ(0U, res.headers.size());
  2292. EXPECT_FALSE(res.has_header("a"));
  2293. res.set_header("a\rb", "0");
  2294. EXPECT_EQ(0U, res.headers.size());
  2295. EXPECT_FALSE(res.has_header("a"));
  2296. res.set_header("a\nb", "0");
  2297. EXPECT_EQ(0U, res.headers.size());
  2298. EXPECT_FALSE(res.has_header("a"));
  2299. res.set_redirect("1\r\nSet-Cookie: a=1");
  2300. EXPECT_EQ(0U, res.headers.size());
  2301. EXPECT_FALSE(res.has_header("Location"));
  2302. })
  2303. .Get("/slow",
  2304. [&](const Request & /*req*/, Response &res) {
  2305. std::this_thread::sleep_for(std::chrono::seconds(2));
  2306. res.set_content("slow", "text/plain");
  2307. })
  2308. #if 0
  2309. .Post("/slowpost",
  2310. [&](const Request & /*req*/, Response &res) {
  2311. std::this_thread::sleep_for(std::chrono::seconds(2));
  2312. res.set_content("slow", "text/plain");
  2313. })
  2314. #endif
  2315. .Get("/remote_addr",
  2316. [&](const Request &req, Response &res) {
  2317. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2318. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2319. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2320. EXPECT_EQ(req.remote_port,
  2321. std::stoi(req.get_header_value("REMOTE_PORT")));
  2322. res.set_content(remote_addr.c_str(), "text/plain");
  2323. })
  2324. .Get("/local_addr",
  2325. [&](const Request &req, Response &res) {
  2326. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2327. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2328. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2329. auto local_port = req.get_header_value("LOCAL_PORT");
  2330. EXPECT_EQ(req.local_addr, local_addr);
  2331. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2332. res.set_content(local_addr.append(":").append(local_port),
  2333. "text/plain");
  2334. })
  2335. .Get("/endwith%",
  2336. [&](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!", "text/plain");
  2338. })
  2339. .Get("/a\\+\\+b",
  2340. [&](const Request &req, Response &res) {
  2341. ASSERT_TRUE(req.has_param("a +b"));
  2342. auto val = req.get_param_value("a +b");
  2343. res.set_content(val, "text/plain");
  2344. })
  2345. .Get("/", [&](const Request & /*req*/,
  2346. Response &res) { res.set_redirect("/hi"); })
  2347. .Post("/1",
  2348. [](const Request & /*req*/, Response &res) {
  2349. res.set_redirect("/2", StatusCode::SeeOther_303);
  2350. })
  2351. .Get("/2",
  2352. [](const Request & /*req*/, Response &res) {
  2353. res.set_content("redirected.", "text/plain");
  2354. res.status = StatusCode::OK_200;
  2355. })
  2356. .Post("/person",
  2357. [&](const Request &req, Response &res) {
  2358. if (req.has_param("name") && req.has_param("note")) {
  2359. persons_[req.get_param_value("name")] =
  2360. req.get_param_value("note");
  2361. } else {
  2362. res.status = StatusCode::BadRequest_400;
  2363. }
  2364. })
  2365. .Put("/person",
  2366. [&](const Request &req, Response &res) {
  2367. if (req.has_param("name") && req.has_param("note")) {
  2368. persons_[req.get_param_value("name")] =
  2369. req.get_param_value("note");
  2370. } else {
  2371. res.status = StatusCode::BadRequest_400;
  2372. }
  2373. })
  2374. .Get("/person/(.*)",
  2375. [&](const Request &req, Response &res) {
  2376. string name = req.matches[1];
  2377. if (persons_.find(name) != persons_.end()) {
  2378. auto note = persons_[name];
  2379. res.set_content(note, "text/plain");
  2380. } else {
  2381. res.status = StatusCode::NotFound_404;
  2382. }
  2383. })
  2384. .Delete("/person",
  2385. [&](const Request &req, Response &res) {
  2386. if (req.has_param("name")) {
  2387. string name = req.get_param_value("name");
  2388. if (persons_.find(name) != persons_.end()) {
  2389. persons_.erase(name);
  2390. res.set_content("DELETED", "text/plain");
  2391. } else {
  2392. res.status = StatusCode::NotFound_404;
  2393. }
  2394. } else {
  2395. res.status = StatusCode::BadRequest_400;
  2396. }
  2397. })
  2398. .Post("/x-www-form-urlencoded-json",
  2399. [&](const Request &req, Response &res) {
  2400. auto json = req.get_param_value("json");
  2401. ASSERT_EQ(JSON_DATA, json);
  2402. res.set_content(json, "appliation/json");
  2403. res.status = StatusCode::OK_200;
  2404. })
  2405. .Get("/streamed-chunked",
  2406. [&](const Request & /*req*/, Response &res) {
  2407. res.set_chunked_content_provider(
  2408. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2409. sink.os << "123";
  2410. sink.os << "456";
  2411. sink.os << "789";
  2412. sink.done();
  2413. return true;
  2414. });
  2415. })
  2416. .Get("/streamed-chunked2",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. auto i = new int(0);
  2419. res.set_chunked_content_provider(
  2420. "text/plain",
  2421. [i](size_t /*offset*/, DataSink &sink) {
  2422. switch (*i) {
  2423. case 0: sink.os << "123"; break;
  2424. case 1: sink.os << "456"; break;
  2425. case 2: sink.os << "789"; break;
  2426. case 3: sink.done(); break;
  2427. }
  2428. (*i)++;
  2429. return true;
  2430. },
  2431. [i](bool success) {
  2432. EXPECT_TRUE(success);
  2433. delete i;
  2434. });
  2435. })
  2436. .Get("/streamed-chunked-with-trailer",
  2437. [&](const Request & /*req*/, Response &res) {
  2438. auto i = new int(0);
  2439. res.set_header("Trailer", "Dummy1, Dummy2");
  2440. res.set_chunked_content_provider(
  2441. "text/plain",
  2442. [i](size_t /*offset*/, DataSink &sink) {
  2443. switch (*i) {
  2444. case 0: sink.os << "123"; break;
  2445. case 1: sink.os << "456"; break;
  2446. case 2: sink.os << "789"; break;
  2447. case 3: {
  2448. sink.done_with_trailer(
  2449. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2450. } break;
  2451. }
  2452. (*i)++;
  2453. return true;
  2454. },
  2455. [i](bool success) {
  2456. EXPECT_TRUE(success);
  2457. delete i;
  2458. });
  2459. })
  2460. .Get("/streamed",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. 6, "text/plain",
  2464. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2465. sink.os << (offset < 3 ? "a" : "b");
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/streamed-with-range",
  2470. [&](const Request &req, Response &res) {
  2471. auto data = new std::string("abcdefg");
  2472. res.set_content_provider(
  2473. data->size(), "text/plain",
  2474. [data](size_t offset, size_t length, DataSink &sink) {
  2475. size_t DATA_CHUNK_SIZE = 4;
  2476. const auto &d = *data;
  2477. auto out_len =
  2478. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2479. auto ret =
  2480. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2481. EXPECT_TRUE(ret);
  2482. return true;
  2483. },
  2484. [data, &req](bool success) {
  2485. EXPECT_EQ(success, !req.has_param("error"));
  2486. delete data;
  2487. });
  2488. })
  2489. .Get("/streamed-cancel",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_content_provider(
  2492. size_t(-1), "text/plain",
  2493. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2494. sink.os << "data_chunk";
  2495. return true;
  2496. });
  2497. })
  2498. .Get("/regex-with-delimiter",
  2499. [&](const Request &req, Response & /*res*/) {
  2500. ASSERT_TRUE(req.has_param("key"));
  2501. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2502. })
  2503. .Get("/with-range",
  2504. [&](const Request & /*req*/, Response &res) {
  2505. res.set_content("abcdefg", "text/plain");
  2506. })
  2507. .Get("/with-range-customized-response",
  2508. [&](const Request & /*req*/, Response &res) {
  2509. res.status = StatusCode::BadRequest_400;
  2510. res.set_content(JSON_DATA, "application/json");
  2511. })
  2512. .Post("/chunked",
  2513. [&](const Request &req, Response & /*res*/) {
  2514. EXPECT_EQ(req.body, "dechunked post body");
  2515. })
  2516. .Post("/large-chunked",
  2517. [&](const Request &req, Response & /*res*/) {
  2518. std::string expected(6 * 30 * 1024u, 'a');
  2519. EXPECT_EQ(req.body, expected);
  2520. })
  2521. .Post("/multipart",
  2522. [&](const Request &req, Response & /*res*/) {
  2523. EXPECT_EQ(6u, req.files.size());
  2524. ASSERT_TRUE(!req.has_file("???"));
  2525. ASSERT_TRUE(req.body.empty());
  2526. {
  2527. const auto &file = req.get_file_value("text1");
  2528. EXPECT_TRUE(file.filename.empty());
  2529. EXPECT_EQ("text default", file.content);
  2530. }
  2531. {
  2532. const auto &file = req.get_file_value("text2");
  2533. EXPECT_TRUE(file.filename.empty());
  2534. EXPECT_EQ("aωb", file.content);
  2535. }
  2536. {
  2537. const auto &file = req.get_file_value("file1");
  2538. EXPECT_EQ("hello.txt", file.filename);
  2539. EXPECT_EQ("text/plain", file.content_type);
  2540. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2541. }
  2542. {
  2543. const auto &file = req.get_file_value("file3");
  2544. EXPECT_TRUE(file.filename.empty());
  2545. EXPECT_EQ("application/octet-stream", file.content_type);
  2546. EXPECT_EQ(0u, file.content.size());
  2547. }
  2548. {
  2549. const auto &file = req.get_file_value("file4");
  2550. EXPECT_TRUE(file.filename.empty());
  2551. EXPECT_EQ(0u, file.content.size());
  2552. EXPECT_EQ("application/json tmp-string", file.content_type);
  2553. }
  2554. })
  2555. .Post("/multipart/multi_file_values",
  2556. [&](const Request &req, Response & /*res*/) {
  2557. EXPECT_EQ(5u, req.files.size());
  2558. ASSERT_TRUE(!req.has_file("???"));
  2559. ASSERT_TRUE(req.body.empty());
  2560. {
  2561. const auto &text_value = req.get_file_values("text");
  2562. EXPECT_EQ(1u, text_value.size());
  2563. auto &text = text_value[0];
  2564. EXPECT_TRUE(text.filename.empty());
  2565. EXPECT_EQ("default text", text.content);
  2566. }
  2567. {
  2568. const auto &text1_values = req.get_file_values("multi_text1");
  2569. EXPECT_EQ(2u, text1_values.size());
  2570. EXPECT_EQ("aaaaa", text1_values[0].content);
  2571. EXPECT_EQ("bbbbb", text1_values[1].content);
  2572. }
  2573. {
  2574. const auto &file1_values = req.get_file_values("multi_file1");
  2575. EXPECT_EQ(2u, file1_values.size());
  2576. auto file1 = file1_values[0];
  2577. EXPECT_EQ(file1.filename, "hello.txt");
  2578. EXPECT_EQ(file1.content_type, "text/plain");
  2579. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2580. auto file2 = file1_values[1];
  2581. EXPECT_EQ(file2.filename, "world.json");
  2582. EXPECT_EQ(file2.content_type, "application/json");
  2583. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2584. }
  2585. })
  2586. .Post("/empty",
  2587. [&](const Request &req, Response &res) {
  2588. EXPECT_EQ(req.body, "");
  2589. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2590. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2591. res.set_content("empty", "text/plain");
  2592. })
  2593. .Post("/empty-no-content-type",
  2594. [&](const Request &req, Response &res) {
  2595. EXPECT_EQ(req.body, "");
  2596. EXPECT_FALSE(req.has_header("Content-Type"));
  2597. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2598. res.set_content("empty-no-content-type", "text/plain");
  2599. })
  2600. .Post("/path-only",
  2601. [&](const Request &req, Response &res) {
  2602. EXPECT_EQ(req.body, "");
  2603. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2604. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2605. res.set_content("path-only", "text/plain");
  2606. })
  2607. .Post("/path-headers-only",
  2608. [&](const Request &req, Response &res) {
  2609. EXPECT_EQ(req.body, "");
  2610. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2611. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2612. EXPECT_EQ("world", req.get_header_value("hello"));
  2613. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2614. res.set_content("path-headers-only", "text/plain");
  2615. })
  2616. .Post("/post-large",
  2617. [&](const Request &req, Response &res) {
  2618. EXPECT_EQ(req.body, LARGE_DATA);
  2619. res.set_content(req.body, "text/plain");
  2620. })
  2621. .Put("/empty-no-content-type",
  2622. [&](const Request &req, Response &res) {
  2623. EXPECT_EQ(req.body, "");
  2624. EXPECT_FALSE(req.has_header("Content-Type"));
  2625. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2626. res.set_content("empty-no-content-type", "text/plain");
  2627. })
  2628. .Put("/put",
  2629. [&](const Request &req, Response &res) {
  2630. EXPECT_EQ(req.body, "PUT");
  2631. res.set_content(req.body, "text/plain");
  2632. })
  2633. .Put("/put-large",
  2634. [&](const Request &req, Response &res) {
  2635. EXPECT_EQ(req.body, LARGE_DATA);
  2636. res.set_content(req.body, "text/plain");
  2637. })
  2638. .Patch("/patch",
  2639. [&](const Request &req, Response &res) {
  2640. EXPECT_EQ(req.body, "PATCH");
  2641. res.set_content(req.body, "text/plain");
  2642. })
  2643. .Delete("/delete",
  2644. [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("DELETE", "text/plain");
  2646. })
  2647. .Delete("/delete-body",
  2648. [&](const Request &req, Response &res) {
  2649. EXPECT_EQ(req.body, "content");
  2650. res.set_content(req.body, "text/plain");
  2651. })
  2652. .Options(R"(\*)",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2655. })
  2656. .Get("/request-target",
  2657. [&](const Request &req, Response & /*res*/) {
  2658. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2659. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2660. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2661. })
  2662. .Get("/long-query-value",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2665. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2666. })
  2667. .Get("/too-long-query-value",
  2668. [&](const Request &req, Response & /*res*/) {
  2669. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2670. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2671. })
  2672. .Get("/array-param",
  2673. [&](const Request &req, Response & /*res*/) {
  2674. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2675. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2676. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2677. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2678. })
  2679. .Post("/validate-no-multiple-headers",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2682. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2683. })
  2684. .Post("/content_receiver",
  2685. [&](const Request &req, Response &res,
  2686. const ContentReader &content_reader) {
  2687. if (req.is_multipart_form_data()) {
  2688. MultipartFormDataItems files;
  2689. content_reader(
  2690. [&](const MultipartFormData &file) {
  2691. files.push_back(file);
  2692. return true;
  2693. },
  2694. [&](const char *data, size_t data_length) {
  2695. files.back().content.append(data, data_length);
  2696. return true;
  2697. });
  2698. EXPECT_EQ(5u, files.size());
  2699. {
  2700. const auto &file = get_file_value(files, "text1");
  2701. EXPECT_TRUE(file.filename.empty());
  2702. EXPECT_EQ("text default", file.content);
  2703. }
  2704. {
  2705. const auto &file = get_file_value(files, "text2");
  2706. EXPECT_TRUE(file.filename.empty());
  2707. EXPECT_EQ("aωb", file.content);
  2708. }
  2709. {
  2710. const auto &file = get_file_value(files, "file1");
  2711. EXPECT_EQ("hello.txt", file.filename);
  2712. EXPECT_EQ("text/plain", file.content_type);
  2713. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2714. }
  2715. {
  2716. const auto &file = get_file_value(files, "file3");
  2717. EXPECT_TRUE(file.filename.empty());
  2718. EXPECT_EQ("application/octet-stream", file.content_type);
  2719. EXPECT_EQ(0u, file.content.size());
  2720. }
  2721. } else {
  2722. std::string body;
  2723. content_reader([&](const char *data, size_t data_length) {
  2724. EXPECT_EQ(7U, data_length);
  2725. body.append(data, data_length);
  2726. return true;
  2727. });
  2728. EXPECT_EQ(body, "content");
  2729. res.set_content(body, "text/plain");
  2730. }
  2731. })
  2732. .Put("/content_receiver",
  2733. [&](const Request & /*req*/, Response &res,
  2734. const ContentReader &content_reader) {
  2735. std::string body;
  2736. content_reader([&](const char *data, size_t data_length) {
  2737. body.append(data, data_length);
  2738. return true;
  2739. });
  2740. EXPECT_EQ(body, "content");
  2741. res.set_content(body, "text/plain");
  2742. })
  2743. .Patch("/content_receiver",
  2744. [&](const Request & /*req*/, Response &res,
  2745. const ContentReader &content_reader) {
  2746. std::string body;
  2747. content_reader([&](const char *data, size_t data_length) {
  2748. body.append(data, data_length);
  2749. return true;
  2750. });
  2751. EXPECT_EQ(body, "content");
  2752. res.set_content(body, "text/plain");
  2753. })
  2754. .Post("/query-string-and-body",
  2755. [&](const Request &req, Response & /*res*/) {
  2756. ASSERT_TRUE(req.has_param("key"));
  2757. EXPECT_EQ(req.get_param_value("key"), "value");
  2758. EXPECT_EQ(req.body, "content");
  2759. })
  2760. .Get("/last-request",
  2761. [&](const Request &req, Response & /*res*/) {
  2762. EXPECT_EQ("close", req.get_header_value("Connection"));
  2763. })
  2764. .Get(R"(/redirect/(\d+))",
  2765. [&](const Request &req, Response &res) {
  2766. auto num = std::stoi(req.matches[1]) + 1;
  2767. std::string url = "/redirect/" + std::to_string(num);
  2768. res.set_redirect(url);
  2769. })
  2770. .Post("/binary",
  2771. [&](const Request &req, Response &res) {
  2772. EXPECT_EQ(4U, req.body.size());
  2773. EXPECT_EQ("application/octet-stream",
  2774. req.get_header_value("Content-Type"));
  2775. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2776. res.set_content(req.body, "application/octet-stream");
  2777. })
  2778. .Put("/binary",
  2779. [&](const Request &req, Response &res) {
  2780. EXPECT_EQ(4U, req.body.size());
  2781. EXPECT_EQ("application/octet-stream",
  2782. req.get_header_value("Content-Type"));
  2783. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2784. res.set_content(req.body, "application/octet-stream");
  2785. })
  2786. .Patch("/binary",
  2787. [&](const Request &req, Response &res) {
  2788. EXPECT_EQ(4U, req.body.size());
  2789. EXPECT_EQ("application/octet-stream",
  2790. req.get_header_value("Content-Type"));
  2791. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2792. res.set_content(req.body, "application/octet-stream");
  2793. })
  2794. .Delete("/binary",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(4U, req.body.size());
  2797. EXPECT_EQ("application/octet-stream",
  2798. req.get_header_value("Content-Type"));
  2799. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2800. res.set_content(req.body, "application/octet-stream");
  2801. })
  2802. .Get("/issue1772",
  2803. [&](const Request & /*req*/, Response &res) {
  2804. res.status = 401;
  2805. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2806. })
  2807. .Delete("/issue609",
  2808. [](const httplib::Request &, httplib::Response &res,
  2809. const httplib::ContentReader &) {
  2810. res.set_content("ok", "text/plain");
  2811. })
  2812. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2813. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2814. .Get("/compress",
  2815. [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(
  2817. "12345678901234567890123456789012345678901234567890123456789"
  2818. "01234567890123456789012345678901234567890",
  2819. "text/plain");
  2820. })
  2821. .Get("/nocompress",
  2822. [&](const Request & /*req*/, Response &res) {
  2823. res.set_content(
  2824. "12345678901234567890123456789012345678901234567890123456789"
  2825. "01234567890123456789012345678901234567890",
  2826. "application/octet-stream");
  2827. })
  2828. .Post("/compress-multipart",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(2u, req.files.size());
  2831. ASSERT_TRUE(!req.has_file("???"));
  2832. {
  2833. const auto &file = req.get_file_value("key1");
  2834. EXPECT_TRUE(file.filename.empty());
  2835. EXPECT_EQ("test", file.content);
  2836. }
  2837. {
  2838. const auto &file = req.get_file_value("key2");
  2839. EXPECT_TRUE(file.filename.empty());
  2840. EXPECT_EQ("--abcdefg123", file.content);
  2841. }
  2842. })
  2843. #endif
  2844. ;
  2845. persons_["john"] = "programmer";
  2846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2847. svr_.wait_until_ready();
  2848. }
  2849. virtual void TearDown() {
  2850. svr_.stop();
  2851. if (!request_threads_.empty()) {
  2852. std::this_thread::sleep_for(std::chrono::seconds(1));
  2853. for (auto &t : request_threads_) {
  2854. t.join();
  2855. }
  2856. }
  2857. t_.join();
  2858. }
  2859. map<string, string> persons_;
  2860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2861. SSLClient cli_;
  2862. SSLServer svr_;
  2863. #else
  2864. Client cli_;
  2865. Server svr_;
  2866. #endif
  2867. thread t_;
  2868. std::vector<thread> request_threads_;
  2869. };
  2870. TEST_F(ServerTest, GetMethod200) {
  2871. auto res = cli_.Get("/hi");
  2872. ASSERT_TRUE(res);
  2873. EXPECT_EQ("HTTP/1.1", res->version);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. EXPECT_EQ("OK", res->reason);
  2876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2877. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2878. EXPECT_EQ("Hello World!", res->body);
  2879. }
  2880. void performance_test(const char *host) {
  2881. auto port = 1234;
  2882. Server svr;
  2883. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2884. res.set_content("Benchmark Response", "text/plain");
  2885. });
  2886. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  2887. auto se = detail::scope_exit([&] {
  2888. svr.stop();
  2889. listen_thread.join();
  2890. ASSERT_FALSE(svr.is_running());
  2891. });
  2892. svr.wait_until_ready();
  2893. Client cli(host, port);
  2894. auto start = std::chrono::high_resolution_clock::now();
  2895. auto res = cli.Get("/benchmark");
  2896. ASSERT_TRUE(res);
  2897. EXPECT_EQ(StatusCode::OK_200, res->status);
  2898. auto end = std::chrono::high_resolution_clock::now();
  2899. auto elapsed =
  2900. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2901. .count();
  2902. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  2903. << "ms (Issue #1777)";
  2904. }
  2905. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  2906. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  2907. TEST_F(ServerTest, GetEmptyFile) {
  2908. auto res = cli_.Get("/empty_file");
  2909. ASSERT_TRUE(res);
  2910. EXPECT_EQ(StatusCode::OK_200, res->status);
  2911. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2912. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2913. EXPECT_EQ("", res->body);
  2914. }
  2915. TEST_F(ServerTest, GetFileContent) {
  2916. auto res = cli_.Get("/file_content");
  2917. ASSERT_TRUE(res);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2920. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2921. EXPECT_EQ("test.html", res->body);
  2922. }
  2923. TEST_F(ServerTest, GetFileContentWithRange) {
  2924. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2925. ASSERT_TRUE(res);
  2926. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2927. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2928. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2929. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2930. EXPECT_EQ("est", res->body);
  2931. }
  2932. TEST_F(ServerTest, GetFileContentWithContentType) {
  2933. auto res = cli_.Get("/file_content_with_content_type");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2937. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2938. EXPECT_EQ("file\n", res->body);
  2939. }
  2940. TEST_F(ServerTest, GetInvalidFileContent) {
  2941. auto res = cli_.Get("/invalid_file_content");
  2942. ASSERT_TRUE(res);
  2943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2944. }
  2945. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2946. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2947. ASSERT_TRUE(res);
  2948. EXPECT_EQ("HTTP/1.1", res->version);
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2951. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2952. EXPECT_EQ("Hello World!", res->body);
  2953. }
  2954. TEST_F(ServerTest, GetMethod302) {
  2955. auto res = cli_.Get("/");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::Found_302, res->status);
  2958. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2959. }
  2960. TEST_F(ServerTest, GetMethod302Redirect) {
  2961. cli_.set_follow_location(true);
  2962. auto res = cli_.Get("/");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::OK_200, res->status);
  2965. EXPECT_EQ("Hello World!", res->body);
  2966. EXPECT_EQ("/hi", res->location);
  2967. }
  2968. TEST_F(ServerTest, GetMethod404) {
  2969. auto res = cli_.Get("/invalid");
  2970. ASSERT_TRUE(res);
  2971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2972. }
  2973. TEST_F(ServerTest, HeadMethod200) {
  2974. auto res = cli_.Head("/hi");
  2975. ASSERT_TRUE(res);
  2976. EXPECT_EQ(StatusCode::OK_200, res->status);
  2977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2978. EXPECT_TRUE(res->body.empty());
  2979. }
  2980. TEST_F(ServerTest, HeadMethod200Static) {
  2981. auto res = cli_.Head("/mount/dir/index.html");
  2982. ASSERT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2986. EXPECT_TRUE(res->body.empty());
  2987. }
  2988. TEST_F(ServerTest, HeadMethod404) {
  2989. auto res = cli_.Head("/invalid");
  2990. ASSERT_TRUE(res);
  2991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2992. EXPECT_TRUE(res->body.empty());
  2993. }
  2994. TEST_F(ServerTest, GetMethodPersonJohn) {
  2995. auto res = cli_.Get("/person/john");
  2996. ASSERT_TRUE(res);
  2997. EXPECT_EQ(StatusCode::OK_200, res->status);
  2998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2999. EXPECT_EQ("programmer", res->body);
  3000. }
  3001. TEST_F(ServerTest, PostMethod1) {
  3002. auto res = cli_.Get("/person/john1");
  3003. ASSERT_TRUE(res);
  3004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3005. res = cli_.Post("/person", "name=john1&note=coder",
  3006. "application/x-www-form-urlencoded");
  3007. ASSERT_TRUE(res);
  3008. ASSERT_EQ(StatusCode::OK_200, res->status);
  3009. res = cli_.Get("/person/john1");
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(StatusCode::OK_200, res->status);
  3012. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3013. ASSERT_EQ("coder", res->body);
  3014. }
  3015. TEST_F(ServerTest, PostMethod2) {
  3016. auto res = cli_.Get("/person/john2");
  3017. ASSERT_TRUE(res);
  3018. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3019. Params params;
  3020. params.emplace("name", "john2");
  3021. params.emplace("note", "coder");
  3022. res = cli_.Post("/person", params);
  3023. ASSERT_TRUE(res);
  3024. ASSERT_EQ(StatusCode::OK_200, res->status);
  3025. res = cli_.Get("/person/john2");
  3026. ASSERT_TRUE(res);
  3027. ASSERT_EQ(StatusCode::OK_200, res->status);
  3028. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3029. ASSERT_EQ("coder", res->body);
  3030. }
  3031. TEST_F(ServerTest, PutMethod3) {
  3032. auto res = cli_.Get("/person/john3");
  3033. ASSERT_TRUE(res);
  3034. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3035. Params params;
  3036. params.emplace("name", "john3");
  3037. params.emplace("note", "coder");
  3038. res = cli_.Put("/person", params);
  3039. ASSERT_TRUE(res);
  3040. ASSERT_EQ(StatusCode::OK_200, res->status);
  3041. res = cli_.Get("/person/john3");
  3042. ASSERT_TRUE(res);
  3043. ASSERT_EQ(StatusCode::OK_200, res->status);
  3044. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3045. ASSERT_EQ("coder", res->body);
  3046. }
  3047. TEST_F(ServerTest, DeleteMethod1) {
  3048. auto res = cli_.Get("/person/john4");
  3049. ASSERT_TRUE(res);
  3050. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3051. Params params;
  3052. params.emplace("name", "john4");
  3053. params.emplace("note", "coder");
  3054. res = cli_.Post("/person", params);
  3055. ASSERT_TRUE(res);
  3056. ASSERT_EQ(StatusCode::OK_200, res->status);
  3057. res = cli_.Get("/person/john4");
  3058. ASSERT_TRUE(res);
  3059. ASSERT_EQ(StatusCode::OK_200, res->status);
  3060. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3061. ASSERT_EQ("coder", res->body);
  3062. Params delete_params;
  3063. delete_params.emplace("name", "john4");
  3064. res = cli_.Delete("/person", delete_params);
  3065. ASSERT_TRUE(res);
  3066. ASSERT_EQ(StatusCode::OK_200, res->status);
  3067. ASSERT_EQ("DELETED", res->body);
  3068. res = cli_.Get("/person/john4");
  3069. ASSERT_TRUE(res);
  3070. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3071. }
  3072. TEST_F(ServerTest, DeleteMethod2) {
  3073. auto res = cli_.Get("/person/john5");
  3074. ASSERT_TRUE(res);
  3075. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3076. Params params;
  3077. params.emplace("name", "john5");
  3078. params.emplace("note", "developer");
  3079. res = cli_.Post("/person", params);
  3080. ASSERT_TRUE(res);
  3081. ASSERT_EQ(StatusCode::OK_200, res->status);
  3082. res = cli_.Get("/person/john5");
  3083. ASSERT_TRUE(res);
  3084. ASSERT_EQ(StatusCode::OK_200, res->status);
  3085. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3086. ASSERT_EQ("developer", res->body);
  3087. Params delete_params;
  3088. delete_params.emplace("name", "john5");
  3089. Headers headers;
  3090. headers.emplace("Custom-Header", "test-value");
  3091. res = cli_.Delete("/person", headers, delete_params);
  3092. ASSERT_TRUE(res);
  3093. ASSERT_EQ(StatusCode::OK_200, res->status);
  3094. ASSERT_EQ("DELETED", res->body);
  3095. res = cli_.Get("/person/john5");
  3096. ASSERT_TRUE(res);
  3097. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3098. }
  3099. TEST_F(ServerTest, DeleteMethod3) {
  3100. auto res = cli_.Get("/person/john6");
  3101. ASSERT_TRUE(res);
  3102. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3103. Params params;
  3104. params.emplace("name", "john6");
  3105. params.emplace("note", "tester");
  3106. res = cli_.Post("/person", params);
  3107. ASSERT_TRUE(res);
  3108. ASSERT_EQ(StatusCode::OK_200, res->status);
  3109. res = cli_.Get("/person/john6");
  3110. ASSERT_TRUE(res);
  3111. ASSERT_EQ(StatusCode::OK_200, res->status);
  3112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3113. ASSERT_EQ("tester", res->body);
  3114. Params delete_params;
  3115. delete_params.emplace("name", "john6");
  3116. Headers headers;
  3117. headers.emplace("Custom-Header", "test-value");
  3118. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3119. ASSERT_TRUE(res);
  3120. ASSERT_EQ(StatusCode::OK_200, res->status);
  3121. ASSERT_EQ("DELETED", res->body);
  3122. res = cli_.Get("/person/john6");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3125. }
  3126. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3127. Params params;
  3128. params.emplace("json", JSON_DATA);
  3129. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(StatusCode::OK_200, res->status);
  3132. ASSERT_EQ(JSON_DATA, res->body);
  3133. }
  3134. TEST_F(ServerTest, PostEmptyContent) {
  3135. auto res = cli_.Post("/empty", "", "text/plain");
  3136. ASSERT_TRUE(res);
  3137. ASSERT_EQ(StatusCode::OK_200, res->status);
  3138. ASSERT_EQ("empty", res->body);
  3139. }
  3140. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3141. auto res = cli_.Post("/empty-no-content-type");
  3142. ASSERT_TRUE(res);
  3143. ASSERT_EQ(StatusCode::OK_200, res->status);
  3144. ASSERT_EQ("empty-no-content-type", res->body);
  3145. }
  3146. TEST_F(ServerTest, PostPathOnly) {
  3147. auto res = cli_.Post("/path-only");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("path-only", res->body);
  3151. }
  3152. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3153. auto res = cli_.Post("/path-headers-only",
  3154. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::OK_200, res->status);
  3157. ASSERT_EQ("path-headers-only", res->body);
  3158. }
  3159. TEST_F(ServerTest, PostLarge) {
  3160. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3161. ASSERT_TRUE(res);
  3162. ASSERT_EQ(StatusCode::OK_200, res->status);
  3163. EXPECT_EQ(LARGE_DATA, res->body);
  3164. }
  3165. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3166. auto res = cli_.Put("/empty-no-content-type");
  3167. ASSERT_TRUE(res);
  3168. ASSERT_EQ(StatusCode::OK_200, res->status);
  3169. ASSERT_EQ("empty-no-content-type", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetMethodDir) {
  3172. auto res = cli_.Get("/dir/");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3176. auto body = R"(<html>
  3177. <head>
  3178. </head>
  3179. <body>
  3180. <a href="/dir/test.html">Test</a>
  3181. <a href="/hi">hi</a>
  3182. </body>
  3183. </html>
  3184. )";
  3185. EXPECT_EQ(body, res->body);
  3186. }
  3187. TEST_F(ServerTest, GetMethodDirTest) {
  3188. auto res = cli_.Get("/dir/test.html");
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3192. EXPECT_EQ("test.html", res->body);
  3193. }
  3194. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3195. auto res = cli_.Get("/dir/../dir/test.html");
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3199. EXPECT_EQ("test.html", res->body);
  3200. }
  3201. TEST_F(ServerTest, GetMethodInvalidPath) {
  3202. auto res = cli_.Get("/dir/../test.html");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3205. }
  3206. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3207. auto res = cli_.Get("/../www/dir/test.html");
  3208. ASSERT_TRUE(res);
  3209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3210. }
  3211. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3212. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3215. }
  3216. TEST_F(ServerTest, GetMethodDirMountTest) {
  3217. auto res = cli_.Get("/mount/dir/test.html");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("test.html", res->body);
  3222. }
  3223. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3224. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3228. EXPECT_EQ("test.html", res->body);
  3229. }
  3230. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3231. auto res = cli_.Get("/mount/dir/../test.html");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3234. }
  3235. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3236. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3239. }
  3240. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3241. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3246. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3249. }
  3250. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3251. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, PostMethod303) {
  3256. auto res = cli_.Post("/1", "body", "text/plain");
  3257. ASSERT_TRUE(res);
  3258. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3259. EXPECT_EQ("/2", res->get_header_value("Location"));
  3260. }
  3261. TEST_F(ServerTest, PostMethod303Redirect) {
  3262. cli_.set_follow_location(true);
  3263. auto res = cli_.Post("/1", "body", "text/plain");
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("redirected.", res->body);
  3267. EXPECT_EQ("/2", res->location);
  3268. }
  3269. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3270. auto res = cli_.Get("/dir/test.abcde");
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3274. EXPECT_EQ("abcde", res->body);
  3275. }
  3276. TEST_F(ServerTest, StaticFileRange) {
  3277. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3280. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3281. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3282. EXPECT_EQ(true, res->has_header("Content-Range"));
  3283. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3284. EXPECT_EQ(std::string("cd"), res->body);
  3285. }
  3286. TEST_F(ServerTest, StaticFileRanges) {
  3287. auto res =
  3288. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3291. EXPECT_TRUE(
  3292. res->get_header_value("Content-Type")
  3293. .find(
  3294. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3295. 0);
  3296. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3297. }
  3298. TEST_F(ServerTest, StaticFileRangeHead) {
  3299. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3302. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ(true, res->has_header("Content-Range"));
  3305. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3306. }
  3307. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3308. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3312. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3313. EXPECT_EQ(true, res->has_header("Content-Range"));
  3314. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3315. res->get_header_value("Content-Range"));
  3316. EXPECT_EQ("LAST\n", res->body);
  3317. }
  3318. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3319. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3324. EXPECT_EQ(true, res->has_header("Content-Range"));
  3325. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3326. }
  3327. TEST_F(ServerTest, StaticFileBigFile) {
  3328. auto res = cli_.Get("/dir/1MB.txt");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3333. }
  3334. TEST_F(ServerTest, InvalidBaseDirMount) {
  3335. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3336. }
  3337. TEST_F(ServerTest, Binary) {
  3338. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3339. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3340. "application/octet-stream");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ(4U, res->body.size());
  3344. res = cli_.Put("/binary", binary.data(), binary.size(),
  3345. "application/octet-stream");
  3346. ASSERT_TRUE(res);
  3347. ASSERT_EQ(StatusCode::OK_200, res->status);
  3348. ASSERT_EQ(4U, res->body.size());
  3349. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3350. "application/octet-stream");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ(4U, res->body.size());
  3354. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3355. "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, BinaryString) {
  3361. auto binary = std::string("\x00\x01\x02\x03", 4);
  3362. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3363. ASSERT_TRUE(res);
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. ASSERT_EQ(4U, res->body.size());
  3366. res = cli_.Put("/binary", binary, "application/octet-stream");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ(4U, res->body.size());
  3370. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::OK_200, res->status);
  3373. ASSERT_EQ(4U, res->body.size());
  3374. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3375. ASSERT_TRUE(res);
  3376. ASSERT_EQ(StatusCode::OK_200, res->status);
  3377. ASSERT_EQ(4U, res->body.size());
  3378. }
  3379. TEST_F(ServerTest, EmptyRequest) {
  3380. auto res = cli_.Get("");
  3381. ASSERT_TRUE(!res);
  3382. EXPECT_EQ(Error::Connection, res.error());
  3383. }
  3384. TEST_F(ServerTest, LongRequest) {
  3385. std::string request;
  3386. for (size_t i = 0; i < 545; i++) {
  3387. request += "/TooLongRequest";
  3388. }
  3389. request += "OK";
  3390. auto res = cli_.Get(request.c_str());
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, TooLongRequest) {
  3395. std::string request;
  3396. for (size_t i = 0; i < 546; i++) {
  3397. request += "/TooLongRequest";
  3398. }
  3399. request += "_NG";
  3400. auto res = cli_.Get(request.c_str());
  3401. ASSERT_TRUE(res);
  3402. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3403. }
  3404. TEST_F(ServerTest, AlmostTooLongRequest) {
  3405. // test for #2046 - URI length check shouldn't include other content on req
  3406. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3407. // leading /, space, HTTP/1.1)
  3408. std::string request =
  3409. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3410. auto res = cli_.Get(request.c_str());
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3413. }
  3414. TEST_F(ServerTest, LongHeader) {
  3415. Request req;
  3416. req.method = "GET";
  3417. req.path = "/hi";
  3418. std::string host_and_port;
  3419. host_and_port += HOST;
  3420. host_and_port += ":";
  3421. host_and_port += std::to_string(PORT);
  3422. req.headers.emplace("Host", host_and_port.c_str());
  3423. req.headers.emplace("Accept", "*/*");
  3424. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3425. req.headers.emplace(
  3426. "Header-Name",
  3427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3455. "@@@@@@@@@@@@@@@@");
  3456. auto res = std::make_shared<Response>();
  3457. auto error = Error::Success;
  3458. auto ret = cli_.send(req, *res, error);
  3459. ASSERT_TRUE(ret);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. }
  3462. TEST_F(ServerTest, LongQueryValue) {
  3463. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3466. }
  3467. TEST_F(ServerTest, TooLongQueryValue) {
  3468. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3469. ASSERT_FALSE(res);
  3470. EXPECT_EQ(Error::Read, res.error());
  3471. }
  3472. TEST_F(ServerTest, TooLongHeader) {
  3473. Request req;
  3474. req.method = "GET";
  3475. req.path = "/hi";
  3476. std::string host_and_port;
  3477. host_and_port += HOST;
  3478. host_and_port += ":";
  3479. host_and_port += std::to_string(PORT);
  3480. req.headers.emplace("Host", host_and_port.c_str());
  3481. req.headers.emplace("Accept", "*/*");
  3482. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3483. req.headers.emplace(
  3484. "Header-Name",
  3485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3513. "@@@@@@@@@@@@@@@@@");
  3514. auto res = std::make_shared<Response>();
  3515. auto error = Error::Success;
  3516. auto ret = cli_.send(req, *res, error);
  3517. ASSERT_TRUE(ret);
  3518. EXPECT_EQ(StatusCode::OK_200, res->status);
  3519. }
  3520. TEST_F(ServerTest, HeaderCountAtLimit) {
  3521. // Test with headers just under the 100 limit
  3522. httplib::Headers headers;
  3523. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3524. // This should keep us just under the 100 header limit
  3525. for (int i = 0; i < 95; i++) {
  3526. std::string name = "X-Test-Header-" + std::to_string(i);
  3527. std::string value = "value" + std::to_string(i);
  3528. headers.emplace(name, value);
  3529. }
  3530. // This should work fine as we're under the limit
  3531. auto res = cli_.Get("/hi", headers);
  3532. EXPECT_TRUE(res);
  3533. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3534. }
  3535. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3536. // Test with many headers to exceed the 100 limit
  3537. httplib::Headers headers;
  3538. // Add 150 headers to definitely exceed the 100 limit
  3539. for (int i = 0; i < 150; i++) {
  3540. std::string name = "X-Test-Header-" + std::to_string(i);
  3541. std::string value = "value" + std::to_string(i);
  3542. headers.emplace(name, value);
  3543. }
  3544. // This should fail due to exceeding header count limit
  3545. auto res = cli_.Get("/hi", headers);
  3546. // The request should either fail or return 400 Bad Request
  3547. if (res) {
  3548. // If we get a response, it should be 400 Bad Request
  3549. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3550. } else {
  3551. // Or the request should fail entirely
  3552. EXPECT_FALSE(res);
  3553. }
  3554. }
  3555. TEST_F(ServerTest, PercentEncoding) {
  3556. auto res = cli_.Get("/e%6edwith%");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. TEST_F(ServerTest, PercentEncodingUnicode) {
  3561. auto res = cli_.Get("/e%u006edwith%");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. }
  3565. TEST_F(ServerTest, InvalidPercentEncoding) {
  3566. auto res = cli_.Get("/%endwith%");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3569. }
  3570. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3571. auto res = cli_.Get("/%uendwith%");
  3572. ASSERT_TRUE(res);
  3573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3574. }
  3575. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3576. auto res = cli_.Get("/hello?aaa=bbb%");
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3579. }
  3580. TEST_F(ServerTest, PlusSignEncoding) {
  3581. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ("a +b", res->body);
  3585. }
  3586. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3587. // This test simulates a potential DoS attack using many headers
  3588. // to verify our security fix prevents memory exhaustion
  3589. httplib::Headers attack_headers;
  3590. // Attempt to add many headers like an attacker would (200 headers to far
  3591. // exceed limit)
  3592. for (int i = 0; i < 200; i++) {
  3593. std::string name = "X-Attack-Header-" + std::to_string(i);
  3594. std::string value = "attack_payload_" + std::to_string(i);
  3595. attack_headers.emplace(name, value);
  3596. }
  3597. // Try to POST with excessive headers
  3598. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3599. // Should either fail or return 400 Bad Request due to security limit
  3600. if (res) {
  3601. // If we get a response, it should be 400 Bad Request
  3602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3603. } else {
  3604. // Request failed, which is the expected behavior for DoS protection
  3605. EXPECT_FALSE(res);
  3606. }
  3607. }
  3608. TEST_F(ServerTest, MultipartFormData) {
  3609. MultipartFormDataItemsForClientInput items = {
  3610. {"text1", "text default", "", ""},
  3611. {"text2", "aωb", "", ""},
  3612. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3613. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3614. {"file3", "", "", "application/octet-stream"},
  3615. {"file4", "", "", " application/json tmp-string "}};
  3616. auto res = cli_.Post("/multipart", items);
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. }
  3620. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3621. MultipartFormDataItemsForClientInput items = {
  3622. {"text", "default text", "", ""},
  3623. {"multi_text1", "aaaaa", "", ""},
  3624. {"multi_text1", "bbbbb", "", ""},
  3625. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3626. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3627. "application/json"},
  3628. };
  3629. auto res = cli_.Post("/multipart/multi_file_values", items);
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. }
  3633. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3634. auto res = cli_.Get("/hi");
  3635. ASSERT_TRUE(res);
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3638. EXPECT_EQ("Hello World!", res->body);
  3639. }
  3640. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3641. Request req;
  3642. req.method = "POST";
  3643. req.path = "/chunked";
  3644. std::string host_and_port;
  3645. host_and_port += HOST;
  3646. host_and_port += ":";
  3647. host_and_port += std::to_string(PORT);
  3648. req.headers.emplace("Host", host_and_port.c_str());
  3649. req.headers.emplace("Accept", "*/*");
  3650. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3651. req.headers.emplace("Content-Type", "text/plain");
  3652. req.headers.emplace("Content-Length", "0");
  3653. req.headers.emplace(
  3654. "Transfer-Encoding",
  3655. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3656. // Client does not chunk, so make a chunked body manually.
  3657. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3658. auto res = std::make_shared<Response>();
  3659. auto error = Error::Success;
  3660. auto ret = cli_.send(req, *res, error);
  3661. ASSERT_TRUE(ret);
  3662. EXPECT_EQ(StatusCode::OK_200, res->status);
  3663. }
  3664. TEST_F(ServerTest, GetStreamed2) {
  3665. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3668. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3669. EXPECT_EQ(true, res->has_header("Content-Range"));
  3670. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3671. EXPECT_EQ(std::string("ab"), res->body);
  3672. }
  3673. TEST_F(ServerTest, GetStreamed) {
  3674. auto res = cli_.Get("/streamed");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::OK_200, res->status);
  3677. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3678. EXPECT_EQ(std::string("aaabbb"), res->body);
  3679. }
  3680. TEST_F(ServerTest, GetStreamedWithRange1) {
  3681. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3684. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3685. EXPECT_EQ(true, res->has_header("Content-Range"));
  3686. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3687. EXPECT_EQ(std::string("def"), res->body);
  3688. }
  3689. TEST_F(ServerTest, GetStreamedWithRange2) {
  3690. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3693. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3694. EXPECT_EQ(true, res->has_header("Content-Range"));
  3695. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3696. EXPECT_EQ(std::string("bcdefg"), res->body);
  3697. }
  3698. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3699. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3702. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3703. EXPECT_EQ(true, res->has_header("Content-Range"));
  3704. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3705. EXPECT_EQ(std::string("efg"), res->body);
  3706. }
  3707. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3708. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3711. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3712. EXPECT_EQ(false, res->has_header("Content-Range"));
  3713. EXPECT_EQ(0U, res->body.size());
  3714. }
  3715. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3716. auto res = cli_.Get("/streamed-with-range",
  3717. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3718. "92233720368547758079223372036854775807"}});
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3721. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3722. EXPECT_EQ(false, res->has_header("Content-Range"));
  3723. EXPECT_EQ(0U, res->body.size());
  3724. }
  3725. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3726. auto res = cli_.Get(
  3727. "/with-range",
  3728. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3729. {"Accept-Encoding", ""}});
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3733. EXPECT_EQ(true, res->has_header("Content-Range"));
  3734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3735. EXPECT_EQ(std::string("abcdefg"), res->body);
  3736. }
  3737. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3738. auto res = cli_.Get("/with-range", {
  3739. {"Range", "bytes=0-"},
  3740. {"Accept-Encoding", ""},
  3741. });
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3744. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ(true, res->has_header("Content-Range"));
  3746. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3747. EXPECT_EQ(std::string("abcdefg"), res->body);
  3748. }
  3749. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3750. auto res =
  3751. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3754. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3755. EXPECT_EQ(false, res->has_header("Content-Range"));
  3756. EXPECT_EQ(267U, res->body.size());
  3757. // Check that both range contents are present
  3758. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3759. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3760. // Check that Content-Range headers are present for both ranges
  3761. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3762. std::string::npos);
  3763. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3764. std::string::npos);
  3765. }
  3766. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3767. Ranges ranges;
  3768. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3769. ranges.emplace_back(0, -1);
  3770. }
  3771. auto res =
  3772. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3775. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(false, res->has_header("Content-Range"));
  3777. EXPECT_EQ(0U, res->body.size());
  3778. }
  3779. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3780. auto res =
  3781. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3784. EXPECT_EQ(5U, res->body.size());
  3785. // Check that overlapping ranges are coalesced into a single range
  3786. EXPECT_EQ("bcdef", res->body);
  3787. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3788. // Should be single range, not multipart
  3789. EXPECT_TRUE(res->has_header("Content-Range"));
  3790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3791. }
  3792. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3793. auto res =
  3794. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3797. EXPECT_EQ(268U, res->body.size());
  3798. // Check that both range contents are present
  3799. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3800. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3801. // Check that Content-Range headers are present for both ranges
  3802. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3803. std::string::npos);
  3804. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3805. std::string::npos);
  3806. }
  3807. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3808. auto res =
  3809. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3812. EXPECT_EQ(269U, res->body.size());
  3813. // Check that both duplicate range contents are present
  3814. size_t first_abc = res->body.find("abc\r\n");
  3815. EXPECT_TRUE(first_abc != std::string::npos);
  3816. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3817. EXPECT_TRUE(second_abc != std::string::npos);
  3818. // Check that Content-Range headers are present for both ranges
  3819. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3820. EXPECT_TRUE(first_range != std::string::npos);
  3821. size_t second_range =
  3822. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3823. EXPECT_TRUE(second_range != std::string::npos);
  3824. }
  3825. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3826. auto res = cli_.Get("/streamed-with-range?error",
  3827. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3830. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3831. EXPECT_EQ(false, res->has_header("Content-Range"));
  3832. EXPECT_EQ(0U, res->body.size());
  3833. }
  3834. TEST_F(ServerTest, GetStreamedEndless) {
  3835. uint64_t offset = 0;
  3836. auto res = cli_.Get("/streamed-cancel",
  3837. [&](const char * /*data*/, uint64_t data_length) {
  3838. if (offset < 100) {
  3839. offset += data_length;
  3840. return true;
  3841. }
  3842. return false;
  3843. });
  3844. ASSERT_TRUE(!res);
  3845. EXPECT_EQ(Error::Canceled, res.error());
  3846. }
  3847. TEST_F(ServerTest, ClientStop) {
  3848. std::atomic_size_t count{4};
  3849. std::vector<std::thread> threads;
  3850. for (auto i = count.load(); i != 0; --i) {
  3851. threads.emplace_back([&]() {
  3852. auto res = cli_.Get("/streamed-cancel",
  3853. [&](const char *, uint64_t) { return true; });
  3854. --count;
  3855. ASSERT_TRUE(!res);
  3856. EXPECT_TRUE(res.error() == Error::Canceled ||
  3857. res.error() == Error::Read || res.error() == Error::Write);
  3858. });
  3859. }
  3860. std::this_thread::sleep_for(std::chrono::seconds(2));
  3861. while (count != 0) {
  3862. cli_.stop();
  3863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3864. }
  3865. for (auto &t : threads) {
  3866. t.join();
  3867. }
  3868. }
  3869. TEST_F(ServerTest, GetWithRange1) {
  3870. auto res = cli_.Get("/with-range", {
  3871. make_range_header({{3, 5}}),
  3872. {"Accept-Encoding", ""},
  3873. });
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3876. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(true, res->has_header("Content-Range"));
  3878. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3879. EXPECT_EQ(std::string("def"), res->body);
  3880. }
  3881. TEST_F(ServerTest, GetWithRange2) {
  3882. auto res = cli_.Get("/with-range", {
  3883. make_range_header({{1, -1}}),
  3884. {"Accept-Encoding", ""},
  3885. });
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3888. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(true, res->has_header("Content-Range"));
  3890. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3891. EXPECT_EQ(std::string("bcdefg"), res->body);
  3892. }
  3893. TEST_F(ServerTest, GetWithRange3) {
  3894. auto res = cli_.Get("/with-range", {
  3895. make_range_header({{0, 0}}),
  3896. {"Accept-Encoding", ""},
  3897. });
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3900. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3901. EXPECT_EQ(true, res->has_header("Content-Range"));
  3902. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3903. EXPECT_EQ(std::string("a"), res->body);
  3904. }
  3905. TEST_F(ServerTest, GetWithRange4) {
  3906. auto res = cli_.Get("/with-range", {
  3907. make_range_header({{-1, 2}}),
  3908. {"Accept-Encoding", ""},
  3909. });
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3912. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3913. EXPECT_EQ(true, res->has_header("Content-Range"));
  3914. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3915. EXPECT_EQ(std::string("fg"), res->body);
  3916. }
  3917. TEST_F(ServerTest, GetWithRange5) {
  3918. auto res = cli_.Get("/with-range", {
  3919. make_range_header({{0, 5}}),
  3920. {"Accept-Encoding", ""},
  3921. });
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3924. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3925. EXPECT_EQ(true, res->has_header("Content-Range"));
  3926. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3927. EXPECT_EQ(std::string("abcdef"), res->body);
  3928. }
  3929. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3930. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3933. }
  3934. TEST_F(ServerTest, GetWithRangeMultipart) {
  3935. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3938. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3939. EXPECT_EQ(false, res->has_header("Content-Range"));
  3940. EXPECT_EQ(267U, res->body.size());
  3941. }
  3942. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3943. auto res =
  3944. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3947. }
  3948. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3949. auto res = cli_.Get("/with-range-customized-response",
  3950. {{make_range_header({{1, 2}})}});
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3953. EXPECT_EQ(true, res->has_header("Content-Length"));
  3954. EXPECT_EQ(false, res->has_header("Content-Range"));
  3955. EXPECT_EQ(JSON_DATA, res->body);
  3956. }
  3957. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3958. auto res = cli_.Get("/with-range-customized-response",
  3959. {{make_range_header({{1, 2}, {4, 5}})}});
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3962. EXPECT_EQ(true, res->has_header("Content-Length"));
  3963. EXPECT_EQ(false, res->has_header("Content-Range"));
  3964. EXPECT_EQ(JSON_DATA, res->body);
  3965. }
  3966. TEST_F(ServerTest, Issue1772) {
  3967. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3968. ASSERT_TRUE(res);
  3969. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3970. }
  3971. TEST_F(ServerTest, Issue609) {
  3972. auto res = cli_.Delete("/issue609");
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::OK_200, res->status);
  3975. EXPECT_EQ(std::string("ok"), res->body);
  3976. }
  3977. TEST_F(ServerTest, GetStreamedChunked) {
  3978. auto res = cli_.Get("/streamed-chunked");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ(std::string("123456789"), res->body);
  3982. }
  3983. TEST_F(ServerTest, GetStreamedChunked2) {
  3984. auto res = cli_.Get("/streamed-chunked2");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ(std::string("123456789"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3990. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::OK_200, res->status);
  3993. EXPECT_EQ(std::string("123456789"), res->body);
  3994. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3995. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3996. }
  3997. TEST_F(ServerTest, LargeChunkedPost) {
  3998. Request req;
  3999. req.method = "POST";
  4000. req.path = "/large-chunked";
  4001. std::string host_and_port;
  4002. host_and_port += HOST;
  4003. host_and_port += ":";
  4004. host_and_port += std::to_string(PORT);
  4005. req.headers.emplace("Host", host_and_port.c_str());
  4006. req.headers.emplace("Accept", "*/*");
  4007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4008. req.headers.emplace("Content-Type", "text/plain");
  4009. req.headers.emplace("Content-Length", "0");
  4010. req.headers.emplace("Transfer-Encoding", "chunked");
  4011. std::string long_string(30 * 1024u, 'a');
  4012. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4013. // Attempt to make a large enough post to exceed OS buffers, to test that
  4014. // the server handles short reads if the full chunk data isn't available.
  4015. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4016. auto res = std::make_shared<Response>();
  4017. auto error = Error::Success;
  4018. auto ret = cli_.send(req, *res, error);
  4019. ASSERT_TRUE(ret);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. }
  4022. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4023. auto res = cli_.Get("/remote_addr");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4027. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4028. }
  4029. TEST_F(ServerTest, GetMethodLocalAddr) {
  4030. auto res = cli_.Get("/local_addr");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::OK_200, res->status);
  4033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4034. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4035. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4036. }
  4037. TEST_F(ServerTest, HTTPResponseSplitting) {
  4038. auto res = cli_.Get("/http_response_splitting");
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. TEST_F(ServerTest, SlowRequest) {
  4043. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4044. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4046. }
  4047. #if 0
  4048. TEST_F(ServerTest, SlowPost) {
  4049. char buffer[64 * 1024];
  4050. memset(buffer, 0x42, sizeof(buffer));
  4051. auto res = cli_.Post(
  4052. "/slowpost", 64 * 1024 * 1024,
  4053. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4054. auto ret = sink.write(buffer, sizeof(buffer));
  4055. EXPECT_TRUE(ret);
  4056. return true;
  4057. },
  4058. "text/plain");
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::OK_200, res->status);
  4061. }
  4062. TEST_F(ServerTest, SlowPostFail) {
  4063. char buffer[64 * 1024];
  4064. memset(buffer, 0x42, sizeof(buffer));
  4065. cli_.set_write_timeout(std::chrono::seconds(0));
  4066. auto res = cli_.Post(
  4067. "/slowpost", 64 * 1024 * 1024,
  4068. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4069. sink.write(buffer, sizeof(buffer));
  4070. return true;
  4071. },
  4072. "text/plain");
  4073. ASSERT_TRUE(!res);
  4074. EXPECT_EQ(Error::Write, res.error());
  4075. }
  4076. #endif
  4077. TEST_F(ServerTest, Put) {
  4078. auto res = cli_.Put("/put", "PUT", "text/plain");
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. EXPECT_EQ("PUT", res->body);
  4082. }
  4083. TEST_F(ServerTest, PutWithContentProvider) {
  4084. auto res = cli_.Put(
  4085. "/put", 3,
  4086. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4087. sink.os << "PUT";
  4088. return true;
  4089. },
  4090. "text/plain");
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("PUT", res->body);
  4094. }
  4095. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4096. auto res = cli_.Post(
  4097. "/post", 42,
  4098. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4099. return false;
  4100. },
  4101. "text/plain");
  4102. ASSERT_TRUE(!res);
  4103. EXPECT_EQ(Error::Canceled, res.error());
  4104. }
  4105. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4106. auto res = cli_.Put(
  4107. "/put",
  4108. [](size_t /*offset*/, DataSink &sink) {
  4109. sink.os << "PUT";
  4110. sink.done();
  4111. return true;
  4112. },
  4113. "text/plain");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. EXPECT_EQ("PUT", res->body);
  4117. }
  4118. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4119. auto res = cli_.Post(
  4120. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4121. "text/plain");
  4122. ASSERT_TRUE(!res);
  4123. EXPECT_EQ(Error::Canceled, res.error());
  4124. }
  4125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4126. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4127. cli_.set_compress(true);
  4128. auto res = cli_.Put(
  4129. "/put", 3,
  4130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4131. sink.os << "PUT";
  4132. return true;
  4133. },
  4134. "text/plain");
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::OK_200, res->status);
  4137. EXPECT_EQ("PUT", res->body);
  4138. }
  4139. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4140. cli_.set_compress(true);
  4141. auto res = cli_.Post(
  4142. "/post", 42,
  4143. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4144. return false;
  4145. },
  4146. "text/plain");
  4147. ASSERT_TRUE(!res);
  4148. EXPECT_EQ(Error::Canceled, res.error());
  4149. }
  4150. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4151. cli_.set_compress(true);
  4152. auto res = cli_.Put(
  4153. "/put",
  4154. [](size_t /*offset*/, DataSink &sink) {
  4155. sink.os << "PUT";
  4156. sink.done();
  4157. return true;
  4158. },
  4159. "text/plain");
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. EXPECT_EQ("PUT", res->body);
  4163. }
  4164. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4165. cli_.set_compress(true);
  4166. auto res = cli_.Post(
  4167. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4168. "text/plain");
  4169. ASSERT_TRUE(!res);
  4170. EXPECT_EQ(Error::Canceled, res.error());
  4171. }
  4172. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4173. cli_.set_compress(true);
  4174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. EXPECT_EQ(LARGE_DATA, res->body);
  4178. }
  4179. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4181. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4182. Client cli(s.c_str());
  4183. cli.enable_server_certificate_verification(false);
  4184. #else
  4185. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4186. Client cli(s.c_str());
  4187. #endif
  4188. cli.set_compress(true);
  4189. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ(LARGE_DATA, res->body);
  4193. // The compressed size should be less than a 10th of the original. May vary
  4194. // depending on the zlib library.
  4195. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4196. static_cast<uint64_t>(10 * 1024 * 1024));
  4197. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4198. }
  4199. TEST_F(ServerTest, PutContentWithDeflate) {
  4200. cli_.set_compress(false);
  4201. Headers headers;
  4202. headers.emplace("Content-Encoding", "deflate");
  4203. // PUT in deflate format:
  4204. auto res = cli_.Put("/put", headers,
  4205. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::OK_200, res->status);
  4208. EXPECT_EQ("PUT", res->body);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4211. Headers headers;
  4212. headers.emplace("Accept-Encoding", "gzip, deflate");
  4213. auto res = cli_.Get("/streamed-chunked", headers);
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::OK_200, res->status);
  4216. EXPECT_EQ(std::string("123456789"), res->body);
  4217. }
  4218. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4219. Headers headers;
  4220. headers.emplace("Accept-Encoding", "gzip, deflate");
  4221. auto res = cli_.Get("/streamed-chunked2", headers);
  4222. ASSERT_TRUE(res);
  4223. EXPECT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(std::string("123456789"), res->body);
  4225. }
  4226. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4227. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST(GzipDecompressor, ChunkedDecompression) {
  4232. std::string data;
  4233. for (size_t i = 0; i < 32 * 1024; ++i) {
  4234. data.push_back(static_cast<char>('a' + i % 26));
  4235. }
  4236. std::string compressed_data;
  4237. {
  4238. httplib::detail::gzip_compressor compressor;
  4239. bool result = compressor.compress(
  4240. data.data(), data.size(),
  4241. /*last=*/true,
  4242. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4243. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4244. compressed_data_size);
  4245. return true;
  4246. });
  4247. ASSERT_TRUE(result);
  4248. }
  4249. std::string decompressed_data;
  4250. {
  4251. httplib::detail::gzip_decompressor decompressor;
  4252. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4253. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4254. size_t chunk_size = 130;
  4255. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4256. chunk_begin += chunk_size) {
  4257. size_t current_chunk_size =
  4258. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4259. bool result = decompressor.decompress(
  4260. compressed_data.data() + chunk_begin, current_chunk_size,
  4261. [&](const char *decompressed_data_chunk,
  4262. size_t decompressed_data_chunk_size) {
  4263. decompressed_data.insert(decompressed_data.size(),
  4264. decompressed_data_chunk,
  4265. decompressed_data_chunk_size);
  4266. return true;
  4267. });
  4268. ASSERT_TRUE(result);
  4269. }
  4270. }
  4271. ASSERT_EQ(data, decompressed_data);
  4272. }
  4273. TEST(GzipDecompressor, DeflateDecompression) {
  4274. std::string original_text = "Raw deflate without gzip";
  4275. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4276. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4277. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4278. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4279. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4280. std::string decompressed_data;
  4281. {
  4282. httplib::detail::gzip_decompressor decompressor;
  4283. bool result = decompressor.decompress(
  4284. compressed_data.data(), compressed_data.size(),
  4285. [&](const char *decompressed_data_chunk,
  4286. size_t decompressed_data_chunk_size) {
  4287. decompressed_data.insert(decompressed_data.size(),
  4288. decompressed_data_chunk,
  4289. decompressed_data_chunk_size);
  4290. return true;
  4291. });
  4292. ASSERT_TRUE(result);
  4293. }
  4294. ASSERT_EQ(original_text, decompressed_data);
  4295. }
  4296. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4297. std::string original_text = "Raw deflate without gzip";
  4298. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4299. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4300. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4301. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4302. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4303. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4304. std::string decompressed_data;
  4305. {
  4306. httplib::detail::gzip_decompressor decompressor;
  4307. bool result = decompressor.decompress(
  4308. compressed_data.data(), compressed_data.size(),
  4309. [&](const char *decompressed_data_chunk,
  4310. size_t decompressed_data_chunk_size) {
  4311. decompressed_data.insert(decompressed_data.size(),
  4312. decompressed_data_chunk,
  4313. decompressed_data_chunk_size);
  4314. return true;
  4315. });
  4316. ASSERT_TRUE(result);
  4317. }
  4318. ASSERT_EQ(original_text, decompressed_data);
  4319. }
  4320. #ifdef _WIN32
  4321. TEST(GzipDecompressor, LargeRandomData) {
  4322. // prepare large random data that is difficult to be compressed and is
  4323. // expected to have large size even when compressed
  4324. std::random_device seed_gen;
  4325. std::mt19937 random(seed_gen());
  4326. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4327. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4328. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4329. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4330. // compress data over 4GiB
  4331. std::string compressed_data;
  4332. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4333. httplib::detail::gzip_compressor compressor;
  4334. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4335. data.size() * sizeof(std::uint32_t), true,
  4336. [&](const char *data, size_t size) {
  4337. compressed_data.insert(
  4338. compressed_data.size(), data, size);
  4339. return true;
  4340. });
  4341. ASSERT_TRUE(result);
  4342. // FIXME: compressed data size is expected to be greater than 4GiB,
  4343. // but there is no guarantee
  4344. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4345. // decompress data over 4GiB
  4346. std::string decompressed_data;
  4347. decompressed_data.reserve(data_size);
  4348. httplib::detail::gzip_decompressor decompressor;
  4349. result = decompressor.decompress(
  4350. compressed_data.data(), compressed_data.size(),
  4351. [&](const char *data, size_t size) {
  4352. decompressed_data.insert(decompressed_data.size(), data, size);
  4353. return true;
  4354. });
  4355. ASSERT_TRUE(result);
  4356. // compare
  4357. ASSERT_EQ(data_size, decompressed_data.size());
  4358. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4359. 0);
  4360. }
  4361. #endif
  4362. #endif
  4363. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4364. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4365. Headers headers;
  4366. headers.emplace("Accept-Encoding", "br");
  4367. auto res = cli_.Get("/streamed-chunked", headers);
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ(std::string("123456789"), res->body);
  4371. }
  4372. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4373. Headers headers;
  4374. headers.emplace("Accept-Encoding", "br");
  4375. auto res = cli_.Get("/streamed-chunked2", headers);
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ(std::string("123456789"), res->body);
  4379. }
  4380. #endif
  4381. TEST_F(ServerTest, Patch) {
  4382. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. EXPECT_EQ("PATCH", res->body);
  4386. }
  4387. TEST_F(ServerTest, Delete) {
  4388. auto res = cli_.Delete("/delete");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ("DELETE", res->body);
  4392. }
  4393. TEST_F(ServerTest, DeleteContentReceiver) {
  4394. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("content", res->body);
  4398. }
  4399. TEST_F(ServerTest, Options) {
  4400. auto res = cli_.Options("*");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4404. EXPECT_TRUE(res->body.empty());
  4405. }
  4406. TEST_F(ServerTest, URL) {
  4407. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. }
  4411. TEST_F(ServerTest, ArrayParam) {
  4412. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4413. ASSERT_TRUE(res);
  4414. EXPECT_EQ(StatusCode::OK_200, res->status);
  4415. }
  4416. TEST_F(ServerTest, NoMultipleHeaders) {
  4417. Headers headers = {{"Content-Length", "5"}};
  4418. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4419. "text/plain");
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::OK_200, res->status);
  4422. }
  4423. TEST_F(ServerTest, PostContentReceiver) {
  4424. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4425. ASSERT_TRUE(res);
  4426. ASSERT_EQ(StatusCode::OK_200, res->status);
  4427. ASSERT_EQ("content", res->body);
  4428. }
  4429. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4430. MultipartFormDataItemsForClientInput items = {
  4431. {"text1", "text default", "", ""},
  4432. {"text2", "aωb", "", ""},
  4433. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4434. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4435. {"file3", "", "", "application/octet-stream"},
  4436. };
  4437. auto res = cli_.Post("/content_receiver", items);
  4438. ASSERT_TRUE(res);
  4439. EXPECT_EQ(StatusCode::OK_200, res->status);
  4440. }
  4441. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4442. MultipartFormDataItemsForClientInput items = {
  4443. {"text1", "text default", "", ""},
  4444. {"text2", "aωb", "", ""},
  4445. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4446. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4447. {"file3", "", "", "application/octet-stream"},
  4448. };
  4449. auto boundary = std::string("+++++");
  4450. std::string body;
  4451. for (const auto &item : items) {
  4452. body += "--" + boundary + "\r\n";
  4453. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4454. if (!item.filename.empty()) {
  4455. body += "; filename=\"" + item.filename + "\"";
  4456. }
  4457. body += "\r\n";
  4458. if (!item.content_type.empty()) {
  4459. body += "Content-Type: " + item.content_type + "\r\n";
  4460. }
  4461. body += "\r\n";
  4462. body += item.content + "\r\n";
  4463. }
  4464. body += "--" + boundary + "--\r\n";
  4465. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4466. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. }
  4470. TEST_F(ServerTest, PostContentReceiverGzip) {
  4471. cli_.set_compress(true);
  4472. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4473. ASSERT_TRUE(res);
  4474. ASSERT_EQ(StatusCode::OK_200, res->status);
  4475. ASSERT_EQ("content", res->body);
  4476. }
  4477. TEST_F(ServerTest, PutContentReceiver) {
  4478. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4479. ASSERT_TRUE(res);
  4480. ASSERT_EQ(StatusCode::OK_200, res->status);
  4481. ASSERT_EQ("content", res->body);
  4482. }
  4483. TEST_F(ServerTest, PatchContentReceiver) {
  4484. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4485. ASSERT_TRUE(res);
  4486. ASSERT_EQ(StatusCode::OK_200, res->status);
  4487. ASSERT_EQ("content", res->body);
  4488. }
  4489. TEST_F(ServerTest, PostQueryStringAndBody) {
  4490. auto res =
  4491. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4492. ASSERT_TRUE(res);
  4493. ASSERT_EQ(StatusCode::OK_200, res->status);
  4494. }
  4495. TEST_F(ServerTest, HTTP2Magic) {
  4496. Request req;
  4497. req.method = "PRI";
  4498. req.path = "*";
  4499. req.body = "SM";
  4500. auto res = std::make_shared<Response>();
  4501. auto error = Error::Success;
  4502. auto ret = cli_.send(req, *res, error);
  4503. ASSERT_TRUE(ret);
  4504. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4505. }
  4506. TEST_F(ServerTest, KeepAlive) {
  4507. auto res = cli_.Get("/hi");
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::OK_200, res->status);
  4510. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4511. EXPECT_EQ("Hello World!", res->body);
  4512. res = cli_.Get("/hi");
  4513. ASSERT_TRUE(res);
  4514. EXPECT_EQ(StatusCode::OK_200, res->status);
  4515. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4516. EXPECT_EQ("Hello World!", res->body);
  4517. res = cli_.Get("/hi");
  4518. ASSERT_TRUE(res);
  4519. EXPECT_EQ(StatusCode::OK_200, res->status);
  4520. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4521. EXPECT_EQ("Hello World!", res->body);
  4522. res = cli_.Get("/not-exist");
  4523. ASSERT_TRUE(res);
  4524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4525. res = cli_.Post("/empty", "", "text/plain");
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4529. EXPECT_EQ("empty", res->body);
  4530. EXPECT_EQ("close", res->get_header_value("Connection"));
  4531. res = cli_.Post(
  4532. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4533. "text/plain");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4537. EXPECT_EQ("empty", res->body);
  4538. cli_.set_keep_alive(false);
  4539. res = cli_.Get("/last-request");
  4540. ASSERT_TRUE(res);
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. EXPECT_EQ("close", res->get_header_value("Connection"));
  4543. }
  4544. TEST_F(ServerTest, TooManyRedirect) {
  4545. cli_.set_follow_location(true);
  4546. auto res = cli_.Get("/redirect/0");
  4547. ASSERT_TRUE(!res);
  4548. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4549. }
  4550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4551. TEST_F(ServerTest, Gzip) {
  4552. Headers headers;
  4553. headers.emplace("Accept-Encoding", "gzip, deflate");
  4554. auto res = cli_.Get("/compress", headers);
  4555. ASSERT_TRUE(res);
  4556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4558. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4560. "7890123456789012345678901234567890",
  4561. res->body);
  4562. EXPECT_EQ(StatusCode::OK_200, res->status);
  4563. }
  4564. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4565. Headers headers;
  4566. headers.emplace("Accept-Encoding", "");
  4567. auto res = cli_.Get("/compress", headers);
  4568. ASSERT_TRUE(res);
  4569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4573. "7890123456789012345678901234567890",
  4574. res->body);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST_F(ServerTest, GzipWithContentReceiver) {
  4578. Headers headers;
  4579. headers.emplace("Accept-Encoding", "gzip, deflate");
  4580. std::string body;
  4581. auto res = cli_.Get("/compress", headers,
  4582. [&](const char *data, uint64_t data_length) {
  4583. EXPECT_EQ(100U, data_length);
  4584. body.append(data, data_length);
  4585. return true;
  4586. });
  4587. ASSERT_TRUE(res);
  4588. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4590. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4592. "7890123456789012345678901234567890",
  4593. body);
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. }
  4596. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4597. Headers headers;
  4598. headers.emplace("Accept-Encoding", "gzip, deflate");
  4599. cli_.set_decompress(false);
  4600. auto res = cli_.Get("/compress", headers);
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4603. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4604. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4605. EXPECT_EQ(33U, res->body.size());
  4606. EXPECT_EQ(StatusCode::OK_200, res->status);
  4607. }
  4608. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4609. Headers headers;
  4610. headers.emplace("Accept-Encoding", "");
  4611. std::string body;
  4612. auto res = cli_.Get("/compress", headers,
  4613. [&](const char *data, uint64_t data_length) {
  4614. EXPECT_EQ(100U, data_length);
  4615. body.append(data, data_length);
  4616. return true;
  4617. });
  4618. ASSERT_TRUE(res);
  4619. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4620. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4621. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4622. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4623. "7890123456789012345678901234567890",
  4624. body);
  4625. EXPECT_EQ(StatusCode::OK_200, res->status);
  4626. }
  4627. TEST_F(ServerTest, NoGzip) {
  4628. Headers headers;
  4629. headers.emplace("Accept-Encoding", "gzip, deflate");
  4630. auto res = cli_.Get("/nocompress", headers);
  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. res->body);
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. }
  4640. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4641. Headers headers;
  4642. headers.emplace("Accept-Encoding", "gzip, deflate");
  4643. std::string body;
  4644. auto res = cli_.Get("/nocompress", headers,
  4645. [&](const char *data, uint64_t data_length) {
  4646. EXPECT_EQ(100U, data_length);
  4647. body.append(data, data_length);
  4648. return true;
  4649. });
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4652. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4653. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4655. "7890123456789012345678901234567890",
  4656. body);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. }
  4659. TEST_F(ServerTest, MultipartFormDataGzip) {
  4660. MultipartFormDataItemsForClientInput items = {
  4661. {"key1", "test", "", ""},
  4662. {"key2", "--abcdefg123", "", ""},
  4663. };
  4664. cli_.set_compress(true);
  4665. auto res = cli_.Post("/compress-multipart", items);
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. }
  4669. #endif
  4670. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4671. TEST_F(ServerTest, Brotli) {
  4672. Headers headers;
  4673. headers.emplace("Accept-Encoding", "br");
  4674. auto res = cli_.Get("/compress", headers);
  4675. ASSERT_TRUE(res);
  4676. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4678. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4679. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4680. "7890123456789012345678901234567890",
  4681. res->body);
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. }
  4684. #endif
  4685. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4686. TEST_F(ServerTest, Zstd) {
  4687. Headers headers;
  4688. headers.emplace("Accept-Encoding", "zstd");
  4689. auto res = cli_.Get("/compress", headers);
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4692. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4693. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4694. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4695. "7890123456789012345678901234567890",
  4696. res->body);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4700. Headers headers;
  4701. headers.emplace("Accept-Encoding", "");
  4702. auto res = cli_.Get("/compress", headers);
  4703. ASSERT_TRUE(res);
  4704. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4706. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4707. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4708. "7890123456789012345678901234567890",
  4709. res->body);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4713. Headers headers;
  4714. headers.emplace("Accept-Encoding", "zstd");
  4715. std::string body;
  4716. auto res = cli_.Get("/compress", headers,
  4717. [&](const char *data, uint64_t data_length) {
  4718. EXPECT_EQ(100U, data_length);
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4725. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4726. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4727. "7890123456789012345678901234567890",
  4728. body);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. }
  4731. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4732. Headers headers;
  4733. headers.emplace("Accept-Encoding", "zstd");
  4734. cli_.set_decompress(false);
  4735. auto res = cli_.Get("/compress", headers);
  4736. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4737. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4738. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4739. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4743. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. ASSERT_EQ(26U, res->body.size());
  4746. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4747. 0);
  4748. }
  4749. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4750. Headers headers;
  4751. headers.emplace("Accept-Encoding", "");
  4752. std::string body;
  4753. auto res = cli_.Get("/compress", headers,
  4754. [&](const char *data, uint64_t data_length) {
  4755. EXPECT_EQ(100U, data_length);
  4756. body.append(data, data_length);
  4757. return true;
  4758. });
  4759. ASSERT_TRUE(res);
  4760. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4762. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4763. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4764. "7890123456789012345678901234567890",
  4765. body);
  4766. EXPECT_EQ(StatusCode::OK_200, res->status);
  4767. }
  4768. TEST_F(ServerTest, NoZstd) {
  4769. Headers headers;
  4770. headers.emplace("Accept-Encoding", "zstd");
  4771. auto res = cli_.Get("/nocompress", headers);
  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. res->body);
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. }
  4781. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4782. Headers headers;
  4783. headers.emplace("Accept-Encoding", "zstd");
  4784. std::string body;
  4785. auto res = cli_.Get("/nocompress", headers,
  4786. [&](const char *data, uint64_t data_length) {
  4787. EXPECT_EQ(100U, data_length);
  4788. body.append(data, data_length);
  4789. return true;
  4790. });
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4793. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4794. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4795. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4796. "7890123456789012345678901234567890",
  4797. body);
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. }
  4800. // TODO: How to enable zstd ??
  4801. TEST_F(ServerTest, MultipartFormDataZstd) {
  4802. MultipartFormDataItemsForClientInput items = {
  4803. {"key1", "test", "", ""},
  4804. {"key2", "--abcdefg123", "", ""},
  4805. };
  4806. Headers headers;
  4807. headers.emplace("Accept-Encoding", "zstd");
  4808. cli_.set_compress(true);
  4809. auto res = cli_.Post("/compress-multipart", headers, items);
  4810. ASSERT_TRUE(res);
  4811. EXPECT_EQ(StatusCode::OK_200, res->status);
  4812. }
  4813. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4814. Headers headers;
  4815. headers.emplace("Accept-Encoding", "zstd");
  4816. cli_.set_compress(true);
  4817. auto res = cli_.Put(
  4818. "/put", headers, 3,
  4819. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4820. sink.os << "PUT";
  4821. return true;
  4822. },
  4823. "text/plain");
  4824. ASSERT_TRUE(res);
  4825. EXPECT_EQ(StatusCode::OK_200, res->status);
  4826. EXPECT_EQ("PUT", res->body);
  4827. }
  4828. TEST(ZstdDecompressor, ChunkedDecompression) {
  4829. std::string data;
  4830. for (size_t i = 0; i < 32 * 1024; ++i) {
  4831. data.push_back(static_cast<char>('a' + i % 26));
  4832. }
  4833. std::string compressed_data;
  4834. {
  4835. httplib::detail::zstd_compressor compressor;
  4836. bool result = compressor.compress(
  4837. data.data(), data.size(),
  4838. /*last=*/true,
  4839. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4840. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4841. compressed_data_size);
  4842. return true;
  4843. });
  4844. ASSERT_TRUE(result);
  4845. }
  4846. std::string decompressed_data;
  4847. {
  4848. httplib::detail::zstd_decompressor decompressor;
  4849. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4850. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4851. size_t chunk_size = 130;
  4852. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4853. chunk_begin += chunk_size) {
  4854. size_t current_chunk_size =
  4855. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4856. bool result = decompressor.decompress(
  4857. compressed_data.data() + chunk_begin, current_chunk_size,
  4858. [&](const char *decompressed_data_chunk,
  4859. size_t decompressed_data_chunk_size) {
  4860. decompressed_data.insert(decompressed_data.size(),
  4861. decompressed_data_chunk,
  4862. decompressed_data_chunk_size);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(result);
  4866. }
  4867. }
  4868. ASSERT_EQ(data, decompressed_data);
  4869. }
  4870. TEST(ZstdDecompressor, Decompress) {
  4871. std::string original_text = "Compressed with ZSTD";
  4872. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4873. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4874. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4875. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4876. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4877. std::string decompressed_data;
  4878. {
  4879. httplib::detail::zstd_decompressor decompressor;
  4880. bool result = decompressor.decompress(
  4881. compressed_data.data(), compressed_data.size(),
  4882. [&](const char *decompressed_data_chunk,
  4883. size_t decompressed_data_chunk_size) {
  4884. decompressed_data.insert(decompressed_data.size(),
  4885. decompressed_data_chunk,
  4886. decompressed_data_chunk_size);
  4887. return true;
  4888. });
  4889. ASSERT_TRUE(result);
  4890. }
  4891. ASSERT_EQ(original_text, decompressed_data);
  4892. }
  4893. #endif
  4894. // Sends a raw request to a server listening at HOST:PORT.
  4895. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4896. std::string *resp = nullptr) {
  4897. auto error = Error::Success;
  4898. auto client_sock = detail::create_client_socket(
  4899. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4900. /*connection_timeout_sec=*/5, 0,
  4901. /*read_timeout_sec=*/5, 0,
  4902. /*write_timeout_sec=*/5, 0, std::string(), error);
  4903. if (client_sock == INVALID_SOCKET) { return false; }
  4904. auto ret = detail::process_client_socket(
  4905. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4906. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4907. if (req.size() !=
  4908. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4909. return false;
  4910. }
  4911. char buf[512];
  4912. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4913. while (line_reader.getline()) {
  4914. if (resp) { *resp += line_reader.ptr(); }
  4915. }
  4916. return true;
  4917. });
  4918. detail::close_socket(client_sock);
  4919. return ret;
  4920. }
  4921. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4922. Server svr;
  4923. std::string header_value;
  4924. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4925. header_value = req.get_header_value("foo");
  4926. res.set_content("ok", "text/plain");
  4927. });
  4928. thread t = thread([&] { svr.listen(HOST, PORT); });
  4929. auto se = detail::scope_exit([&] {
  4930. svr.stop();
  4931. t.join();
  4932. ASSERT_FALSE(svr.is_running());
  4933. });
  4934. svr.wait_until_ready();
  4935. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4936. // like characters are not treated the same - use vertical tab and escape.
  4937. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4938. "foo: \t \v bar \x1B\t \r\n"
  4939. "Connection: close\r\n"
  4940. "\r\n";
  4941. std::string res;
  4942. ASSERT_TRUE(send_request(5, req, &res));
  4943. EXPECT_EQ(header_value, "");
  4944. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4945. }
  4946. // Sends a raw request and verifies that there isn't a crash or exception.
  4947. static void test_raw_request(const std::string &req,
  4948. std::string *out = nullptr) {
  4949. Server svr;
  4950. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4951. res.set_content("ok", "text/plain");
  4952. });
  4953. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4954. res.set_content("ok", "text/plain");
  4955. });
  4956. svr.Get("/header_field_value_check",
  4957. [&](const Request & /*req*/, Response &res) {
  4958. res.set_content("ok", "text/plain");
  4959. });
  4960. // Server read timeout must be longer than the client read timeout for the
  4961. // bug to reproduce, probably to force the server to process a request
  4962. // without a trailing blank line.
  4963. const time_t client_read_timeout_sec = 1;
  4964. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4965. bool listen_thread_ok = false;
  4966. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4967. auto se = detail::scope_exit([&] {
  4968. svr.stop();
  4969. t.join();
  4970. ASSERT_FALSE(svr.is_running());
  4971. EXPECT_TRUE(listen_thread_ok);
  4972. });
  4973. svr.wait_until_ready();
  4974. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4975. }
  4976. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4977. // A certain header line causes an exception if the header property is parsed
  4978. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4979. test_raw_request(
  4980. "GET /hi HTTP/1.1\r\n"
  4981. " : "
  4982. " "
  4983. " ");
  4984. }
  4985. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4986. // A certain header line causes an exception if the header property *name* is
  4987. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4988. // greedy matcher and requires backtracking when there are a lot of ":"
  4989. // characters.
  4990. // This occurs with libc++ but not libstdc++.
  4991. test_raw_request(
  4992. "GET /hi HTTP/1.1\r\n"
  4993. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4994. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4995. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4996. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4997. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4998. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4999. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5000. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5001. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5002. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5003. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5004. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5005. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5006. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5007. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5008. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5009. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5010. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5011. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5012. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5013. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5014. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5015. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5016. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5017. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5018. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5019. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5020. "&&&%%%");
  5021. }
  5022. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5023. // Make sure this doesn't crash the server.
  5024. // In a previous version of the header line regex, the "\r" rendered the line
  5025. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5026. // a new position where the leading white space ended and the field value
  5027. // began.
  5028. // The crash occurs with libc++ but not libstdc++.
  5029. test_raw_request("GET /hi HTTP/1.1\r\n"
  5030. "a:" +
  5031. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5032. "\r\n"
  5033. "\r\n");
  5034. }
  5035. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5036. std::string out;
  5037. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5038. "Content-Type: text/plain\r\n"
  5039. "Transfer-Encoding: chunked\r\n"
  5040. "\r\n"
  5041. "nothex\r\n",
  5042. &out);
  5043. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5044. }
  5045. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5046. std::string out;
  5047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5048. "Content-Type: text/plain\r\n"
  5049. "Transfer-Encoding: chunked\r\n"
  5050. "\r\n"
  5051. "3\r\n"
  5052. "xyz\r\n"
  5053. "NaN\r\n",
  5054. &out);
  5055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5056. }
  5057. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5058. std::string out;
  5059. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5060. "Content-Type: text/plain\r\n"
  5061. "Transfer-Encoding: chunked\r\n"
  5062. "\r\n"
  5063. // Length is too large for 64 bits.
  5064. "1ffffffffffffffff\r\n"
  5065. "xyz\r\n",
  5066. &out);
  5067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5068. }
  5069. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5070. test_raw_request("GET /hi HTTP/1.1\r\n"
  5071. "Content-Type: text/plain\r\n\r");
  5072. }
  5073. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5074. std::string out;
  5075. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5076. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5077. }
  5078. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5079. std::string out;
  5080. std::string request(
  5081. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5082. test_raw_request(request, &out);
  5083. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5084. }
  5085. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5086. std::string out;
  5087. std::string request(
  5088. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5089. test_raw_request(request, &out);
  5090. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5091. }
  5092. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5093. std::string out;
  5094. std::string request(
  5095. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5096. test_raw_request(request, &out);
  5097. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5098. }
  5099. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5100. std::string out;
  5101. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5102. "Test: \r\n\r\n",
  5103. &out);
  5104. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5105. }
  5106. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5107. Server svr;
  5108. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5109. res.set_header("Cache-Control", "no-cache");
  5110. res.set_chunked_content_provider(
  5111. "text/event-stream", [](size_t offset, DataSink &sink) {
  5112. std::string s = "data:";
  5113. s += std::to_string(offset);
  5114. s += "\n\n";
  5115. auto ret = sink.write(s.data(), s.size());
  5116. EXPECT_TRUE(ret);
  5117. std::this_thread::sleep_for(std::chrono::seconds(1));
  5118. return true;
  5119. });
  5120. });
  5121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5122. svr.wait_until_ready();
  5123. Client client(HOST, PORT);
  5124. const Headers headers = {{"Accept", "text/event-stream"}};
  5125. auto get_thread = std::thread([&client, &headers]() {
  5126. auto res = client.Get(
  5127. "/events", headers,
  5128. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5129. });
  5130. auto se = detail::scope_exit([&] {
  5131. svr.stop();
  5132. get_thread.join();
  5133. listen_thread.join();
  5134. ASSERT_FALSE(svr.is_running());
  5135. });
  5136. // Give GET time to get a few messages.
  5137. std::this_thread::sleep_for(std::chrono::seconds(2));
  5138. }
  5139. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5140. httplib::Server svr;
  5141. svr.Post("/hi",
  5142. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5143. res.status = StatusCode::OK_200;
  5144. });
  5145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5146. svr.wait_until_ready();
  5147. Client cli(HOST, PORT);
  5148. auto res = cli.Post("/hi", "data", "text/plain");
  5149. ASSERT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. svr.stop();
  5152. thread.join();
  5153. ASSERT_FALSE(svr.is_running());
  5154. res = cli.Post("/hi", "data", "text/plain");
  5155. ASSERT_FALSE(res);
  5156. }
  5157. TEST(ServerStopTest, ListenFailure) {
  5158. Server svr;
  5159. auto t = thread([&]() {
  5160. auto ret = svr.listen("????", PORT);
  5161. EXPECT_FALSE(ret);
  5162. });
  5163. svr.wait_until_ready();
  5164. svr.stop();
  5165. t.join();
  5166. }
  5167. TEST(ServerStopTest, Decommision) {
  5168. Server svr;
  5169. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5170. for (int i = 0; i < 4; i++) {
  5171. auto is_even = !(i % 2);
  5172. std::thread t{[&] {
  5173. try {
  5174. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5175. if (is_even) {
  5176. throw std::runtime_error("Some thing that happens to go wrong.");
  5177. }
  5178. svr.listen(HOST, PORT);
  5179. } catch (...) { svr.decommission(); }
  5180. }};
  5181. svr.wait_until_ready();
  5182. // Server is up
  5183. {
  5184. Client cli(HOST, PORT);
  5185. auto res = cli.Get("/hi");
  5186. if (is_even) {
  5187. EXPECT_FALSE(res);
  5188. } else {
  5189. EXPECT_TRUE(res);
  5190. EXPECT_EQ("hi...", res->body);
  5191. }
  5192. }
  5193. svr.stop();
  5194. t.join();
  5195. // Server is down...
  5196. {
  5197. Client cli(HOST, PORT);
  5198. auto res = cli.Get("/hi");
  5199. EXPECT_FALSE(res);
  5200. }
  5201. }
  5202. }
  5203. // Helper function for string body upload progress tests
  5204. template <typename SetupHandler, typename ClientCall>
  5205. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5206. ClientCall &&client_call,
  5207. const string &body) {
  5208. Server svr;
  5209. setup_handler(svr);
  5210. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5211. auto se = detail::scope_exit([&] {
  5212. svr.stop();
  5213. t.join();
  5214. });
  5215. svr.wait_until_ready();
  5216. Client cli(HOST, PORT);
  5217. vector<uint64_t> progress_values;
  5218. bool progress_called = false;
  5219. auto res =
  5220. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5221. progress_values.push_back(current);
  5222. progress_called = true;
  5223. return true;
  5224. });
  5225. ASSERT_TRUE(res);
  5226. EXPECT_EQ(200, res->status);
  5227. EXPECT_TRUE(progress_called);
  5228. }
  5229. TEST(UploadProgressTest, PostStringBodyBasic) {
  5230. TestStringBodyUploadProgress(
  5231. [](Server &svr) {
  5232. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5233. res.set_content("received", "text/plain");
  5234. });
  5235. },
  5236. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5237. return cli.Post("/test", body, "text/plain", progress_callback);
  5238. },
  5239. "test data for upload progress");
  5240. }
  5241. TEST(UploadProgressTest, PutStringBodyBasic) {
  5242. TestStringBodyUploadProgress(
  5243. [](Server &svr) {
  5244. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5245. res.set_content("put received", "text/plain");
  5246. });
  5247. },
  5248. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5249. return cli.Put("/test", body, "text/plain", progress_callback);
  5250. },
  5251. "put test data for upload progress");
  5252. }
  5253. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5254. TestStringBodyUploadProgress(
  5255. [](Server &svr) {
  5256. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5257. res.set_content("patch received", "text/plain");
  5258. });
  5259. },
  5260. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5261. return cli.Patch("/test", body, "text/plain", progress_callback);
  5262. },
  5263. "patch test data for upload progress");
  5264. }
  5265. // Helper function for content provider upload progress tests
  5266. template <typename SetupHandler, typename ClientCall>
  5267. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5268. ClientCall &&client_call) {
  5269. Server svr;
  5270. setup_handler(svr);
  5271. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5272. auto se = detail::scope_exit([&] {
  5273. svr.stop();
  5274. t.join();
  5275. });
  5276. svr.wait_until_ready();
  5277. Client cli(HOST, PORT);
  5278. vector<uint64_t> progress_values;
  5279. auto res =
  5280. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5281. progress_values.push_back(current);
  5282. return true;
  5283. });
  5284. ASSERT_TRUE(res);
  5285. EXPECT_EQ(200, res->status);
  5286. EXPECT_FALSE(progress_values.empty());
  5287. }
  5288. TEST(UploadProgressTest, PostContentProviderProgress) {
  5289. TestContentProviderUploadProgress(
  5290. [](Server &svr) {
  5291. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5292. res.set_content("provider received", "text/plain");
  5293. });
  5294. },
  5295. [](Client &cli, UploadProgress progress_callback) {
  5296. return cli.Post(
  5297. "/test", 10,
  5298. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5299. sink.os << "test data";
  5300. return true;
  5301. },
  5302. "text/plain", progress_callback);
  5303. });
  5304. }
  5305. // Helper function for multipart upload progress tests
  5306. template <typename SetupHandler, typename ClientCall>
  5307. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5308. ClientCall &&client_call,
  5309. const string &endpoint) {
  5310. Server svr;
  5311. setup_handler(svr);
  5312. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5313. auto se = detail::scope_exit([&] {
  5314. svr.stop();
  5315. t.join();
  5316. });
  5317. svr.wait_until_ready();
  5318. Client cli(HOST, PORT);
  5319. vector<uint64_t> progress_values;
  5320. MultipartFormDataItemsForClientInput items = {
  5321. {"field1", "value1", "", ""},
  5322. {"field2", "longer value for progress tracking test", "", ""},
  5323. {"file1", "file content data for upload progress", "test.txt",
  5324. "text/plain"}};
  5325. auto res = client_call(cli, endpoint, items,
  5326. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5327. progress_values.push_back(current);
  5328. return true;
  5329. });
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ(200, res->status);
  5332. EXPECT_FALSE(progress_values.empty());
  5333. }
  5334. TEST(UploadProgressTest, PostMultipartProgress) {
  5335. TestMultipartUploadProgress(
  5336. [](Server &svr) {
  5337. svr.Post("/multipart", [](const Request &req, Response &res) {
  5338. EXPECT_FALSE(req.files.empty());
  5339. res.set_content("multipart received", "text/plain");
  5340. });
  5341. },
  5342. [](Client &cli, const string &endpoint,
  5343. const MultipartFormDataItemsForClientInput &items,
  5344. UploadProgress progress_callback) {
  5345. return cli.Post(endpoint, items, progress_callback);
  5346. },
  5347. "/multipart");
  5348. }
  5349. // Helper function for basic download progress tests
  5350. template <typename SetupHandler, typename ClientCall>
  5351. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5352. ClientCall &&client_call, const string &endpoint,
  5353. size_t expected_content_size) {
  5354. Server svr;
  5355. setup_handler(svr);
  5356. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5357. auto se = detail::scope_exit([&] {
  5358. svr.stop();
  5359. t.join();
  5360. });
  5361. svr.wait_until_ready();
  5362. Client cli(HOST, PORT);
  5363. vector<uint64_t> progress_values;
  5364. auto res = client_call(cli, endpoint,
  5365. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5366. progress_values.push_back(current);
  5367. return true;
  5368. });
  5369. ASSERT_TRUE(res);
  5370. EXPECT_EQ(200, res->status);
  5371. EXPECT_FALSE(progress_values.empty());
  5372. EXPECT_EQ(expected_content_size, res->body.size());
  5373. }
  5374. TEST(DownloadProgressTest, GetBasic) {
  5375. TestBasicDownloadProgress(
  5376. [](Server &svr) {
  5377. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5378. string content(1000, 'D');
  5379. res.set_content(content, "text/plain");
  5380. });
  5381. },
  5382. [](Client &cli, const string &endpoint,
  5383. DownloadProgress progress_callback) {
  5384. return cli.Get(endpoint, progress_callback);
  5385. },
  5386. "/download", 1000u);
  5387. }
  5388. // Helper function for content receiver download progress tests
  5389. template <typename SetupHandler, typename ClientCall>
  5390. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5391. ClientCall &&client_call,
  5392. const string &endpoint,
  5393. size_t expected_content_size) {
  5394. Server svr;
  5395. setup_handler(svr);
  5396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5397. auto se = detail::scope_exit([&] {
  5398. svr.stop();
  5399. t.join();
  5400. });
  5401. svr.wait_until_ready();
  5402. Client cli(HOST, PORT);
  5403. vector<uint64_t> progress_values;
  5404. string received_body;
  5405. auto res = client_call(
  5406. cli, endpoint,
  5407. [&](const char *data, size_t data_length) -> bool {
  5408. received_body.append(data, data_length);
  5409. return true;
  5410. },
  5411. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5412. progress_values.push_back(current);
  5413. return true;
  5414. });
  5415. ASSERT_TRUE(res);
  5416. EXPECT_EQ(200, res->status);
  5417. EXPECT_FALSE(progress_values.empty());
  5418. EXPECT_EQ(expected_content_size, received_body.size());
  5419. EXPECT_TRUE(res->body.empty());
  5420. }
  5421. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5422. TestContentReceiverDownloadProgress(
  5423. [](Server &svr) {
  5424. svr.Get("/download-receiver",
  5425. [](const Request & /*req*/, Response &res) {
  5426. string content(2000, 'R');
  5427. res.set_content(content, "text/plain");
  5428. });
  5429. },
  5430. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5431. DownloadProgress progress_callback) {
  5432. return cli.Get(endpoint, content_receiver, progress_callback);
  5433. },
  5434. "/download-receiver", 2000u);
  5435. }
  5436. TEST(StreamingTest, NoContentLengthStreaming) {
  5437. Server svr;
  5438. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5439. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5440. if (offset < 6) {
  5441. sink.os << (offset < 3 ? "a" : "b");
  5442. } else {
  5443. sink.done();
  5444. }
  5445. return true;
  5446. });
  5447. });
  5448. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5449. auto listen_se = detail::scope_exit([&] {
  5450. svr.stop();
  5451. listen_thread.join();
  5452. ASSERT_FALSE(svr.is_running());
  5453. });
  5454. svr.wait_until_ready();
  5455. Client client(HOST, PORT);
  5456. auto get_thread = std::thread([&client]() {
  5457. std::string s;
  5458. auto res =
  5459. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5460. s += std::string(data, len);
  5461. return true;
  5462. });
  5463. ASSERT_TRUE(res);
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. EXPECT_EQ("aaabbb", s);
  5466. });
  5467. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5468. // Give GET time to get a few messages.
  5469. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5470. }
  5471. TEST(MountTest, Unmount) {
  5472. Server svr;
  5473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5474. auto se = detail::scope_exit([&] {
  5475. svr.stop();
  5476. listen_thread.join();
  5477. ASSERT_FALSE(svr.is_running());
  5478. });
  5479. svr.wait_until_ready();
  5480. Client cli("localhost", PORT);
  5481. svr.set_mount_point("/mount2", "./www2");
  5482. auto res = cli.Get("/");
  5483. ASSERT_TRUE(res);
  5484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5485. res = cli.Get("/mount2/dir/test.html");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. svr.set_mount_point("/", "./www");
  5489. res = cli.Get("/dir/");
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. svr.remove_mount_point("/");
  5493. res = cli.Get("/dir/");
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5496. svr.remove_mount_point("/mount2");
  5497. res = cli.Get("/mount2/dir/test.html");
  5498. ASSERT_TRUE(res);
  5499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5500. }
  5501. TEST(MountTest, Redicect) {
  5502. Server svr;
  5503. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5504. auto se = detail::scope_exit([&] {
  5505. svr.stop();
  5506. listen_thread.join();
  5507. ASSERT_FALSE(svr.is_running());
  5508. });
  5509. svr.set_mount_point("/", "./www");
  5510. svr.wait_until_ready();
  5511. Client cli("localhost", PORT);
  5512. auto res = cli.Get("/dir/");
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. res = cli.Get("/dir");
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5518. res = cli.Get("/file");
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. res = cli.Get("/file/");
  5522. ASSERT_TRUE(res);
  5523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5524. cli.set_follow_location(true);
  5525. res = cli.Get("/dir");
  5526. ASSERT_TRUE(res);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. }
  5529. TEST(MountTest, MultibytesPathName) {
  5530. Server svr;
  5531. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5532. auto se = detail::scope_exit([&] {
  5533. svr.stop();
  5534. listen_thread.join();
  5535. ASSERT_FALSE(svr.is_running());
  5536. });
  5537. svr.set_mount_point("/", "./www");
  5538. svr.wait_until_ready();
  5539. Client cli("localhost", PORT);
  5540. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5541. ASSERT_TRUE(res);
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5544. }
  5545. TEST(KeepAliveTest, ReadTimeout) {
  5546. Server svr;
  5547. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5548. std::this_thread::sleep_for(std::chrono::seconds(2));
  5549. res.set_content("a", "text/plain");
  5550. });
  5551. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5552. res.set_content("b", "text/plain");
  5553. });
  5554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5555. auto se = detail::scope_exit([&] {
  5556. svr.stop();
  5557. listen_thread.join();
  5558. ASSERT_FALSE(svr.is_running());
  5559. });
  5560. svr.wait_until_ready();
  5561. Client cli("localhost", PORT);
  5562. cli.set_keep_alive(true);
  5563. cli.set_read_timeout(std::chrono::seconds(1));
  5564. auto resa = cli.Get("/a");
  5565. ASSERT_FALSE(resa);
  5566. EXPECT_EQ(Error::Read, resa.error());
  5567. auto resb = cli.Get("/b");
  5568. ASSERT_TRUE(resb);
  5569. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5570. EXPECT_EQ("b", resb->body);
  5571. }
  5572. TEST(KeepAliveTest, MaxCount) {
  5573. size_t keep_alive_max_count = 3;
  5574. Server svr;
  5575. svr.set_keep_alive_max_count(keep_alive_max_count);
  5576. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5577. res.set_content("Hello World!", "text/plain");
  5578. });
  5579. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5580. auto se = detail::scope_exit([&] {
  5581. svr.stop();
  5582. listen_thread.join();
  5583. ASSERT_FALSE(svr.is_running());
  5584. });
  5585. svr.wait_until_ready();
  5586. Client cli(HOST, PORT);
  5587. cli.set_keep_alive(true);
  5588. for (size_t i = 0; i < 5; i++) {
  5589. auto result = cli.Get("/hi");
  5590. ASSERT_TRUE(result);
  5591. EXPECT_EQ(StatusCode::OK_200, result->status);
  5592. if (i == keep_alive_max_count - 1) {
  5593. EXPECT_EQ("close", result->get_header_value("Connection"));
  5594. } else {
  5595. EXPECT_FALSE(result->has_header("Connection"));
  5596. }
  5597. }
  5598. }
  5599. TEST(KeepAliveTest, Issue1041) {
  5600. Server svr;
  5601. svr.set_keep_alive_timeout(3);
  5602. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5603. res.set_content("Hello World!", "text/plain");
  5604. });
  5605. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5606. auto se = detail::scope_exit([&] {
  5607. svr.stop();
  5608. listen_thread.join();
  5609. ASSERT_FALSE(svr.is_running());
  5610. });
  5611. svr.wait_until_ready();
  5612. Client cli(HOST, PORT);
  5613. cli.set_keep_alive(true);
  5614. auto result = cli.Get("/hi");
  5615. ASSERT_TRUE(result);
  5616. EXPECT_EQ(StatusCode::OK_200, result->status);
  5617. std::this_thread::sleep_for(std::chrono::seconds(5));
  5618. result = cli.Get("/hi");
  5619. ASSERT_TRUE(result);
  5620. EXPECT_EQ(StatusCode::OK_200, result->status);
  5621. }
  5622. TEST(KeepAliveTest, Issue1959) {
  5623. Server svr;
  5624. svr.set_keep_alive_timeout(5);
  5625. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5626. res.set_content("a", "text/plain");
  5627. });
  5628. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5629. auto se = detail::scope_exit([&] {
  5630. if (!svr.is_running()) return;
  5631. svr.stop();
  5632. listen_thread.join();
  5633. ASSERT_FALSE(svr.is_running());
  5634. });
  5635. svr.wait_until_ready();
  5636. Client cli("localhost", PORT);
  5637. cli.set_keep_alive(true);
  5638. using namespace std::chrono;
  5639. auto start = steady_clock::now();
  5640. cli.Get("/a");
  5641. svr.stop();
  5642. listen_thread.join();
  5643. auto end = steady_clock::now();
  5644. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5645. EXPECT_LT(elapsed, 5000);
  5646. }
  5647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5648. TEST(KeepAliveTest, SSLClientReconnection) {
  5649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5650. ASSERT_TRUE(svr.is_valid());
  5651. svr.set_keep_alive_timeout(1);
  5652. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5653. res.set_content("Hello World!", "text/plain");
  5654. });
  5655. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5656. auto se = detail::scope_exit([&] {
  5657. svr.stop();
  5658. listen_thread.join();
  5659. ASSERT_FALSE(svr.is_running());
  5660. });
  5661. svr.wait_until_ready();
  5662. SSLClient cli(HOST, PORT);
  5663. cli.enable_server_certificate_verification(false);
  5664. cli.set_keep_alive(true);
  5665. auto result = cli.Get("/hi");
  5666. ASSERT_TRUE(result);
  5667. EXPECT_EQ(StatusCode::OK_200, result->status);
  5668. result = cli.Get("/hi");
  5669. ASSERT_TRUE(result);
  5670. EXPECT_EQ(StatusCode::OK_200, result->status);
  5671. std::this_thread::sleep_for(std::chrono::seconds(2));
  5672. // Recoonect
  5673. result = cli.Get("/hi");
  5674. ASSERT_TRUE(result);
  5675. EXPECT_EQ(StatusCode::OK_200, result->status);
  5676. result = cli.Get("/hi");
  5677. ASSERT_TRUE(result);
  5678. EXPECT_EQ(StatusCode::OK_200, result->status);
  5679. }
  5680. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5682. ASSERT_TRUE(svr.is_valid());
  5683. svr.set_keep_alive_timeout(1);
  5684. std::string content = "reconnect";
  5685. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5686. res.set_content("Hello World!", "text/plain");
  5687. });
  5688. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5689. auto se = detail::scope_exit([&] {
  5690. svr.stop();
  5691. listen_thread.join();
  5692. ASSERT_FALSE(svr.is_running());
  5693. });
  5694. svr.wait_until_ready();
  5695. SSLClient cli(HOST, PORT);
  5696. cli.enable_server_certificate_verification(false);
  5697. cli.set_keep_alive(true);
  5698. auto result = cli.Post(
  5699. "/hi", content.size(),
  5700. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5701. sink.write(content.c_str(), content.size());
  5702. return true;
  5703. },
  5704. "text/plain");
  5705. ASSERT_TRUE(result);
  5706. EXPECT_EQ(200, result->status);
  5707. std::this_thread::sleep_for(std::chrono::seconds(2));
  5708. // Recoonect
  5709. result = cli.Post(
  5710. "/hi", content.size(),
  5711. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5712. sink.write(content.c_str(), content.size());
  5713. return true;
  5714. },
  5715. "text/plain");
  5716. ASSERT_TRUE(result);
  5717. EXPECT_EQ(200, result->status);
  5718. result = cli.Post(
  5719. "/hi", content.size(),
  5720. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5721. sink.write(content.c_str(), content.size());
  5722. return true;
  5723. },
  5724. "text/plain");
  5725. ASSERT_TRUE(result);
  5726. EXPECT_EQ(200, result->status);
  5727. }
  5728. #endif
  5729. TEST(ClientProblemDetectionTest, ContentProvider) {
  5730. Server svr;
  5731. size_t content_length = 1024 * 1024;
  5732. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5733. res.set_content_provider(
  5734. content_length, "text/plain",
  5735. [&](size_t offset, size_t length, DataSink &sink) {
  5736. auto out_len = std::min(length, static_cast<size_t>(1024));
  5737. std::string out(out_len, '@');
  5738. sink.write(out.data(), out_len);
  5739. return offset < 4096;
  5740. },
  5741. [](bool success) { ASSERT_FALSE(success); });
  5742. });
  5743. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5744. res.set_content_provider(
  5745. 0, "text/plain",
  5746. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5747. EXPECT_TRUE(false);
  5748. return true;
  5749. },
  5750. [](bool success) { ASSERT_FALSE(success); });
  5751. });
  5752. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5753. auto se = detail::scope_exit([&] {
  5754. svr.stop();
  5755. listen_thread.join();
  5756. ASSERT_FALSE(svr.is_running());
  5757. });
  5758. svr.wait_until_ready();
  5759. Client cli("localhost", PORT);
  5760. {
  5761. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5762. size_t /*data_length*/) { return false; });
  5763. ASSERT_FALSE(res);
  5764. }
  5765. {
  5766. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5767. size_t /*data_length*/) { return false; });
  5768. ASSERT_TRUE(res);
  5769. }
  5770. }
  5771. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5772. Server svr;
  5773. svr.set_error_handler([](Request const &, Response &res) -> void {
  5774. res.set_chunked_content_provider(
  5775. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5776. sink.os << "hello";
  5777. sink.os << "world";
  5778. sink.done();
  5779. return true;
  5780. });
  5781. });
  5782. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5783. auto se = detail::scope_exit([&] {
  5784. svr.stop();
  5785. listen_thread.join();
  5786. ASSERT_FALSE(svr.is_running());
  5787. });
  5788. svr.wait_until_ready();
  5789. Client cli("localhost", PORT);
  5790. auto res = cli.Get("/");
  5791. ASSERT_TRUE(res);
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. EXPECT_EQ("helloworld", res->body);
  5794. }
  5795. TEST(LongPollingTest, ClientCloseDetection) {
  5796. Server svr;
  5797. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5798. res.set_chunked_content_provider(
  5799. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5800. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5801. sink.os << "hello";
  5802. auto count = 10;
  5803. while (count > 0 && sink.is_writable()) {
  5804. this_thread::sleep_for(chrono::milliseconds(10));
  5805. count--;
  5806. }
  5807. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5808. return true;
  5809. });
  5810. });
  5811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5812. auto se = detail::scope_exit([&] {
  5813. svr.stop();
  5814. listen_thread.join();
  5815. ASSERT_FALSE(svr.is_running());
  5816. });
  5817. svr.wait_until_ready();
  5818. Client cli("localhost", PORT);
  5819. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5820. EXPECT_EQ("hello", string(data, data_length));
  5821. return false; // close the socket immediately.
  5822. });
  5823. ASSERT_FALSE(res);
  5824. }
  5825. TEST(GetWithParametersTest, GetWithParameters) {
  5826. Server svr;
  5827. svr.Get("/", [&](const Request &req, Response &) {
  5828. EXPECT_EQ("world", req.get_param_value("hello"));
  5829. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5830. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5831. });
  5832. svr.Get("/params", [&](const Request &req, Response &) {
  5833. EXPECT_EQ("world", req.get_param_value("hello"));
  5834. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5835. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5836. });
  5837. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5838. EXPECT_EQ("resource-id", req.matches[1]);
  5839. EXPECT_EQ("foo", req.get_param_value("param1"));
  5840. EXPECT_EQ("bar", req.get_param_value("param2"));
  5841. });
  5842. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5843. EXPECT_EQ("user-id", req.path_params.at("id"));
  5844. EXPECT_EQ("foo", req.get_param_value("param1"));
  5845. EXPECT_EQ("bar", req.get_param_value("param2"));
  5846. });
  5847. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5848. auto se = detail::scope_exit([&] {
  5849. svr.stop();
  5850. listen_thread.join();
  5851. ASSERT_FALSE(svr.is_running());
  5852. });
  5853. svr.wait_until_ready();
  5854. {
  5855. Client cli(HOST, PORT);
  5856. Params params;
  5857. params.emplace("hello", "world");
  5858. params.emplace("hello2", "world2");
  5859. params.emplace("hello3", "world3");
  5860. auto res = cli.Get("/", params, Headers{});
  5861. ASSERT_TRUE(res);
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. }
  5864. {
  5865. Client cli(HOST, PORT);
  5866. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5867. ASSERT_TRUE(res);
  5868. EXPECT_EQ(StatusCode::OK_200, res->status);
  5869. }
  5870. {
  5871. Client cli(HOST, PORT);
  5872. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5873. ASSERT_TRUE(res);
  5874. EXPECT_EQ(StatusCode::OK_200, res->status);
  5875. }
  5876. {
  5877. Client cli(HOST, PORT);
  5878. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5879. ASSERT_TRUE(res);
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. }
  5882. }
  5883. TEST(GetWithParametersTest, GetWithParameters2) {
  5884. Server svr;
  5885. svr.Get("/", [&](const Request &req, Response &res) {
  5886. auto text = req.get_param_value("hello");
  5887. res.set_content(text, "text/plain");
  5888. });
  5889. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. listen_thread.join();
  5893. ASSERT_FALSE(svr.is_running());
  5894. });
  5895. svr.wait_until_ready();
  5896. Client cli("localhost", PORT);
  5897. Params params;
  5898. params.emplace("hello", "world");
  5899. std::string body;
  5900. auto res = cli.Get("/", params, Headers{},
  5901. [&](const char *data, size_t data_length) {
  5902. body.append(data, data_length);
  5903. return true;
  5904. });
  5905. ASSERT_TRUE(res);
  5906. EXPECT_EQ(StatusCode::OK_200, res->status);
  5907. EXPECT_EQ("world", body);
  5908. }
  5909. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5910. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5911. auto host = "httpbin.org";
  5912. auto path = std::string{"/range/32"};
  5913. #else
  5914. auto host = "nghttp2.org";
  5915. auto path = std::string{"/httpbin/range/32"};
  5916. #endif
  5917. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5918. SSLClient cli(host);
  5919. #else
  5920. Client cli(host);
  5921. #endif
  5922. cli.set_default_headers({make_range_header({{1, 10}})});
  5923. cli.set_connection_timeout(5);
  5924. {
  5925. auto res = cli.Get(path);
  5926. ASSERT_TRUE(res);
  5927. EXPECT_EQ("bcdefghijk", res->body);
  5928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5929. }
  5930. {
  5931. auto res = cli.Get(path);
  5932. ASSERT_TRUE(res);
  5933. EXPECT_EQ("bcdefghijk", res->body);
  5934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5935. }
  5936. }
  5937. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5938. Server svr;
  5939. svr.set_default_headers({{"Hello", "World"}});
  5940. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5941. res.set_content("ok", "text/plain");
  5942. });
  5943. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5944. auto se = detail::scope_exit([&] {
  5945. svr.stop();
  5946. listen_thread.join();
  5947. ASSERT_FALSE(svr.is_running());
  5948. });
  5949. svr.wait_until_ready();
  5950. Client cli("localhost", PORT);
  5951. auto res = cli.Get("/");
  5952. ASSERT_TRUE(res);
  5953. EXPECT_EQ(StatusCode::OK_200, res->status);
  5954. EXPECT_EQ("ok", res->body);
  5955. EXPECT_EQ("World", res->get_header_value("Hello"));
  5956. }
  5957. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5958. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5960. ASSERT_TRUE(svr.is_valid());
  5961. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5962. std::this_thread::sleep_for(std::chrono::seconds(2));
  5963. res.set_content("a", "text/plain");
  5964. });
  5965. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5966. res.set_content("b", "text/plain");
  5967. });
  5968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5969. auto se = detail::scope_exit([&] {
  5970. svr.stop();
  5971. listen_thread.join();
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.wait_until_ready();
  5975. SSLClient cli("localhost", PORT);
  5976. cli.enable_server_certificate_verification(false);
  5977. cli.set_keep_alive(true);
  5978. cli.set_read_timeout(std::chrono::seconds(1));
  5979. auto resa = cli.Get("/a");
  5980. ASSERT_TRUE(!resa);
  5981. EXPECT_EQ(Error::Read, resa.error());
  5982. auto resb = cli.Get("/b");
  5983. ASSERT_TRUE(resb);
  5984. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5985. EXPECT_EQ("b", resb->body);
  5986. }
  5987. #endif
  5988. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5989. protected:
  5990. ServerTestWithAI_PASSIVE()
  5991. : cli_(HOST, PORT)
  5992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5993. ,
  5994. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5995. #endif
  5996. {
  5997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5998. cli_.enable_server_certificate_verification(false);
  5999. #endif
  6000. }
  6001. virtual void SetUp() {
  6002. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6003. res.set_content("Hello World!", "text/plain");
  6004. });
  6005. t_ = thread(
  6006. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6007. svr_.wait_until_ready();
  6008. }
  6009. virtual void TearDown() {
  6010. svr_.stop();
  6011. t_.join();
  6012. }
  6013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6014. SSLClient cli_;
  6015. SSLServer svr_;
  6016. #else
  6017. Client cli_;
  6018. Server svr_;
  6019. #endif
  6020. thread t_;
  6021. };
  6022. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6023. auto res = cli_.Get("/hi");
  6024. ASSERT_TRUE(res);
  6025. EXPECT_EQ(StatusCode::OK_200, res->status);
  6026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6027. EXPECT_EQ("Hello World!", res->body);
  6028. }
  6029. class ServerUpDownTest : public ::testing::Test {
  6030. protected:
  6031. ServerUpDownTest() : cli_(HOST, PORT) {}
  6032. virtual void SetUp() {
  6033. t_ = thread([&]() {
  6034. svr_.bind_to_any_port(HOST);
  6035. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6036. ASSERT_TRUE(svr_.listen_after_bind());
  6037. });
  6038. svr_.wait_until_ready();
  6039. }
  6040. virtual void TearDown() {
  6041. svr_.stop();
  6042. t_.join();
  6043. }
  6044. Client cli_;
  6045. Server svr_;
  6046. thread t_;
  6047. };
  6048. TEST_F(ServerUpDownTest, QuickStartStop) {
  6049. // Should not crash, especially when run with
  6050. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6051. }
  6052. class PayloadMaxLengthTest : public ::testing::Test {
  6053. protected:
  6054. PayloadMaxLengthTest()
  6055. : cli_(HOST, PORT)
  6056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6057. ,
  6058. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6059. #endif
  6060. {
  6061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6062. cli_.enable_server_certificate_verification(false);
  6063. #endif
  6064. }
  6065. virtual void SetUp() {
  6066. svr_.set_payload_max_length(8);
  6067. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6068. res.set_content("test", "text/plain");
  6069. });
  6070. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6071. svr_.wait_until_ready();
  6072. }
  6073. virtual void TearDown() {
  6074. svr_.stop();
  6075. t_.join();
  6076. }
  6077. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6078. SSLClient cli_;
  6079. SSLServer svr_;
  6080. #else
  6081. Client cli_;
  6082. Server svr_;
  6083. #endif
  6084. thread t_;
  6085. };
  6086. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6087. auto res = cli_.Post("/test", "123456789", "text/plain");
  6088. ASSERT_TRUE(res);
  6089. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6090. res = cli_.Post("/test", "12345678", "text/plain");
  6091. ASSERT_TRUE(res);
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. }
  6094. TEST(HostAndPortPropertiesTest, NoSSL) {
  6095. httplib::Client cli("www.google.com", 1234);
  6096. ASSERT_EQ("www.google.com", cli.host());
  6097. ASSERT_EQ(1234, cli.port());
  6098. }
  6099. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6100. httplib::Client cli("www.google.com:1234");
  6101. ASSERT_EQ("www.google.com", cli.host());
  6102. ASSERT_EQ(1234, cli.port());
  6103. }
  6104. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6105. TEST(HostAndPortPropertiesTest, SSL) {
  6106. httplib::SSLClient cli("www.google.com");
  6107. ASSERT_EQ("www.google.com", cli.host());
  6108. ASSERT_EQ(443, cli.port());
  6109. }
  6110. #endif
  6111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6112. TEST(SSLClientTest, UpdateCAStore) {
  6113. httplib::SSLClient httplib_client("www.google.com");
  6114. auto ca_store_1 = X509_STORE_new();
  6115. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6116. nullptr);
  6117. httplib_client.set_ca_cert_store(ca_store_1);
  6118. auto ca_store_2 = X509_STORE_new();
  6119. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6120. nullptr);
  6121. httplib_client.set_ca_cert_store(ca_store_2);
  6122. }
  6123. TEST(SSLClientTest, ServerNameIndication_Online) {
  6124. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6125. auto host = "httpbin.org";
  6126. auto path = std::string{"/get"};
  6127. #else
  6128. auto host = "nghttp2.org";
  6129. auto path = std::string{"/httpbin/get"};
  6130. #endif
  6131. SSLClient cli(host, 443);
  6132. auto res = cli.Get(path);
  6133. ASSERT_TRUE(res);
  6134. ASSERT_EQ(StatusCode::OK_200, res->status);
  6135. }
  6136. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6137. Client cli("https://google.com");
  6138. auto res = cli.Get("/");
  6139. ASSERT_TRUE(res);
  6140. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6141. }
  6142. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6143. SSLClient cli("google.com");
  6144. cli.enable_server_certificate_verification(true);
  6145. cli.set_ca_cert_path("hello");
  6146. auto res = cli.Get("/");
  6147. ASSERT_TRUE(!res);
  6148. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6149. }
  6150. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6151. SSLClient cli("google.com");
  6152. cli.set_ca_cert_path(CA_CERT_FILE);
  6153. auto res = cli.Get("/");
  6154. ASSERT_TRUE(res);
  6155. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6156. }
  6157. TEST(SSLClientTest, ServerCertificateVerification4) {
  6158. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6159. ASSERT_TRUE(svr.is_valid());
  6160. svr.Get("/test", [&](const Request &, Response &res) {
  6161. res.set_content("test", "text/plain");
  6162. svr.stop();
  6163. ASSERT_TRUE(true);
  6164. });
  6165. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6166. auto se = detail::scope_exit([&] {
  6167. t.join();
  6168. ASSERT_FALSE(svr.is_running());
  6169. });
  6170. svr.wait_until_ready();
  6171. SSLClient cli("127.0.0.1", PORT);
  6172. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6173. cli.enable_server_certificate_verification(true);
  6174. cli.set_connection_timeout(30);
  6175. auto res = cli.Get("/test");
  6176. ASSERT_TRUE(res);
  6177. ASSERT_EQ(StatusCode::OK_200, res->status);
  6178. }
  6179. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6180. std::string cert;
  6181. read_file(CA_CERT_FILE, cert);
  6182. SSLClient cli("google.com");
  6183. cli.load_ca_cert_store(cert.data(), cert.size());
  6184. const auto res = cli.Get("/");
  6185. ASSERT_TRUE(res);
  6186. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6187. }
  6188. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6189. // clang-format off
  6190. static constexpr char cert[] =
  6191. "GlobalSign Root CA\n"
  6192. "==================\n"
  6193. "-----BEGIN CERTIFICATE-----\n"
  6194. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6195. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6196. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6197. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6198. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6199. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6200. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6201. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6202. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6203. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6204. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6205. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6206. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6207. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6208. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6209. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6210. "-----END CERTIFICATE-----\n";
  6211. // clang-format on
  6212. SSLClient cli("google.com");
  6213. cli.load_ca_cert_store(cert, sizeof(cert));
  6214. const auto res = cli.Get("/");
  6215. ASSERT_TRUE(res);
  6216. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6217. }
  6218. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6219. SSLClient cli("www.youtube.com");
  6220. cli.set_ca_cert_path(CA_CERT_FILE);
  6221. cli.enable_server_certificate_verification(true);
  6222. cli.set_follow_location(true);
  6223. auto res = cli.Get("/");
  6224. ASSERT_TRUE(res);
  6225. ASSERT_EQ(StatusCode::OK_200, res->status);
  6226. }
  6227. TEST(SSLClientTest, Issue2004_Online) {
  6228. Client client("https://google.com");
  6229. client.set_follow_location(true);
  6230. auto res = client.Get("/");
  6231. ASSERT_TRUE(res);
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. auto body = res->body;
  6234. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6235. }
  6236. #if 0
  6237. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6238. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6239. ASSERT_TRUE(cli != nullptr);
  6240. cli->set_address_family(AF_INET6);
  6241. cli->set_interface("en0");
  6242. auto res = cli->Get("/get");
  6243. ASSERT_TRUE(res);
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. }
  6246. #endif
  6247. void ClientCertPresent(
  6248. const std::string &client_cert_file,
  6249. const std::string &client_private_key_file,
  6250. const std::string &client_encrypted_private_key_pass = std::string()) {
  6251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6252. CLIENT_CA_CERT_DIR);
  6253. ASSERT_TRUE(svr.is_valid());
  6254. svr.Get("/test", [&](const Request &req, Response &res) {
  6255. res.set_content("test", "text/plain");
  6256. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6257. ASSERT_TRUE(peer_cert != nullptr);
  6258. auto subject_name = X509_get_subject_name(peer_cert);
  6259. ASSERT_TRUE(subject_name != nullptr);
  6260. std::string common_name;
  6261. {
  6262. char name[BUFSIZ];
  6263. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6264. name, sizeof(name));
  6265. common_name.assign(name, static_cast<size_t>(name_len));
  6266. }
  6267. EXPECT_EQ("Common Name", common_name);
  6268. X509_free(peer_cert);
  6269. });
  6270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6271. auto se = detail::scope_exit([&] {
  6272. svr.stop();
  6273. t.join();
  6274. ASSERT_FALSE(svr.is_running());
  6275. });
  6276. svr.wait_until_ready();
  6277. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6278. client_encrypted_private_key_pass);
  6279. cli.enable_server_certificate_verification(false);
  6280. cli.set_connection_timeout(30);
  6281. auto res = cli.Get("/test");
  6282. ASSERT_TRUE(res);
  6283. ASSERT_EQ(StatusCode::OK_200, res->status);
  6284. }
  6285. TEST(SSLClientServerTest, ClientCertPresent) {
  6286. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6287. }
  6288. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6289. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6290. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6291. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6292. }
  6293. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6294. void MemoryClientCertPresent(
  6295. const std::string &client_cert_file,
  6296. const std::string &client_private_key_file,
  6297. const std::string &client_encrypted_private_key_pass = std::string()) {
  6298. auto f = fopen(SERVER_CERT_FILE, "r+");
  6299. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6300. fclose(f);
  6301. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6302. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6303. fclose(f);
  6304. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6305. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6306. auto client_ca_cert_store = X509_STORE_new();
  6307. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6308. X509_free(client_cert);
  6309. fclose(f);
  6310. f = fopen(client_cert_file.c_str(), "r+");
  6311. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6312. fclose(f);
  6313. f = fopen(client_private_key_file.c_str(), "r+");
  6314. auto client_private_key = PEM_read_PrivateKey(
  6315. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6316. fclose(f);
  6317. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6318. ASSERT_TRUE(svr.is_valid());
  6319. svr.Get("/test", [&](const Request &req, Response &res) {
  6320. res.set_content("test", "text/plain");
  6321. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6322. ASSERT_TRUE(peer_cert != nullptr);
  6323. auto subject_name = X509_get_subject_name(peer_cert);
  6324. ASSERT_TRUE(subject_name != nullptr);
  6325. std::string common_name;
  6326. {
  6327. char name[BUFSIZ];
  6328. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6329. name, sizeof(name));
  6330. common_name.assign(name, static_cast<size_t>(name_len));
  6331. }
  6332. EXPECT_EQ("Common Name", common_name);
  6333. X509_free(peer_cert);
  6334. });
  6335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6336. auto se = detail::scope_exit([&] {
  6337. svr.stop();
  6338. t.join();
  6339. ASSERT_FALSE(svr.is_running());
  6340. });
  6341. svr.wait_until_ready();
  6342. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6343. client_encrypted_private_key_pass);
  6344. cli.enable_server_certificate_verification(false);
  6345. cli.set_connection_timeout(30);
  6346. auto res = cli.Get("/test");
  6347. ASSERT_TRUE(res);
  6348. ASSERT_EQ(StatusCode::OK_200, res->status);
  6349. X509_free(server_cert);
  6350. EVP_PKEY_free(server_private_key);
  6351. X509_free(client_cert);
  6352. EVP_PKEY_free(client_private_key);
  6353. }
  6354. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6355. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6356. }
  6357. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6358. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6359. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6360. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6361. }
  6362. #endif
  6363. TEST(SSLClientServerTest, ClientCertMissing) {
  6364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6365. CLIENT_CA_CERT_DIR);
  6366. ASSERT_TRUE(svr.is_valid());
  6367. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  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);
  6376. auto res = cli.Get("/test");
  6377. cli.set_connection_timeout(30);
  6378. ASSERT_TRUE(!res);
  6379. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6380. }
  6381. TEST(SSLClientServerTest, TrustDirOptional) {
  6382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6383. ASSERT_TRUE(svr.is_valid());
  6384. svr.Get("/test", [&](const Request &, Response &res) {
  6385. res.set_content("test", "text/plain");
  6386. });
  6387. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6388. auto se = detail::scope_exit([&] {
  6389. svr.stop();
  6390. t.join();
  6391. ASSERT_FALSE(svr.is_running());
  6392. });
  6393. svr.wait_until_ready();
  6394. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6395. cli.enable_server_certificate_verification(false);
  6396. cli.set_connection_timeout(30);
  6397. auto res = cli.Get("/test");
  6398. ASSERT_TRUE(res);
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. }
  6401. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6402. class NoListenSSLServer : public SSLServer {
  6403. public:
  6404. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6405. const char *client_ca_cert_file_path,
  6406. const char *client_ca_cert_dir_path = nullptr)
  6407. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6408. client_ca_cert_dir_path),
  6409. stop_(false) {}
  6410. std::atomic_bool stop_;
  6411. private:
  6412. bool process_and_close_socket(socket_t /*sock*/) override {
  6413. // Don't create SSL context
  6414. while (!stop_.load()) {
  6415. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6416. }
  6417. return true;
  6418. }
  6419. };
  6420. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6421. CLIENT_CA_CERT_FILE);
  6422. ASSERT_TRUE(svr.is_valid());
  6423. svr.Get("/test", [&](const Request &, Response &res) {
  6424. res.set_content("test", "text/plain");
  6425. });
  6426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6427. auto se = detail::scope_exit([&] {
  6428. svr.stop_ = true;
  6429. svr.stop();
  6430. t.join();
  6431. ASSERT_FALSE(svr.is_running());
  6432. });
  6433. svr.wait_until_ready();
  6434. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6435. cli.enable_server_certificate_verification(false);
  6436. cli.set_connection_timeout(1);
  6437. auto res = cli.Get("/test");
  6438. ASSERT_TRUE(!res);
  6439. EXPECT_EQ(Error::SSLConnection, res.error());
  6440. }
  6441. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6442. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6443. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6444. SSL_CTX_set_options(&ssl_ctx,
  6445. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6446. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6447. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6448. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6449. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6450. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6451. "ECDHE-DSS-AES128-SHA256:"
  6452. "ECDHE-RSA-AES256-SHA256:"
  6453. "ECDHE-DSS-AES256-SHA256:";
  6454. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6455. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6456. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6457. SSL_FILETYPE_PEM) != 1) {
  6458. return false;
  6459. }
  6460. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6461. CLIENT_CA_CERT_DIR);
  6462. SSL_CTX_set_verify(
  6463. &ssl_ctx,
  6464. SSL_VERIFY_PEER |
  6465. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6466. nullptr);
  6467. return true;
  6468. };
  6469. SSLServer svr(setup_ssl_ctx_callback);
  6470. ASSERT_TRUE(svr.is_valid());
  6471. svr.Get("/test", [&](const Request &req, Response &res) {
  6472. res.set_content("test", "text/plain");
  6473. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6474. ASSERT_TRUE(peer_cert != nullptr);
  6475. auto subject_name = X509_get_subject_name(peer_cert);
  6476. ASSERT_TRUE(subject_name != nullptr);
  6477. std::string common_name;
  6478. {
  6479. char name[BUFSIZ];
  6480. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6481. name, sizeof(name));
  6482. common_name.assign(name, static_cast<size_t>(name_len));
  6483. }
  6484. EXPECT_EQ("Common Name", common_name);
  6485. X509_free(peer_cert);
  6486. });
  6487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6488. auto se = detail::scope_exit([&] {
  6489. svr.stop();
  6490. t.join();
  6491. ASSERT_FALSE(svr.is_running());
  6492. });
  6493. svr.wait_until_ready();
  6494. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6495. cli.enable_server_certificate_verification(false);
  6496. cli.set_connection_timeout(30);
  6497. auto res = cli.Get("/test");
  6498. ASSERT_TRUE(res);
  6499. ASSERT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6502. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6503. // prepare large data
  6504. std::random_device seed_gen;
  6505. std::mt19937 random(seed_gen());
  6506. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6507. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6508. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6509. // server
  6510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6511. ASSERT_TRUE(svr.is_valid());
  6512. svr.Post("/binary", [&](const Request &req, Response &res) {
  6513. EXPECT_EQ(large_size_byte, req.body.size());
  6514. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6515. res.set_content(req.body, "application/octet-stream");
  6516. });
  6517. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6518. auto se = detail::scope_exit([&] {
  6519. svr.stop();
  6520. listen_thread.join();
  6521. ASSERT_FALSE(svr.is_running());
  6522. });
  6523. svr.wait_until_ready();
  6524. // client POST
  6525. SSLClient cli("localhost", PORT);
  6526. cli.enable_server_certificate_verification(false);
  6527. cli.set_read_timeout(std::chrono::seconds(100));
  6528. cli.set_write_timeout(std::chrono::seconds(100));
  6529. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6530. large_size_byte, "application/octet-stream");
  6531. // compare
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. EXPECT_EQ(large_size_byte, res->body.size());
  6534. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6535. }
  6536. #endif
  6537. #ifdef _WIN32
  6538. TEST(CleanupTest, WSACleanup) {
  6539. int ret = WSACleanup();
  6540. ASSERT_EQ(0, ret);
  6541. }
  6542. #endif
  6543. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6544. TEST(NoSSLSupport, SimpleInterface) {
  6545. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6546. }
  6547. #endif
  6548. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6549. TEST(InvalidScheme, SimpleInterface) {
  6550. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6551. }
  6552. #endif
  6553. TEST(NoScheme, SimpleInterface) {
  6554. Client cli("yahoo.com:80");
  6555. ASSERT_TRUE(cli.is_valid());
  6556. }
  6557. TEST(SendAPI, SimpleInterface_Online) {
  6558. Client cli("http://yahoo.com");
  6559. Request req;
  6560. req.method = "GET";
  6561. req.path = "/";
  6562. auto res = cli.send(req);
  6563. ASSERT_TRUE(res);
  6564. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6565. }
  6566. TEST(SendAPI, WithParamsInRequest) {
  6567. Server svr;
  6568. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6569. EXPECT_TRUE(req.has_param("test"));
  6570. EXPECT_EQ("test_value", req.get_param_value("test"));
  6571. });
  6572. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6573. auto se = detail::scope_exit([&] {
  6574. svr.stop();
  6575. t.join();
  6576. ASSERT_FALSE(svr.is_running());
  6577. });
  6578. svr.wait_until_ready();
  6579. Client cli(HOST, PORT);
  6580. {
  6581. Request req;
  6582. req.method = "GET";
  6583. req.path = "/";
  6584. req.params.emplace("test", "test_value");
  6585. auto res = cli.send(req);
  6586. ASSERT_TRUE(res);
  6587. }
  6588. {
  6589. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6590. ASSERT_TRUE(res);
  6591. }
  6592. }
  6593. TEST(ClientImplMethods, GetSocketTest) {
  6594. httplib::Server svr;
  6595. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6596. res.status = StatusCode::OK_200;
  6597. });
  6598. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6599. auto se = detail::scope_exit([&] {
  6600. svr.stop();
  6601. thread.join();
  6602. ASSERT_FALSE(svr.is_running());
  6603. });
  6604. svr.wait_until_ready();
  6605. {
  6606. httplib::Client cli("http://127.0.0.1:3333");
  6607. cli.set_keep_alive(true);
  6608. // Use the behavior of cpp-httplib of opening the connection
  6609. // only when the first request happens. If that changes,
  6610. // this test would be obsolete.
  6611. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6612. // This also implicitly tests the server. But other tests would fail much
  6613. // earlier than this one to be considered.
  6614. auto res = cli.Get("/");
  6615. ASSERT_TRUE(res);
  6616. EXPECT_EQ(StatusCode::OK_200, res->status);
  6617. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6618. }
  6619. }
  6620. // Disabled due to out-of-memory problem on GitHub Actions
  6621. #ifdef _WIN64
  6622. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6623. // allocate content size larger than 2GB in memory
  6624. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6625. char *content = (char *)malloc(content_size);
  6626. ASSERT_TRUE(content);
  6627. Server svr;
  6628. svr.Get("/foo",
  6629. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6630. res.set_content(content, content_size, "application/octet-stream");
  6631. });
  6632. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6633. auto se = detail::scope_exit([&] {
  6634. svr.stop();
  6635. listen_thread.join();
  6636. if (content) free(content);
  6637. ASSERT_FALSE(svr.is_running());
  6638. });
  6639. svr.wait_until_ready();
  6640. Client cli(HOST, PORT);
  6641. auto res = cli.Get("/foo");
  6642. ASSERT_TRUE(res);
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ(content_size, res->body.length());
  6645. }
  6646. #endif
  6647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6648. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6649. Client cli("http://yahoo.com");
  6650. auto res = cli.Get("/");
  6651. ASSERT_TRUE(res);
  6652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6653. cli.set_follow_location(true);
  6654. res = cli.Get("/");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6658. }
  6659. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6660. Client cli("https://yahoo.com");
  6661. auto res = cli.Get("/");
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6664. cli.set_follow_location(true);
  6665. res = cli.Get("/");
  6666. ASSERT_TRUE(res);
  6667. EXPECT_EQ(StatusCode::OK_200, res->status);
  6668. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6669. }
  6670. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6671. Client cli("https://yahoo.com");
  6672. auto res = cli.Get("/");
  6673. ASSERT_TRUE(res);
  6674. ASSERT_FALSE(!res);
  6675. ASSERT_TRUE(res);
  6676. ASSERT_FALSE(res == nullptr);
  6677. ASSERT_TRUE(res != nullptr);
  6678. EXPECT_EQ(Error::Success, res.error());
  6679. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6680. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6681. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6682. cli.set_follow_location(true);
  6683. res = cli.Get("/");
  6684. ASSERT_TRUE(res);
  6685. EXPECT_EQ(Error::Success, res.error());
  6686. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6687. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6690. }
  6691. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6692. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6693. Client cli("https://cdnjs.cloudflare.com");
  6694. auto res =
  6695. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6696. ASSERT_TRUE(res);
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ(287630U, res->body.size());
  6699. EXPECT_EQ("application/javascript; charset=utf-8",
  6700. res->get_header_value("Content-Type"));
  6701. }
  6702. #endif
  6703. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6704. #undef REDIR_HOST // Silence compiler warning
  6705. #define REDIR_HOST "https://httpbingo.org"
  6706. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6707. Client cli(REDIR_HOST);
  6708. cli.set_follow_location(true);
  6709. auto res =
  6710. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6711. ASSERT_TRUE(res);
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. }
  6714. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6715. Client cli(REDIR_HOST);
  6716. cli.set_follow_location(true);
  6717. Params params;
  6718. params.emplace("url", "http://example.com");
  6719. params.emplace("status_code", "302");
  6720. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6721. ASSERT_TRUE(res);
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6725. Client cli(REDIR_HOST);
  6726. cli.set_follow_location(true);
  6727. Params params;
  6728. params.emplace("url", "http://example.com");
  6729. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6730. ASSERT_TRUE(res);
  6731. EXPECT_EQ(StatusCode::OK_200, res->status);
  6732. }
  6733. TEST(HttpToHttpsRedirectTest, CertFile) {
  6734. Server svr;
  6735. ASSERT_TRUE(svr.is_valid());
  6736. svr.Get("/index", [&](const Request &, Response &res) {
  6737. res.set_redirect("https://127.0.0.1:1235/index");
  6738. svr.stop();
  6739. });
  6740. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6741. ASSERT_TRUE(ssl_svr.is_valid());
  6742. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6743. res.set_content("test", "text/plain");
  6744. ssl_svr.stop();
  6745. });
  6746. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6747. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6748. auto se = detail::scope_exit([&] {
  6749. t2.join();
  6750. t.join();
  6751. ASSERT_FALSE(svr.is_running());
  6752. });
  6753. svr.wait_until_ready();
  6754. ssl_svr.wait_until_ready();
  6755. Client cli("127.0.0.1", PORT);
  6756. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6757. cli.enable_server_certificate_verification(true);
  6758. cli.set_follow_location(true);
  6759. cli.set_connection_timeout(30);
  6760. auto res = cli.Get("/index");
  6761. ASSERT_TRUE(res);
  6762. ASSERT_EQ(StatusCode::OK_200, res->status);
  6763. }
  6764. TEST(MultipartFormDataTest, LargeData) {
  6765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6766. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6767. const ContentReader &content_reader) {
  6768. if (req.is_multipart_form_data()) {
  6769. MultipartFormDataItems files;
  6770. content_reader(
  6771. [&](const MultipartFormData &file) {
  6772. files.push_back(file);
  6773. return true;
  6774. },
  6775. [&](const char *data, size_t data_length) {
  6776. files.back().content.append(data, data_length);
  6777. return true;
  6778. });
  6779. EXPECT_TRUE(std::string(files[0].name) == "document");
  6780. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6781. EXPECT_TRUE(files[0].filename == "2MB_data");
  6782. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6783. EXPECT_TRUE(files[1].name == "hello");
  6784. EXPECT_TRUE(files[1].content == "world");
  6785. EXPECT_TRUE(files[1].filename == "");
  6786. EXPECT_TRUE(files[1].content_type == "");
  6787. } else {
  6788. std::string body;
  6789. content_reader([&](const char *data, size_t data_length) {
  6790. body.append(data, data_length);
  6791. return true;
  6792. });
  6793. }
  6794. });
  6795. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6796. auto se = detail::scope_exit([&] {
  6797. svr.stop();
  6798. t.join();
  6799. ASSERT_FALSE(svr.is_running());
  6800. });
  6801. svr.wait_until_ready();
  6802. {
  6803. std::string data(1024 * 1024 * 2, '.');
  6804. std::stringstream buffer;
  6805. buffer << data;
  6806. Client cli("https://localhost:8080");
  6807. cli.enable_server_certificate_verification(false);
  6808. MultipartFormDataItemsForClientInput items{
  6809. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6810. {"hello", "world", "", ""},
  6811. };
  6812. auto res = cli.Post("/post", items);
  6813. ASSERT_TRUE(res);
  6814. ASSERT_EQ(StatusCode::OK_200, res->status);
  6815. }
  6816. }
  6817. TEST(MultipartFormDataTest, DataProviderItems) {
  6818. std::random_device seed_gen;
  6819. std::mt19937 random(seed_gen());
  6820. std::string rand1;
  6821. rand1.resize(1000);
  6822. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6823. std::string rand2;
  6824. rand2.resize(3000);
  6825. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6827. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6828. const ContentReader &content_reader) {
  6829. ASSERT_FALSE(req.is_multipart_form_data());
  6830. std::string body;
  6831. content_reader([&](const char *data, size_t data_length) {
  6832. body.append(data, data_length);
  6833. return true;
  6834. });
  6835. EXPECT_EQ(body, "");
  6836. });
  6837. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6838. const ContentReader &content_reader) {
  6839. ASSERT_TRUE(req.is_multipart_form_data());
  6840. MultipartFormDataItems files;
  6841. content_reader(
  6842. [&](const MultipartFormData &file) {
  6843. files.push_back(file);
  6844. return true;
  6845. },
  6846. [&](const char *data, size_t data_length) {
  6847. files.back().content.append(data, data_length);
  6848. return true;
  6849. });
  6850. ASSERT_TRUE(files.size() == 2);
  6851. EXPECT_EQ(std::string(files[0].name), "name1");
  6852. EXPECT_EQ(files[0].content, "Testing123");
  6853. EXPECT_EQ(files[0].filename, "filename1");
  6854. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6855. EXPECT_EQ(files[1].name, "name2");
  6856. EXPECT_EQ(files[1].content, "Testing456");
  6857. EXPECT_EQ(files[1].filename, "");
  6858. EXPECT_EQ(files[1].content_type, "");
  6859. });
  6860. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6861. const ContentReader &content_reader) {
  6862. ASSERT_TRUE(req.is_multipart_form_data());
  6863. MultipartFormDataItems files;
  6864. content_reader(
  6865. [&](const MultipartFormData &file) {
  6866. files.push_back(file);
  6867. return true;
  6868. },
  6869. [&](const char *data, size_t data_length) {
  6870. files.back().content.append(data, data_length);
  6871. return true;
  6872. });
  6873. ASSERT_TRUE(files.size() == 2);
  6874. EXPECT_EQ(files[0].name, "name3");
  6875. EXPECT_EQ(files[0].content, rand1);
  6876. EXPECT_EQ(files[0].filename, "filename3");
  6877. EXPECT_EQ(files[0].content_type, "");
  6878. EXPECT_EQ(files[1].name, "name4");
  6879. EXPECT_EQ(files[1].content, rand2);
  6880. EXPECT_EQ(files[1].filename, "filename4");
  6881. EXPECT_EQ(files[1].content_type, "");
  6882. });
  6883. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6884. const ContentReader &content_reader) {
  6885. ASSERT_TRUE(req.is_multipart_form_data());
  6886. MultipartFormDataItems files;
  6887. content_reader(
  6888. [&](const MultipartFormData &file) {
  6889. files.push_back(file);
  6890. return true;
  6891. },
  6892. [&](const char *data, size_t data_length) {
  6893. files.back().content.append(data, data_length);
  6894. return true;
  6895. });
  6896. ASSERT_TRUE(files.size() == 4);
  6897. EXPECT_EQ(std::string(files[0].name), "name1");
  6898. EXPECT_EQ(files[0].content, "Testing123");
  6899. EXPECT_EQ(files[0].filename, "filename1");
  6900. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6901. EXPECT_EQ(files[1].name, "name2");
  6902. EXPECT_EQ(files[1].content, "Testing456");
  6903. EXPECT_EQ(files[1].filename, "");
  6904. EXPECT_EQ(files[1].content_type, "");
  6905. EXPECT_EQ(files[2].name, "name3");
  6906. EXPECT_EQ(files[2].content, rand1);
  6907. EXPECT_EQ(files[2].filename, "filename3");
  6908. EXPECT_EQ(files[2].content_type, "");
  6909. EXPECT_EQ(files[3].name, "name4");
  6910. EXPECT_EQ(files[3].content, rand2);
  6911. EXPECT_EQ(files[3].filename, "filename4");
  6912. EXPECT_EQ(files[3].content_type, "");
  6913. });
  6914. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6915. auto se = detail::scope_exit([&] {
  6916. svr.stop();
  6917. t.join();
  6918. ASSERT_FALSE(svr.is_running());
  6919. });
  6920. svr.wait_until_ready();
  6921. {
  6922. Client cli("https://localhost:8080");
  6923. cli.enable_server_certificate_verification(false);
  6924. MultipartFormDataItemsForClientInput items{
  6925. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6926. {"name2", "Testing456", "", ""}, // not a file
  6927. };
  6928. {
  6929. auto res = cli.Post("/post-none", {}, {}, {});
  6930. ASSERT_TRUE(res);
  6931. ASSERT_EQ(StatusCode::OK_200, res->status);
  6932. }
  6933. MultipartFormDataProviderItems providers;
  6934. {
  6935. auto res =
  6936. cli.Post("/post-items", {}, items, providers); // empty providers
  6937. ASSERT_TRUE(res);
  6938. ASSERT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. providers.push_back({"name3",
  6941. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6942. // test the offset is given correctly at each step
  6943. if (!offset)
  6944. sink.os.write(rand1.data(), 30);
  6945. else if (offset == 30)
  6946. sink.os.write(rand1.data() + 30, 300);
  6947. else if (offset == 330)
  6948. sink.os.write(rand1.data() + 330, 670);
  6949. else if (offset == rand1.size())
  6950. sink.done();
  6951. return true;
  6952. },
  6953. "filename3",
  6954. {}});
  6955. providers.push_back({"name4",
  6956. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6957. // test the offset is given correctly at each step
  6958. if (!offset)
  6959. sink.os.write(rand2.data(), 2000);
  6960. else if (offset == 2000)
  6961. sink.os.write(rand2.data() + 2000, 1);
  6962. else if (offset == 2001)
  6963. sink.os.write(rand2.data() + 2001, 999);
  6964. else if (offset == rand2.size())
  6965. sink.done();
  6966. return true;
  6967. },
  6968. "filename4",
  6969. {}});
  6970. {
  6971. auto res = cli.Post("/post-providers", {}, {}, providers);
  6972. ASSERT_TRUE(res);
  6973. ASSERT_EQ(StatusCode::OK_200, res->status);
  6974. }
  6975. {
  6976. auto res = cli.Post("/post-both", {}, items, providers);
  6977. ASSERT_TRUE(res);
  6978. ASSERT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. }
  6981. }
  6982. TEST(MultipartFormDataTest, BadHeader) {
  6983. Server svr;
  6984. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6985. res.set_content("ok", "text/plain");
  6986. });
  6987. thread t = thread([&] { svr.listen(HOST, PORT); });
  6988. auto se = detail::scope_exit([&] {
  6989. svr.stop();
  6990. t.join();
  6991. ASSERT_FALSE(svr.is_running());
  6992. });
  6993. svr.wait_until_ready();
  6994. const std::string body =
  6995. "This is the preamble. It is to be ignored, though it\r\n"
  6996. "is a handy place for composition agents to include an\r\n"
  6997. "explanatory note to non-MIME conformant readers.\r\n"
  6998. "\r\n"
  6999. "\r\n"
  7000. "--simple boundary\r\n"
  7001. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7002. ": BAD...\r\n"
  7003. "\r\n"
  7004. "value1\r\n"
  7005. "--simple boundary\r\n"
  7006. "Content-Disposition: form-data; name=\"field2\"; "
  7007. "filename=\"example.txt\"\r\n"
  7008. "\r\n"
  7009. "value2\r\n"
  7010. "--simple boundary--\r\n"
  7011. "This is the epilogue. It is also to be ignored.\r\n";
  7012. std::string content_type =
  7013. R"(multipart/form-data; boundary="simple boundary")";
  7014. Client cli(HOST, PORT);
  7015. auto res = cli.Post("/post", body, content_type.c_str());
  7016. ASSERT_TRUE(res);
  7017. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7018. }
  7019. TEST(MultipartFormDataTest, WithPreamble) {
  7020. Server svr;
  7021. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7022. res.set_content("ok", "text/plain");
  7023. });
  7024. thread t = thread([&] { svr.listen(HOST, PORT); });
  7025. auto se = detail::scope_exit([&] {
  7026. svr.stop();
  7027. t.join();
  7028. ASSERT_FALSE(svr.is_running());
  7029. });
  7030. svr.wait_until_ready();
  7031. const std::string body =
  7032. "This is the preamble. It is to be ignored, though it\r\n"
  7033. "is a handy place for composition agents to include an\r\n"
  7034. "explanatory note to non-MIME conformant readers.\r\n"
  7035. "\r\n"
  7036. "\r\n"
  7037. "--simple boundary\r\n"
  7038. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7039. "\r\n"
  7040. "value1\r\n"
  7041. "--simple boundary\r\n"
  7042. "Content-Disposition: form-data; name=\"field2\"; "
  7043. "filename=\"example.txt\"\r\n"
  7044. "\r\n"
  7045. "value2\r\n"
  7046. "--simple boundary--\r\n"
  7047. "This is the epilogue. It is also to be ignored.\r\n";
  7048. std::string content_type =
  7049. R"(multipart/form-data; boundary="simple boundary")";
  7050. Client cli(HOST, PORT);
  7051. auto res = cli.Post("/post", body, content_type.c_str());
  7052. ASSERT_TRUE(res);
  7053. EXPECT_EQ(StatusCode::OK_200, res->status);
  7054. }
  7055. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7056. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7057. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7058. const ContentReader &content_reader) {
  7059. if (req.is_multipart_form_data()) {
  7060. MultipartFormDataItems files;
  7061. content_reader(
  7062. [&](const MultipartFormData &file) {
  7063. files.push_back(file);
  7064. return true;
  7065. },
  7066. [&](const char *data, size_t data_length) {
  7067. files.back().content.append(data, data_length);
  7068. return true;
  7069. });
  7070. EXPECT_TRUE(std::string(files[0].name) == "document");
  7071. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7072. EXPECT_TRUE(files[0].filename == "2MB_data");
  7073. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7074. EXPECT_TRUE(files[1].name == "hello");
  7075. EXPECT_TRUE(files[1].content == "world");
  7076. EXPECT_TRUE(files[1].filename == "");
  7077. EXPECT_TRUE(files[1].content_type == "");
  7078. } else {
  7079. std::string body;
  7080. content_reader([&](const char *data, size_t data_length) {
  7081. body.append(data, data_length);
  7082. return true;
  7083. });
  7084. }
  7085. });
  7086. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7087. auto se = detail::scope_exit([&] {
  7088. svr.stop();
  7089. t.join();
  7090. ASSERT_FALSE(svr.is_running());
  7091. });
  7092. svr.wait_until_ready();
  7093. {
  7094. std::string data(1024 * 1024 * 2, '.');
  7095. std::stringstream buffer;
  7096. buffer << data;
  7097. Client cli("https://localhost:8080");
  7098. cli.enable_server_certificate_verification(false);
  7099. MultipartFormDataItemsForClientInput items{
  7100. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7101. {"hello", "world", "", ""},
  7102. };
  7103. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7104. ASSERT_TRUE(res);
  7105. ASSERT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. }
  7108. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7109. std::string data(1024 * 1024 * 2, '&');
  7110. std::stringstream buffer;
  7111. buffer << data;
  7112. Client cli("https://localhost:8080");
  7113. MultipartFormDataItemsForClientInput items{
  7114. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7115. {"hello", "world", "", ""},
  7116. };
  7117. for (const char &c : " \t\r\n") {
  7118. auto res =
  7119. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7120. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7121. ASSERT_FALSE(res);
  7122. }
  7123. }
  7124. TEST(MultipartFormDataTest, PutFormData) {
  7125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7126. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7127. const ContentReader &content_reader) {
  7128. if (req.is_multipart_form_data()) {
  7129. MultipartFormDataItems files;
  7130. content_reader(
  7131. [&](const MultipartFormData &file) {
  7132. files.push_back(file);
  7133. return true;
  7134. },
  7135. [&](const char *data, size_t data_length) {
  7136. files.back().content.append(data, data_length);
  7137. return true;
  7138. });
  7139. EXPECT_TRUE(std::string(files[0].name) == "document");
  7140. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7141. EXPECT_TRUE(files[0].filename == "2MB_data");
  7142. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7143. EXPECT_TRUE(files[1].name == "hello");
  7144. EXPECT_TRUE(files[1].content == "world");
  7145. EXPECT_TRUE(files[1].filename == "");
  7146. EXPECT_TRUE(files[1].content_type == "");
  7147. } else {
  7148. std::string body;
  7149. content_reader([&](const char *data, size_t data_length) {
  7150. body.append(data, data_length);
  7151. return true;
  7152. });
  7153. }
  7154. });
  7155. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7156. auto se = detail::scope_exit([&] {
  7157. svr.stop();
  7158. t.join();
  7159. ASSERT_FALSE(svr.is_running());
  7160. });
  7161. svr.wait_until_ready();
  7162. {
  7163. std::string data(1024 * 1024 * 2, '&');
  7164. std::stringstream buffer;
  7165. buffer << data;
  7166. Client cli("https://localhost:8080");
  7167. cli.enable_server_certificate_verification(false);
  7168. MultipartFormDataItemsForClientInput items{
  7169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7170. {"hello", "world", "", ""},
  7171. };
  7172. auto res = cli.Put("/put", items);
  7173. ASSERT_TRUE(res);
  7174. ASSERT_EQ(StatusCode::OK_200, res->status);
  7175. }
  7176. }
  7177. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7179. svr.Put("/put_customboundary",
  7180. [&](const Request &req, const Response & /*res*/,
  7181. const ContentReader &content_reader) {
  7182. if (req.is_multipart_form_data()) {
  7183. MultipartFormDataItems files;
  7184. content_reader(
  7185. [&](const MultipartFormData &file) {
  7186. files.push_back(file);
  7187. return true;
  7188. },
  7189. [&](const char *data, size_t data_length) {
  7190. files.back().content.append(data, data_length);
  7191. return true;
  7192. });
  7193. EXPECT_TRUE(std::string(files[0].name) == "document");
  7194. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7195. EXPECT_TRUE(files[0].filename == "2MB_data");
  7196. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7197. EXPECT_TRUE(files[1].name == "hello");
  7198. EXPECT_TRUE(files[1].content == "world");
  7199. EXPECT_TRUE(files[1].filename == "");
  7200. EXPECT_TRUE(files[1].content_type == "");
  7201. } else {
  7202. std::string body;
  7203. content_reader([&](const char *data, size_t data_length) {
  7204. body.append(data, data_length);
  7205. return true;
  7206. });
  7207. }
  7208. });
  7209. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7210. auto se = detail::scope_exit([&] {
  7211. svr.stop();
  7212. t.join();
  7213. ASSERT_FALSE(svr.is_running());
  7214. });
  7215. svr.wait_until_ready();
  7216. {
  7217. std::string data(1024 * 1024 * 2, '&');
  7218. std::stringstream buffer;
  7219. buffer << data;
  7220. Client cli("https://localhost:8080");
  7221. cli.enable_server_certificate_verification(false);
  7222. MultipartFormDataItemsForClientInput items{
  7223. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7224. {"hello", "world", "", ""},
  7225. };
  7226. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7227. ASSERT_TRUE(res);
  7228. ASSERT_EQ(StatusCode::OK_200, res->status);
  7229. }
  7230. }
  7231. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7232. std::string data(1024 * 1024 * 2, '&');
  7233. std::stringstream buffer;
  7234. buffer << data;
  7235. Client cli("https://localhost:8080");
  7236. cli.enable_server_certificate_verification(false);
  7237. MultipartFormDataItemsForClientInput items{
  7238. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7239. {"hello", "world", "", ""},
  7240. };
  7241. for (const char &c : " \t\r\n") {
  7242. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7243. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7244. ASSERT_FALSE(res);
  7245. }
  7246. }
  7247. TEST(MultipartFormDataTest, AlternateFilename) {
  7248. auto handled = false;
  7249. Server svr;
  7250. svr.Post("/test", [&](const Request &req, Response &res) {
  7251. ASSERT_EQ(3u, req.files.size());
  7252. auto it = req.files.begin();
  7253. ASSERT_EQ("file1", it->second.name);
  7254. ASSERT_EQ("A.txt", it->second.filename);
  7255. ASSERT_EQ("text/plain", it->second.content_type);
  7256. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7257. ++it;
  7258. ASSERT_EQ("file2", it->second.name);
  7259. ASSERT_EQ("a.html", it->second.filename);
  7260. ASSERT_EQ("text/html", it->second.content_type);
  7261. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7262. it->second.content);
  7263. ++it;
  7264. ASSERT_EQ("text", it->second.name);
  7265. ASSERT_EQ("", it->second.filename);
  7266. ASSERT_EQ("", it->second.content_type);
  7267. ASSERT_EQ("text default", it->second.content);
  7268. res.set_content("ok", "text/plain");
  7269. handled = true;
  7270. });
  7271. thread t = thread([&] { svr.listen(HOST, PORT); });
  7272. auto se = detail::scope_exit([&] {
  7273. svr.stop();
  7274. t.join();
  7275. ASSERT_FALSE(svr.is_running());
  7276. ASSERT_TRUE(handled);
  7277. });
  7278. svr.wait_until_ready();
  7279. auto req = "POST /test HTTP/1.1\r\n"
  7280. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7281. "Content-Length: 399\r\n"
  7282. "\r\n"
  7283. "----------\r\n"
  7284. "Content-Disposition: form-data; name=\"text\"\r\n"
  7285. "\r\n"
  7286. "text default\r\n"
  7287. "----------\r\n"
  7288. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7289. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7290. "Content-Type: text/plain\r\n"
  7291. "\r\n"
  7292. "Content of a.txt.\r\n"
  7293. "\r\n"
  7294. "----------\r\n"
  7295. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7296. "\"a.html\"\r\n"
  7297. "Content-Type: text/html\r\n"
  7298. "\r\n"
  7299. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7300. "\r\n"
  7301. "------------\r\n";
  7302. ASSERT_TRUE(send_request(1, req));
  7303. }
  7304. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7305. auto handled = false;
  7306. Server svr;
  7307. svr.Post("/test", [&](const Request &req, Response &) {
  7308. ASSERT_EQ(2u, req.files.size());
  7309. auto it = req.files.begin();
  7310. ASSERT_EQ("text1", it->second.name);
  7311. ASSERT_EQ("text1", it->second.content);
  7312. ++it;
  7313. ASSERT_EQ("text2", it->second.name);
  7314. ASSERT_EQ("text2", it->second.content);
  7315. handled = true;
  7316. });
  7317. thread t = thread([&] { svr.listen(HOST, PORT); });
  7318. auto se = detail::scope_exit([&] {
  7319. svr.stop();
  7320. t.join();
  7321. ASSERT_FALSE(svr.is_running());
  7322. ASSERT_TRUE(handled);
  7323. });
  7324. svr.wait_until_ready();
  7325. auto req = "POST /test HTTP/1.1\r\n"
  7326. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7327. "Content-Length: 146\r\n"
  7328. "\r\n----------\r\n"
  7329. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7330. "\r\n"
  7331. "text1"
  7332. "\r\n----------\r\n"
  7333. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7334. "\r\n"
  7335. "text2"
  7336. "\r\n------------";
  7337. std::string response;
  7338. ASSERT_TRUE(send_request(1, req, &response));
  7339. ASSERT_EQ("200", response.substr(9, 3));
  7340. }
  7341. TEST(MultipartFormDataTest, ContentLength) {
  7342. auto handled = false;
  7343. Server svr;
  7344. svr.Post("/test", [&](const Request &req, Response &) {
  7345. ASSERT_EQ(2u, req.files.size());
  7346. auto it = req.files.begin();
  7347. ASSERT_EQ("text1", it->second.name);
  7348. ASSERT_EQ("text1", it->second.content);
  7349. ++it;
  7350. ASSERT_EQ("text2", it->second.name);
  7351. ASSERT_EQ("text2", it->second.content);
  7352. handled = true;
  7353. });
  7354. thread t = thread([&] { svr.listen(HOST, PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. t.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. ASSERT_TRUE(handled);
  7360. });
  7361. svr.wait_until_ready();
  7362. auto req = "POST /test HTTP/1.1\r\n"
  7363. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7364. "Content-Length: 167\r\n"
  7365. "\r\n----------\r\n"
  7366. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7367. "Content-Length: 5\r\n"
  7368. "\r\n"
  7369. "text1"
  7370. "\r\n----------\r\n"
  7371. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7372. "\r\n"
  7373. "text2"
  7374. "\r\n------------\r\n";
  7375. std::string response;
  7376. ASSERT_TRUE(send_request(1, req, &response));
  7377. ASSERT_EQ("200", response.substr(9, 3));
  7378. }
  7379. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7380. auto handled = false;
  7381. Server svr;
  7382. svr.Post("/test", [&](const Request &req, Response &) {
  7383. ASSERT_EQ(2u, req.files.size());
  7384. auto it = req.files.begin();
  7385. ASSERT_EQ("text1", it->second.name);
  7386. ASSERT_EQ("text1", it->second.content);
  7387. ASSERT_EQ(1U, it->second.headers.count("Content-Length"));
  7388. auto content_length = it->second.headers.find("CONTENT-length");
  7389. ASSERT_EQ("5", content_length->second);
  7390. ASSERT_EQ(3U, it->second.headers.size());
  7391. ++it;
  7392. ASSERT_EQ("text2", it->second.name);
  7393. ASSERT_EQ("text2", it->second.content);
  7394. auto &headers = it->second.headers;
  7395. ASSERT_EQ(3U, headers.size());
  7396. auto custom_header = headers.find("x-whatever");
  7397. ASSERT_TRUE(custom_header != headers.end());
  7398. ASSERT_NE("customvalue", custom_header->second);
  7399. ASSERT_EQ("CustomValue", custom_header->second);
  7400. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7401. handled = true;
  7402. });
  7403. thread t = thread([&] { svr.listen(HOST, PORT); });
  7404. auto se = detail::scope_exit([&] {
  7405. svr.stop();
  7406. t.join();
  7407. ASSERT_FALSE(svr.is_running());
  7408. ASSERT_TRUE(handled);
  7409. });
  7410. svr.wait_until_ready();
  7411. auto req = "POST /test HTTP/1.1\r\n"
  7412. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7413. "Content-Length: 232\r\n"
  7414. "\r\n----------\r\n"
  7415. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7416. "Content-Length: 5\r\n"
  7417. "X-Test: 1\r\n"
  7418. "\r\n"
  7419. "text1"
  7420. "\r\n----------\r\n"
  7421. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7422. "Content-Type: text/plain\r\n"
  7423. "X-Whatever: CustomValue\r\n"
  7424. "\r\n"
  7425. "text2"
  7426. "\r\n------------\r\n"
  7427. "That should be disregarded. Not even read";
  7428. std::string response;
  7429. ASSERT_TRUE(send_request(1, req, &response));
  7430. ASSERT_EQ("200", response.substr(9, 3));
  7431. }
  7432. #endif
  7433. TEST(MultipartFormDataTest, LargeHeader) {
  7434. auto handled = false;
  7435. Server svr;
  7436. svr.Post("/test", [&](const Request &req, Response &) {
  7437. ASSERT_EQ(1u, req.files.size());
  7438. auto it = req.files.begin();
  7439. ASSERT_EQ("name1", it->second.name);
  7440. ASSERT_EQ("text1", it->second.content);
  7441. handled = true;
  7442. });
  7443. thread t = thread([&] { svr.listen(HOST, PORT); });
  7444. auto se = detail::scope_exit([&] {
  7445. svr.stop();
  7446. t.join();
  7447. ASSERT_FALSE(svr.is_running());
  7448. ASSERT_TRUE(handled);
  7449. });
  7450. svr.wait_until_ready();
  7451. auto boundary = std::string("cpp-httplib-multipart-data");
  7452. std::string content = "--" + boundary +
  7453. "\r\n"
  7454. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7455. "\r\n"
  7456. "text1\r\n"
  7457. "--" +
  7458. boundary + "--\r\n";
  7459. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7460. "Content-Type: multipart/form-data;boundary=" +
  7461. boundary +
  7462. "\r\n"
  7463. "Content-Length: " +
  7464. std::to_string(content.size()) +
  7465. "\r\n"
  7466. "Dummy-Header: ";
  7467. std::string header_suffix = "\r\n"
  7468. "\r\n";
  7469. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7470. size_t header_dummy_size =
  7471. read_buff_size -
  7472. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7473. auto header_dummy = std::string(header_dummy_size, '@');
  7474. auto req = header_prefix + header_dummy + header_suffix + content;
  7475. std::string response;
  7476. ASSERT_TRUE(send_request(1, req, &response));
  7477. ASSERT_EQ("200", response.substr(9, 3));
  7478. }
  7479. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7480. static constexpr unsigned int number_of_tasks{1000000};
  7481. std::atomic_uint count{0};
  7482. std::unique_ptr<TaskQueue> task_queue{
  7483. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7484. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7485. auto queued = task_queue->enqueue(
  7486. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7487. EXPECT_TRUE(queued);
  7488. }
  7489. EXPECT_NO_THROW(task_queue->shutdown());
  7490. EXPECT_EQ(number_of_tasks, count.load());
  7491. }
  7492. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7493. static constexpr unsigned int number_of_tasks{1000000};
  7494. static constexpr unsigned int qlimit{2};
  7495. unsigned int queued_count{0};
  7496. std::atomic_uint count{0};
  7497. std::unique_ptr<TaskQueue> task_queue{
  7498. new ThreadPool{/*num_threads=*/1, qlimit}};
  7499. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7500. if (task_queue->enqueue(
  7501. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7502. queued_count++;
  7503. }
  7504. }
  7505. EXPECT_NO_THROW(task_queue->shutdown());
  7506. EXPECT_EQ(queued_count, count.load());
  7507. EXPECT_TRUE(queued_count <= number_of_tasks);
  7508. EXPECT_TRUE(queued_count >= qlimit);
  7509. }
  7510. TEST(TaskQueueTest, MaxQueuedRequests) {
  7511. static constexpr unsigned int qlimit{3};
  7512. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7513. std::condition_variable sem_cv;
  7514. std::mutex sem_mtx;
  7515. int credits = 0;
  7516. bool queued;
  7517. /* Fill up the queue with tasks that will block until we give them credits to
  7518. * complete. */
  7519. for (unsigned int n = 0; n <= qlimit;) {
  7520. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7521. std::unique_lock<std::mutex> lock(sem_mtx);
  7522. while (credits <= 0) {
  7523. sem_cv.wait(lock);
  7524. }
  7525. /* Consume the credit and signal the test code if they are all gone. */
  7526. if (--credits == 0) { sem_cv.notify_one(); }
  7527. });
  7528. if (n < qlimit) {
  7529. /* The first qlimit enqueues must succeed. */
  7530. EXPECT_TRUE(queued);
  7531. } else {
  7532. /* The last one will succeed only when the worker thread
  7533. * starts and dequeues the first blocking task. Although
  7534. * not necessary for the correctness of this test, we sleep for
  7535. * a short while to avoid busy waiting. */
  7536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7537. }
  7538. if (queued) { n++; }
  7539. }
  7540. /* Further enqueues must fail since the queue is full. */
  7541. for (auto i = 0; i < 4; i++) {
  7542. queued = task_queue->enqueue([] {});
  7543. EXPECT_FALSE(queued);
  7544. }
  7545. /* Give the credits to allow the previous tasks to complete. */
  7546. {
  7547. std::unique_lock<std::mutex> lock(sem_mtx);
  7548. credits += qlimit + 1;
  7549. }
  7550. sem_cv.notify_all();
  7551. /* Wait for all the credits to be consumed. */
  7552. {
  7553. std::unique_lock<std::mutex> lock(sem_mtx);
  7554. while (credits > 0) {
  7555. sem_cv.wait(lock);
  7556. }
  7557. }
  7558. /* Check that we are able again to enqueue at least qlimit tasks. */
  7559. for (unsigned int i = 0; i < qlimit; i++) {
  7560. queued = task_queue->enqueue([] {});
  7561. EXPECT_TRUE(queued);
  7562. }
  7563. EXPECT_NO_THROW(task_queue->shutdown());
  7564. }
  7565. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7566. Server svr;
  7567. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7568. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7569. });
  7570. svr.Get("/hello", [](const Request &req, Response &res) {
  7571. res.set_content(req.get_param_value("key"), "text/plain");
  7572. });
  7573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7574. auto se = detail::scope_exit([&] {
  7575. svr.stop();
  7576. thread.join();
  7577. ASSERT_FALSE(svr.is_running());
  7578. });
  7579. svr.wait_until_ready();
  7580. {
  7581. Client cli(HOST, PORT);
  7582. cli.set_follow_location(true);
  7583. auto res = cli.Get("/");
  7584. ASSERT_TRUE(res);
  7585. EXPECT_EQ(StatusCode::OK_200, res->status);
  7586. EXPECT_EQ("val&key2=val2", res->body);
  7587. }
  7588. }
  7589. TEST(VulnerabilityTest, CRLFInjection) {
  7590. Server svr;
  7591. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7592. res.set_content("Hello 1", "text/plain");
  7593. });
  7594. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7595. res.set_content("Hello 2", "text/plain");
  7596. });
  7597. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7598. res.set_content("Hello 3", "text/plain");
  7599. });
  7600. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7601. res.set_content("Hello 4", "text/plain");
  7602. });
  7603. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7604. for (const auto &x : req.headers) {
  7605. auto key = x.first;
  7606. EXPECT_STRNE("evil", key.c_str());
  7607. }
  7608. });
  7609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7610. auto se = detail::scope_exit([&] {
  7611. svr.stop();
  7612. thread.join();
  7613. ASSERT_FALSE(svr.is_running());
  7614. });
  7615. svr.wait_until_ready();
  7616. {
  7617. Client cli(HOST, PORT);
  7618. cli.Post("/test1", "A=B",
  7619. "application/x-www-form-urlencoded\r\nevil: hello1");
  7620. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7621. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7622. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7623. }
  7624. }
  7625. TEST(PathParamsTest, StaticMatch) {
  7626. const auto pattern = "/users/all";
  7627. detail::PathParamsMatcher matcher(pattern);
  7628. Request request;
  7629. request.path = "/users/all";
  7630. ASSERT_TRUE(matcher.match(request));
  7631. std::unordered_map<std::string, std::string> expected_params = {};
  7632. EXPECT_EQ(request.path_params, expected_params);
  7633. }
  7634. TEST(PathParamsTest, StaticMismatch) {
  7635. const auto pattern = "/users/all";
  7636. detail::PathParamsMatcher matcher(pattern);
  7637. Request request;
  7638. request.path = "/users/1";
  7639. ASSERT_FALSE(matcher.match(request));
  7640. }
  7641. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7642. const auto pattern = "/users/:id/subscriptions";
  7643. detail::PathParamsMatcher matcher(pattern);
  7644. Request request;
  7645. request.path = "/users/42/subscriptions";
  7646. ASSERT_TRUE(matcher.match(request));
  7647. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7648. EXPECT_EQ(request.path_params, expected_params);
  7649. }
  7650. TEST(PathParamsTest, SingleParamInTheEnd) {
  7651. const auto pattern = "/users/:id";
  7652. detail::PathParamsMatcher matcher(pattern);
  7653. Request request;
  7654. request.path = "/users/24";
  7655. ASSERT_TRUE(matcher.match(request));
  7656. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7657. EXPECT_EQ(request.path_params, expected_params);
  7658. }
  7659. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7660. const auto pattern = "/users/:id/";
  7661. detail::PathParamsMatcher matcher(pattern);
  7662. Request request;
  7663. request.path = "/users/42/";
  7664. ASSERT_TRUE(matcher.match(request));
  7665. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7666. EXPECT_EQ(request.path_params, expected_params);
  7667. }
  7668. TEST(PathParamsTest, EmptyParam) {
  7669. const auto pattern = "/users/:id/";
  7670. detail::PathParamsMatcher matcher(pattern);
  7671. Request request;
  7672. request.path = "/users//";
  7673. ASSERT_TRUE(matcher.match(request));
  7674. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  7675. EXPECT_EQ(request.path_params, expected_params);
  7676. }
  7677. TEST(PathParamsTest, FragmentMismatch) {
  7678. const auto pattern = "/users/:id/";
  7679. detail::PathParamsMatcher matcher(pattern);
  7680. Request request;
  7681. request.path = "/admins/24/";
  7682. ASSERT_FALSE(matcher.match(request));
  7683. }
  7684. TEST(PathParamsTest, ExtraFragments) {
  7685. const auto pattern = "/users/:id";
  7686. detail::PathParamsMatcher matcher(pattern);
  7687. Request request;
  7688. request.path = "/users/42/subscriptions";
  7689. ASSERT_FALSE(matcher.match(request));
  7690. }
  7691. TEST(PathParamsTest, MissingTrailingParam) {
  7692. const auto pattern = "/users/:id";
  7693. detail::PathParamsMatcher matcher(pattern);
  7694. Request request;
  7695. request.path = "/users";
  7696. ASSERT_FALSE(matcher.match(request));
  7697. }
  7698. TEST(PathParamsTest, MissingParamInTheMiddle) {
  7699. const auto pattern = "/users/:id/subscriptions";
  7700. detail::PathParamsMatcher matcher(pattern);
  7701. Request request;
  7702. request.path = "/users/subscriptions";
  7703. ASSERT_FALSE(matcher.match(request));
  7704. }
  7705. TEST(PathParamsTest, MultipleParams) {
  7706. const auto pattern = "/users/:userid/subscriptions/:subid";
  7707. detail::PathParamsMatcher matcher(pattern);
  7708. Request request;
  7709. request.path = "/users/42/subscriptions/2";
  7710. ASSERT_TRUE(matcher.match(request));
  7711. std::unordered_map<std::string, std::string> expected_params = {
  7712. {"userid", "42"}, {"subid", "2"}};
  7713. EXPECT_EQ(request.path_params, expected_params);
  7714. }
  7715. TEST(PathParamsTest, SequenceOfParams) {
  7716. const auto pattern = "/values/:x/:y/:z";
  7717. detail::PathParamsMatcher matcher(pattern);
  7718. Request request;
  7719. request.path = "/values/1/2/3";
  7720. ASSERT_TRUE(matcher.match(request));
  7721. std::unordered_map<std::string, std::string> expected_params = {
  7722. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  7723. EXPECT_EQ(request.path_params, expected_params);
  7724. }
  7725. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  7726. const auto pattern = "/prefix:suffix";
  7727. detail::PathParamsMatcher matcher(pattern);
  7728. Request request;
  7729. request.path = "/prefix:suffix";
  7730. ASSERT_TRUE(matcher.match(request));
  7731. const std::unordered_map<std::string, std::string> expected_params = {};
  7732. EXPECT_EQ(request.path_params, expected_params);
  7733. }
  7734. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  7735. // If ipv6 regex working, regex match codepath is taken.
  7736. // else port will default to 80 in Client impl
  7737. int clientImplMagicPort = 80;
  7738. int port = 4321;
  7739. // above ports must be different to avoid false negative
  7740. EXPECT_NE(clientImplMagicPort, port);
  7741. std::string ipV6TestURL = "http://[ff06::c3]";
  7742. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  7743. CLIENT_PRIVATE_KEY_FILE);
  7744. EXPECT_EQ(cli.port(), port);
  7745. }
  7746. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  7747. auto file_path = "./www/dir/index.html";
  7748. auto dir_path = "./www/dir";
  7749. detail::FileStat stat_file(file_path);
  7750. EXPECT_TRUE(stat_file.is_file());
  7751. EXPECT_FALSE(stat_file.is_dir());
  7752. detail::FileStat stat_dir(dir_path);
  7753. EXPECT_FALSE(stat_dir.is_file());
  7754. EXPECT_TRUE(stat_dir.is_dir());
  7755. }
  7756. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  7757. Server svr;
  7758. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7759. EXPECT_EQ(res.status, 400);
  7760. });
  7761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7762. auto se = detail::scope_exit([&] {
  7763. svr.stop();
  7764. thread.join();
  7765. ASSERT_FALSE(svr.is_running());
  7766. });
  7767. svr.wait_until_ready();
  7768. Client cli(HOST, PORT);
  7769. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  7770. }
  7771. TEST(InvalidHeaderCharsTest, is_field_name) {
  7772. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  7773. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  7774. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  7775. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  7776. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  7777. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  7778. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  7779. EXPECT_FALSE(detail::fields::is_field_name(""));
  7780. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  7781. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  7782. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  7783. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  7784. }
  7785. TEST(InvalidHeaderCharsTest, is_field_value) {
  7786. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  7787. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  7788. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  7789. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  7790. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  7791. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  7792. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  7793. EXPECT_TRUE(detail::fields::is_field_value(""));
  7794. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  7795. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  7796. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  7797. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  7798. EXPECT_TRUE(detail::fields::is_field_value("0"));
  7799. }
  7800. TEST(InvalidHeaderCharsTest, OnServer) {
  7801. Server svr;
  7802. svr.Get("/test_name", [&](const Request &req, Response &res) {
  7803. std::string header = "Not Set";
  7804. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7805. res.set_header(header, "value");
  7806. res.set_content("Page Content Page Content", "text/plain");
  7807. });
  7808. svr.Get("/test_value", [&](const Request &req, Response &res) {
  7809. std::string header = "Not Set";
  7810. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7811. res.set_header("X-Test", header);
  7812. res.set_content("Page Content Page Content", "text/plain");
  7813. });
  7814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7815. auto se = detail::scope_exit([&] {
  7816. svr.stop();
  7817. thread.join();
  7818. ASSERT_FALSE(svr.is_running());
  7819. });
  7820. svr.wait_until_ready();
  7821. Client cli(HOST, PORT);
  7822. {
  7823. auto res = cli.Get(
  7824. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7825. ASSERT_TRUE(res);
  7826. EXPECT_EQ("Page Content Page Content", res->body);
  7827. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7828. }
  7829. {
  7830. auto res = cli.Get(
  7831. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7832. ASSERT_TRUE(res);
  7833. EXPECT_EQ("Page Content Page Content", res->body);
  7834. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7835. }
  7836. }
  7837. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  7838. auto handled = false;
  7839. Server svr;
  7840. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  7841. thread t = thread([&] { svr.listen(HOST, PORT); });
  7842. auto se = detail::scope_exit([&] {
  7843. svr.stop();
  7844. t.join();
  7845. ASSERT_FALSE(svr.is_running());
  7846. ASSERT_FALSE(handled);
  7847. });
  7848. svr.wait_until_ready();
  7849. auto req = "POST /test HTTP/1.1\r\n"
  7850. "Content-Length: x\r\n"
  7851. "\r\n";
  7852. std::string response;
  7853. ASSERT_TRUE(send_request(1, req, &response));
  7854. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7855. response.substr(0, response.find("\r\n")));
  7856. }
  7857. #ifndef _WIN32
  7858. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7859. static constexpr char reject[] = "Unauthorized";
  7860. static constexpr char accept[] = "Upload accepted";
  7861. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7862. Server svr;
  7863. svr.set_expect_100_continue_handler(
  7864. [](const Request & /*req*/, Response &res) {
  7865. res.status = StatusCode::Unauthorized_401;
  7866. res.set_content(reject, "text/plain");
  7867. return res.status;
  7868. });
  7869. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7870. res.set_content(accept, "text/plain");
  7871. });
  7872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7873. auto se = detail::scope_exit([&] {
  7874. svr.stop();
  7875. thread.join();
  7876. ASSERT_FALSE(svr.is_running());
  7877. });
  7878. svr.wait_until_ready();
  7879. {
  7880. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7881. curl_easy_init(), &curl_easy_cleanup};
  7882. ASSERT_NE(curl, nullptr);
  7883. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7884. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7885. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7886. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7887. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7888. &curl_slist_free_all};
  7889. ASSERT_NE(list, nullptr);
  7890. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7891. struct read_data {
  7892. size_t read_size;
  7893. size_t total_size;
  7894. } data = {0, total_size};
  7895. using read_callback_t =
  7896. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7897. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7898. void *userdata) -> size_t {
  7899. read_data *data = (read_data *)userdata;
  7900. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7901. std::fill_n(ptr, size * nmemb, 'A');
  7902. data->read_size += size * nmemb;
  7903. return size * nmemb;
  7904. };
  7905. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7906. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7907. std::vector<char> buffer;
  7908. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7909. using write_callback_t =
  7910. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7911. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7912. void *userdata) -> size_t {
  7913. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7914. buffer->reserve(buffer->size() + size * nmemb + 1);
  7915. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7916. return size * nmemb;
  7917. };
  7918. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7919. {
  7920. const auto res = curl_easy_perform(curl.get());
  7921. ASSERT_EQ(res, CURLE_OK);
  7922. }
  7923. {
  7924. auto response_code = long{};
  7925. const auto res =
  7926. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7927. ASSERT_EQ(res, CURLE_OK);
  7928. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7929. }
  7930. {
  7931. auto dl = curl_off_t{};
  7932. const auto res =
  7933. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7934. ASSERT_EQ(res, CURLE_OK);
  7935. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7936. }
  7937. {
  7938. buffer.push_back('\0');
  7939. ASSERT_STRCASEEQ(buffer.data(), reject);
  7940. }
  7941. }
  7942. }
  7943. #endif
  7944. template <typename S, typename C>
  7945. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7946. svr.Get("/stream", [&](const Request &, Response &res) {
  7947. auto data = new std::string("01234567890123456789");
  7948. res.set_content_provider(
  7949. data->size(), "text/plain",
  7950. [&, data](size_t offset, size_t length, DataSink &sink) {
  7951. const size_t DATA_CHUNK_SIZE = 4;
  7952. const auto &d = *data;
  7953. std::this_thread::sleep_for(std::chrono::seconds(1));
  7954. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7955. return true;
  7956. },
  7957. [data](bool success) {
  7958. EXPECT_FALSE(success);
  7959. delete data;
  7960. });
  7961. });
  7962. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7963. auto i = new size_t(0);
  7964. res.set_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.write("abcd", 4);
  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. svr.Get("/chunked", [&](const Request &, Response &res) {
  7982. auto i = new size_t(0);
  7983. res.set_chunked_content_provider(
  7984. "text/plain",
  7985. [i](size_t, DataSink &sink) {
  7986. if (*i < 5) {
  7987. std::this_thread::sleep_for(std::chrono::seconds(1));
  7988. sink.os << "abcd";
  7989. (*i)++;
  7990. } else {
  7991. sink.done();
  7992. }
  7993. return true;
  7994. },
  7995. [i](bool success) {
  7996. EXPECT_FALSE(success);
  7997. delete i;
  7998. });
  7999. });
  8000. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8001. auto se = detail::scope_exit([&] {
  8002. svr.stop();
  8003. listen_thread.join();
  8004. ASSERT_FALSE(svr.is_running());
  8005. });
  8006. svr.wait_until_ready();
  8007. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8008. {
  8009. auto start = std::chrono::steady_clock::now();
  8010. auto res = cli.Get("/stream");
  8011. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8012. std::chrono::steady_clock::now() - start)
  8013. .count();
  8014. ASSERT_FALSE(res);
  8015. EXPECT_EQ(Error::Read, res.error());
  8016. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8017. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8018. }
  8019. {
  8020. auto start = std::chrono::steady_clock::now();
  8021. auto res = cli.Get("/stream_without_length");
  8022. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8023. std::chrono::steady_clock::now() - start)
  8024. .count();
  8025. ASSERT_FALSE(res);
  8026. EXPECT_EQ(Error::Read, res.error());
  8027. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8028. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8029. }
  8030. {
  8031. auto start = std::chrono::steady_clock::now();
  8032. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8033. EXPECT_EQ("abcd", string(data, data_length));
  8034. return true;
  8035. });
  8036. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8037. std::chrono::steady_clock::now() - start)
  8038. .count();
  8039. ASSERT_FALSE(res);
  8040. EXPECT_EQ(Error::Read, res.error());
  8041. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8042. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8043. }
  8044. }
  8045. TEST(MaxTimeoutTest, ContentStream) {
  8046. time_t timeout = 2000;
  8047. time_t threshold = 200;
  8048. Server svr;
  8049. Client cli("localhost", PORT);
  8050. max_timeout_test(svr, cli, timeout, threshold);
  8051. }
  8052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8053. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8054. time_t timeout = 2000;
  8055. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8056. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8057. SSLClient cli("localhost", PORT);
  8058. cli.enable_server_certificate_verification(false);
  8059. max_timeout_test(svr, cli, timeout, threshold);
  8060. }
  8061. #endif
  8062. class EventDispatcher {
  8063. public:
  8064. EventDispatcher() {}
  8065. void wait_event(DataSink *sink) {
  8066. unique_lock<mutex> lk(m_);
  8067. int id = id_;
  8068. cv_.wait(lk, [&] { return cid_ == id; });
  8069. sink->write(message_.data(), message_.size());
  8070. }
  8071. void send_event(const string &message) {
  8072. lock_guard<mutex> lk(m_);
  8073. cid_ = id_++;
  8074. message_ = message;
  8075. cv_.notify_all();
  8076. }
  8077. private:
  8078. mutex m_;
  8079. condition_variable cv_;
  8080. atomic_int id_{0};
  8081. atomic_int cid_{-1};
  8082. string message_;
  8083. };
  8084. TEST(ClientInThreadTest, Issue2068) {
  8085. EventDispatcher ed;
  8086. Server svr;
  8087. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8088. res.set_chunked_content_provider("text/event-stream",
  8089. [&](size_t /*offset*/, DataSink &sink) {
  8090. ed.wait_event(&sink);
  8091. return true;
  8092. });
  8093. });
  8094. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8095. svr.wait_until_ready();
  8096. thread event_thread([&] {
  8097. int id = 0;
  8098. while (svr.is_running()) {
  8099. this_thread::sleep_for(chrono::milliseconds(500));
  8100. std::stringstream ss;
  8101. ss << "data: " << id << "\n\n";
  8102. ed.send_event(ss.str());
  8103. id++;
  8104. }
  8105. });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. listen_thread.join();
  8109. event_thread.join();
  8110. ASSERT_FALSE(svr.is_running());
  8111. });
  8112. {
  8113. auto client = detail::make_unique<Client>(HOST, PORT);
  8114. client->set_read_timeout(std::chrono::minutes(10));
  8115. std::atomic<bool> stop{false};
  8116. std::thread t([&] {
  8117. client->Get("/event1",
  8118. [&](const char *, size_t) -> bool { return !stop; });
  8119. });
  8120. std::this_thread::sleep_for(std::chrono::seconds(2));
  8121. stop = true;
  8122. client->stop();
  8123. client.reset();
  8124. t.join();
  8125. }
  8126. }