test.cc 238 KB

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