test.cc 245 KB

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