test.cc 286 KB

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