From 123a9597a52bdb20848cb1df366ae972bf07202d Mon Sep 17 00:00:00 2001 From: John-Mark Gurney Date: Tue, 30 Aug 2022 15:22:16 -0700 Subject: [PATCH] properly escape file names when using rglob --- ui/medashare/btv/__init__.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/ui/medashare/btv/__init__.py b/ui/medashare/btv/__init__.py index 6c12f32..c753345 100644 --- a/ui/medashare/btv/__init__.py +++ b/ui/medashare/btv/__init__.py @@ -1,5 +1,6 @@ from . import bencode +import fnmatch from functools import reduce from hashlib import sha1 import importlib.resources @@ -15,6 +16,11 @@ _encoding = 'utf-8' __all__ = [ 'validate', 'validate_file' ] +_escapes = '*?[]' + +def glob_escape(s): + return ''.join(x if x not in _escapes else '[%s]' % x for x in s) + class Storage: '''A class to help read pieces of a torrent. ''' @@ -123,7 +129,9 @@ def validate_file(fname): with open(fname, 'rb') as fp: torrent = bencode.bdecode(fp.read()) - dirname = list(fname.parent.rglob(torrent['info']['name'].decode(_encoding)))[0] + finddname = glob_escape(torrent['info']['name'].decode(_encoding)) + + dirname = list(fname.parent.rglob(finddname))[0] tordir = dirname.parent @@ -244,6 +252,12 @@ class _TestCases(unittest.TestCase): self.assertFalse(bad) + def test_escapeglob(self): + for i in [ + '*', '?', '[', '[]', '*?[][[*?', + ]: + self.assertTrue(fnmatch.fnmatch(i, glob_escape(i))) + def test_verification(self): # Testing for "missing" files # piece size 2 (aka 4 bytes)