test.cc 254 KB

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