test.cc 270 KB

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