diff --git a/.coverage b/.coverage new file mode 100644 index 0000000..2770929 Binary files /dev/null and b/.coverage differ diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dd84ea7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..4e1ef42 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,31 @@ +# This workflows will upload a Python Package using Twine when a release is created +# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries + +name: Upload Python Package + +on: + release: + types: [created] + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build and publish + env: + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.github/workflows/python-test.yml b/.github/workflows/python-test.yml new file mode 100644 index 0000000..d76f8fe --- /dev/null +++ b/.github/workflows/python-test.yml @@ -0,0 +1,18 @@ +name: Python test + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Test with pytest + run: | + sudo pip install pytest pytest-cov + sudo -E pytest --doctest-modules --junitxml=junit/test-results.xml --cov=com --cov-report=xml --cov-report=html diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..b2b8866 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "python.testing.pytestArgs": [ + "test" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true +} \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2d26031 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team by raising an issue on GitHub. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..dd4b587 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,16 @@ +# Contributing + +When contributing to this repository, please first discuss the change you wish to make via issue +here on GitHub. + +Please note we have a code of conduct, please follow it in all your interactions with the project. + +## Pull Request Process +** All PRs must merge into the dev branch, and not into master**. The dev branch is the only one that can merge into master directly. + +1. Ensure any install or build dependencies are removed before the end of the layer when doing a + build. +2. Make sure all corresponding test cases pass. +3. Update the README.md with details of changes to the interface, this includes new environment + variables, exposed ports, useful file locations and container parameters. +4. Version number will be increased only when merging dev into master, so that a version update may carry multiple PRs from various developers. The versioning scheme we use is [SemVer](http://semver.org/). diff --git a/README.md b/README.md index 25162f4..0101415 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ # pythonping -PythonPing is simple way to ping in Python. With it, you can send ICMP Probes to remote devices like you would do from the terminal. PythonPing is modular, so that you can run it in a script as a standalone function, or integrate its components in a fully-fledged application. +PythonPing is simple way to ping in Python. With it, you can send ICMP Probes to remote devices like +you would do from the terminal. PythonPing is modular, so that you can run it in a script as a +standalone function, or integrate its components in a fully-fledged application. ## Basic Usage -The simplest usage of PythonPing is in a script. You can use the `ping` function to ping a target. If you want to see the output immediately, emulating what happens on the terminal, use the `verbose` flag as below. +The simplest usage of PythonPing is in a script. You can use the `ping` function to ping a target. +If you want to see the output immediately, emulating what happens on the terminal, use the +`verbose` flag as below. + ```python from pythonping import ping - ping('127.0.0.1', verbose=True) ``` This will yeld the following result. @@ -16,17 +20,142 @@ Reply from 127.0.0.1, 9 bytes in 0.14ms Reply from 127.0.0.1, 9 bytes in 0.12ms Reply from 127.0.0.1, 9 bytes in 0.12ms ``` -Regardless of the verbose mode, the `ping` function will always return a `ResponseList` object. This is a special iterable object, containing a list of `Response` items. In each response, you can find the packet received and some meta information, like the time it took to receive the response and any error message. + +Regardless of the verbose mode, the `ping` function will always return a `ResponseList` object. +This is a special iterable object, containing a list of `Response` items. In each response, you can +find the packet received and some meta information, like the time it took to receive the response +and any error message. + You can also tune your ping by using some of its additional parameters: * `size` is an integer that allows you to specify the size of the ICMP payload you desire -* `timeout` is the number of seconds you wish to wait for a response, before assuming the target is unreachable +* `timeout` is the number of seconds you wish to wait for a response, before assuming the target +is unreachable * `payload` allows you to use a specific payload (bytes) * `count` specify allows you to define how many ICMP packets to send -* `sweep_start` and `sweep_end` allows you to perform a ping sweep, starting from payload size defined in `sweep_start` and growing up to size defined in `sweep_end`. Here, we repeat the payload you provided to match the desired size, or we generate a random one if no payload was provided. Note that if you defined `size`, these two fields will be ignored +* `interval` the time to wait between pings, in seconds +* `sweep_start` and `sweep_end` allows you to perform a ping sweep, starting from payload size +defined in `sweep_start` and growing up to size defined in `sweep_end`. Here, we repeat the payload +you provided to match the desired size, or we generate a random one if no payload was provided. +Note that if you defined `size`, these two fields will be ignored * `df` is a flag that, if set to True, will enable the *Don't Fragment* flag in the IP header * `verbose` enables the verbose mode, printing output to a stream (see `out`) -* `out` is the target stream of verbose mode. If you enable the verbose mode and do not provide `out`, verbose output will be send to the `sys.stdout` stream. You may want to use a file here, for example. +* `out` is the target stream of verbose mode. If you enable the verbose mode and do not provide +`out`, verbose output will be send to the `sys.stdout` stream. You may want to use a file here. +* `match` is a flag that, if set to True, will enable payload matching between a ping request +and reply (default behaviour follows that of Windows which counts a successful reply by a +matched packet identifier only; Linux behaviour counts a non equivalent payload with a matched +packet identifier in reply as fail, such as when pinging 8.8.8.8 with 1000 bytes and the reply +is truncated to only the first 74 of request payload with a matching packet identifier) + +## FAQ +### Do I need privileged mode or root? +Yes, you need to be root to use pythonping. + +### Why do I need to be root to use pythonping? +All operating systems allow programs to create TCP or UDP sockets without requiring particular +permissions. However, ping runs in ICMP (which is neither TCP or UDP). This means we have to create +raw IP packets, and sniff the traffic on the network card. +**Operating systems are designed to require root for such operations**. This is because having +unrestricted access to the NIC can expose the user to risks if the application running has bad +intentions. This is not the case with pythonping of course, but nonetheless we need this capability +to create custom IP packets. Unfortunately, there is simply no other way to create ICMP packets. ## Advanced Usage -If you wish to extend PythonPing, or integrate it in your application, we recommend to use the classes that are part of Python Ping instead of the `ping` function. -`executor.Communicator` handles the communication with the target device, it takes care of sending ICMP requests and processing responses. It ultimately produces the `executor.ResponseList` object. The `Communicator` needs to know a target and which payloads to send to the remote device. For that, we have several classes in the `payload_provider` module. You may want to create your own provider by extending `payload_provider.PayloadProvider`. If you are interested in that, you should check the documentation of both `executor` and `payload_provider` module. +If you wish to extend PythonPing, or integrate it in your application, we recommend to use the +classes that are part of Python Ping instead of the `ping` function. `executor.Communicator` +handles the communication with the target device, it takes care of sending ICMP requests and +processing responses (note that for it to be thread safe you must then handle making a unique +seed ID for each thread instance, see ping.__init\__ for an example of this). It ultimately +produces the `executor.ResponseList` object. The `Communicator` needs to know a target and +which payloads to send to the remote device. For that, we have several classes in the +`payload_provider` module. You may want to create your own provider by extending +`payload_provider.PayloadProvider`. If you are interested in that, you should check the +documentation of both `executor` and `payload_provider` module. + +## Code Structure + +### Top Level Directory Layout +Our project directory structure contains all src files in the pythonping folder, test cases in another folder, and helping documentation in on the top level directory. + +``` +. +├── pythonping # Source files +├── test # Automated Testcases for the package +├── CODE_OF_CONDUCT # An md file containing code of conduct +├── CONTRIBUTING # Contributing Guidlins +├── LICENSE # MIT License +├── README.md # An md file +└── setup.py # Instalation +``` + +A UML Diagram of the code structure is below: + +![ER1](https://raw.githubusercontent.com/alessandromaggio/pythonping/master/docs/UML-Diagram.png) + +As per the uml diagram above five distinct classes outside of init exist in this package: Executor, Icmp, Payload Provider, and Utils. Each of them rely on attributes which have been listed as sub-classes for brevities sake. An overview of each class is as follows. + +### Utils +Simply generates random text. See function random_text. + +### Network +Opens a socket to send and recive data. See functions send, recv, and del. + +### Payload Provider +Generates ICMP Payloads with no Headers. It's functionaly a interface. It has three +functions init, iter, and next, which are all implmented by subclasses List, Repeat, and Sweep which store payloads in diffrent lists. + +### ICMP +Generates the ICMP heaser through subclass ICMPType, and various helper functions. + +### Executor +Has various subclasses including Message, Response, Success, and Communicator used for sending icmp packets and collecting data. + +### Init +Uses network, executor, payload_provider and utils.random_text to construct and send ICMP packets to ping a network. + +## Tests +A test package exists under the folder test, and contains a serise of unit tests. Before commiting changes make sure to run the test bench and make sure all corrisponding cases pass. For new functionality new test cases must be added and documented. + +To run testcases we can simply use the ```unitest discover``` utility by running the following command: + +``` +python -m unittest discover +``` + +To run the test cases in a specific file FILE we must run the following command: + +``` +python -m unittest discover -s -p FILE +``` + +Another option is to run the following from the top level directory: + +``` +pytest test +``` + +To test for coverage simply run: + +``` +coverage run -m pytest test +``` + +## Contributing +Before contributing read through the contribution guidlines found the CONTRIBUTING file. + +### Code Style +A few key points when contributing to this repo are as follows: +1. Use tabs over spaces. +2. Format doc strings as such: + ``` + DESCRIPTION + + :param X: DESCRIPTION + :type X: Type + :param Y: DESCRIPTION + :type Y: Type + ``` + Please add doc strings to all functions added. +3. Do not add spaces between docstring and first function line. +4. Do not go over 200 characters per line. +5. When closing multiline items under brackets('()', '[]', ... etc) put the closing bracket on it's own line. \ No newline at end of file diff --git a/docs/UML-Diagram.png b/docs/UML-Diagram.png new file mode 100644 index 0000000..6766f5f Binary files /dev/null and b/docs/UML-Diagram.png differ diff --git a/pythonping/__init__.py b/pythonping/__init__.py index 3e9abe5..2b3c29e 100644 --- a/pythonping/__init__.py +++ b/pythonping/__init__.py @@ -1,28 +1,39 @@ import sys +from random import randint from . import network, executor, payload_provider from .utils import random_text +# this needs to be available across all thread usages and will hold ints +SEED_IDs = [] + + def ping(target, timeout=2, count=4, size=1, + interval=0, payload=None, sweep_start=None, sweep_end=None, df=False, verbose=False, - out=sys.stdout): + out=sys.stdout, + match=False, + source=None, + out_format='legacy'): """Pings a remote host and handles the responses :param target: The remote hostname or IP address to ping :type target: str - :param timeout: How long before considering each non-arrived reply permanently lost - :type timeout: int + :param timeout: Time in seconds before considering each non-arrived reply permanently lost. + :type timeout: Union[int, float] :param count: How many times to attempt the ping :type count: int :param size: Size of the entire packet to send :type size: int + :param interval: Interval to wait between pings + :type interval: int :param payload: Payload content, leave None if size is set to use random text :type payload: Union[str, bytes] :param sweep_start: If size is not set, initial size in a sweep of sizes @@ -35,20 +46,43 @@ def ping(target, :type verbose: bool :param out: Stream to which redirect the verbose output :type out: stream + :param match: Do payload matching between request and reply (default behaviour follows that of Windows which is + by packet identifier only, Linux behaviour counts a non equivalent payload in reply as fail, such as when pinging + 8.8.8.8 with 1000 bytes and reply is truncated to only the first 74 of request payload with packet identifiers + the same in request and reply) + :type match: bool + :param repr_format: How to __repr__ the response. Allowed: legacy, None + :type repr_format: str :return: List with the result of each ping :rtype: executor.ResponseList""" provider = payload_provider.Repeat(b'', 0) - if size and size > 0: - if not payload: - payload = random_text(size) - provider = payload_provider.Repeat(payload, count) - elif sweep_start and sweep_end and sweep_end >= sweep_start: + if sweep_start and sweep_end and sweep_end >= sweep_start: if not payload: payload = random_text(sweep_start) provider = payload_provider.Sweep(payload, sweep_start, sweep_end) + elif size and size > 0: + if not payload: + payload = random_text(size) + provider = payload_provider.Repeat(payload, count) options = () if df: options = network.Socket.DONT_FRAGMENT - comm = executor.Communicator(target, provider, timeout, socket_options=options, verbose=verbose, output=out) - comm.run() + + # Fix to allow for pythonping multithreaded usage; + # no need to protect this loop as no one will ever surpass 0xFFFF amount of threads + while True: + # seed_id needs to be less than or equal to 65535 (as original code was seed_id = getpid() & 0xFFFF) + seed_id = randint(0x1, 0xFFFF) + if seed_id not in SEED_IDs: + SEED_IDs.append(seed_id) + break + + + comm = executor.Communicator(target, provider, timeout, interval, socket_options=options, verbose=verbose, output=out, + seed_id=seed_id, source=source, repr_format=out_format) + + comm.run(match_payloads=match) + + SEED_IDs.remove(seed_id) + return comm.responses diff --git a/pythonping/executor.py b/pythonping/executor.py index 6c9b9de..085c6b1 100644 --- a/pythonping/executor.py +++ b/pythonping/executor.py @@ -2,6 +2,7 @@ import os import sys +import time from . import icmp from . import network @@ -51,6 +52,9 @@ def send(self, source_socket): :type source_socket: network.Socket""" source_socket.send(self.packet.packet) + def __repr__(self): + return repr(self.packet) + def represent_seconds_in_ms(seconds): """Converts seconds into human-readable milliseconds with 2 digits decimal precision @@ -64,15 +68,21 @@ def represent_seconds_in_ms(seconds): class Response: """Represents a response to an ICMP message, with metadata like timing""" - def __init__(self, message, time_elapsed): + def __init__(self, message, time_elapsed, source_request=None, repr_format=None): """Creates a representation of ICMP message received in response :param message: The message received :type message: Union[None, Message] :param time_elapsed: Time elapsed since the original request was sent, in seconds - :type time_elapsed: float""" + :type time_elapsed: float + :param source_request: ICMP packet represeting the request that originated this response + :type source_request: ICMP + :param repr_format: How to __repr__ the response. Allowed: legacy, None + :type repr_format: str""" self.message = message self.time_elapsed = time_elapsed + self.source_request = source_request + self.repr_format = repr_format @property def success(self): @@ -82,35 +92,34 @@ def success(self): def error_message(self): if self.message is None: return 'No response' - else: - if self.message.packet.message_type == 0 and self.message.packet.message_code == 0: - # Echo Reply, response OK - no error - return None - elif self.message.packet.message_type == 3: - # Destination unreachable, returning more details based on message code - unreachable_messages = [ - 'Network Unreachable', - 'Host Unreachable', - 'Protocol Unreachable', - 'Port Unreachable', - 'Fragmentation Required', - 'Source Route Failed', - 'Network Unknown', - 'Host Unknown', - 'Source Host Isolated', - 'Communication with Destination Network is Administratively Prohibited', - 'Communication with Destination Host is Administratively Prohibited', - 'Network Unreachable for ToS', - 'Host Unreachable for ToS', - 'Communication Administratively Prohibited', - 'Host Precedence Violation', - 'Precedence Cutoff in Effect' - ] - try: - return unreachable_messages[self.message.packet.message_code] - except IndexError: - # Should never generate IndexError, this serves as additional protection - return 'Unreachable' + if self.message.packet.message_type == 0 and self.message.packet.message_code == 0: + # Echo Reply, response OK - no error + return None + if self.message.packet.message_type == 3: + # Destination unreachable, returning more details based on message code + unreachable_messages = [ + 'Network Unreachable', + 'Host Unreachable', + 'Protocol Unreachable', + 'Port Unreachable', + 'Fragmentation Required', + 'Source Route Failed', + 'Network Unknown', + 'Host Unknown', + 'Source Host Isolated', + 'Communication with Destination Network is Administratively Prohibited', + 'Communication with Destination Host is Administratively Prohibited', + 'Network Unreachable for ToS', + 'Host Unreachable for ToS', + 'Communication Administratively Prohibited', + 'Host Precedence Violation', + 'Precedence Cutoff in Effect' + ] + try: + return unreachable_messages[self.message.packet.message_code] + except IndexError: + # Should never generate IndexError, this serves as additional protection + return 'Unreachable' # Error was not identified return 'Network Error' @@ -118,17 +127,29 @@ def error_message(self): def time_elapsed_ms(self): return represent_seconds_in_ms(self.time_elapsed) - def __repr__(self): + def legacy_repr(self): if self.message is None: return 'Request timed out' - elif self.success: + if self.success: return 'Reply from {0}, {1} bytes in {2}ms'.format(self.message.source, - len(self.message.packet.packet), + len(self.message.packet.raw), self.time_elapsed_ms) - else: - # Not successful, but with some code (e.g. destination unreachable) - return '{0} from {1} in {2}ms'.format(self.error_message, self.message.source, self.time_elapsed_ms) + # Not successful, but with some code (e.g. destination unreachable) + return '{0} from {1} in {2}ms'.format(self.error_message, self.message.source, self.time_elapsed_ms) + def __repr__(self): + if self.repr_format == 'legacy': + return self.legacy_repr() + if self.message is None: + return 'Timed out' + if self.success: + return 'status=OK\tfrom={0}\tms={1}\t\tbytes\tsnt={2}\trcv={3}'.format( + self.message.source, + self.time_elapsed_ms, + len(self.source_request.raw)+20, + len(self.message.packet.raw) + ) + return 'status=ERR\tfrom={1}\terror="{0}"'.format(self.message.source, self.error_message) class ResponseList: """Represents a series of ICMP responses""" @@ -148,6 +169,8 @@ def __init__(self, initial_set=[], verbose=False, output=sys.stdout): self.rtt_avg = 0 self.rtt_min = 0 self.rtt_max = 0 + self.stats_packets_sent = 0 + self.stats_packets_returned = 0 for response in initial_set: self.append(response) @@ -169,6 +192,10 @@ def success(self, option=SuccessOn.One): result = False not in success_list return result + @property + def packet_loss(self): + return self.packets_lost + @property def rtt_min_ms(self): return represent_seconds_in_ms(self.rtt_min) @@ -183,9 +210,13 @@ def rtt_avg_ms(self): def clear(self): self._responses = [] + self.stats_packets_sent = 0 + self.stats_packets_returned = 0 + def append(self, value): self._responses.append(value) + self.stats_packets_sent += 1 if len(self) == 1: self.rtt_avg = value.time_elapsed self.rtt_max = value.time_elapsed @@ -197,9 +228,28 @@ def append(self, value): self.rtt_max = value.time_elapsed if value.time_elapsed < self.rtt_min: self.rtt_min = value.time_elapsed + if value.success: + self.stats_packets_returned += 1 + if self.verbose: print(value, file=self.output) + @property + def stats_packets_lost(self): + return self.stats_packets_sent - self.stats_packets_returned + + @property + def stats_success_ratio(self): + return self.stats_packets_returned / self.stats_packets_sent + + @property + def stats_lost_ratio(self): + return 1 - self.stats_success_ratio + + @property + def packets_lost(self): + return self.stats_lost_ratio + def __len__(self): return len(self._responses) @@ -218,8 +268,8 @@ def __iter__(self): class Communicator: """Instance actually communicating over the network, sending messages and handling responses""" - def __init__(self, target, payload_provider, timeout, socket_options=(), seed_id=None, - verbose=False, output=sys.stdout): + def __init__(self, target, payload_provider, timeout, interval, socket_options=(), seed_id=None, + verbose=False, output=sys.stdout, source=None, repr_format=None): """Creates an instance that can handle communication with the target device :param target: IP or hostname of the remote device @@ -227,7 +277,9 @@ def __init__(self, target, payload_provider, timeout, socket_options=(), seed_id :param payload_provider: An iterable list of payloads to send :type payload_provider: PayloadProvider :param timeout: Timeout that will apply to all ping messages, in seconds - :type timeout: int + :type timeout: Union[int, float] + :param interval: Interval to wait between pings, in seconds + :type interval: int :param socket_options: Options to specify for the network.Socket :type socket_options: tuple :param seed_id: The first ICMP packet ID to use @@ -235,12 +287,17 @@ def __init__(self, target, payload_provider, timeout, socket_options=(), seed_id :param verbose: Flag to enable verbose mode, defaults to False :type verbose: bool :param output: File where to write verbose output, defaults to stdout - :type output: file""" - self.socket = network.Socket(target, 'icmp', source=None, options=socket_options) + :type output: file + :param repr_format: How to __repr__ the response. Allowed: legacy, None + :type repr_format: str""" + self.socket = network.Socket(target, 'icmp', options=socket_options, source=source) self.provider = payload_provider self.timeout = timeout + self.interval = interval self.responses = ResponseList(verbose=verbose, output=output) self.seed_id = seed_id + self.repr_format = repr_format + # note that to make Communicator instances thread safe, the seed ID must be unique per thread if self.seed_id is None: self.seed_id = os.getpid() & 0xFFFF @@ -252,22 +309,27 @@ def send_ping(self, packet_id, sequence_number, payload): :param packet_id: The ID to use for the packet :type packet_id: int - :param sequence_number: The seuqnce number to use for the packet + :param sequence_number: The sequence number to use for the packet :type sequence_number: int :param payload: The payload of the ICMP message - :type payload: bytes""" - self.socket.send(icmp.ICMP( + :type payload: Union[str, bytes] + :rtype: ICMP""" + i = icmp.ICMP( icmp.Types.EchoRequest, payload=payload, - identifier=packet_id, sequence_number=sequence_number).packet) + identifier=packet_id, sequence_number=sequence_number) + self.socket.send(i.packet) + return i - def listen_for(self, packet_id, timeout): + def listen_for(self, packet_id, timeout, payload_pattern=None, source_request=None): """Listens for a packet of a given id for a given timeout :param packet_id: The ID of the packet to listen for, the same for request and response :type packet_id: int :param timeout: How long to listen for the specified packet, in seconds :type timeout: float + :param payload_pattern: Payload reply pattern to match to request, if set to None, match by ID only + :type payload_pattern: Union[None, bytes] :return: The response to the request with the specified packet_id :rtype: Response""" time_left = timeout @@ -278,10 +340,19 @@ def listen_for(self, packet_id, timeout): # If we actually received something if raw_packet != b'': response.unpack(raw_packet) + # Ensure we have not unpacked the packet we sent (RHEL will also listen to outgoing packets) if response.id == packet_id and response.message_type != icmp.Types.EchoRequest.type_id: - return Response(Message('', response, source_socket[0]), timeout-time_left) - return Response(None, timeout) + if payload_pattern is None: + # To allow Windows-like behaviour (no payload inspection, but only match packet identifiers), + # simply allow for it to be an always true in the legacy usage case + payload_matched = True + else: + payload_matched = (payload_pattern == response.payload) + + if payload_matched: + return Response(Message('', response, source_socket[0]), timeout - time_left, source_request, repr_format=self.repr_format) + return Response(None, timeout, source_request, repr_format=self.repr_format) @staticmethod def increase_seq(sequence_number): @@ -296,12 +367,22 @@ def increase_seq(sequence_number): sequence_number = 1 return sequence_number - def run(self): - """Performs all the pings and stores the responses""" + def run(self, match_payloads=False): + """Performs all the pings and stores the responses + + :param match_payloads: optional to set to True to make sure requests and replies have equivalent payloads + :type match_payloads: bool""" self.responses.clear() identifier = self.seed_id seq = 1 for payload in self.provider: - self.send_ping(identifier, seq, payload) - self.responses.append(self.listen_for(identifier, self.timeout)) + icmp_out = self.send_ping(identifier, seq, payload) + if not match_payloads: + self.responses.append(self.listen_for(identifier, self.timeout, None, icmp_out)) + else: + self.responses.append(self.listen_for(identifier, self.timeout, icmp_out.payload, icmp_out)) + seq = self.increase_seq(seq) + + if self.interval: + time.sleep(self.interval) diff --git a/pythonping/icmp.py b/pythonping/icmp.py index a5e3aeb..2814a99 100644 --- a/pythonping/icmp.py +++ b/pythonping/icmp.py @@ -1,9 +1,5 @@ import os -import socket import struct -import select -import time - def checksum(data): """Creates the ICMP checksum as in RFC 1071 @@ -61,64 +57,64 @@ class DestinationUnreachable(ICMPType): class SourceQuench(ICMPType): type_id = 4 SOURCE_QUENCH = (type_id, 0,) - + class Redirect(ICMPType): type_id = 5 FOR_NETWORK = (type_id, 0,) FOR_HOST = (type_id, 1,) FOR_TOS_AND_NETWORK = (type_id, 2,) FOR_TOS_AND_HOST = (type_id, 3,) - + class EchoRequest(ICMPType): type_id = 8 ECHO_REQUEST = (type_id, 0,) - + class RouterAdvertisement(ICMPType): type_id = 9 ROUTER_ADVERTISEMENT = (type_id, 0,) - + class RouterSolicitation(ICMPType): type_id = 10 ROUTER_SOLICITATION = (type_id, 0) # Aliases ROUTER_DISCOVERY = ROUTER_SOLICITATION ROUTER_SELECTION = ROUTER_SOLICITATION - + class TimeExceeded(ICMPType): type_id = 11 TTL_EXPIRED_IN_TRANSIT = (type_id, 0) FRAGMENT_REASSEMBLY_TIME_EXCEEDED = (type_id, 1) - + class BadIPHeader(ICMPType): type_id = 12 POINTER_INDICATES_ERROR = (type_id, 0) MISSING_REQUIRED_OPTION = (type_id, 1) BAD_LENGTH = (type_id, 2) - + class Timestamp(ICMPType): type_id = 13 TIMESTAMP = (type_id, 0) - + class TimestampReply(ICMPType): type_id = 14 TIMESTAMP_REPLY = (type_id, 0) - + class InformationRequest(ICMPType): type_id = 15 INFORMATION_REQUEST = (type_id, 0) - + class InformationReply(ICMPType): type_id = 16 INFORMATION_REPLY = (type_id, 0) - + class AddressMaskRequest(ICMPType): type_id = 17 ADDRESS_MASK_REQUEST = (type_id, 0) - + class AddressMaskReply(ICMPType): type_id = 18 ADDRESS_MASK_REPLY = (type_id, 0) - + class Traceroute(ICMPType): type_id = 30 INFORMATION_REQUEST = (type_id, 30) @@ -154,11 +150,15 @@ def __init__(self, message_type=Types.EchoReply, payload=None, identifier=None, self.id = identifier & 0xFFFF # Prevent identifiers bigger than 16 bits self.sequence_number = sequence_number self.received_checksum = None + self.raw = None @property def packet(self): """The raw packet with header, ready to be sent from a socket""" - return self._header(check=self.expected_checksum) + self.payload + p = self._header(check=self.expected_checksum) + self.payload + if self.raw is None: + self.raw = p + return p def _header(self, check=0): """The raw ICMP header @@ -168,13 +168,16 @@ def _header(self, check=0): :return: The packed header :rtype: bytes""" # TODO implement sequence number - return struct.pack("bbHHh", + return struct.pack("BBHHH", self.message_type, self.message_code, check, self.id, self.sequence_number) + def __repr__(self): + return ' '.join('{:02x}'.format(b) for b in self.raw) + @property def is_valid(self): """True if the received checksum is valid, otherwise False""" @@ -209,9 +212,10 @@ def unpack(self, raw): :param raw: The raw packet, including payload :type raw: bytes""" + self.raw = raw self.message_type, \ self.message_code, \ self.received_checksum, \ self.id, \ - sequence = struct.unpack("bbHHh", raw[20:28]) + self.sequence_number = struct.unpack("BBHHH", raw[20:28]) self.payload = raw[28:] diff --git a/pythonping/network.py b/pythonping/network.py index 4c06ca9..080b9b0 100644 --- a/pythonping/network.py +++ b/pythonping/network.py @@ -4,10 +4,11 @@ class Socket: - BUFFER_SIZE = 1024 DONT_FRAGMENT = (socket.SOL_IP, 10, 1) # Option value for raw socket + PROTO_LOOKUP = {"icmp": socket.IPPROTO_ICMP, "tcp": socket.IPPROTO_TCP, "udp": socket.IPPROTO_UDP, + "ip": socket.IPPROTO_IP, "raw": socket.IPPROTO_RAW} - def __init__(self, destination, protocol, source=None, options=()): + def __init__(self, destination, protocol, options=(), buffer_size=2048, source=None): """Creates a network socket to exchange messages :param destination: Destination IP address @@ -17,20 +18,42 @@ def __init__(self, destination, protocol, source=None, options=()): :param options: Options to set on the socket :type options: tuple :param source: Source IP to use - implemented in future releases - :type source: Union[None, str]""" - self.destination = socket.gethostbyname(destination) - self.protocol = socket.getprotobyname(protocol) - if source is not None: - raise NotImplementedError('PythonPing currently does not support specification of source IP') + :type source: Union[None, str] + :param buffer_size: Size in bytes of the listening buffer for incoming packets (replies) + :type buffer_size: int""" + try: + self.destination = socket.gethostbyname(destination) + except socket.gaierror as e: + raise RuntimeError('Cannot resolve address "' + destination + '", try verify your DNS or host file') + + self.protocol = Socket.getprotobyname(protocol) + self.buffer_size = buffer_size self.socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.protocol) + self.source = source if options: self.socket.setsockopt(*options) + # Implementing a version of socket.getprotobyname for this library since built-in is not thread safe + # for python 3.5, 3.6, and 3.7: + # https://bugs.python.org/issue30482 + # This bug was causing failures as it would occasionally return a 0 (incorrect) instead of a 1 (correct) + # for the 'icmp' string, causing a OSError for "Protocol not supported" in multi-threaded usage: + # https://github.com/alessandromaggio/pythonping/issues/40 + @staticmethod + def getprotobyname(name): + try: + return Socket.PROTO_LOOKUP[name.lower()] + except KeyError: + raise KeyError("'" + str(name) + "' is not in the list of supported proto types: " + + str(list(Socket.PROTO_LOOKUP.keys()))) + def send(self, packet): """Sends a raw packet on the stream :param packet: The raw packet to send :type packet: bytes""" + if self.source: + self.socket.bind((self.source, 0)) self.socket.sendto(packet, (self.destination, 0)) def receive(self, timeout=2): @@ -49,13 +72,13 @@ def receive(self, timeout=2): if not data_ready[0]: # Timeout return b'', '', time_left - packet, source = self.socket.recvfrom(self.BUFFER_SIZE) + packet, source = self.socket.recvfrom(self.buffer_size) return packet, source, time_left def __del__(self): try: - if self.socket: + if hasattr(self, "socket") and self.socket: self.socket.close() except AttributeError: raise AttributeError("Attribute error because of failed socket init. Make sure you have the root privilege." - " This error may also be caused from DNS resolution problems.") \ No newline at end of file + " This error may also be caused from DNS resolution problems.") diff --git a/pythonping/payload_provider.py b/pythonping/payload_provider.py index c456295..25fea77 100644 --- a/pythonping/payload_provider.py +++ b/pythonping/payload_provider.py @@ -38,7 +38,7 @@ def __init__(self, pattern, count): """Creates a provider of many identical payloads :param pattern: The existing payload - :type pattern: bytes + :type pattern: Union[str, bytes] :param count: How many payloads to generate :type count: int""" self.pattern = pattern @@ -61,7 +61,7 @@ def __init__(self, pattern, start_size, end_size): """Creates a provider of payloads of increasing size :param pattern: The existing payload, may be cut or replicated to fit the size - :type pattern: bytes + :type pattern: Union[str, bytes] :param start_size: The first payload size to start with, included :type start_size: int :param end_size: The payload size to end with, included diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e7af550 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pexpect==4.0.8 \ No newline at end of file diff --git a/setup.py b/setup.py index ff66ff7..379ca3f 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,10 @@ from setuptools import setup -with open('README.md', 'r') as file: +with open('README.md', 'r', encoding='utf-8') as file: long_description = file.read() setup(name='pythonping', - version='1.0.8', + version='1.1.4', description='A simple way to ping in Python', url='https://github.com/alessandromaggio/pythonping', author='Alessandro Maggio', diff --git a/test/test_executor.py b/test/test_executor.py index 1fb4364..0b62a5d 100644 --- a/test/test_executor.py +++ b/test/test_executor.py @@ -247,6 +247,65 @@ def test_success_half_success(self): 'Unable to calculate success on all with half responses successful' ) + def test_no_packets_lost(self): + rs = executor.ResponseList([ + SuccessfulResponseMock(None, 1), + SuccessfulResponseMock(None, 1), + SuccessfulResponseMock(None, 1), + SuccessfulResponseMock(None, 1) + ]) + + self.assertEqual(rs.stats_packets_sent, rs.stats_packets_returned, 'unable to correctly count sent and returned packets when all responses successful') + self.assertEqual( + rs.stats_packets_lost, + 0, + "Unable to calculate packet loss correctly when all responses successful" + ) + + def test_all_packets_lost(self): + rs = executor.ResponseList([ + FailingResponseMock(None, 1), + FailingResponseMock(None, 1), + FailingResponseMock(None, 1), + FailingResponseMock(None, 1) + ]) + self.assertEqual(rs.stats_packets_returned, 0, 'unable to correctly count sent and returned packets when all responses failed') + self.assertEqual( + rs.stats_lost_ratio, + 1.0, + "Unable to calculate packet loss correctly when all responses failed" + ) + + def test_some_packets_lost(self): + rs = executor.ResponseList([ + SuccessfulResponseMock(None, 1), + SuccessfulResponseMock(None, 1), + FailingResponseMock(None, 1), + FailingResponseMock(None, 1) + ]) + self.assertEqual(rs.stats_packets_sent, 4, 'unable to correctly count sent packets when some of the responses failed') + self.assertEqual(rs.stats_packets_returned, 2, 'unable to correctly count returned packets when some of the responses failed') + self.assertEqual( + rs.stats_lost_ratio, + 0.5, + "Unable to calculate packet loss correctly when some of the responses failed" + ) + + def test_some_packets_lost_mixed(self): + rs = executor.ResponseList([ + FailingResponseMock(None, 1), + SuccessfulResponseMock(None, 1), + FailingResponseMock(None, 1), + SuccessfulResponseMock(None, 1), + ]) + self.assertEqual(rs.stats_packets_sent, 4, 'unable to correctly count sent packets when when failing responses are mixed with successful responses') + self.assertEqual(rs.stats_packets_returned, 2, 'unable to correctly count returned packets when failing responses are mixed with successful responses') + self.assertEqual( + rs.packet_loss, + 0.5, + "Unable to calculate packet loss correctly when failing responses are mixed with successful responses" + ) + class CommunicatorTestCase(unittest.TestCase): """Tests for Communicator""" diff --git a/test/test_network.py b/test/test_network.py new file mode 100644 index 0000000..144a58a --- /dev/null +++ b/test/test_network.py @@ -0,0 +1,12 @@ +import unittest +from pythonping.network import Socket + +class UtilsTestCase(unittest.TestCase): + """Tests for Socket class""" + + + + def test_raise_explicative_error_on_name_resolution_failure(self): + """Test a runtime error is generated if the name cannot be resolved""" + with self.assertRaises(RuntimeError): + Socket('invalid', 'raw') \ No newline at end of file diff --git a/test/test_payload_provider.py b/test/test_payload_provider.py index 48a20ef..9cbc474 100644 --- a/test/test_payload_provider.py +++ b/test/test_payload_provider.py @@ -1,10 +1,17 @@ import unittest + +from pexpect import ExceptionPexpect from pythonping import payload_provider class PayloadProviderTestCase(unittest.TestCase): """Tests for PayloadProvider class""" + def test_basic(self): + """Verifies that a provider raises error when calling own functions""" + self.assertRaises(NotImplementedError, payload_provider.PayloadProvider) + + def test_list(self): """Verifies that a list provider generates the correct payloads""" payloads = [ diff --git a/test/test_ping.py b/test/test_ping.py index 4799ff5..f3e2413 100644 --- a/test/test_ping.py +++ b/test/test_ping.py @@ -1,4 +1,5 @@ import unittest +import os from pythonping import ping @@ -10,3 +11,12 @@ def test_ping_execution(self): # NOTE, this may be considered an e2e test self.assertEqual(len(ping('10.127.0.1', count=4, size=10)), 4, 'Sent 4 pings to localhost, but not received 4 responses') + + # Github Actions does not support ICMP + if os.getenv("GITHUB_ACTIONS") is None: + self.assertEqual(ping('8.8.8.8', count=4, size=992).success(), True, + 'Sent 4 large pings to google DNS A with payload match off, received all replies') + + self.assertEqual(ping('8.8.8.8', count=4, size=992, match=True).success(), False, + 'Sent 4 large pings to google DNS A with payload match on,' + + 'expected all to fail since they truncate large payloads')