test.cc 251 KB

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