Skip to content

Commit

Permalink
PEP8 + typing
Browse files Browse the repository at this point in the history
  • Loading branch information
KimiNewt committed Jun 7, 2022
1 parent b9a3902 commit b12cfd1
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 120 deletions.
7 changes: 4 additions & 3 deletions src/pyshark/capture/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
from packaging import version

from pyshark.packet.packet import Packet
from pyshark.tshark.tshark import get_process_path, get_tshark_display_filter_flag, \
tshark_supports_json, TSharkVersionException, get_tshark_version, tshark_supports_duplicate_keys
from pyshark.tshark.tshark_json import packet_from_json_packet
Expand Down Expand Up @@ -36,7 +37,7 @@ class StopCapture(Exception):
pass


class Capture(object):
class Capture:
"""Base class for packet captures."""
DEFAULT_BATCH_SIZE = 2 ** 16
SUMMARIES_BATCH_SIZE = 64
Expand Down Expand Up @@ -99,12 +100,12 @@ def __getitem__(self, item):
def __len__(self):
return len(self._packets)

def next(self):
def next(self) -> Packet:
return self.next_packet()

# Allows for child classes to call next() from super() without 2to3 "fixing"
# the call
def next_packet(self):
def next_packet(self) -> Packet:
if self._current_packet >= len(self._packets):
raise StopIteration()
cur_packet = self._packets[self._current_packet]
Expand Down
3 changes: 2 additions & 1 deletion src/pyshark/capture/file_capture.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os

from pyshark.capture.capture import Capture
from pyshark.packet.packet import Packet


class FileCapture(Capture):
Expand Down Expand Up @@ -50,7 +51,7 @@ def __init__(self, input_file=None, keep_packets=True, display_filter=None, only
self.keep_packets = keep_packets
self._packet_generator = self._packets_from_tshark_sync()

def next(self):
def next(self) -> Packet:
"""Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list.
Expand Down
5 changes: 1 addition & 4 deletions src/pyshark/capture/live_capture.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
import asyncio
import sys
from packaging import version

from pyshark.capture.capture import Capture
Expand Down Expand Up @@ -54,9 +53,7 @@ def __init__(self, interface=None, bpf_filter=None, display_filter=None, only_su
self.interfaces = interface

def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
"""Returns the special tshark parameters to be used according to the configuration of this class."""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
# Read from STDIN
params += ["-i", "-"]
Expand Down
10 changes: 3 additions & 7 deletions src/pyshark/capture/live_ring_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@


class LiveRingCapture(LiveCapture):
"""
Represents a live ringbuffer capture on a network interface.
"""
"""Represents a live ringbuffer capture on a network interface."""

def __init__(self, ring_file_size=1024, num_ring_files=1, ring_file_name='/tmp/pyshark.pcap', interface=None,
bpf_filter=None, display_filter=None, only_summaries=False, decryption_key=None,
Expand Down Expand Up @@ -42,9 +40,7 @@ def __init__(self, ring_file_size=1024, num_ring_files=1, ring_file_name='/tmp/p
self.ring_file_name = ring_file_name

def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveRingCapture, self).get_parameters(packet_count=packet_count)
params += ['-b', 'filesize:' + str(self.ring_file_size), '-b', 'files:' + str(self.num_ring_files), '-w', self.ring_file_name, '-P']
params += ['-b', 'filesize:' + str(self.ring_file_size), '-b', 'files:' + str(self.num_ring_files),
'-w', self.ring_file_name, '-P']
return params
11 changes: 6 additions & 5 deletions src/pyshark/capture/pipe_capture.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from pyshark.capture.capture import Capture
import os

from pyshark.capture.capture import Capture


class PipeCapture(Capture):
def __init__(self, pipe, display_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk', decode_as=None,
disable_protocol=None, tshark_path=None, override_prefs=None, use_json=False, include_raw=False,
eventloop=None, custom_parameters=None, debug=False):
"""
Receives a file-like and reads the packets from there (pcap format).
disable_protocol=None, tshark_path=None, override_prefs=None, use_json=False,
include_raw=False, eventloop=None, custom_parameters=None, debug=False):
"""Receives a file-like and reads the packets from there (pcap format).
:param bpf_filter: BPF filter to use on packets.
:param display_filter: Display (wireshark) filter to use.
Expand Down
4 changes: 1 addition & 3 deletions src/pyshark/capture/remote_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@


class RemoteCapture(LiveCapture):
"""
A capture which is performed on a remote machine which has an rpcapd service running.
"""
"""A capture which is performed on a remote machine which has an rpcapd service running."""

def __init__(self, remote_host, remote_interface, remote_port=2002, bpf_filter=None, only_summaries=False,
decryption_key=None, encryption_type='wpa-pwk', decode_as=None,
Expand Down
63 changes: 27 additions & 36 deletions src/pyshark/packet/fields.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import binascii
import typing

from pyshark.packet.common import Pickleable, SlotsPickleable


class LayerField(SlotsPickleable):
"""
Holds all data about a field of a layer, both its actual value and its name and nice representation.
"""
"""Holds all data about a field of a layer, both its actual value and its name and nice representation."""

# Note: We use this object with slots and not just a dict because
# it's much more memory-efficient (cuts about a third of the memory).
__slots__ = ['name', 'showname', 'raw_value', 'show', 'hide', 'pos', 'size', 'unmaskedvalue']
Expand All @@ -28,10 +28,8 @@ def __init__(self, name=None, showname=None, value=None, show=None, hide=None, p
def __repr__(self):
return '<LayerField %s: %s>' % (self.name, self.get_default_value())

def get_default_value(self):
"""
Gets the best 'value' string this field has.
"""
def get_default_value(self) -> str:
"""Gets the best 'value' string this field has."""
val = self.show
if not val:
val = self.raw_value
Expand All @@ -40,50 +38,47 @@ def get_default_value(self):
return val

@property
def showname_value(self):
"""
For fields which do not contain a normal value, we attempt to take their value from the showname.
"""
def showname_value(self) -> typing.Union[str, None]:
"""The "pretty value" (as displayed by Wireshark) of the field."""
if self.showname and ': ' in self.showname:
return self.showname.split(': ', 1)[1]
return None

@property
def showname_key(self):
def showname_key(self) -> typing.Union[str, None]:
"""The "pretty name" (as displayed by Wireshark) of the field."""
if self.showname and ': ' in self.showname:
return self.showname.split(': ', 1)[0]
return None

@property
def binary_value(self):
"""
Converts this field to binary (assuming it's a binary string)
"""
def binary_value(self) -> bytes:
"""Converts this field to binary (assuming it's a binary string)"""
str_raw_value = str(self.raw_value)
if len(str_raw_value) % 2 == 1:
str_raw_value = '0' + str_raw_value

return binascii.unhexlify(str_raw_value)

@property
def int_value(self):
"""
Returns the int value of this field (assuming it's an integer integer).
"""
def int_value(self) -> int:
"""Returns the int value of this field (assuming it's represented as a decimal integer)."""
return int(self.raw_value)

@property
def hex_value(self):
"""
Returns the int value of this field if it's in base 16 (either as a normal number or in
a "0xFFFF"-style hex value)
def hex_value(self) -> int:
"""Returns the int value of this field if it's in base 16
(either as a normal number or in a "0xFFFF"-style hex value)
"""
return int(self.raw_value, 16)

base16_value = hex_value


class LayerFieldsContainer(str, Pickleable):
"""
An object which contains one or more fields (of the same name).
"""An object which contains one or more fields (of the same name).
When accessing member, such as showname, raw_value, etc. the appropriate member of the main (first) field saved
in this container will be shown.
"""
Expand All @@ -102,23 +97,19 @@ def __dir__(self):
def add_field(self, field):
self.fields.append(field)

@property
def all_fields(self):
"""Returns all fields in a list, the main field followed by the alternate fields."""
return self.fields

@property
def main_field(self):
return self.fields[0]

@property
def alternate_fields(self):
"""
Return the alternate values of this field containers (non-main ones).
"""
"""Return the alternate values of this field containers (non-main ones)."""
return self.fields[1:]

@property
def all_fields(self):
"""
Returns all fields in a list, the main field followed by the alternate fields.
"""
return self.fields

def __getattr__(self, item):
return getattr(self.main_field, item)
Loading

0 comments on commit b12cfd1

Please sign in to comment.