From 4f3975522b3d2fa8c5f0febaf9c91fd3a94aaf13 Mon Sep 17 00:00:00 2001 From: tanwirahmad Date: Wed, 4 May 2022 18:32:09 +0300 Subject: [PATCH] Fix #3596 (pass Path to PcapReader) --- scapy/compat.py | 7 +++++++ scapy/utils.py | 27 ++++++++++++++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/scapy/compat.py b/scapy/compat.py index eb55c3d6ba1..fd075e25a03 100644 --- a/scapy/compat.py +++ b/scapy/compat.py @@ -390,6 +390,13 @@ def bytes_base64(x): html_escape = html.escape +if six.PY34: + from pathlib import PurePath + file_path_types = (str, bytes, PurePath) # type: Tuple[Type[Any], ...] +else: + file_path_types = (str, bytes) + + if six.PY2: from StringIO import StringIO diff --git a/scapy/utils.py b/scapy/utils.py index cd0f7a4cb0a..40ce6c8b30c 100644 --- a/scapy/utils.py +++ b/scapy/utils.py @@ -35,8 +35,17 @@ from scapy.config import conf from scapy.consts import DARWIN, OPENBSD, WINDOWS from scapy.data import MTU, DLT_EN10MB -from scapy.compat import orb, plain_str, chb, bytes_base64,\ - base64_bytes, hex_bytes, lambda_tuple_converter, bytes_encode +from scapy.compat import ( + base64_bytes, + bytes_base64, + bytes_encode, + chb, + file_path_types, + hex_bytes, + lambda_tuple_converter, + orb, + plain_str, +) from scapy.error import log_runtime, Scapy_Exception, warning from scapy.pton_ntop import inet_pton @@ -63,6 +72,7 @@ from scapy.packet import Packet from scapy.plist import _PacketIterable, PacketList from scapy.supersocket import SuperSocket + import pathlib _SuperSocket = SuperSocket else: _SuperSocket = object @@ -1142,7 +1152,7 @@ def __new__(cls, name, bases, dct): return newcls def __call__(cls, filename): # type: ignore - # type: (Union[IO[bytes], str]) -> Any + # type: (Union[IO[bytes], str, bytes, pathlib.PurePath]) -> Any """Creates a cls instance, use the `alternative` if that fails. @@ -1171,12 +1181,15 @@ def __call__(cls, filename): # type: ignore raise Scapy_Exception("Not a supported capture file") @staticmethod - def open(fname # type: Union[IO[bytes], str] + def open(fname # type: Union[IO[bytes], str, bytes, pathlib.PurePath] ): # type: (...) -> Tuple[str, _ByteStream, bytes] """Open (if necessary) filename, and read the magic.""" - if isinstance(fname, str): - filename = fname + if isinstance(fname, file_path_types): + if isinstance(fname, (str, bytes)): + filename = plain_str(fname) + else: + filename = fname.name try: fdesc = gzip.open(filename, "rb") # type: _ByteStream magic = fdesc.read(4) @@ -1184,7 +1197,7 @@ def open(fname # type: Union[IO[bytes], str] fdesc = open(filename, "rb") magic = fdesc.read(4) else: - fdesc = fname + fdesc = cast("IO[bytes]", fname) filename = getattr(fdesc, "name", "No name") magic = fdesc.read(4) return filename, fdesc, magic