Skip to content

Commit

Permalink
Fix #3596 (pass Path to PcapReader)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanwirahmad authored and gpotter2 committed Jul 26, 2022
1 parent 53c764d commit 4f39755
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
7 changes: 7 additions & 0 deletions scapy/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 20 additions & 7 deletions scapy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -1171,20 +1181,23 @@ 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)
except IOError:
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
Expand Down

0 comments on commit 4f39755

Please sign in to comment.