test.cc 253 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458
  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 line
  3007. // URI is max URI length, minus 14 other chars in req line (GET, space, leading /, space, HTTP/1.1)
  3008. std::string request = "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3009. auto res = cli_.Get(request.c_str());
  3010. ASSERT_TRUE(res);
  3011. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3012. }
  3013. TEST_F(ServerTest, LongHeader) {
  3014. Request req;
  3015. req.method = "GET";
  3016. req.path = "/hi";
  3017. std::string host_and_port;
  3018. host_and_port += HOST;
  3019. host_and_port += ":";
  3020. host_and_port += std::to_string(PORT);
  3021. req.headers.emplace("Host", host_and_port.c_str());
  3022. req.headers.emplace("Accept", "*/*");
  3023. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3024. req.headers.emplace(
  3025. "Header-Name",
  3026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3056. auto error = Error::Success;
  3057. auto ret = cli_.send(req, *res, error);
  3058. ASSERT_TRUE(ret);
  3059. EXPECT_EQ(StatusCode::OK_200, res->status);
  3060. }
  3061. TEST_F(ServerTest, LongQueryValue) {
  3062. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3063. ASSERT_TRUE(res);
  3064. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3065. }
  3066. TEST_F(ServerTest, TooLongHeader) {
  3067. Request req;
  3068. req.method = "GET";
  3069. req.path = "/hi";
  3070. std::string host_and_port;
  3071. host_and_port += HOST;
  3072. host_and_port += ":";
  3073. host_and_port += std::to_string(PORT);
  3074. req.headers.emplace("Host", host_and_port.c_str());
  3075. req.headers.emplace("Accept", "*/*");
  3076. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3077. req.headers.emplace(
  3078. "Header-Name",
  3079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3109. auto error = Error::Success;
  3110. auto ret = cli_.send(req, *res, error);
  3111. ASSERT_TRUE(ret);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. }
  3114. TEST_F(ServerTest, PercentEncoding) {
  3115. auto res = cli_.Get("/e%6edwith%");
  3116. ASSERT_TRUE(res);
  3117. EXPECT_EQ(StatusCode::OK_200, res->status);
  3118. }
  3119. TEST_F(ServerTest, PercentEncodingUnicode) {
  3120. auto res = cli_.Get("/e%u006edwith%");
  3121. ASSERT_TRUE(res);
  3122. EXPECT_EQ(StatusCode::OK_200, res->status);
  3123. }
  3124. TEST_F(ServerTest, InvalidPercentEncoding) {
  3125. auto res = cli_.Get("/%endwith%");
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3128. }
  3129. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3130. auto res = cli_.Get("/%uendwith%");
  3131. ASSERT_TRUE(res);
  3132. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3133. }
  3134. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3135. auto res = cli_.Get("/hello?aaa=bbb%");
  3136. ASSERT_TRUE(res);
  3137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3138. }
  3139. TEST_F(ServerTest, PlusSignEncoding) {
  3140. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3141. ASSERT_TRUE(res);
  3142. EXPECT_EQ(StatusCode::OK_200, res->status);
  3143. EXPECT_EQ("a +b", res->body);
  3144. }
  3145. TEST_F(ServerTest, MultipartFormData) {
  3146. MultipartFormDataItems items = {
  3147. {"text1", "text default", "", ""},
  3148. {"text2", "aωb", "", ""},
  3149. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3150. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3151. {"file3", "", "", "application/octet-stream"},
  3152. {"file4", "", "", " application/json tmp-string "}};
  3153. auto res = cli_.Post("/multipart", items);
  3154. ASSERT_TRUE(res);
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. }
  3157. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3158. MultipartFormDataItems items = {
  3159. {"text", "default text", "", ""},
  3160. {"multi_text1", "aaaaa", "", ""},
  3161. {"multi_text1", "bbbbb", "", ""},
  3162. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3163. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3164. "application/json"},
  3165. };
  3166. auto res = cli_.Post("/multipart/multi_file_values", items);
  3167. ASSERT_TRUE(res);
  3168. EXPECT_EQ(StatusCode::OK_200, res->status);
  3169. }
  3170. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3171. auto res = cli_.Get("/hi");
  3172. ASSERT_TRUE(res);
  3173. EXPECT_EQ(StatusCode::OK_200, res->status);
  3174. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3175. EXPECT_EQ("Hello World!", res->body);
  3176. }
  3177. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3178. Request req;
  3179. req.method = "POST";
  3180. req.path = "/chunked";
  3181. std::string host_and_port;
  3182. host_and_port += HOST;
  3183. host_and_port += ":";
  3184. host_and_port += std::to_string(PORT);
  3185. req.headers.emplace("Host", host_and_port.c_str());
  3186. req.headers.emplace("Accept", "*/*");
  3187. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3188. req.headers.emplace("Content-Type", "text/plain");
  3189. req.headers.emplace("Content-Length", "0");
  3190. req.headers.emplace(
  3191. "Transfer-Encoding",
  3192. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3193. // Client does not chunk, so make a chunked body manually.
  3194. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3195. auto res = std::make_shared<Response>();
  3196. auto error = Error::Success;
  3197. auto ret = cli_.send(req, *res, error);
  3198. ASSERT_TRUE(ret);
  3199. EXPECT_EQ(StatusCode::OK_200, res->status);
  3200. }
  3201. TEST_F(ServerTest, GetStreamed2) {
  3202. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3205. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3206. EXPECT_EQ(true, res->has_header("Content-Range"));
  3207. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3208. EXPECT_EQ(std::string("ab"), res->body);
  3209. }
  3210. TEST_F(ServerTest, GetStreamed) {
  3211. auto res = cli_.Get("/streamed");
  3212. ASSERT_TRUE(res);
  3213. EXPECT_EQ(StatusCode::OK_200, res->status);
  3214. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3215. EXPECT_EQ(std::string("aaabbb"), res->body);
  3216. }
  3217. TEST_F(ServerTest, GetStreamedWithRange1) {
  3218. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3221. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3222. EXPECT_EQ(true, res->has_header("Content-Range"));
  3223. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3224. EXPECT_EQ(std::string("def"), res->body);
  3225. }
  3226. TEST_F(ServerTest, GetStreamedWithRange2) {
  3227. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3230. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3231. EXPECT_EQ(true, res->has_header("Content-Range"));
  3232. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3233. EXPECT_EQ(std::string("bcdefg"), res->body);
  3234. }
  3235. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3236. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3239. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3240. EXPECT_EQ(true, res->has_header("Content-Range"));
  3241. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3242. EXPECT_EQ(std::string("efg"), res->body);
  3243. }
  3244. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3245. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3246. ASSERT_TRUE(res);
  3247. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3248. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3249. EXPECT_EQ(false, res->has_header("Content-Range"));
  3250. EXPECT_EQ(0U, res->body.size());
  3251. }
  3252. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3253. auto res = cli_.Get("/streamed-with-range",
  3254. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3255. "92233720368547758079223372036854775807"}});
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3259. EXPECT_EQ(false, res->has_header("Content-Range"));
  3260. EXPECT_EQ(0U, res->body.size());
  3261. }
  3262. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3263. auto res = cli_.Get(
  3264. "/with-range",
  3265. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3266. {"Accept-Encoding", ""}});
  3267. ASSERT_TRUE(res);
  3268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3269. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3270. EXPECT_EQ(true, res->has_header("Content-Range"));
  3271. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3272. EXPECT_EQ(std::string("abcdefg"), res->body);
  3273. }
  3274. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3275. auto res = cli_.Get("/with-range", {
  3276. {"Range", "bytes=0-"},
  3277. {"Accept-Encoding", ""},
  3278. });
  3279. ASSERT_TRUE(res);
  3280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3281. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3282. EXPECT_EQ(true, res->has_header("Content-Range"));
  3283. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3284. EXPECT_EQ(std::string("abcdefg"), res->body);
  3285. }
  3286. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3287. auto res =
  3288. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3291. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3292. EXPECT_EQ(false, res->has_header("Content-Range"));
  3293. EXPECT_EQ(267U, res->body.size());
  3294. }
  3295. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3296. Ranges ranges;
  3297. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3298. ranges.emplace_back(0, -1);
  3299. }
  3300. auto res =
  3301. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3302. ASSERT_TRUE(res);
  3303. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3304. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3305. EXPECT_EQ(false, res->has_header("Content-Range"));
  3306. EXPECT_EQ(0U, res->body.size());
  3307. }
  3308. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3309. auto res = cli_.Get("/streamed-with-range?error",
  3310. {{make_range_header({{0, -1}, {0, -1}})}});
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3313. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3314. EXPECT_EQ(false, res->has_header("Content-Range"));
  3315. EXPECT_EQ(0U, res->body.size());
  3316. }
  3317. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3318. auto res = cli_.Get("/streamed-with-range?error",
  3319. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3322. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3323. EXPECT_EQ(false, res->has_header("Content-Range"));
  3324. EXPECT_EQ(0U, res->body.size());
  3325. }
  3326. TEST_F(ServerTest, GetStreamedEndless) {
  3327. uint64_t offset = 0;
  3328. auto res = cli_.Get("/streamed-cancel",
  3329. [&](const char * /*data*/, uint64_t data_length) {
  3330. if (offset < 100) {
  3331. offset += data_length;
  3332. return true;
  3333. }
  3334. return false;
  3335. });
  3336. ASSERT_TRUE(!res);
  3337. EXPECT_EQ(Error::Canceled, res.error());
  3338. }
  3339. TEST_F(ServerTest, ClientStop) {
  3340. std::atomic_size_t count{4};
  3341. std::vector<std::thread> threads;
  3342. for (auto i = count.load(); i != 0; --i) {
  3343. threads.emplace_back([&]() {
  3344. auto res = cli_.Get("/streamed-cancel",
  3345. [&](const char *, uint64_t) { return true; });
  3346. --count;
  3347. ASSERT_TRUE(!res);
  3348. EXPECT_TRUE(res.error() == Error::Canceled ||
  3349. res.error() == Error::Read || res.error() == Error::Write);
  3350. });
  3351. }
  3352. std::this_thread::sleep_for(std::chrono::seconds(2));
  3353. while (count != 0) {
  3354. cli_.stop();
  3355. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3356. }
  3357. for (auto &t : threads) {
  3358. t.join();
  3359. }
  3360. }
  3361. TEST_F(ServerTest, GetWithRange1) {
  3362. auto res = cli_.Get("/with-range", {
  3363. make_range_header({{3, 5}}),
  3364. {"Accept-Encoding", ""},
  3365. });
  3366. ASSERT_TRUE(res);
  3367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3368. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3369. EXPECT_EQ(true, res->has_header("Content-Range"));
  3370. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3371. EXPECT_EQ(std::string("def"), res->body);
  3372. }
  3373. TEST_F(ServerTest, GetWithRange2) {
  3374. auto res = cli_.Get("/with-range", {
  3375. make_range_header({{1, -1}}),
  3376. {"Accept-Encoding", ""},
  3377. });
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3380. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3381. EXPECT_EQ(true, res->has_header("Content-Range"));
  3382. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3383. EXPECT_EQ(std::string("bcdefg"), res->body);
  3384. }
  3385. TEST_F(ServerTest, GetWithRange3) {
  3386. auto res = cli_.Get("/with-range", {
  3387. make_range_header({{0, 0}}),
  3388. {"Accept-Encoding", ""},
  3389. });
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3392. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3393. EXPECT_EQ(true, res->has_header("Content-Range"));
  3394. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3395. EXPECT_EQ(std::string("a"), res->body);
  3396. }
  3397. TEST_F(ServerTest, GetWithRange4) {
  3398. auto res = cli_.Get("/with-range", {
  3399. make_range_header({{-1, 2}}),
  3400. {"Accept-Encoding", ""},
  3401. });
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3404. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3405. EXPECT_EQ(true, res->has_header("Content-Range"));
  3406. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3407. EXPECT_EQ(std::string("fg"), res->body);
  3408. }
  3409. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3410. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3413. }
  3414. TEST_F(ServerTest, GetWithRangeMultipart) {
  3415. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3416. ASSERT_TRUE(res);
  3417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3418. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3419. EXPECT_EQ(false, res->has_header("Content-Range"));
  3420. EXPECT_EQ(267U, res->body.size());
  3421. }
  3422. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3423. auto res =
  3424. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3425. ASSERT_TRUE(res);
  3426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3427. }
  3428. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3429. auto res = cli_.Get("/with-range-customized-response",
  3430. {{make_range_header({{1, 2}})}});
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3433. EXPECT_EQ(true, res->has_header("Content-Length"));
  3434. EXPECT_EQ(false, res->has_header("Content-Range"));
  3435. EXPECT_EQ(JSON_DATA, res->body);
  3436. }
  3437. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3438. auto res = cli_.Get("/with-range-customized-response",
  3439. {{make_range_header({{1, 2}, {4, 5}})}});
  3440. ASSERT_TRUE(res);
  3441. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3442. EXPECT_EQ(true, res->has_header("Content-Length"));
  3443. EXPECT_EQ(false, res->has_header("Content-Range"));
  3444. EXPECT_EQ(JSON_DATA, res->body);
  3445. }
  3446. TEST_F(ServerTest, Issue1772) {
  3447. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3450. }
  3451. TEST_F(ServerTest, Issue609) {
  3452. auto res = cli_.Delete("/issue609");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ(std::string("ok"), res->body);
  3456. }
  3457. TEST_F(ServerTest, GetStreamedChunked) {
  3458. auto res = cli_.Get("/streamed-chunked");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. EXPECT_EQ(std::string("123456789"), res->body);
  3462. }
  3463. TEST_F(ServerTest, GetStreamedChunked2) {
  3464. auto res = cli_.Get("/streamed-chunked2");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::OK_200, res->status);
  3467. EXPECT_EQ(std::string("123456789"), res->body);
  3468. }
  3469. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3470. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3471. ASSERT_TRUE(res);
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ(std::string("123456789"), res->body);
  3474. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3475. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3476. }
  3477. TEST_F(ServerTest, LargeChunkedPost) {
  3478. Request req;
  3479. req.method = "POST";
  3480. req.path = "/large-chunked";
  3481. std::string host_and_port;
  3482. host_and_port += HOST;
  3483. host_and_port += ":";
  3484. host_and_port += std::to_string(PORT);
  3485. req.headers.emplace("Host", host_and_port.c_str());
  3486. req.headers.emplace("Accept", "*/*");
  3487. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3488. req.headers.emplace("Content-Type", "text/plain");
  3489. req.headers.emplace("Content-Length", "0");
  3490. req.headers.emplace("Transfer-Encoding", "chunked");
  3491. std::string long_string(30 * 1024u, 'a');
  3492. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3493. // Attempt to make a large enough post to exceed OS buffers, to test that
  3494. // the server handles short reads if the full chunk data isn't available.
  3495. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3496. auto res = std::make_shared<Response>();
  3497. auto error = Error::Success;
  3498. auto ret = cli_.send(req, *res, error);
  3499. ASSERT_TRUE(ret);
  3500. EXPECT_EQ(StatusCode::OK_200, res->status);
  3501. }
  3502. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3503. auto res = cli_.Get("/remote_addr");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::OK_200, res->status);
  3506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3508. }
  3509. TEST_F(ServerTest, GetMethodLocalAddr) {
  3510. auto res = cli_.Get("/local_addr");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3514. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3515. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3516. }
  3517. TEST_F(ServerTest, HTTPResponseSplitting) {
  3518. auto res = cli_.Get("/http_response_splitting");
  3519. ASSERT_TRUE(res);
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. }
  3522. TEST_F(ServerTest, SlowRequest) {
  3523. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3524. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3525. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3526. }
  3527. #if 0
  3528. TEST_F(ServerTest, SlowPost) {
  3529. char buffer[64 * 1024];
  3530. memset(buffer, 0x42, sizeof(buffer));
  3531. auto res = cli_.Post(
  3532. "/slowpost", 64 * 1024 * 1024,
  3533. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3534. auto ret = sink.write(buffer, sizeof(buffer));
  3535. EXPECT_TRUE(ret);
  3536. return true;
  3537. },
  3538. "text/plain");
  3539. ASSERT_TRUE(res);
  3540. EXPECT_EQ(StatusCode::OK_200, res->status);
  3541. }
  3542. TEST_F(ServerTest, SlowPostFail) {
  3543. char buffer[64 * 1024];
  3544. memset(buffer, 0x42, sizeof(buffer));
  3545. cli_.set_write_timeout(std::chrono::seconds(0));
  3546. auto res = cli_.Post(
  3547. "/slowpost", 64 * 1024 * 1024,
  3548. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3549. sink.write(buffer, sizeof(buffer));
  3550. return true;
  3551. },
  3552. "text/plain");
  3553. ASSERT_TRUE(!res);
  3554. EXPECT_EQ(Error::Write, res.error());
  3555. }
  3556. #endif
  3557. TEST_F(ServerTest, Put) {
  3558. auto res = cli_.Put("/put", "PUT", "text/plain");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("PUT", res->body);
  3562. }
  3563. TEST_F(ServerTest, PutWithContentProvider) {
  3564. auto res = cli_.Put(
  3565. "/put", 3,
  3566. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3567. sink.os << "PUT";
  3568. return true;
  3569. },
  3570. "text/plain");
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ("PUT", res->body);
  3574. }
  3575. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3576. auto res = cli_.Post(
  3577. "/post", 42,
  3578. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3579. return false;
  3580. },
  3581. "text/plain");
  3582. ASSERT_TRUE(!res);
  3583. EXPECT_EQ(Error::Canceled, res.error());
  3584. }
  3585. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3586. auto res = cli_.Put(
  3587. "/put",
  3588. [](size_t /*offset*/, DataSink &sink) {
  3589. sink.os << "PUT";
  3590. sink.done();
  3591. return true;
  3592. },
  3593. "text/plain");
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::OK_200, res->status);
  3596. EXPECT_EQ("PUT", res->body);
  3597. }
  3598. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3599. auto res = cli_.Post(
  3600. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3601. "text/plain");
  3602. ASSERT_TRUE(!res);
  3603. EXPECT_EQ(Error::Canceled, res.error());
  3604. }
  3605. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3606. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3607. cli_.set_compress(true);
  3608. auto res = cli_.Put(
  3609. "/put", 3,
  3610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3611. sink.os << "PUT";
  3612. return true;
  3613. },
  3614. "text/plain");
  3615. ASSERT_TRUE(res);
  3616. EXPECT_EQ(StatusCode::OK_200, res->status);
  3617. EXPECT_EQ("PUT", res->body);
  3618. }
  3619. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3620. cli_.set_compress(true);
  3621. auto res = cli_.Post(
  3622. "/post", 42,
  3623. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3624. return false;
  3625. },
  3626. "text/plain");
  3627. ASSERT_TRUE(!res);
  3628. EXPECT_EQ(Error::Canceled, res.error());
  3629. }
  3630. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3631. cli_.set_compress(true);
  3632. auto res = cli_.Put(
  3633. "/put",
  3634. [](size_t /*offset*/, DataSink &sink) {
  3635. sink.os << "PUT";
  3636. sink.done();
  3637. return true;
  3638. },
  3639. "text/plain");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::OK_200, res->status);
  3642. EXPECT_EQ("PUT", res->body);
  3643. }
  3644. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3645. cli_.set_compress(true);
  3646. auto res = cli_.Post(
  3647. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3648. "text/plain");
  3649. ASSERT_TRUE(!res);
  3650. EXPECT_EQ(Error::Canceled, res.error());
  3651. }
  3652. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3653. cli_.set_compress(true);
  3654. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3655. ASSERT_TRUE(res);
  3656. EXPECT_EQ(StatusCode::OK_200, res->status);
  3657. EXPECT_EQ(LARGE_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3660. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3661. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3662. Client cli(s.c_str());
  3663. cli.enable_server_certificate_verification(false);
  3664. #else
  3665. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3666. Client cli(s.c_str());
  3667. #endif
  3668. cli.set_compress(true);
  3669. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. EXPECT_EQ(LARGE_DATA, res->body);
  3673. // The compressed size should be less than a 10th of the original. May vary
  3674. // depending on the zlib library.
  3675. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  3676. static_cast<uint64_t>(10 * 1024 * 1024));
  3677. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3678. }
  3679. TEST_F(ServerTest, PutContentWithDeflate) {
  3680. cli_.set_compress(false);
  3681. Headers headers;
  3682. headers.emplace("Content-Encoding", "deflate");
  3683. // PUT in deflate format:
  3684. auto res = cli_.Put("/put", headers,
  3685. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ("PUT", res->body);
  3689. }
  3690. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3691. Headers headers;
  3692. headers.emplace("Accept-Encoding", "gzip, deflate");
  3693. auto res = cli_.Get("/streamed-chunked", headers);
  3694. ASSERT_TRUE(res);
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. EXPECT_EQ(std::string("123456789"), res->body);
  3697. }
  3698. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3699. Headers headers;
  3700. headers.emplace("Accept-Encoding", "gzip, deflate");
  3701. auto res = cli_.Get("/streamed-chunked2", headers);
  3702. ASSERT_TRUE(res);
  3703. EXPECT_EQ(StatusCode::OK_200, res->status);
  3704. EXPECT_EQ(std::string("123456789"), res->body);
  3705. }
  3706. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3707. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3708. ASSERT_TRUE(res);
  3709. EXPECT_EQ(StatusCode::OK_200, res->status);
  3710. }
  3711. TEST(GzipDecompressor, ChunkedDecompression) {
  3712. std::string data;
  3713. for (size_t i = 0; i < 32 * 1024; ++i) {
  3714. data.push_back(static_cast<char>('a' + i % 26));
  3715. }
  3716. std::string compressed_data;
  3717. {
  3718. httplib::detail::gzip_compressor compressor;
  3719. bool result = compressor.compress(
  3720. data.data(), data.size(),
  3721. /*last=*/true,
  3722. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3723. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3724. compressed_data_size);
  3725. return true;
  3726. });
  3727. ASSERT_TRUE(result);
  3728. }
  3729. std::string decompressed_data;
  3730. {
  3731. httplib::detail::gzip_decompressor decompressor;
  3732. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3733. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3734. size_t chunk_size = 130;
  3735. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3736. chunk_begin += chunk_size) {
  3737. size_t current_chunk_size =
  3738. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3739. bool result = decompressor.decompress(
  3740. compressed_data.data() + chunk_begin, current_chunk_size,
  3741. [&](const char *decompressed_data_chunk,
  3742. size_t decompressed_data_chunk_size) {
  3743. decompressed_data.insert(decompressed_data.size(),
  3744. decompressed_data_chunk,
  3745. decompressed_data_chunk_size);
  3746. return true;
  3747. });
  3748. ASSERT_TRUE(result);
  3749. }
  3750. }
  3751. ASSERT_EQ(data, decompressed_data);
  3752. }
  3753. TEST(GzipDecompressor, DeflateDecompression) {
  3754. std::string original_text = "Raw deflate without gzip";
  3755. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3756. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3757. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3758. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3759. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3760. std::string decompressed_data;
  3761. {
  3762. httplib::detail::gzip_decompressor decompressor;
  3763. bool result = decompressor.decompress(
  3764. compressed_data.data(), compressed_data.size(),
  3765. [&](const char *decompressed_data_chunk,
  3766. size_t decompressed_data_chunk_size) {
  3767. decompressed_data.insert(decompressed_data.size(),
  3768. decompressed_data_chunk,
  3769. decompressed_data_chunk_size);
  3770. return true;
  3771. });
  3772. ASSERT_TRUE(result);
  3773. }
  3774. ASSERT_EQ(original_text, decompressed_data);
  3775. }
  3776. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3777. std::string original_text = "Raw deflate without gzip";
  3778. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3782. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3783. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3784. std::string decompressed_data;
  3785. {
  3786. httplib::detail::gzip_decompressor decompressor;
  3787. bool result = decompressor.decompress(
  3788. compressed_data.data(), compressed_data.size(),
  3789. [&](const char *decompressed_data_chunk,
  3790. size_t decompressed_data_chunk_size) {
  3791. decompressed_data.insert(decompressed_data.size(),
  3792. decompressed_data_chunk,
  3793. decompressed_data_chunk_size);
  3794. return true;
  3795. });
  3796. ASSERT_TRUE(result);
  3797. }
  3798. ASSERT_EQ(original_text, decompressed_data);
  3799. }
  3800. #ifdef _WIN32
  3801. TEST(GzipDecompressor, LargeRandomData) {
  3802. // prepare large random data that is difficult to be compressed and is
  3803. // expected to have large size even when compressed
  3804. std::random_device seed_gen;
  3805. std::mt19937 random(seed_gen());
  3806. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3807. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3808. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3809. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3810. // compress data over 4GiB
  3811. std::string compressed_data;
  3812. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3813. httplib::detail::gzip_compressor compressor;
  3814. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3815. data.size() * sizeof(std::uint32_t), true,
  3816. [&](const char *data, size_t size) {
  3817. compressed_data.insert(
  3818. compressed_data.size(), data, size);
  3819. return true;
  3820. });
  3821. ASSERT_TRUE(result);
  3822. // FIXME: compressed data size is expected to be greater than 4GiB,
  3823. // but there is no guarantee
  3824. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3825. // decompress data over 4GiB
  3826. std::string decompressed_data;
  3827. decompressed_data.reserve(data_size);
  3828. httplib::detail::gzip_decompressor decompressor;
  3829. result = decompressor.decompress(
  3830. compressed_data.data(), compressed_data.size(),
  3831. [&](const char *data, size_t size) {
  3832. decompressed_data.insert(decompressed_data.size(), data, size);
  3833. return true;
  3834. });
  3835. ASSERT_TRUE(result);
  3836. // compare
  3837. ASSERT_EQ(data_size, decompressed_data.size());
  3838. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3839. 0);
  3840. }
  3841. #endif
  3842. #endif
  3843. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3844. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3845. Headers headers;
  3846. headers.emplace("Accept-Encoding", "br");
  3847. auto res = cli_.Get("/streamed-chunked", headers);
  3848. ASSERT_TRUE(res);
  3849. EXPECT_EQ(StatusCode::OK_200, res->status);
  3850. EXPECT_EQ(std::string("123456789"), res->body);
  3851. }
  3852. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3853. Headers headers;
  3854. headers.emplace("Accept-Encoding", "br");
  3855. auto res = cli_.Get("/streamed-chunked2", headers);
  3856. ASSERT_TRUE(res);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. EXPECT_EQ(std::string("123456789"), res->body);
  3859. }
  3860. #endif
  3861. TEST_F(ServerTest, Patch) {
  3862. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("PATCH", res->body);
  3866. }
  3867. TEST_F(ServerTest, Delete) {
  3868. auto res = cli_.Delete("/delete");
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::OK_200, res->status);
  3871. EXPECT_EQ("DELETE", res->body);
  3872. }
  3873. TEST_F(ServerTest, DeleteContentReceiver) {
  3874. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("content", res->body);
  3878. }
  3879. TEST_F(ServerTest, Options) {
  3880. auto res = cli_.Options("*");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::OK_200, res->status);
  3883. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3884. EXPECT_TRUE(res->body.empty());
  3885. }
  3886. TEST_F(ServerTest, URL) {
  3887. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. }
  3891. TEST_F(ServerTest, ArrayParam) {
  3892. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. TEST_F(ServerTest, NoMultipleHeaders) {
  3897. Headers headers = {{"Content-Length", "5"}};
  3898. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3899. "text/plain");
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::OK_200, res->status);
  3902. }
  3903. TEST_F(ServerTest, PostContentReceiver) {
  3904. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3905. ASSERT_TRUE(res);
  3906. ASSERT_EQ(StatusCode::OK_200, res->status);
  3907. ASSERT_EQ("content", res->body);
  3908. }
  3909. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3910. MultipartFormDataItems items = {
  3911. {"text1", "text default", "", ""},
  3912. {"text2", "aωb", "", ""},
  3913. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3914. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3915. {"file3", "", "", "application/octet-stream"},
  3916. };
  3917. auto res = cli_.Post("/content_receiver", items);
  3918. ASSERT_TRUE(res);
  3919. EXPECT_EQ(StatusCode::OK_200, res->status);
  3920. }
  3921. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3922. MultipartFormDataItems items = {
  3923. {"text1", "text default", "", ""},
  3924. {"text2", "aωb", "", ""},
  3925. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3926. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3927. {"file3", "", "", "application/octet-stream"},
  3928. };
  3929. auto boundary = std::string("+++++");
  3930. std::string body;
  3931. for (const auto &item : items) {
  3932. body += "--" + boundary + "\r\n";
  3933. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3934. if (!item.filename.empty()) {
  3935. body += "; filename=\"" + item.filename + "\"";
  3936. }
  3937. body += "\r\n";
  3938. if (!item.content_type.empty()) {
  3939. body += "Content-Type: " + item.content_type + "\r\n";
  3940. }
  3941. body += "\r\n";
  3942. body += item.content + "\r\n";
  3943. }
  3944. body += "--" + boundary + "--\r\n";
  3945. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3946. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::OK_200, res->status);
  3949. }
  3950. TEST_F(ServerTest, PostContentReceiverGzip) {
  3951. cli_.set_compress(true);
  3952. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3953. ASSERT_TRUE(res);
  3954. ASSERT_EQ(StatusCode::OK_200, res->status);
  3955. ASSERT_EQ("content", res->body);
  3956. }
  3957. TEST_F(ServerTest, PutContentReceiver) {
  3958. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3959. ASSERT_TRUE(res);
  3960. ASSERT_EQ(StatusCode::OK_200, res->status);
  3961. ASSERT_EQ("content", res->body);
  3962. }
  3963. TEST_F(ServerTest, PatchContentReceiver) {
  3964. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3965. ASSERT_TRUE(res);
  3966. ASSERT_EQ(StatusCode::OK_200, res->status);
  3967. ASSERT_EQ("content", res->body);
  3968. }
  3969. TEST_F(ServerTest, PostQueryStringAndBody) {
  3970. auto res =
  3971. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3972. ASSERT_TRUE(res);
  3973. ASSERT_EQ(StatusCode::OK_200, res->status);
  3974. }
  3975. TEST_F(ServerTest, HTTP2Magic) {
  3976. Request req;
  3977. req.method = "PRI";
  3978. req.path = "*";
  3979. req.body = "SM";
  3980. auto res = std::make_shared<Response>();
  3981. auto error = Error::Success;
  3982. auto ret = cli_.send(req, *res, error);
  3983. ASSERT_TRUE(ret);
  3984. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3985. }
  3986. TEST_F(ServerTest, KeepAlive) {
  3987. auto res = cli_.Get("/hi");
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3991. EXPECT_EQ("Hello World!", res->body);
  3992. res = cli_.Get("/hi");
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3996. EXPECT_EQ("Hello World!", res->body);
  3997. res = cli_.Get("/hi");
  3998. ASSERT_TRUE(res);
  3999. EXPECT_EQ(StatusCode::OK_200, res->status);
  4000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4001. EXPECT_EQ("Hello World!", res->body);
  4002. res = cli_.Get("/not-exist");
  4003. ASSERT_TRUE(res);
  4004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4005. res = cli_.Post("/empty", "", "text/plain");
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::OK_200, res->status);
  4008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4009. EXPECT_EQ("empty", res->body);
  4010. EXPECT_EQ("close", res->get_header_value("Connection"));
  4011. res = cli_.Post(
  4012. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4013. "text/plain");
  4014. ASSERT_TRUE(res);
  4015. EXPECT_EQ(StatusCode::OK_200, res->status);
  4016. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4017. EXPECT_EQ("empty", res->body);
  4018. cli_.set_keep_alive(false);
  4019. res = cli_.Get("/last-request");
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::OK_200, res->status);
  4022. EXPECT_EQ("close", res->get_header_value("Connection"));
  4023. }
  4024. TEST_F(ServerTest, TooManyRedirect) {
  4025. cli_.set_follow_location(true);
  4026. auto res = cli_.Get("/redirect/0");
  4027. ASSERT_TRUE(!res);
  4028. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4029. }
  4030. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4031. TEST_F(ServerTest, Gzip) {
  4032. Headers headers;
  4033. headers.emplace("Accept-Encoding", "gzip, deflate");
  4034. auto res = cli_.Get("/compress", headers);
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4038. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4040. "7890123456789012345678901234567890",
  4041. res->body);
  4042. EXPECT_EQ(StatusCode::OK_200, res->status);
  4043. }
  4044. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4045. Headers headers;
  4046. headers.emplace("Accept-Encoding", "");
  4047. auto res = cli_.Get("/compress", headers);
  4048. ASSERT_TRUE(res);
  4049. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4051. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4053. "7890123456789012345678901234567890",
  4054. res->body);
  4055. EXPECT_EQ(StatusCode::OK_200, res->status);
  4056. }
  4057. TEST_F(ServerTest, GzipWithContentReceiver) {
  4058. Headers headers;
  4059. headers.emplace("Accept-Encoding", "gzip, deflate");
  4060. std::string body;
  4061. auto res = cli_.Get("/compress", headers,
  4062. [&](const char *data, uint64_t data_length) {
  4063. EXPECT_EQ(100U, data_length);
  4064. body.append(data, data_length);
  4065. return true;
  4066. });
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4069. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4070. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4071. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4072. "7890123456789012345678901234567890",
  4073. body);
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4077. Headers headers;
  4078. headers.emplace("Accept-Encoding", "gzip, deflate");
  4079. cli_.set_decompress(false);
  4080. auto res = cli_.Get("/compress", headers);
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4083. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4084. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(33U, res->body.size());
  4086. EXPECT_EQ(StatusCode::OK_200, res->status);
  4087. }
  4088. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4089. Headers headers;
  4090. headers.emplace("Accept-Encoding", "");
  4091. std::string body;
  4092. auto res = cli_.Get("/compress", headers,
  4093. [&](const char *data, uint64_t data_length) {
  4094. EXPECT_EQ(100U, data_length);
  4095. body.append(data, data_length);
  4096. return true;
  4097. });
  4098. ASSERT_TRUE(res);
  4099. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4103. "7890123456789012345678901234567890",
  4104. body);
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. }
  4107. TEST_F(ServerTest, NoGzip) {
  4108. Headers headers;
  4109. headers.emplace("Accept-Encoding", "gzip, deflate");
  4110. auto res = cli_.Get("/nocompress", headers);
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4113. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4114. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4115. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4116. "7890123456789012345678901234567890",
  4117. res->body);
  4118. EXPECT_EQ(StatusCode::OK_200, res->status);
  4119. }
  4120. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4121. Headers headers;
  4122. headers.emplace("Accept-Encoding", "gzip, deflate");
  4123. std::string body;
  4124. auto res = cli_.Get("/nocompress", headers,
  4125. [&](const char *data, uint64_t data_length) {
  4126. EXPECT_EQ(100U, data_length);
  4127. body.append(data, data_length);
  4128. return true;
  4129. });
  4130. ASSERT_TRUE(res);
  4131. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4132. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4133. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4134. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4135. "7890123456789012345678901234567890",
  4136. body);
  4137. EXPECT_EQ(StatusCode::OK_200, res->status);
  4138. }
  4139. TEST_F(ServerTest, MultipartFormDataGzip) {
  4140. MultipartFormDataItems items = {
  4141. {"key1", "test", "", ""},
  4142. {"key2", "--abcdefg123", "", ""},
  4143. };
  4144. cli_.set_compress(true);
  4145. auto res = cli_.Post("/compress-multipart", items);
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. }
  4149. #endif
  4150. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4151. TEST_F(ServerTest, Brotli) {
  4152. Headers headers;
  4153. headers.emplace("Accept-Encoding", "br");
  4154. auto res = cli_.Get("/compress", headers);
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4158. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4159. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4160. "7890123456789012345678901234567890",
  4161. res->body);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. }
  4164. #endif
  4165. // Sends a raw request to a server listening at HOST:PORT.
  4166. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4167. std::string *resp = nullptr) {
  4168. auto error = Error::Success;
  4169. auto client_sock = detail::create_client_socket(
  4170. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4171. /*connection_timeout_sec=*/5, 0,
  4172. /*read_timeout_sec=*/5, 0,
  4173. /*write_timeout_sec=*/5, 0, std::string(), error);
  4174. if (client_sock == INVALID_SOCKET) { return false; }
  4175. auto ret = detail::process_client_socket(
  4176. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4177. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4178. if (req.size() !=
  4179. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4180. return false;
  4181. }
  4182. char buf[512];
  4183. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4184. while (line_reader.getline()) {
  4185. if (resp) { *resp += line_reader.ptr(); }
  4186. }
  4187. return true;
  4188. });
  4189. detail::close_socket(client_sock);
  4190. return ret;
  4191. }
  4192. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4193. Server svr;
  4194. std::string header_value;
  4195. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4196. header_value = req.get_header_value("foo");
  4197. res.set_content("ok", "text/plain");
  4198. });
  4199. thread t = thread([&] { svr.listen(HOST, PORT); });
  4200. auto se = detail::scope_exit([&] {
  4201. svr.stop();
  4202. t.join();
  4203. ASSERT_FALSE(svr.is_running());
  4204. });
  4205. svr.wait_until_ready();
  4206. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4207. // like characters are not treated the same - use vertical tab and escape.
  4208. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4209. "foo: \t \v bar \x1B\t \r\n"
  4210. "Connection: close\r\n"
  4211. "\r\n";
  4212. std::string res;
  4213. ASSERT_TRUE(send_request(5, req, &res));
  4214. EXPECT_EQ(header_value, "");
  4215. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4216. }
  4217. // Sends a raw request and verifies that there isn't a crash or exception.
  4218. static void test_raw_request(const std::string &req,
  4219. std::string *out = nullptr) {
  4220. Server svr;
  4221. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4222. res.set_content("ok", "text/plain");
  4223. });
  4224. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. svr.Get("/header_field_value_check",
  4228. [&](const Request & /*req*/, Response &res) {
  4229. res.set_content("ok", "text/plain");
  4230. });
  4231. // Server read timeout must be longer than the client read timeout for the
  4232. // bug to reproduce, probably to force the server to process a request
  4233. // without a trailing blank line.
  4234. const time_t client_read_timeout_sec = 1;
  4235. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4236. bool listen_thread_ok = false;
  4237. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4238. auto se = detail::scope_exit([&] {
  4239. svr.stop();
  4240. t.join();
  4241. ASSERT_FALSE(svr.is_running());
  4242. EXPECT_TRUE(listen_thread_ok);
  4243. });
  4244. svr.wait_until_ready();
  4245. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4246. }
  4247. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4248. // A certain header line causes an exception if the header property is parsed
  4249. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4250. test_raw_request(
  4251. "GET /hi HTTP/1.1\r\n"
  4252. " : "
  4253. " "
  4254. " ");
  4255. }
  4256. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4257. // A certain header line causes an exception if the header property *name* is
  4258. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4259. // greedy matcher and requires backtracking when there are a lot of ":"
  4260. // characters.
  4261. // This occurs with libc++ but not libstdc++.
  4262. test_raw_request(
  4263. "GET /hi HTTP/1.1\r\n"
  4264. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4265. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4266. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4267. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4268. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4269. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4270. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4271. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4272. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4273. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4274. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4275. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4276. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4277. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4278. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4279. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4280. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4281. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4282. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4283. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4284. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4285. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4286. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4287. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4288. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4289. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4290. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4291. "&&&%%%");
  4292. }
  4293. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4294. // Make sure this doesn't crash the server.
  4295. // In a previous version of the header line regex, the "\r" rendered the line
  4296. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4297. // a new position where the leading white space ended and the field value
  4298. // began.
  4299. // The crash occurs with libc++ but not libstdc++.
  4300. test_raw_request("GET /hi HTTP/1.1\r\n"
  4301. "a:" +
  4302. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4303. "\r\n"
  4304. "\r\n");
  4305. }
  4306. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4307. std::string out;
  4308. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4309. "Content-Type: text/plain\r\n"
  4310. "Transfer-Encoding: chunked\r\n"
  4311. "\r\n"
  4312. "nothex\r\n",
  4313. &out);
  4314. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4315. }
  4316. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4317. std::string out;
  4318. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4319. "Content-Type: text/plain\r\n"
  4320. "Transfer-Encoding: chunked\r\n"
  4321. "\r\n"
  4322. "3\r\n"
  4323. "xyz\r\n"
  4324. "NaN\r\n",
  4325. &out);
  4326. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4327. }
  4328. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4329. std::string out;
  4330. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4331. "Content-Type: text/plain\r\n"
  4332. "Transfer-Encoding: chunked\r\n"
  4333. "\r\n"
  4334. // Length is too large for 64 bits.
  4335. "1ffffffffffffffff\r\n"
  4336. "xyz\r\n",
  4337. &out);
  4338. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4339. }
  4340. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4341. test_raw_request("GET /hi HTTP/1.1\r\n"
  4342. "Content-Type: text/plain\r\n\r");
  4343. }
  4344. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4345. std::string out;
  4346. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4347. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4348. }
  4349. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4350. std::string out;
  4351. std::string request(
  4352. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4353. test_raw_request(request, &out);
  4354. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4355. }
  4356. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  4357. std::string out;
  4358. std::string request(
  4359. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  4360. test_raw_request(request, &out);
  4361. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4362. }
  4363. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  4364. std::string out;
  4365. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  4366. "Test: \r\n\r\n",
  4367. &out);
  4368. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  4369. }
  4370. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4371. Server svr;
  4372. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4373. res.set_header("Cache-Control", "no-cache");
  4374. res.set_chunked_content_provider(
  4375. "text/event-stream", [](size_t offset, DataSink &sink) {
  4376. std::string s = "data:";
  4377. s += std::to_string(offset);
  4378. s += "\n\n";
  4379. auto ret = sink.write(s.data(), s.size());
  4380. EXPECT_TRUE(ret);
  4381. std::this_thread::sleep_for(std::chrono::seconds(1));
  4382. return true;
  4383. });
  4384. });
  4385. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4386. svr.wait_until_ready();
  4387. Client client(HOST, PORT);
  4388. const Headers headers = {{"Accept", "text/event-stream"}};
  4389. auto get_thread = std::thread([&client, &headers]() {
  4390. auto res = client.Get(
  4391. "/events", headers,
  4392. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4393. });
  4394. auto se = detail::scope_exit([&] {
  4395. svr.stop();
  4396. get_thread.join();
  4397. listen_thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. // Give GET time to get a few messages.
  4401. std::this_thread::sleep_for(std::chrono::seconds(2));
  4402. }
  4403. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4404. httplib::Server svr;
  4405. svr.Post("/hi",
  4406. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4407. res.status = StatusCode::OK_200;
  4408. });
  4409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4410. svr.wait_until_ready();
  4411. Client cli(HOST, PORT);
  4412. auto res = cli.Post("/hi", "data", "text/plain");
  4413. ASSERT_TRUE(res);
  4414. EXPECT_EQ(StatusCode::OK_200, res->status);
  4415. svr.stop();
  4416. thread.join();
  4417. ASSERT_FALSE(svr.is_running());
  4418. res = cli.Post("/hi", "data", "text/plain");
  4419. ASSERT_FALSE(res);
  4420. }
  4421. TEST(ServerStopTest, ListenFailure) {
  4422. Server svr;
  4423. auto t = thread([&]() {
  4424. auto ret = svr.listen("????", PORT);
  4425. EXPECT_FALSE(ret);
  4426. });
  4427. svr.wait_until_ready();
  4428. svr.stop();
  4429. t.join();
  4430. }
  4431. TEST(ServerStopTest, Decommision) {
  4432. Server svr;
  4433. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4434. for (int i = 0; i < 4; i++) {
  4435. auto is_even = !(i % 2);
  4436. std::thread t{[&] {
  4437. try {
  4438. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4439. if (is_even) {
  4440. throw std::runtime_error("Some thing that happens to go wrong.");
  4441. }
  4442. svr.listen(HOST, PORT);
  4443. } catch (...) { svr.decommission(); }
  4444. }};
  4445. svr.wait_until_ready();
  4446. // Server is up
  4447. {
  4448. Client cli(HOST, PORT);
  4449. auto res = cli.Get("/hi");
  4450. if (is_even) {
  4451. EXPECT_FALSE(res);
  4452. } else {
  4453. EXPECT_TRUE(res);
  4454. EXPECT_EQ("hi...", res->body);
  4455. }
  4456. }
  4457. svr.stop();
  4458. t.join();
  4459. // Server is down...
  4460. {
  4461. Client cli(HOST, PORT);
  4462. auto res = cli.Get("/hi");
  4463. EXPECT_FALSE(res);
  4464. }
  4465. }
  4466. }
  4467. TEST(StreamingTest, NoContentLengthStreaming) {
  4468. Server svr;
  4469. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4470. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4471. if (offset < 6) {
  4472. sink.os << (offset < 3 ? "a" : "b");
  4473. } else {
  4474. sink.done();
  4475. }
  4476. return true;
  4477. });
  4478. });
  4479. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4480. auto listen_se = detail::scope_exit([&] {
  4481. svr.stop();
  4482. listen_thread.join();
  4483. ASSERT_FALSE(svr.is_running());
  4484. });
  4485. svr.wait_until_ready();
  4486. Client client(HOST, PORT);
  4487. auto get_thread = std::thread([&client]() {
  4488. std::string s;
  4489. auto res =
  4490. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4491. s += std::string(data, len);
  4492. return true;
  4493. });
  4494. EXPECT_EQ("aaabbb", s);
  4495. });
  4496. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4497. // Give GET time to get a few messages.
  4498. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4499. }
  4500. TEST(MountTest, Unmount) {
  4501. Server svr;
  4502. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4503. auto se = detail::scope_exit([&] {
  4504. svr.stop();
  4505. listen_thread.join();
  4506. ASSERT_FALSE(svr.is_running());
  4507. });
  4508. svr.wait_until_ready();
  4509. Client cli("localhost", PORT);
  4510. svr.set_mount_point("/mount2", "./www2");
  4511. auto res = cli.Get("/");
  4512. ASSERT_TRUE(res);
  4513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4514. res = cli.Get("/mount2/dir/test.html");
  4515. ASSERT_TRUE(res);
  4516. EXPECT_EQ(StatusCode::OK_200, res->status);
  4517. svr.set_mount_point("/", "./www");
  4518. res = cli.Get("/dir/");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::OK_200, res->status);
  4521. svr.remove_mount_point("/");
  4522. res = cli.Get("/dir/");
  4523. ASSERT_TRUE(res);
  4524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4525. svr.remove_mount_point("/mount2");
  4526. res = cli.Get("/mount2/dir/test.html");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4529. }
  4530. TEST(MountTest, Redicect) {
  4531. Server svr;
  4532. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4533. auto se = detail::scope_exit([&] {
  4534. svr.stop();
  4535. listen_thread.join();
  4536. ASSERT_FALSE(svr.is_running());
  4537. });
  4538. svr.set_mount_point("/", "./www");
  4539. svr.wait_until_ready();
  4540. Client cli("localhost", PORT);
  4541. auto res = cli.Get("/dir/");
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. res = cli.Get("/dir");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4547. res = cli.Get("/file");
  4548. ASSERT_TRUE(res);
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. res = cli.Get("/file/");
  4551. ASSERT_TRUE(res);
  4552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4553. cli.set_follow_location(true);
  4554. res = cli.Get("/dir");
  4555. ASSERT_TRUE(res);
  4556. EXPECT_EQ(StatusCode::OK_200, res->status);
  4557. }
  4558. TEST(MountTest, MultibytesPathName) {
  4559. Server svr;
  4560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4561. auto se = detail::scope_exit([&] {
  4562. svr.stop();
  4563. listen_thread.join();
  4564. ASSERT_FALSE(svr.is_running());
  4565. });
  4566. svr.set_mount_point("/", "./www");
  4567. svr.wait_until_ready();
  4568. Client cli("localhost", PORT);
  4569. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  4573. }
  4574. TEST(KeepAliveTest, ReadTimeout) {
  4575. Server svr;
  4576. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4577. std::this_thread::sleep_for(std::chrono::seconds(2));
  4578. res.set_content("a", "text/plain");
  4579. });
  4580. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4581. res.set_content("b", "text/plain");
  4582. });
  4583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4584. auto se = detail::scope_exit([&] {
  4585. svr.stop();
  4586. listen_thread.join();
  4587. ASSERT_FALSE(svr.is_running());
  4588. });
  4589. svr.wait_until_ready();
  4590. Client cli("localhost", PORT);
  4591. cli.set_keep_alive(true);
  4592. cli.set_read_timeout(std::chrono::seconds(1));
  4593. auto resa = cli.Get("/a");
  4594. ASSERT_FALSE(resa);
  4595. EXPECT_EQ(Error::Read, resa.error());
  4596. auto resb = cli.Get("/b");
  4597. ASSERT_TRUE(resb);
  4598. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4599. EXPECT_EQ("b", resb->body);
  4600. }
  4601. TEST(KeepAliveTest, Issue1041) {
  4602. Server svr;
  4603. svr.set_keep_alive_timeout(3);
  4604. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4605. res.set_content("Hello World!", "text/plain");
  4606. });
  4607. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4608. auto se = detail::scope_exit([&] {
  4609. svr.stop();
  4610. listen_thread.join();
  4611. ASSERT_FALSE(svr.is_running());
  4612. });
  4613. svr.wait_until_ready();
  4614. Client cli(HOST, PORT);
  4615. cli.set_keep_alive(true);
  4616. auto result = cli.Get("/hi");
  4617. ASSERT_TRUE(result);
  4618. EXPECT_EQ(StatusCode::OK_200, result->status);
  4619. std::this_thread::sleep_for(std::chrono::seconds(5));
  4620. result = cli.Get("/hi");
  4621. ASSERT_TRUE(result);
  4622. EXPECT_EQ(StatusCode::OK_200, result->status);
  4623. }
  4624. TEST(KeepAliveTest, Issue1959) {
  4625. Server svr;
  4626. svr.set_keep_alive_timeout(5);
  4627. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4628. res.set_content("a", "text/plain");
  4629. });
  4630. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. if (!svr.is_running()) return;
  4633. svr.stop();
  4634. listen_thread.join();
  4635. ASSERT_FALSE(svr.is_running());
  4636. });
  4637. svr.wait_until_ready();
  4638. Client cli("localhost", PORT);
  4639. cli.set_keep_alive(true);
  4640. using namespace std::chrono;
  4641. auto start = steady_clock::now();
  4642. cli.Get("/a");
  4643. svr.stop();
  4644. listen_thread.join();
  4645. auto end = steady_clock::now();
  4646. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4647. EXPECT_LT(elapsed, 5000);
  4648. }
  4649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4650. TEST(KeepAliveTest, SSLClientReconnection) {
  4651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4652. ASSERT_TRUE(svr.is_valid());
  4653. svr.set_keep_alive_timeout(1);
  4654. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4655. res.set_content("Hello World!", "text/plain");
  4656. });
  4657. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4658. auto se = detail::scope_exit([&] {
  4659. svr.stop();
  4660. listen_thread.join();
  4661. ASSERT_FALSE(svr.is_running());
  4662. });
  4663. svr.wait_until_ready();
  4664. SSLClient cli(HOST, PORT);
  4665. cli.enable_server_certificate_verification(false);
  4666. cli.set_keep_alive(true);
  4667. auto result = cli.Get("/hi");
  4668. ASSERT_TRUE(result);
  4669. EXPECT_EQ(StatusCode::OK_200, result->status);
  4670. result = cli.Get("/hi");
  4671. ASSERT_TRUE(result);
  4672. EXPECT_EQ(StatusCode::OK_200, result->status);
  4673. std::this_thread::sleep_for(std::chrono::seconds(2));
  4674. // Recoonect
  4675. result = cli.Get("/hi");
  4676. ASSERT_TRUE(result);
  4677. EXPECT_EQ(StatusCode::OK_200, result->status);
  4678. result = cli.Get("/hi");
  4679. ASSERT_TRUE(result);
  4680. EXPECT_EQ(StatusCode::OK_200, result->status);
  4681. }
  4682. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4684. ASSERT_TRUE(svr.is_valid());
  4685. svr.set_keep_alive_timeout(1);
  4686. std::string content = "reconnect";
  4687. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4688. res.set_content("Hello World!", "text/plain");
  4689. });
  4690. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4691. auto se = detail::scope_exit([&] {
  4692. svr.stop();
  4693. listen_thread.join();
  4694. ASSERT_FALSE(svr.is_running());
  4695. });
  4696. svr.wait_until_ready();
  4697. SSLClient cli(HOST, PORT);
  4698. cli.enable_server_certificate_verification(false);
  4699. cli.set_keep_alive(true);
  4700. auto result = cli.Post(
  4701. "/hi", content.size(),
  4702. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4703. sink.write(content.c_str(), content.size());
  4704. return true;
  4705. },
  4706. "text/plain");
  4707. ASSERT_TRUE(result);
  4708. EXPECT_EQ(200, result->status);
  4709. std::this_thread::sleep_for(std::chrono::seconds(2));
  4710. // Recoonect
  4711. result = cli.Post(
  4712. "/hi", content.size(),
  4713. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4714. sink.write(content.c_str(), content.size());
  4715. return true;
  4716. },
  4717. "text/plain");
  4718. ASSERT_TRUE(result);
  4719. EXPECT_EQ(200, result->status);
  4720. result = cli.Post(
  4721. "/hi", content.size(),
  4722. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4723. sink.write(content.c_str(), content.size());
  4724. return true;
  4725. },
  4726. "text/plain");
  4727. ASSERT_TRUE(result);
  4728. EXPECT_EQ(200, result->status);
  4729. }
  4730. #endif
  4731. TEST(ClientProblemDetectionTest, ContentProvider) {
  4732. Server svr;
  4733. size_t content_length = 1024 * 1024;
  4734. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4735. res.set_content_provider(
  4736. content_length, "text/plain",
  4737. [&](size_t offset, size_t length, DataSink &sink) {
  4738. auto out_len = std::min(length, static_cast<size_t>(1024));
  4739. std::string out(out_len, '@');
  4740. sink.write(out.data(), out_len);
  4741. return offset < 4096;
  4742. },
  4743. [](bool success) { ASSERT_FALSE(success); });
  4744. });
  4745. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4746. res.set_content_provider(
  4747. 0, "text/plain",
  4748. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4749. EXPECT_TRUE(false);
  4750. return true;
  4751. },
  4752. [](bool success) { ASSERT_FALSE(success); });
  4753. });
  4754. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4755. auto se = detail::scope_exit([&] {
  4756. svr.stop();
  4757. listen_thread.join();
  4758. ASSERT_FALSE(svr.is_running());
  4759. });
  4760. svr.wait_until_ready();
  4761. Client cli("localhost", PORT);
  4762. {
  4763. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4764. size_t /*data_length*/) { return false; });
  4765. ASSERT_FALSE(res);
  4766. }
  4767. {
  4768. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4769. size_t /*data_length*/) { return false; });
  4770. ASSERT_TRUE(res);
  4771. }
  4772. }
  4773. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4774. Server svr;
  4775. svr.set_error_handler([](Request const &, Response &res) -> void {
  4776. res.set_chunked_content_provider(
  4777. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4778. sink.os << "hello";
  4779. sink.os << "world";
  4780. sink.done();
  4781. return true;
  4782. });
  4783. });
  4784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4785. auto se = detail::scope_exit([&] {
  4786. svr.stop();
  4787. listen_thread.join();
  4788. ASSERT_FALSE(svr.is_running());
  4789. });
  4790. svr.wait_until_ready();
  4791. Client cli("localhost", PORT);
  4792. auto res = cli.Get("/");
  4793. ASSERT_TRUE(res);
  4794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4795. EXPECT_EQ("helloworld", res->body);
  4796. }
  4797. TEST(LongPollingTest, ClientCloseDetection) {
  4798. Server svr;
  4799. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4800. res.set_chunked_content_provider(
  4801. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4802. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4803. sink.os << "hello";
  4804. auto count = 10;
  4805. while (count > 0 && sink.is_writable()) {
  4806. this_thread::sleep_for(chrono::milliseconds(10));
  4807. count--;
  4808. }
  4809. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4810. return true;
  4811. });
  4812. });
  4813. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4814. auto se = detail::scope_exit([&] {
  4815. svr.stop();
  4816. listen_thread.join();
  4817. ASSERT_FALSE(svr.is_running());
  4818. });
  4819. svr.wait_until_ready();
  4820. Client cli("localhost", PORT);
  4821. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4822. EXPECT_EQ("hello", string(data, data_length));
  4823. return false; // close the socket immediately.
  4824. });
  4825. ASSERT_FALSE(res);
  4826. }
  4827. TEST(GetWithParametersTest, GetWithParameters) {
  4828. Server svr;
  4829. svr.Get("/", [&](const Request &req, Response &) {
  4830. EXPECT_EQ("world", req.get_param_value("hello"));
  4831. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4832. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4833. });
  4834. svr.Get("/params", [&](const Request &req, Response &) {
  4835. EXPECT_EQ("world", req.get_param_value("hello"));
  4836. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4837. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4838. });
  4839. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4840. EXPECT_EQ("resource-id", req.matches[1]);
  4841. EXPECT_EQ("foo", req.get_param_value("param1"));
  4842. EXPECT_EQ("bar", req.get_param_value("param2"));
  4843. });
  4844. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4845. EXPECT_EQ("user-id", req.path_params.at("id"));
  4846. EXPECT_EQ("foo", req.get_param_value("param1"));
  4847. EXPECT_EQ("bar", req.get_param_value("param2"));
  4848. });
  4849. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4850. auto se = detail::scope_exit([&] {
  4851. svr.stop();
  4852. listen_thread.join();
  4853. ASSERT_FALSE(svr.is_running());
  4854. });
  4855. svr.wait_until_ready();
  4856. {
  4857. Client cli(HOST, PORT);
  4858. Params params;
  4859. params.emplace("hello", "world");
  4860. params.emplace("hello2", "world2");
  4861. params.emplace("hello3", "world3");
  4862. auto res = cli.Get("/", params, Headers{});
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. }
  4866. {
  4867. Client cli(HOST, PORT);
  4868. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4869. ASSERT_TRUE(res);
  4870. EXPECT_EQ(StatusCode::OK_200, res->status);
  4871. }
  4872. {
  4873. Client cli(HOST, PORT);
  4874. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. {
  4879. Client cli(HOST, PORT);
  4880. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::OK_200, res->status);
  4883. }
  4884. }
  4885. TEST(GetWithParametersTest, GetWithParameters2) {
  4886. Server svr;
  4887. svr.Get("/", [&](const Request &req, Response &res) {
  4888. auto text = req.get_param_value("hello");
  4889. res.set_content(text, "text/plain");
  4890. });
  4891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4892. auto se = detail::scope_exit([&] {
  4893. svr.stop();
  4894. listen_thread.join();
  4895. ASSERT_FALSE(svr.is_running());
  4896. });
  4897. svr.wait_until_ready();
  4898. Client cli("localhost", PORT);
  4899. Params params;
  4900. params.emplace("hello", "world");
  4901. std::string body;
  4902. auto res = cli.Get("/", params, Headers{},
  4903. [&](const char *data, size_t data_length) {
  4904. body.append(data, data_length);
  4905. return true;
  4906. });
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("world", body);
  4910. }
  4911. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4912. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4913. auto host = "httpbin.org";
  4914. auto path = std::string{"/range/32"};
  4915. #else
  4916. auto host = "nghttp2.org";
  4917. auto path = std::string{"/httpbin/range/32"};
  4918. #endif
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. SSLClient cli(host);
  4921. #else
  4922. Client cli(host);
  4923. #endif
  4924. cli.set_default_headers({make_range_header({{1, 10}})});
  4925. cli.set_connection_timeout(5);
  4926. {
  4927. auto res = cli.Get(path);
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ("bcdefghijk", res->body);
  4930. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4931. }
  4932. {
  4933. auto res = cli.Get(path);
  4934. ASSERT_TRUE(res);
  4935. EXPECT_EQ("bcdefghijk", res->body);
  4936. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4937. }
  4938. }
  4939. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4940. Server svr;
  4941. svr.set_default_headers({{"Hello", "World"}});
  4942. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4943. res.set_content("ok", "text/plain");
  4944. });
  4945. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4946. auto se = detail::scope_exit([&] {
  4947. svr.stop();
  4948. listen_thread.join();
  4949. ASSERT_FALSE(svr.is_running());
  4950. });
  4951. svr.wait_until_ready();
  4952. Client cli("localhost", PORT);
  4953. auto res = cli.Get("/");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ("ok", res->body);
  4957. EXPECT_EQ("World", res->get_header_value("Hello"));
  4958. }
  4959. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4960. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4962. ASSERT_TRUE(svr.is_valid());
  4963. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4964. std::this_thread::sleep_for(std::chrono::seconds(2));
  4965. res.set_content("a", "text/plain");
  4966. });
  4967. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4968. res.set_content("b", "text/plain");
  4969. });
  4970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4971. auto se = detail::scope_exit([&] {
  4972. svr.stop();
  4973. listen_thread.join();
  4974. ASSERT_FALSE(svr.is_running());
  4975. });
  4976. svr.wait_until_ready();
  4977. SSLClient cli("localhost", PORT);
  4978. cli.enable_server_certificate_verification(false);
  4979. cli.set_keep_alive(true);
  4980. cli.set_read_timeout(std::chrono::seconds(1));
  4981. auto resa = cli.Get("/a");
  4982. ASSERT_TRUE(!resa);
  4983. EXPECT_EQ(Error::Read, resa.error());
  4984. auto resb = cli.Get("/b");
  4985. ASSERT_TRUE(resb);
  4986. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4987. EXPECT_EQ("b", resb->body);
  4988. }
  4989. #endif
  4990. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4991. protected:
  4992. ServerTestWithAI_PASSIVE()
  4993. : cli_(HOST, PORT)
  4994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4995. ,
  4996. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4997. #endif
  4998. {
  4999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5000. cli_.enable_server_certificate_verification(false);
  5001. #endif
  5002. }
  5003. virtual void SetUp() {
  5004. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5005. res.set_content("Hello World!", "text/plain");
  5006. });
  5007. t_ = thread(
  5008. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5009. svr_.wait_until_ready();
  5010. }
  5011. virtual void TearDown() {
  5012. svr_.stop();
  5013. t_.join();
  5014. }
  5015. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5016. SSLClient cli_;
  5017. SSLServer svr_;
  5018. #else
  5019. Client cli_;
  5020. Server svr_;
  5021. #endif
  5022. thread t_;
  5023. };
  5024. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5025. auto res = cli_.Get("/hi");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5029. EXPECT_EQ("Hello World!", res->body);
  5030. }
  5031. class ServerUpDownTest : public ::testing::Test {
  5032. protected:
  5033. ServerUpDownTest() : cli_(HOST, PORT) {}
  5034. virtual void SetUp() {
  5035. t_ = thread([&]() {
  5036. svr_.bind_to_any_port(HOST);
  5037. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5038. ASSERT_TRUE(svr_.listen_after_bind());
  5039. });
  5040. svr_.wait_until_ready();
  5041. }
  5042. virtual void TearDown() {
  5043. svr_.stop();
  5044. t_.join();
  5045. }
  5046. Client cli_;
  5047. Server svr_;
  5048. thread t_;
  5049. };
  5050. TEST_F(ServerUpDownTest, QuickStartStop) {
  5051. // Should not crash, especially when run with
  5052. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5053. }
  5054. class PayloadMaxLengthTest : public ::testing::Test {
  5055. protected:
  5056. PayloadMaxLengthTest()
  5057. : cli_(HOST, PORT)
  5058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5059. ,
  5060. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5061. #endif
  5062. {
  5063. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5064. cli_.enable_server_certificate_verification(false);
  5065. #endif
  5066. }
  5067. virtual void SetUp() {
  5068. svr_.set_payload_max_length(8);
  5069. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5070. res.set_content("test", "text/plain");
  5071. });
  5072. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5073. svr_.wait_until_ready();
  5074. }
  5075. virtual void TearDown() {
  5076. svr_.stop();
  5077. t_.join();
  5078. }
  5079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5080. SSLClient cli_;
  5081. SSLServer svr_;
  5082. #else
  5083. Client cli_;
  5084. Server svr_;
  5085. #endif
  5086. thread t_;
  5087. };
  5088. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5089. auto res = cli_.Post("/test", "123456789", "text/plain");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5092. res = cli_.Post("/test", "12345678", "text/plain");
  5093. ASSERT_TRUE(res);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. }
  5096. TEST(HostAndPortPropertiesTest, NoSSL) {
  5097. httplib::Client cli("www.google.com", 1234);
  5098. ASSERT_EQ("www.google.com", cli.host());
  5099. ASSERT_EQ(1234, cli.port());
  5100. }
  5101. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5102. httplib::Client cli("www.google.com:1234");
  5103. ASSERT_EQ("www.google.com", cli.host());
  5104. ASSERT_EQ(1234, cli.port());
  5105. }
  5106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5107. TEST(HostAndPortPropertiesTest, SSL) {
  5108. httplib::SSLClient cli("www.google.com");
  5109. ASSERT_EQ("www.google.com", cli.host());
  5110. ASSERT_EQ(443, cli.port());
  5111. }
  5112. #endif
  5113. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5114. TEST(SSLClientTest, UpdateCAStore) {
  5115. httplib::SSLClient httplib_client("www.google.com");
  5116. auto ca_store_1 = X509_STORE_new();
  5117. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5118. nullptr);
  5119. httplib_client.set_ca_cert_store(ca_store_1);
  5120. auto ca_store_2 = X509_STORE_new();
  5121. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5122. nullptr);
  5123. httplib_client.set_ca_cert_store(ca_store_2);
  5124. }
  5125. TEST(SSLClientTest, ServerNameIndication_Online) {
  5126. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5127. auto host = "httpbin.org";
  5128. auto path = std::string{"/get"};
  5129. #else
  5130. auto host = "nghttp2.org";
  5131. auto path = std::string{"/httpbin/get"};
  5132. #endif
  5133. SSLClient cli(host, 443);
  5134. auto res = cli.Get(path);
  5135. ASSERT_TRUE(res);
  5136. ASSERT_EQ(StatusCode::OK_200, res->status);
  5137. }
  5138. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5139. Client cli("https://google.com");
  5140. auto res = cli.Get("/");
  5141. ASSERT_TRUE(res);
  5142. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5143. }
  5144. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5145. SSLClient cli("google.com");
  5146. cli.enable_server_certificate_verification(true);
  5147. cli.set_ca_cert_path("hello");
  5148. auto res = cli.Get("/");
  5149. ASSERT_TRUE(!res);
  5150. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5151. }
  5152. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5153. SSLClient cli("google.com");
  5154. cli.set_ca_cert_path(CA_CERT_FILE);
  5155. auto res = cli.Get("/");
  5156. ASSERT_TRUE(res);
  5157. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5158. }
  5159. TEST(SSLClientTest, ServerCertificateVerification4) {
  5160. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5161. ASSERT_TRUE(svr.is_valid());
  5162. svr.Get("/test", [&](const Request &, Response &res) {
  5163. res.set_content("test", "text/plain");
  5164. svr.stop();
  5165. ASSERT_TRUE(true);
  5166. });
  5167. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5168. auto se = detail::scope_exit([&] {
  5169. t.join();
  5170. ASSERT_FALSE(svr.is_running());
  5171. });
  5172. svr.wait_until_ready();
  5173. SSLClient cli("127.0.0.1", PORT);
  5174. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5175. cli.enable_server_certificate_verification(true);
  5176. cli.set_connection_timeout(30);
  5177. auto res = cli.Get("/test");
  5178. ASSERT_TRUE(res);
  5179. ASSERT_EQ(StatusCode::OK_200, res->status);
  5180. }
  5181. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5182. std::string cert;
  5183. detail::read_file(CA_CERT_FILE, cert);
  5184. SSLClient cli("google.com");
  5185. cli.load_ca_cert_store(cert.data(), cert.size());
  5186. const auto res = cli.Get("/");
  5187. ASSERT_TRUE(res);
  5188. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5189. }
  5190. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5191. // clang-format off
  5192. static constexpr char cert[] =
  5193. "GlobalSign Root CA\n"
  5194. "==================\n"
  5195. "-----BEGIN CERTIFICATE-----\n"
  5196. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5197. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5198. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5199. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5200. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5201. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5202. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5203. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5204. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5205. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5206. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5207. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5208. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5209. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5210. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5211. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5212. "-----END CERTIFICATE-----\n";
  5213. // clang-format on
  5214. SSLClient cli("google.com");
  5215. cli.load_ca_cert_store(cert, sizeof(cert));
  5216. const auto res = cli.Get("/");
  5217. ASSERT_TRUE(res);
  5218. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5219. }
  5220. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5221. SSLClient cli("www.youtube.com");
  5222. cli.set_ca_cert_path(CA_CERT_FILE);
  5223. cli.enable_server_certificate_verification(true);
  5224. cli.set_follow_location(true);
  5225. auto res = cli.Get("/");
  5226. ASSERT_TRUE(res);
  5227. ASSERT_EQ(StatusCode::OK_200, res->status);
  5228. }
  5229. TEST(SSLClientTest, Issue2004_Online) {
  5230. Client client("https://google.com");
  5231. client.set_follow_location(true);
  5232. auto res = client.Get("/");
  5233. ASSERT_TRUE(res);
  5234. ASSERT_EQ(StatusCode::OK_200, res->status);
  5235. auto body = res->body;
  5236. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5237. }
  5238. #if 0
  5239. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5240. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5241. ASSERT_TRUE(cli != nullptr);
  5242. cli->set_address_family(AF_INET6);
  5243. cli->set_interface("en0");
  5244. auto res = cli->Get("/get");
  5245. ASSERT_TRUE(res);
  5246. ASSERT_EQ(StatusCode::OK_200, res->status);
  5247. }
  5248. #endif
  5249. void ClientCertPresent(
  5250. const std::string &client_cert_file,
  5251. const std::string &client_private_key_file,
  5252. const std::string &client_encrypted_private_key_pass = std::string()) {
  5253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5254. CLIENT_CA_CERT_DIR);
  5255. ASSERT_TRUE(svr.is_valid());
  5256. svr.Get("/test", [&](const Request &req, Response &res) {
  5257. res.set_content("test", "text/plain");
  5258. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5259. ASSERT_TRUE(peer_cert != nullptr);
  5260. auto subject_name = X509_get_subject_name(peer_cert);
  5261. ASSERT_TRUE(subject_name != nullptr);
  5262. std::string common_name;
  5263. {
  5264. char name[BUFSIZ];
  5265. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5266. name, sizeof(name));
  5267. common_name.assign(name, static_cast<size_t>(name_len));
  5268. }
  5269. EXPECT_EQ("Common Name", common_name);
  5270. X509_free(peer_cert);
  5271. });
  5272. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5273. auto se = detail::scope_exit([&] {
  5274. svr.stop();
  5275. t.join();
  5276. ASSERT_FALSE(svr.is_running());
  5277. });
  5278. svr.wait_until_ready();
  5279. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5280. client_encrypted_private_key_pass);
  5281. cli.enable_server_certificate_verification(false);
  5282. cli.set_connection_timeout(30);
  5283. auto res = cli.Get("/test");
  5284. ASSERT_TRUE(res);
  5285. ASSERT_EQ(StatusCode::OK_200, res->status);
  5286. }
  5287. TEST(SSLClientServerTest, ClientCertPresent) {
  5288. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5289. }
  5290. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5291. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5292. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5293. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5294. }
  5295. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5296. void MemoryClientCertPresent(
  5297. const std::string &client_cert_file,
  5298. const std::string &client_private_key_file,
  5299. const std::string &client_encrypted_private_key_pass = std::string()) {
  5300. auto f = fopen(SERVER_CERT_FILE, "r+");
  5301. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5302. fclose(f);
  5303. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5304. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5305. fclose(f);
  5306. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5307. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5308. auto client_ca_cert_store = X509_STORE_new();
  5309. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5310. X509_free(client_cert);
  5311. fclose(f);
  5312. f = fopen(client_cert_file.c_str(), "r+");
  5313. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5314. fclose(f);
  5315. f = fopen(client_private_key_file.c_str(), "r+");
  5316. auto client_private_key = PEM_read_PrivateKey(
  5317. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5318. fclose(f);
  5319. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5320. ASSERT_TRUE(svr.is_valid());
  5321. svr.Get("/test", [&](const Request &req, Response &res) {
  5322. res.set_content("test", "text/plain");
  5323. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5324. ASSERT_TRUE(peer_cert != nullptr);
  5325. auto subject_name = X509_get_subject_name(peer_cert);
  5326. ASSERT_TRUE(subject_name != nullptr);
  5327. std::string common_name;
  5328. {
  5329. char name[BUFSIZ];
  5330. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5331. name, sizeof(name));
  5332. common_name.assign(name, static_cast<size_t>(name_len));
  5333. }
  5334. EXPECT_EQ("Common Name", common_name);
  5335. X509_free(peer_cert);
  5336. });
  5337. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5338. auto se = detail::scope_exit([&] {
  5339. svr.stop();
  5340. t.join();
  5341. ASSERT_FALSE(svr.is_running());
  5342. });
  5343. svr.wait_until_ready();
  5344. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5345. client_encrypted_private_key_pass);
  5346. cli.enable_server_certificate_verification(false);
  5347. cli.set_connection_timeout(30);
  5348. auto res = cli.Get("/test");
  5349. ASSERT_TRUE(res);
  5350. ASSERT_EQ(StatusCode::OK_200, res->status);
  5351. X509_free(server_cert);
  5352. EVP_PKEY_free(server_private_key);
  5353. X509_free(client_cert);
  5354. EVP_PKEY_free(client_private_key);
  5355. }
  5356. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5357. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5358. }
  5359. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5360. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5361. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5362. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5363. }
  5364. #endif
  5365. TEST(SSLClientServerTest, ClientCertMissing) {
  5366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5367. CLIENT_CA_CERT_DIR);
  5368. ASSERT_TRUE(svr.is_valid());
  5369. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5370. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5371. auto se = detail::scope_exit([&] {
  5372. svr.stop();
  5373. t.join();
  5374. ASSERT_FALSE(svr.is_running());
  5375. });
  5376. svr.wait_until_ready();
  5377. SSLClient cli(HOST, PORT);
  5378. auto res = cli.Get("/test");
  5379. cli.set_connection_timeout(30);
  5380. ASSERT_TRUE(!res);
  5381. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5382. }
  5383. TEST(SSLClientServerTest, TrustDirOptional) {
  5384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5385. ASSERT_TRUE(svr.is_valid());
  5386. svr.Get("/test", [&](const Request &, Response &res) {
  5387. res.set_content("test", "text/plain");
  5388. });
  5389. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5390. auto se = detail::scope_exit([&] {
  5391. svr.stop();
  5392. t.join();
  5393. ASSERT_FALSE(svr.is_running());
  5394. });
  5395. svr.wait_until_ready();
  5396. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5397. cli.enable_server_certificate_verification(false);
  5398. cli.set_connection_timeout(30);
  5399. auto res = cli.Get("/test");
  5400. ASSERT_TRUE(res);
  5401. ASSERT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5404. class NoListenSSLServer : public SSLServer {
  5405. public:
  5406. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5407. const char *client_ca_cert_file_path,
  5408. const char *client_ca_cert_dir_path = nullptr)
  5409. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5410. client_ca_cert_dir_path),
  5411. stop_(false) {}
  5412. std::atomic_bool stop_;
  5413. private:
  5414. bool process_and_close_socket(socket_t /*sock*/) override {
  5415. // Don't create SSL context
  5416. while (!stop_.load()) {
  5417. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5418. }
  5419. return true;
  5420. }
  5421. };
  5422. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5423. CLIENT_CA_CERT_FILE);
  5424. ASSERT_TRUE(svr.is_valid());
  5425. svr.Get("/test", [&](const Request &, Response &res) {
  5426. res.set_content("test", "text/plain");
  5427. });
  5428. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5429. auto se = detail::scope_exit([&] {
  5430. svr.stop_ = true;
  5431. svr.stop();
  5432. t.join();
  5433. ASSERT_FALSE(svr.is_running());
  5434. });
  5435. svr.wait_until_ready();
  5436. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5437. cli.enable_server_certificate_verification(false);
  5438. cli.set_connection_timeout(1);
  5439. auto res = cli.Get("/test");
  5440. ASSERT_TRUE(!res);
  5441. EXPECT_EQ(Error::SSLConnection, res.error());
  5442. }
  5443. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5444. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5445. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5446. SSL_CTX_set_options(&ssl_ctx,
  5447. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5448. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5449. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5450. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5451. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5452. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5453. "ECDHE-DSS-AES128-SHA256:"
  5454. "ECDHE-RSA-AES256-SHA256:"
  5455. "ECDHE-DSS-AES256-SHA256:";
  5456. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5457. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5458. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5459. SSL_FILETYPE_PEM) != 1) {
  5460. return false;
  5461. }
  5462. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5463. CLIENT_CA_CERT_DIR);
  5464. SSL_CTX_set_verify(
  5465. &ssl_ctx,
  5466. SSL_VERIFY_PEER |
  5467. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5468. nullptr);
  5469. return true;
  5470. };
  5471. SSLServer svr(setup_ssl_ctx_callback);
  5472. ASSERT_TRUE(svr.is_valid());
  5473. svr.Get("/test", [&](const Request &req, Response &res) {
  5474. res.set_content("test", "text/plain");
  5475. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5476. ASSERT_TRUE(peer_cert != nullptr);
  5477. auto subject_name = X509_get_subject_name(peer_cert);
  5478. ASSERT_TRUE(subject_name != nullptr);
  5479. std::string common_name;
  5480. {
  5481. char name[BUFSIZ];
  5482. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5483. name, sizeof(name));
  5484. common_name.assign(name, static_cast<size_t>(name_len));
  5485. }
  5486. EXPECT_EQ("Common Name", common_name);
  5487. X509_free(peer_cert);
  5488. });
  5489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5490. auto se = detail::scope_exit([&] {
  5491. svr.stop();
  5492. t.join();
  5493. ASSERT_FALSE(svr.is_running());
  5494. });
  5495. svr.wait_until_ready();
  5496. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5497. cli.enable_server_certificate_verification(false);
  5498. cli.set_connection_timeout(30);
  5499. auto res = cli.Get("/test");
  5500. ASSERT_TRUE(res);
  5501. ASSERT_EQ(StatusCode::OK_200, res->status);
  5502. }
  5503. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5504. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5505. // prepare large data
  5506. std::random_device seed_gen;
  5507. std::mt19937 random(seed_gen());
  5508. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5509. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5510. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5511. // server
  5512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5513. ASSERT_TRUE(svr.is_valid());
  5514. svr.Post("/binary", [&](const Request &req, Response &res) {
  5515. EXPECT_EQ(large_size_byte, req.body.size());
  5516. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5517. res.set_content(req.body, "application/octet-stream");
  5518. });
  5519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5520. auto se = detail::scope_exit([&] {
  5521. svr.stop();
  5522. listen_thread.join();
  5523. ASSERT_FALSE(svr.is_running());
  5524. });
  5525. svr.wait_until_ready();
  5526. // client POST
  5527. SSLClient cli("localhost", PORT);
  5528. cli.enable_server_certificate_verification(false);
  5529. cli.set_read_timeout(std::chrono::seconds(100));
  5530. cli.set_write_timeout(std::chrono::seconds(100));
  5531. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5532. large_size_byte, "application/octet-stream");
  5533. // compare
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. EXPECT_EQ(large_size_byte, res->body.size());
  5536. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5537. }
  5538. #endif
  5539. #ifdef _WIN32
  5540. TEST(CleanupTest, WSACleanup) {
  5541. int ret = WSACleanup();
  5542. ASSERT_EQ(0, ret);
  5543. }
  5544. #endif
  5545. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5546. TEST(NoSSLSupport, SimpleInterface) {
  5547. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5548. }
  5549. #endif
  5550. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5551. TEST(InvalidScheme, SimpleInterface) {
  5552. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5553. }
  5554. #endif
  5555. TEST(NoScheme, SimpleInterface) {
  5556. Client cli("yahoo.com:80");
  5557. ASSERT_TRUE(cli.is_valid());
  5558. }
  5559. TEST(SendAPI, SimpleInterface_Online) {
  5560. Client cli("http://yahoo.com");
  5561. Request req;
  5562. req.method = "GET";
  5563. req.path = "/";
  5564. auto res = cli.send(req);
  5565. ASSERT_TRUE(res);
  5566. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5567. }
  5568. TEST(SendAPI, WithParamsInRequest) {
  5569. Server svr;
  5570. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  5571. EXPECT_TRUE(req.has_param("test"));
  5572. EXPECT_EQ("test_value", req.get_param_value("test"));
  5573. });
  5574. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  5575. auto se = detail::scope_exit([&] {
  5576. svr.stop();
  5577. t.join();
  5578. ASSERT_FALSE(svr.is_running());
  5579. });
  5580. svr.wait_until_ready();
  5581. Client cli(HOST, PORT);
  5582. {
  5583. Request req;
  5584. req.method = "GET";
  5585. req.path = "/";
  5586. req.params.emplace("test", "test_value");
  5587. auto res = cli.send(req);
  5588. ASSERT_TRUE(res);
  5589. }
  5590. {
  5591. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  5592. ASSERT_TRUE(res);
  5593. }
  5594. }
  5595. TEST(ClientImplMethods, GetSocketTest) {
  5596. httplib::Server svr;
  5597. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5598. res.status = StatusCode::OK_200;
  5599. });
  5600. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5601. auto se = detail::scope_exit([&] {
  5602. svr.stop();
  5603. thread.join();
  5604. ASSERT_FALSE(svr.is_running());
  5605. });
  5606. svr.wait_until_ready();
  5607. {
  5608. httplib::Client cli("http://127.0.0.1:3333");
  5609. cli.set_keep_alive(true);
  5610. // Use the behavior of cpp-httplib of opening the connection
  5611. // only when the first request happens. If that changes,
  5612. // this test would be obsolete.
  5613. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5614. // This also implicitly tests the server. But other tests would fail much
  5615. // earlier than this one to be considered.
  5616. auto res = cli.Get("/");
  5617. ASSERT_TRUE(res);
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5620. }
  5621. }
  5622. // Disabled due to out-of-memory problem on GitHub Actions
  5623. #ifdef _WIN64
  5624. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5625. // allocate content size larger than 2GB in memory
  5626. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5627. char *content = (char *)malloc(content_size);
  5628. ASSERT_TRUE(content);
  5629. Server svr;
  5630. svr.Get("/foo",
  5631. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5632. res.set_content(content, content_size, "application/octet-stream");
  5633. });
  5634. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5635. auto se = detail::scope_exit([&] {
  5636. svr.stop();
  5637. listen_thread.join();
  5638. if (content) free(content);
  5639. ASSERT_FALSE(svr.is_running());
  5640. });
  5641. svr.wait_until_ready();
  5642. Client cli(HOST, PORT);
  5643. auto res = cli.Get("/foo");
  5644. ASSERT_TRUE(res);
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. EXPECT_EQ(content_size, res->body.length());
  5647. }
  5648. #endif
  5649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5650. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5651. Client cli("http://yahoo.com");
  5652. auto res = cli.Get("/");
  5653. ASSERT_TRUE(res);
  5654. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5655. cli.set_follow_location(true);
  5656. res = cli.Get("/");
  5657. ASSERT_TRUE(res);
  5658. EXPECT_EQ(StatusCode::OK_200, res->status);
  5659. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5660. }
  5661. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5662. Client cli("https://yahoo.com");
  5663. auto res = cli.Get("/");
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5666. cli.set_follow_location(true);
  5667. res = cli.Get("/");
  5668. ASSERT_TRUE(res);
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5671. }
  5672. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5673. Client cli("https://yahoo.com");
  5674. auto res = cli.Get("/");
  5675. ASSERT_TRUE(res);
  5676. ASSERT_FALSE(!res);
  5677. ASSERT_TRUE(res);
  5678. ASSERT_FALSE(res == nullptr);
  5679. ASSERT_TRUE(res != nullptr);
  5680. EXPECT_EQ(Error::Success, res.error());
  5681. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5682. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5683. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5684. cli.set_follow_location(true);
  5685. res = cli.Get("/");
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(Error::Success, res.error());
  5688. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5689. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5692. }
  5693. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5694. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5695. Client cli("https://cdnjs.cloudflare.com");
  5696. auto res =
  5697. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5698. ASSERT_TRUE(res);
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ(287630U, res->body.size());
  5701. EXPECT_EQ("application/javascript; charset=utf-8",
  5702. res->get_header_value("Content-Type"));
  5703. }
  5704. #endif
  5705. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5706. Client cli("https://nghttp2.org");
  5707. cli.set_follow_location(true);
  5708. auto res =
  5709. cli.Get("/httpbin/"
  5710. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. }
  5714. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5715. Client cli("https://nghttp2.org");
  5716. cli.set_follow_location(true);
  5717. Params params;
  5718. params.emplace("url", "http://www.google.com");
  5719. params.emplace("status_code", "302");
  5720. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5721. ASSERT_TRUE(res);
  5722. EXPECT_EQ(StatusCode::OK_200, res->status);
  5723. }
  5724. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5725. Client cli("https://nghttp2.org");
  5726. cli.set_follow_location(true);
  5727. Params params;
  5728. params.emplace("url", "http://www.google.com");
  5729. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5730. ASSERT_TRUE(res);
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. }
  5733. TEST(HttpToHttpsRedirectTest, CertFile) {
  5734. Server svr;
  5735. ASSERT_TRUE(svr.is_valid());
  5736. svr.Get("/index", [&](const Request &, Response &res) {
  5737. res.set_redirect("https://127.0.0.1:1235/index");
  5738. svr.stop();
  5739. });
  5740. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5741. ASSERT_TRUE(ssl_svr.is_valid());
  5742. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5743. res.set_content("test", "text/plain");
  5744. ssl_svr.stop();
  5745. });
  5746. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5747. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5748. auto se = detail::scope_exit([&] {
  5749. t2.join();
  5750. t.join();
  5751. ASSERT_FALSE(svr.is_running());
  5752. });
  5753. svr.wait_until_ready();
  5754. ssl_svr.wait_until_ready();
  5755. Client cli("127.0.0.1", PORT);
  5756. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5757. cli.enable_server_certificate_verification(true);
  5758. cli.set_follow_location(true);
  5759. cli.set_connection_timeout(30);
  5760. auto res = cli.Get("/index");
  5761. ASSERT_TRUE(res);
  5762. ASSERT_EQ(StatusCode::OK_200, res->status);
  5763. }
  5764. TEST(MultipartFormDataTest, LargeData) {
  5765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5766. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5767. const ContentReader &content_reader) {
  5768. if (req.is_multipart_form_data()) {
  5769. MultipartFormDataItems files;
  5770. content_reader(
  5771. [&](const MultipartFormData &file) {
  5772. files.push_back(file);
  5773. return true;
  5774. },
  5775. [&](const char *data, size_t data_length) {
  5776. files.back().content.append(data, data_length);
  5777. return true;
  5778. });
  5779. EXPECT_TRUE(std::string(files[0].name) == "document");
  5780. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5781. EXPECT_TRUE(files[0].filename == "2MB_data");
  5782. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5783. EXPECT_TRUE(files[1].name == "hello");
  5784. EXPECT_TRUE(files[1].content == "world");
  5785. EXPECT_TRUE(files[1].filename == "");
  5786. EXPECT_TRUE(files[1].content_type == "");
  5787. } else {
  5788. std::string body;
  5789. content_reader([&](const char *data, size_t data_length) {
  5790. body.append(data, data_length);
  5791. return true;
  5792. });
  5793. }
  5794. });
  5795. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5796. auto se = detail::scope_exit([&] {
  5797. svr.stop();
  5798. t.join();
  5799. ASSERT_FALSE(svr.is_running());
  5800. });
  5801. svr.wait_until_ready();
  5802. {
  5803. std::string data(1024 * 1024 * 2, '.');
  5804. std::stringstream buffer;
  5805. buffer << data;
  5806. Client cli("https://localhost:8080");
  5807. cli.enable_server_certificate_verification(false);
  5808. MultipartFormDataItems items{
  5809. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5810. {"hello", "world", "", ""},
  5811. };
  5812. auto res = cli.Post("/post", items);
  5813. ASSERT_TRUE(res);
  5814. ASSERT_EQ(StatusCode::OK_200, res->status);
  5815. }
  5816. }
  5817. TEST(MultipartFormDataTest, DataProviderItems) {
  5818. std::random_device seed_gen;
  5819. std::mt19937 random(seed_gen());
  5820. std::string rand1;
  5821. rand1.resize(1000);
  5822. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5823. std::string rand2;
  5824. rand2.resize(3000);
  5825. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5827. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5828. const ContentReader &content_reader) {
  5829. ASSERT_FALSE(req.is_multipart_form_data());
  5830. std::string body;
  5831. content_reader([&](const char *data, size_t data_length) {
  5832. body.append(data, data_length);
  5833. return true;
  5834. });
  5835. EXPECT_EQ(body, "");
  5836. });
  5837. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5838. const ContentReader &content_reader) {
  5839. ASSERT_TRUE(req.is_multipart_form_data());
  5840. MultipartFormDataItems files;
  5841. content_reader(
  5842. [&](const MultipartFormData &file) {
  5843. files.push_back(file);
  5844. return true;
  5845. },
  5846. [&](const char *data, size_t data_length) {
  5847. files.back().content.append(data, data_length);
  5848. return true;
  5849. });
  5850. ASSERT_TRUE(files.size() == 2);
  5851. EXPECT_EQ(std::string(files[0].name), "name1");
  5852. EXPECT_EQ(files[0].content, "Testing123");
  5853. EXPECT_EQ(files[0].filename, "filename1");
  5854. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5855. EXPECT_EQ(files[1].name, "name2");
  5856. EXPECT_EQ(files[1].content, "Testing456");
  5857. EXPECT_EQ(files[1].filename, "");
  5858. EXPECT_EQ(files[1].content_type, "");
  5859. });
  5860. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5861. const ContentReader &content_reader) {
  5862. ASSERT_TRUE(req.is_multipart_form_data());
  5863. MultipartFormDataItems files;
  5864. content_reader(
  5865. [&](const MultipartFormData &file) {
  5866. files.push_back(file);
  5867. return true;
  5868. },
  5869. [&](const char *data, size_t data_length) {
  5870. files.back().content.append(data, data_length);
  5871. return true;
  5872. });
  5873. ASSERT_TRUE(files.size() == 2);
  5874. EXPECT_EQ(files[0].name, "name3");
  5875. EXPECT_EQ(files[0].content, rand1);
  5876. EXPECT_EQ(files[0].filename, "filename3");
  5877. EXPECT_EQ(files[0].content_type, "");
  5878. EXPECT_EQ(files[1].name, "name4");
  5879. EXPECT_EQ(files[1].content, rand2);
  5880. EXPECT_EQ(files[1].filename, "filename4");
  5881. EXPECT_EQ(files[1].content_type, "");
  5882. });
  5883. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5884. const ContentReader &content_reader) {
  5885. ASSERT_TRUE(req.is_multipart_form_data());
  5886. MultipartFormDataItems files;
  5887. content_reader(
  5888. [&](const MultipartFormData &file) {
  5889. files.push_back(file);
  5890. return true;
  5891. },
  5892. [&](const char *data, size_t data_length) {
  5893. files.back().content.append(data, data_length);
  5894. return true;
  5895. });
  5896. ASSERT_TRUE(files.size() == 4);
  5897. EXPECT_EQ(std::string(files[0].name), "name1");
  5898. EXPECT_EQ(files[0].content, "Testing123");
  5899. EXPECT_EQ(files[0].filename, "filename1");
  5900. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5901. EXPECT_EQ(files[1].name, "name2");
  5902. EXPECT_EQ(files[1].content, "Testing456");
  5903. EXPECT_EQ(files[1].filename, "");
  5904. EXPECT_EQ(files[1].content_type, "");
  5905. EXPECT_EQ(files[2].name, "name3");
  5906. EXPECT_EQ(files[2].content, rand1);
  5907. EXPECT_EQ(files[2].filename, "filename3");
  5908. EXPECT_EQ(files[2].content_type, "");
  5909. EXPECT_EQ(files[3].name, "name4");
  5910. EXPECT_EQ(files[3].content, rand2);
  5911. EXPECT_EQ(files[3].filename, "filename4");
  5912. EXPECT_EQ(files[3].content_type, "");
  5913. });
  5914. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5915. auto se = detail::scope_exit([&] {
  5916. svr.stop();
  5917. t.join();
  5918. ASSERT_FALSE(svr.is_running());
  5919. });
  5920. svr.wait_until_ready();
  5921. {
  5922. Client cli("https://localhost:8080");
  5923. cli.enable_server_certificate_verification(false);
  5924. MultipartFormDataItems items{
  5925. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5926. {"name2", "Testing456", "", ""}, // not a file
  5927. };
  5928. {
  5929. auto res = cli.Post("/post-none", {}, {}, {});
  5930. ASSERT_TRUE(res);
  5931. ASSERT_EQ(StatusCode::OK_200, res->status);
  5932. }
  5933. MultipartFormDataProviderItems providers;
  5934. {
  5935. auto res =
  5936. cli.Post("/post-items", {}, items, providers); // empty providers
  5937. ASSERT_TRUE(res);
  5938. ASSERT_EQ(StatusCode::OK_200, res->status);
  5939. }
  5940. providers.push_back({"name3",
  5941. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5942. // test the offset is given correctly at each step
  5943. if (!offset)
  5944. sink.os.write(rand1.data(), 30);
  5945. else if (offset == 30)
  5946. sink.os.write(rand1.data() + 30, 300);
  5947. else if (offset == 330)
  5948. sink.os.write(rand1.data() + 330, 670);
  5949. else if (offset == rand1.size())
  5950. sink.done();
  5951. return true;
  5952. },
  5953. "filename3",
  5954. {}});
  5955. providers.push_back({"name4",
  5956. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5957. // test the offset is given correctly at each step
  5958. if (!offset)
  5959. sink.os.write(rand2.data(), 2000);
  5960. else if (offset == 2000)
  5961. sink.os.write(rand2.data() + 2000, 1);
  5962. else if (offset == 2001)
  5963. sink.os.write(rand2.data() + 2001, 999);
  5964. else if (offset == rand2.size())
  5965. sink.done();
  5966. return true;
  5967. },
  5968. "filename4",
  5969. {}});
  5970. {
  5971. auto res = cli.Post("/post-providers", {}, {}, providers);
  5972. ASSERT_TRUE(res);
  5973. ASSERT_EQ(StatusCode::OK_200, res->status);
  5974. }
  5975. {
  5976. auto res = cli.Post("/post-both", {}, items, providers);
  5977. ASSERT_TRUE(res);
  5978. ASSERT_EQ(StatusCode::OK_200, res->status);
  5979. }
  5980. }
  5981. }
  5982. TEST(MultipartFormDataTest, BadHeader) {
  5983. Server svr;
  5984. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5985. res.set_content("ok", "text/plain");
  5986. });
  5987. thread t = thread([&] { svr.listen(HOST, PORT); });
  5988. auto se = detail::scope_exit([&] {
  5989. svr.stop();
  5990. t.join();
  5991. ASSERT_FALSE(svr.is_running());
  5992. });
  5993. svr.wait_until_ready();
  5994. const std::string body =
  5995. "This is the preamble. It is to be ignored, though it\r\n"
  5996. "is a handy place for composition agents to include an\r\n"
  5997. "explanatory note to non-MIME conformant readers.\r\n"
  5998. "\r\n"
  5999. "\r\n"
  6000. "--simple boundary\r\n"
  6001. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6002. ": BAD...\r\n"
  6003. "\r\n"
  6004. "value1\r\n"
  6005. "--simple boundary\r\n"
  6006. "Content-Disposition: form-data; name=\"field2\"; "
  6007. "filename=\"example.txt\"\r\n"
  6008. "\r\n"
  6009. "value2\r\n"
  6010. "--simple boundary--\r\n"
  6011. "This is the epilogue. It is also to be ignored.\r\n";
  6012. std::string content_type =
  6013. R"(multipart/form-data; boundary="simple boundary")";
  6014. Client cli(HOST, PORT);
  6015. auto res = cli.Post("/post", body, content_type.c_str());
  6016. ASSERT_TRUE(res);
  6017. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6018. }
  6019. TEST(MultipartFormDataTest, WithPreamble) {
  6020. Server svr;
  6021. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6022. res.set_content("ok", "text/plain");
  6023. });
  6024. thread t = thread([&] { svr.listen(HOST, PORT); });
  6025. auto se = detail::scope_exit([&] {
  6026. svr.stop();
  6027. t.join();
  6028. ASSERT_FALSE(svr.is_running());
  6029. });
  6030. svr.wait_until_ready();
  6031. const std::string body =
  6032. "This is the preamble. It is to be ignored, though it\r\n"
  6033. "is a handy place for composition agents to include an\r\n"
  6034. "explanatory note to non-MIME conformant readers.\r\n"
  6035. "\r\n"
  6036. "\r\n"
  6037. "--simple boundary\r\n"
  6038. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6039. "\r\n"
  6040. "value1\r\n"
  6041. "--simple boundary\r\n"
  6042. "Content-Disposition: form-data; name=\"field2\"; "
  6043. "filename=\"example.txt\"\r\n"
  6044. "\r\n"
  6045. "value2\r\n"
  6046. "--simple boundary--\r\n"
  6047. "This is the epilogue. It is also to be ignored.\r\n";
  6048. std::string content_type =
  6049. R"(multipart/form-data; boundary="simple boundary")";
  6050. Client cli(HOST, PORT);
  6051. auto res = cli.Post("/post", body, content_type.c_str());
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ(StatusCode::OK_200, res->status);
  6054. }
  6055. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6056. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6057. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6058. const ContentReader &content_reader) {
  6059. if (req.is_multipart_form_data()) {
  6060. MultipartFormDataItems files;
  6061. content_reader(
  6062. [&](const MultipartFormData &file) {
  6063. files.push_back(file);
  6064. return true;
  6065. },
  6066. [&](const char *data, size_t data_length) {
  6067. files.back().content.append(data, data_length);
  6068. return true;
  6069. });
  6070. EXPECT_TRUE(std::string(files[0].name) == "document");
  6071. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6072. EXPECT_TRUE(files[0].filename == "2MB_data");
  6073. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6074. EXPECT_TRUE(files[1].name == "hello");
  6075. EXPECT_TRUE(files[1].content == "world");
  6076. EXPECT_TRUE(files[1].filename == "");
  6077. EXPECT_TRUE(files[1].content_type == "");
  6078. } else {
  6079. std::string body;
  6080. content_reader([&](const char *data, size_t data_length) {
  6081. body.append(data, data_length);
  6082. return true;
  6083. });
  6084. }
  6085. });
  6086. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6087. auto se = detail::scope_exit([&] {
  6088. svr.stop();
  6089. t.join();
  6090. ASSERT_FALSE(svr.is_running());
  6091. });
  6092. svr.wait_until_ready();
  6093. {
  6094. std::string data(1024 * 1024 * 2, '.');
  6095. std::stringstream buffer;
  6096. buffer << data;
  6097. Client cli("https://localhost:8080");
  6098. cli.enable_server_certificate_verification(false);
  6099. MultipartFormDataItems items{
  6100. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6101. {"hello", "world", "", ""},
  6102. };
  6103. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6104. ASSERT_TRUE(res);
  6105. ASSERT_EQ(StatusCode::OK_200, res->status);
  6106. }
  6107. }
  6108. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6109. std::string data(1024 * 1024 * 2, '&');
  6110. std::stringstream buffer;
  6111. buffer << data;
  6112. Client cli("https://localhost:8080");
  6113. MultipartFormDataItems items{
  6114. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6115. {"hello", "world", "", ""},
  6116. };
  6117. for (const char &c : " \t\r\n") {
  6118. auto res =
  6119. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6120. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6121. ASSERT_FALSE(res);
  6122. }
  6123. }
  6124. TEST(MultipartFormDataTest, PutFormData) {
  6125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6126. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6127. const ContentReader &content_reader) {
  6128. if (req.is_multipart_form_data()) {
  6129. MultipartFormDataItems files;
  6130. content_reader(
  6131. [&](const MultipartFormData &file) {
  6132. files.push_back(file);
  6133. return true;
  6134. },
  6135. [&](const char *data, size_t data_length) {
  6136. files.back().content.append(data, data_length);
  6137. return true;
  6138. });
  6139. EXPECT_TRUE(std::string(files[0].name) == "document");
  6140. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6141. EXPECT_TRUE(files[0].filename == "2MB_data");
  6142. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6143. EXPECT_TRUE(files[1].name == "hello");
  6144. EXPECT_TRUE(files[1].content == "world");
  6145. EXPECT_TRUE(files[1].filename == "");
  6146. EXPECT_TRUE(files[1].content_type == "");
  6147. } else {
  6148. std::string body;
  6149. content_reader([&](const char *data, size_t data_length) {
  6150. body.append(data, data_length);
  6151. return true;
  6152. });
  6153. }
  6154. });
  6155. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6156. auto se = detail::scope_exit([&] {
  6157. svr.stop();
  6158. t.join();
  6159. ASSERT_FALSE(svr.is_running());
  6160. });
  6161. svr.wait_until_ready();
  6162. {
  6163. std::string data(1024 * 1024 * 2, '&');
  6164. std::stringstream buffer;
  6165. buffer << data;
  6166. Client cli("https://localhost:8080");
  6167. cli.enable_server_certificate_verification(false);
  6168. MultipartFormDataItems items{
  6169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6170. {"hello", "world", "", ""},
  6171. };
  6172. auto res = cli.Put("/put", items);
  6173. ASSERT_TRUE(res);
  6174. ASSERT_EQ(StatusCode::OK_200, res->status);
  6175. }
  6176. }
  6177. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6179. svr.Put("/put_customboundary",
  6180. [&](const Request &req, const Response & /*res*/,
  6181. const ContentReader &content_reader) {
  6182. if (req.is_multipart_form_data()) {
  6183. MultipartFormDataItems files;
  6184. content_reader(
  6185. [&](const MultipartFormData &file) {
  6186. files.push_back(file);
  6187. return true;
  6188. },
  6189. [&](const char *data, size_t data_length) {
  6190. files.back().content.append(data, data_length);
  6191. return true;
  6192. });
  6193. EXPECT_TRUE(std::string(files[0].name) == "document");
  6194. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6195. EXPECT_TRUE(files[0].filename == "2MB_data");
  6196. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6197. EXPECT_TRUE(files[1].name == "hello");
  6198. EXPECT_TRUE(files[1].content == "world");
  6199. EXPECT_TRUE(files[1].filename == "");
  6200. EXPECT_TRUE(files[1].content_type == "");
  6201. } else {
  6202. std::string body;
  6203. content_reader([&](const char *data, size_t data_length) {
  6204. body.append(data, data_length);
  6205. return true;
  6206. });
  6207. }
  6208. });
  6209. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6210. auto se = detail::scope_exit([&] {
  6211. svr.stop();
  6212. t.join();
  6213. ASSERT_FALSE(svr.is_running());
  6214. });
  6215. svr.wait_until_ready();
  6216. {
  6217. std::string data(1024 * 1024 * 2, '&');
  6218. std::stringstream buffer;
  6219. buffer << data;
  6220. Client cli("https://localhost:8080");
  6221. cli.enable_server_certificate_verification(false);
  6222. MultipartFormDataItems items{
  6223. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6224. {"hello", "world", "", ""},
  6225. };
  6226. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6227. ASSERT_TRUE(res);
  6228. ASSERT_EQ(StatusCode::OK_200, res->status);
  6229. }
  6230. }
  6231. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6232. std::string data(1024 * 1024 * 2, '&');
  6233. std::stringstream buffer;
  6234. buffer << data;
  6235. Client cli("https://localhost:8080");
  6236. cli.enable_server_certificate_verification(false);
  6237. MultipartFormDataItems items{
  6238. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6239. {"hello", "world", "", ""},
  6240. };
  6241. for (const char &c : " \t\r\n") {
  6242. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6243. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6244. ASSERT_FALSE(res);
  6245. }
  6246. }
  6247. TEST(MultipartFormDataTest, AlternateFilename) {
  6248. auto handled = false;
  6249. Server svr;
  6250. svr.Post("/test", [&](const Request &req, Response &res) {
  6251. ASSERT_EQ(3u, req.files.size());
  6252. auto it = req.files.begin();
  6253. ASSERT_EQ("file1", it->second.name);
  6254. ASSERT_EQ("A.txt", it->second.filename);
  6255. ASSERT_EQ("text/plain", it->second.content_type);
  6256. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6257. ++it;
  6258. ASSERT_EQ("file2", it->second.name);
  6259. ASSERT_EQ("a.html", it->second.filename);
  6260. ASSERT_EQ("text/html", it->second.content_type);
  6261. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6262. it->second.content);
  6263. ++it;
  6264. ASSERT_EQ("text", it->second.name);
  6265. ASSERT_EQ("", it->second.filename);
  6266. ASSERT_EQ("", it->second.content_type);
  6267. ASSERT_EQ("text default", it->second.content);
  6268. res.set_content("ok", "text/plain");
  6269. handled = true;
  6270. });
  6271. thread t = thread([&] { svr.listen(HOST, PORT); });
  6272. auto se = detail::scope_exit([&] {
  6273. svr.stop();
  6274. t.join();
  6275. ASSERT_FALSE(svr.is_running());
  6276. ASSERT_TRUE(handled);
  6277. });
  6278. svr.wait_until_ready();
  6279. auto req = "POST /test HTTP/1.1\r\n"
  6280. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6281. "Content-Length: 399\r\n"
  6282. "\r\n"
  6283. "----------\r\n"
  6284. "Content-Disposition: form-data; name=\"text\"\r\n"
  6285. "\r\n"
  6286. "text default\r\n"
  6287. "----------\r\n"
  6288. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6289. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6290. "Content-Type: text/plain\r\n"
  6291. "\r\n"
  6292. "Content of a.txt.\r\n"
  6293. "\r\n"
  6294. "----------\r\n"
  6295. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6296. "\"a.html\"\r\n"
  6297. "Content-Type: text/html\r\n"
  6298. "\r\n"
  6299. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6300. "\r\n"
  6301. "------------\r\n";
  6302. ASSERT_TRUE(send_request(1, req));
  6303. }
  6304. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6305. auto handled = false;
  6306. Server svr;
  6307. svr.Post("/test", [&](const Request &req, Response &) {
  6308. ASSERT_EQ(2u, req.files.size());
  6309. auto it = req.files.begin();
  6310. ASSERT_EQ("text1", it->second.name);
  6311. ASSERT_EQ("text1", it->second.content);
  6312. ++it;
  6313. ASSERT_EQ("text2", it->second.name);
  6314. ASSERT_EQ("text2", it->second.content);
  6315. handled = true;
  6316. });
  6317. thread t = thread([&] { svr.listen(HOST, PORT); });
  6318. auto se = detail::scope_exit([&] {
  6319. svr.stop();
  6320. t.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. ASSERT_TRUE(handled);
  6323. });
  6324. svr.wait_until_ready();
  6325. auto req = "POST /test HTTP/1.1\r\n"
  6326. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6327. "Content-Length: 146\r\n"
  6328. "\r\n----------\r\n"
  6329. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6330. "\r\n"
  6331. "text1"
  6332. "\r\n----------\r\n"
  6333. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6334. "\r\n"
  6335. "text2"
  6336. "\r\n------------";
  6337. std::string response;
  6338. ASSERT_TRUE(send_request(1, req, &response));
  6339. ASSERT_EQ("200", response.substr(9, 3));
  6340. }
  6341. TEST(MultipartFormDataTest, ContentLength) {
  6342. auto handled = false;
  6343. Server svr;
  6344. svr.Post("/test", [&](const Request &req, Response &) {
  6345. ASSERT_EQ(2u, req.files.size());
  6346. auto it = req.files.begin();
  6347. ASSERT_EQ("text1", it->second.name);
  6348. ASSERT_EQ("text1", it->second.content);
  6349. ++it;
  6350. ASSERT_EQ("text2", it->second.name);
  6351. ASSERT_EQ("text2", it->second.content);
  6352. handled = true;
  6353. });
  6354. thread t = thread([&] { svr.listen(HOST, PORT); });
  6355. auto se = detail::scope_exit([&] {
  6356. svr.stop();
  6357. t.join();
  6358. ASSERT_FALSE(svr.is_running());
  6359. ASSERT_TRUE(handled);
  6360. });
  6361. svr.wait_until_ready();
  6362. auto req = "POST /test HTTP/1.1\r\n"
  6363. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6364. "Content-Length: 167\r\n"
  6365. "\r\n----------\r\n"
  6366. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6367. "Content-Length: 5\r\n"
  6368. "\r\n"
  6369. "text1"
  6370. "\r\n----------\r\n"
  6371. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6372. "\r\n"
  6373. "text2"
  6374. "\r\n------------\r\n";
  6375. std::string response;
  6376. ASSERT_TRUE(send_request(1, req, &response));
  6377. ASSERT_EQ("200", response.substr(9, 3));
  6378. }
  6379. #endif
  6380. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6381. static constexpr unsigned int number_of_tasks{1000000};
  6382. std::atomic_uint count{0};
  6383. std::unique_ptr<TaskQueue> task_queue{
  6384. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6385. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6386. auto queued = task_queue->enqueue(
  6387. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6388. EXPECT_TRUE(queued);
  6389. }
  6390. EXPECT_NO_THROW(task_queue->shutdown());
  6391. EXPECT_EQ(number_of_tasks, count.load());
  6392. }
  6393. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6394. static constexpr unsigned int number_of_tasks{1000000};
  6395. static constexpr unsigned int qlimit{2};
  6396. unsigned int queued_count{0};
  6397. std::atomic_uint count{0};
  6398. std::unique_ptr<TaskQueue> task_queue{
  6399. new ThreadPool{/*num_threads=*/1, qlimit}};
  6400. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6401. if (task_queue->enqueue(
  6402. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6403. queued_count++;
  6404. }
  6405. }
  6406. EXPECT_NO_THROW(task_queue->shutdown());
  6407. EXPECT_EQ(queued_count, count.load());
  6408. EXPECT_TRUE(queued_count <= number_of_tasks);
  6409. EXPECT_TRUE(queued_count >= qlimit);
  6410. }
  6411. TEST(TaskQueueTest, MaxQueuedRequests) {
  6412. static constexpr unsigned int qlimit{3};
  6413. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6414. std::condition_variable sem_cv;
  6415. std::mutex sem_mtx;
  6416. int credits = 0;
  6417. bool queued;
  6418. /* Fill up the queue with tasks that will block until we give them credits to
  6419. * complete. */
  6420. for (unsigned int n = 0; n <= qlimit;) {
  6421. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6422. std::unique_lock<std::mutex> lock(sem_mtx);
  6423. while (credits <= 0) {
  6424. sem_cv.wait(lock);
  6425. }
  6426. /* Consume the credit and signal the test code if they are all gone. */
  6427. if (--credits == 0) { sem_cv.notify_one(); }
  6428. });
  6429. if (n < qlimit) {
  6430. /* The first qlimit enqueues must succeed. */
  6431. EXPECT_TRUE(queued);
  6432. } else {
  6433. /* The last one will succeed only when the worker thread
  6434. * starts and dequeues the first blocking task. Although
  6435. * not necessary for the correctness of this test, we sleep for
  6436. * a short while to avoid busy waiting. */
  6437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6438. }
  6439. if (queued) { n++; }
  6440. }
  6441. /* Further enqueues must fail since the queue is full. */
  6442. for (auto i = 0; i < 4; i++) {
  6443. queued = task_queue->enqueue([] {});
  6444. EXPECT_FALSE(queued);
  6445. }
  6446. /* Give the credits to allow the previous tasks to complete. */
  6447. {
  6448. std::unique_lock<std::mutex> lock(sem_mtx);
  6449. credits += qlimit + 1;
  6450. }
  6451. sem_cv.notify_all();
  6452. /* Wait for all the credits to be consumed. */
  6453. {
  6454. std::unique_lock<std::mutex> lock(sem_mtx);
  6455. while (credits > 0) {
  6456. sem_cv.wait(lock);
  6457. }
  6458. }
  6459. /* Check that we are able again to enqueue at least qlimit tasks. */
  6460. for (unsigned int i = 0; i < qlimit; i++) {
  6461. queued = task_queue->enqueue([] {});
  6462. EXPECT_TRUE(queued);
  6463. }
  6464. EXPECT_NO_THROW(task_queue->shutdown());
  6465. }
  6466. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6467. Server svr;
  6468. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6469. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6470. });
  6471. svr.Get("/hello", [](const Request &req, Response &res) {
  6472. res.set_content(req.get_param_value("key"), "text/plain");
  6473. });
  6474. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6475. auto se = detail::scope_exit([&] {
  6476. svr.stop();
  6477. thread.join();
  6478. ASSERT_FALSE(svr.is_running());
  6479. });
  6480. svr.wait_until_ready();
  6481. {
  6482. Client cli(HOST, PORT);
  6483. cli.set_follow_location(true);
  6484. auto res = cli.Get("/");
  6485. ASSERT_TRUE(res);
  6486. EXPECT_EQ(StatusCode::OK_200, res->status);
  6487. EXPECT_EQ("val&key2=val2", res->body);
  6488. }
  6489. }
  6490. TEST(VulnerabilityTest, CRLFInjection) {
  6491. Server svr;
  6492. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6493. res.set_content("Hello 1", "text/plain");
  6494. });
  6495. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6496. res.set_content("Hello 2", "text/plain");
  6497. });
  6498. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6499. res.set_content("Hello 3", "text/plain");
  6500. });
  6501. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6502. res.set_content("Hello 4", "text/plain");
  6503. });
  6504. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6505. for (const auto &x : req.headers) {
  6506. auto key = x.first;
  6507. EXPECT_STRNE("evil", key.c_str());
  6508. }
  6509. });
  6510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6511. auto se = detail::scope_exit([&] {
  6512. svr.stop();
  6513. thread.join();
  6514. ASSERT_FALSE(svr.is_running());
  6515. });
  6516. svr.wait_until_ready();
  6517. {
  6518. Client cli(HOST, PORT);
  6519. cli.Post("/test1", "A=B",
  6520. "application/x-www-form-urlencoded\r\nevil: hello1");
  6521. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6522. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6523. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6524. }
  6525. }
  6526. TEST(PathParamsTest, StaticMatch) {
  6527. const auto pattern = "/users/all";
  6528. detail::PathParamsMatcher matcher(pattern);
  6529. Request request;
  6530. request.path = "/users/all";
  6531. ASSERT_TRUE(matcher.match(request));
  6532. std::unordered_map<std::string, std::string> expected_params = {};
  6533. EXPECT_EQ(request.path_params, expected_params);
  6534. }
  6535. TEST(PathParamsTest, StaticMismatch) {
  6536. const auto pattern = "/users/all";
  6537. detail::PathParamsMatcher matcher(pattern);
  6538. Request request;
  6539. request.path = "/users/1";
  6540. ASSERT_FALSE(matcher.match(request));
  6541. }
  6542. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6543. const auto pattern = "/users/:id/subscriptions";
  6544. detail::PathParamsMatcher matcher(pattern);
  6545. Request request;
  6546. request.path = "/users/42/subscriptions";
  6547. ASSERT_TRUE(matcher.match(request));
  6548. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6549. EXPECT_EQ(request.path_params, expected_params);
  6550. }
  6551. TEST(PathParamsTest, SingleParamInTheEnd) {
  6552. const auto pattern = "/users/:id";
  6553. detail::PathParamsMatcher matcher(pattern);
  6554. Request request;
  6555. request.path = "/users/24";
  6556. ASSERT_TRUE(matcher.match(request));
  6557. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6558. EXPECT_EQ(request.path_params, expected_params);
  6559. }
  6560. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6561. const auto pattern = "/users/:id/";
  6562. detail::PathParamsMatcher matcher(pattern);
  6563. Request request;
  6564. request.path = "/users/42/";
  6565. ASSERT_TRUE(matcher.match(request));
  6566. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6567. EXPECT_EQ(request.path_params, expected_params);
  6568. }
  6569. TEST(PathParamsTest, EmptyParam) {
  6570. const auto pattern = "/users/:id/";
  6571. detail::PathParamsMatcher matcher(pattern);
  6572. Request request;
  6573. request.path = "/users//";
  6574. ASSERT_TRUE(matcher.match(request));
  6575. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6576. EXPECT_EQ(request.path_params, expected_params);
  6577. }
  6578. TEST(PathParamsTest, FragmentMismatch) {
  6579. const auto pattern = "/users/:id/";
  6580. detail::PathParamsMatcher matcher(pattern);
  6581. Request request;
  6582. request.path = "/admins/24/";
  6583. ASSERT_FALSE(matcher.match(request));
  6584. }
  6585. TEST(PathParamsTest, ExtraFragments) {
  6586. const auto pattern = "/users/:id";
  6587. detail::PathParamsMatcher matcher(pattern);
  6588. Request request;
  6589. request.path = "/users/42/subscriptions";
  6590. ASSERT_FALSE(matcher.match(request));
  6591. }
  6592. TEST(PathParamsTest, MissingTrailingParam) {
  6593. const auto pattern = "/users/:id";
  6594. detail::PathParamsMatcher matcher(pattern);
  6595. Request request;
  6596. request.path = "/users";
  6597. ASSERT_FALSE(matcher.match(request));
  6598. }
  6599. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6600. const auto pattern = "/users/:id/subscriptions";
  6601. detail::PathParamsMatcher matcher(pattern);
  6602. Request request;
  6603. request.path = "/users/subscriptions";
  6604. ASSERT_FALSE(matcher.match(request));
  6605. }
  6606. TEST(PathParamsTest, MultipleParams) {
  6607. const auto pattern = "/users/:userid/subscriptions/:subid";
  6608. detail::PathParamsMatcher matcher(pattern);
  6609. Request request;
  6610. request.path = "/users/42/subscriptions/2";
  6611. ASSERT_TRUE(matcher.match(request));
  6612. std::unordered_map<std::string, std::string> expected_params = {
  6613. {"userid", "42"}, {"subid", "2"}};
  6614. EXPECT_EQ(request.path_params, expected_params);
  6615. }
  6616. TEST(PathParamsTest, SequenceOfParams) {
  6617. const auto pattern = "/values/:x/:y/:z";
  6618. detail::PathParamsMatcher matcher(pattern);
  6619. Request request;
  6620. request.path = "/values/1/2/3";
  6621. ASSERT_TRUE(matcher.match(request));
  6622. std::unordered_map<std::string, std::string> expected_params = {
  6623. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6624. EXPECT_EQ(request.path_params, expected_params);
  6625. }
  6626. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6627. const auto pattern = "/prefix:suffix";
  6628. detail::PathParamsMatcher matcher(pattern);
  6629. Request request;
  6630. request.path = "/prefix:suffix";
  6631. ASSERT_TRUE(matcher.match(request));
  6632. const std::unordered_map<std::string, std::string> expected_params = {};
  6633. EXPECT_EQ(request.path_params, expected_params);
  6634. }
  6635. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6636. // If ipv6 regex working, regex match codepath is taken.
  6637. // else port will default to 80 in Client impl
  6638. int clientImplMagicPort = 80;
  6639. int port = 4321;
  6640. // above ports must be different to avoid false negative
  6641. EXPECT_NE(clientImplMagicPort, port);
  6642. std::string ipV6TestURL = "http://[ff06::c3]";
  6643. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6644. CLIENT_PRIVATE_KEY_FILE);
  6645. EXPECT_EQ(cli.port(), port);
  6646. }
  6647. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6648. auto file_path = "./www/dir/index.html";
  6649. auto dir_path = "./www/dir";
  6650. detail::FileStat stat_file(file_path);
  6651. EXPECT_TRUE(stat_file.is_file());
  6652. EXPECT_FALSE(stat_file.is_dir());
  6653. detail::FileStat stat_dir(dir_path);
  6654. EXPECT_FALSE(stat_dir.is_file());
  6655. EXPECT_TRUE(stat_dir.is_dir());
  6656. }
  6657. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6658. Server svr;
  6659. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6660. EXPECT_EQ(res.status, 400);
  6661. });
  6662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. Client cli(HOST, PORT);
  6670. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6671. }
  6672. TEST(InvalidHeaderCharsTest, is_field_name) {
  6673. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  6674. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  6675. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  6676. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  6677. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  6678. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  6679. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  6680. EXPECT_FALSE(detail::fields::is_field_name(""));
  6681. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  6682. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  6683. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  6684. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  6685. }
  6686. TEST(InvalidHeaderCharsTest, is_field_value) {
  6687. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  6688. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  6689. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  6690. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  6691. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  6692. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  6693. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  6694. EXPECT_TRUE(detail::fields::is_field_value(""));
  6695. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  6696. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  6697. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  6698. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  6699. EXPECT_TRUE(detail::fields::is_field_value("0"));
  6700. }
  6701. TEST(InvalidHeaderCharsTest, OnServer) {
  6702. Server svr;
  6703. svr.Get("/test_name", [&](const Request &req, Response &res) {
  6704. std::string header = "Not Set";
  6705. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6706. res.set_header(header, "value");
  6707. res.set_content("Page Content Page Content", "text/plain");
  6708. });
  6709. svr.Get("/test_value", [&](const Request &req, Response &res) {
  6710. std::string header = "Not Set";
  6711. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6712. res.set_header("X-Test", header);
  6713. res.set_content("Page Content Page Content", "text/plain");
  6714. });
  6715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6716. auto se = detail::scope_exit([&] {
  6717. svr.stop();
  6718. thread.join();
  6719. ASSERT_FALSE(svr.is_running());
  6720. });
  6721. svr.wait_until_ready();
  6722. Client cli(HOST, PORT);
  6723. {
  6724. auto res = cli.Get(
  6725. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6726. ASSERT_TRUE(res);
  6727. EXPECT_EQ("Page Content Page Content", res->body);
  6728. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6729. }
  6730. {
  6731. auto res = cli.Get(
  6732. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6733. ASSERT_TRUE(res);
  6734. EXPECT_EQ("Page Content Page Content", res->body);
  6735. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6736. }
  6737. }
  6738. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  6739. auto handled = false;
  6740. Server svr;
  6741. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  6742. thread t = thread([&] { svr.listen(HOST, PORT); });
  6743. auto se = detail::scope_exit([&] {
  6744. svr.stop();
  6745. t.join();
  6746. ASSERT_FALSE(svr.is_running());
  6747. ASSERT_FALSE(handled);
  6748. });
  6749. svr.wait_until_ready();
  6750. auto req = "POST /test HTTP/1.1\r\n"
  6751. "Content-Length: x\r\n"
  6752. "\r\n";
  6753. std::string response;
  6754. ASSERT_TRUE(send_request(1, req, &response));
  6755. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  6756. response.substr(0, response.find("\r\n")));
  6757. }
  6758. #ifndef _WIN32
  6759. TEST(Expect100ContinueTest, ServerClosesConnection) {
  6760. static constexpr char reject[] = "Unauthorized";
  6761. static constexpr char accept[] = "Upload accepted";
  6762. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  6763. Server svr;
  6764. svr.set_expect_100_continue_handler(
  6765. [](const Request & /*req*/, Response &res) {
  6766. res.status = StatusCode::Unauthorized_401;
  6767. res.set_content(reject, "text/plain");
  6768. return res.status;
  6769. });
  6770. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  6771. res.set_content(accept, "text/plain");
  6772. });
  6773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6774. auto se = detail::scope_exit([&] {
  6775. svr.stop();
  6776. thread.join();
  6777. ASSERT_FALSE(svr.is_running());
  6778. });
  6779. svr.wait_until_ready();
  6780. {
  6781. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  6782. curl_easy_init(), &curl_easy_cleanup};
  6783. ASSERT_NE(curl, nullptr);
  6784. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  6785. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  6786. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  6787. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  6788. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  6789. &curl_slist_free_all};
  6790. ASSERT_NE(list, nullptr);
  6791. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  6792. struct read_data {
  6793. size_t read_size;
  6794. size_t total_size;
  6795. } data = {0, total_size};
  6796. using read_callback_t =
  6797. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6798. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  6799. void *userdata) -> size_t {
  6800. read_data *data = (read_data *)userdata;
  6801. if (!userdata || data->read_size >= data->total_size) { return 0; }
  6802. std::fill_n(ptr, size * nmemb, 'A');
  6803. data->read_size += size * nmemb;
  6804. return size * nmemb;
  6805. };
  6806. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  6807. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  6808. std::vector<char> buffer;
  6809. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  6810. using write_callback_t =
  6811. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6812. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  6813. void *userdata) -> size_t {
  6814. std::vector<char> *buffer = (std::vector<char> *)userdata;
  6815. buffer->reserve(buffer->size() + size * nmemb + 1);
  6816. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  6817. return size * nmemb;
  6818. };
  6819. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  6820. {
  6821. const auto res = curl_easy_perform(curl.get());
  6822. ASSERT_EQ(res, CURLE_OK);
  6823. }
  6824. {
  6825. auto response_code = long{};
  6826. const auto res =
  6827. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  6828. ASSERT_EQ(res, CURLE_OK);
  6829. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  6830. }
  6831. {
  6832. auto dl = curl_off_t{};
  6833. const auto res =
  6834. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  6835. ASSERT_EQ(res, CURLE_OK);
  6836. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  6837. }
  6838. {
  6839. buffer.push_back('\0');
  6840. ASSERT_STRCASEEQ(buffer.data(), reject);
  6841. }
  6842. }
  6843. }
  6844. #endif
  6845. TEST(MaxTimeoutTest, ContentStream) {
  6846. Server svr;
  6847. svr.Get("/stream", [&](const Request &, Response &res) {
  6848. auto data = new std::string("01234567890123456789");
  6849. res.set_content_provider(
  6850. data->size(), "text/plain",
  6851. [&, data](size_t offset, size_t length, DataSink &sink) {
  6852. const size_t DATA_CHUNK_SIZE = 4;
  6853. const auto &d = *data;
  6854. std::this_thread::sleep_for(std::chrono::seconds(1));
  6855. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  6856. return true;
  6857. },
  6858. [data](bool success) {
  6859. EXPECT_FALSE(success);
  6860. delete data;
  6861. });
  6862. });
  6863. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  6864. auto i = new size_t(0);
  6865. res.set_content_provider(
  6866. "text/plain",
  6867. [i](size_t, DataSink &sink) {
  6868. if (*i < 5) {
  6869. std::this_thread::sleep_for(std::chrono::seconds(1));
  6870. sink.write("abcd", 4);
  6871. (*i)++;
  6872. } else {
  6873. sink.done();
  6874. }
  6875. return true;
  6876. },
  6877. [i](bool success) {
  6878. EXPECT_FALSE(success);
  6879. delete i;
  6880. });
  6881. });
  6882. svr.Get("/chunked", [&](const Request &, Response &res) {
  6883. auto i = new size_t(0);
  6884. res.set_chunked_content_provider(
  6885. "text/plain",
  6886. [i](size_t, DataSink &sink) {
  6887. if (*i < 5) {
  6888. std::this_thread::sleep_for(std::chrono::seconds(1));
  6889. sink.os << "abcd";
  6890. (*i)++;
  6891. } else {
  6892. sink.done();
  6893. }
  6894. return true;
  6895. },
  6896. [i](bool success) {
  6897. EXPECT_FALSE(success);
  6898. delete i;
  6899. });
  6900. });
  6901. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6902. auto se = detail::scope_exit([&] {
  6903. svr.stop();
  6904. listen_thread.join();
  6905. ASSERT_FALSE(svr.is_running());
  6906. });
  6907. svr.wait_until_ready();
  6908. const time_t timeout = 2000;
  6909. const time_t threshold = 200;
  6910. Client cli("localhost", PORT);
  6911. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  6912. {
  6913. auto start = std::chrono::steady_clock::now();
  6914. auto res = cli.Get("/stream");
  6915. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  6916. std::chrono::steady_clock::now() - start)
  6917. .count();
  6918. ASSERT_FALSE(res);
  6919. EXPECT_EQ(Error::Read, res.error());
  6920. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold);
  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. }
  6932. {
  6933. auto start = std::chrono::steady_clock::now();
  6934. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  6935. EXPECT_EQ("abcd", string(data, data_length));
  6936. return true;
  6937. });
  6938. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  6939. std::chrono::steady_clock::now() - start)
  6940. .count();
  6941. ASSERT_FALSE(res);
  6942. EXPECT_EQ(Error::Read, res.error());
  6943. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold);
  6944. }
  6945. }
  6946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6947. TEST(MaxTimeoutTest, ContentStreamSSL) {
  6948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6949. svr.Get("/stream", [&](const Request &, Response &res) {
  6950. auto data = new std::string("01234567890123456789");
  6951. res.set_content_provider(
  6952. data->size(), "text/plain",
  6953. [&, data](size_t offset, size_t length, DataSink &sink) {
  6954. const size_t DATA_CHUNK_SIZE = 4;
  6955. const auto &d = *data;
  6956. std::this_thread::sleep_for(std::chrono::seconds(1));
  6957. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  6958. return true;
  6959. },
  6960. [data](bool success) {
  6961. EXPECT_FALSE(success);
  6962. delete data;
  6963. });
  6964. });
  6965. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  6966. auto i = new size_t(0);
  6967. res.set_content_provider(
  6968. "text/plain",
  6969. [i](size_t, DataSink &sink) {
  6970. if (*i < 5) {
  6971. std::this_thread::sleep_for(std::chrono::seconds(1));
  6972. sink.write("abcd", 4);
  6973. (*i)++;
  6974. } else {
  6975. sink.done();
  6976. }
  6977. return true;
  6978. },
  6979. [i](bool success) {
  6980. EXPECT_FALSE(success);
  6981. delete i;
  6982. });
  6983. });
  6984. svr.Get("/chunked", [&](const Request &, Response &res) {
  6985. auto i = new size_t(0);
  6986. res.set_chunked_content_provider(
  6987. "text/plain",
  6988. [i](size_t, DataSink &sink) {
  6989. if (*i < 5) {
  6990. std::this_thread::sleep_for(std::chrono::seconds(1));
  6991. sink.os << "abcd";
  6992. (*i)++;
  6993. } else {
  6994. sink.done();
  6995. }
  6996. return true;
  6997. },
  6998. [i](bool success) {
  6999. EXPECT_FALSE(success);
  7000. delete i;
  7001. });
  7002. });
  7003. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7004. auto se = detail::scope_exit([&] {
  7005. svr.stop();
  7006. listen_thread.join();
  7007. ASSERT_FALSE(svr.is_running());
  7008. });
  7009. svr.wait_until_ready();
  7010. const time_t timeout = 2000;
  7011. const time_t threshold = 1000; // SSL_shutdown is slow...
  7012. SSLClient cli("localhost", PORT);
  7013. cli.enable_server_certificate_verification(false);
  7014. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7015. {
  7016. auto start = std::chrono::steady_clock::now();
  7017. auto res = cli.Get("/stream");
  7018. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7019. std::chrono::steady_clock::now() - start)
  7020. .count();
  7021. ASSERT_FALSE(res);
  7022. EXPECT_EQ(Error::Read, res.error());
  7023. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold);
  7024. }
  7025. {
  7026. auto start = std::chrono::steady_clock::now();
  7027. auto res = cli.Get("/stream_without_length");
  7028. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7029. std::chrono::steady_clock::now() - start)
  7030. .count();
  7031. ASSERT_FALSE(res);
  7032. EXPECT_EQ(Error::Read, res.error());
  7033. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold);
  7034. }
  7035. {
  7036. auto start = std::chrono::steady_clock::now();
  7037. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  7038. EXPECT_EQ("abcd", string(data, data_length));
  7039. return true;
  7040. });
  7041. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7042. std::chrono::steady_clock::now() - start)
  7043. .count();
  7044. ASSERT_FALSE(res);
  7045. EXPECT_EQ(Error::Read, res.error());
  7046. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold);
  7047. }
  7048. }
  7049. #endif