1
0

test.cc 282 KB

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