├── README.md └── switchyard-master ├── .gitignore ├── .travis.yml ├── COPYING ├── Dockerfile ├── README.rst ├── docs ├── .buildinfo ├── .nojekyll ├── _images │ ├── applayer.png │ ├── applayer_detail.png │ ├── packet.png │ └── srpyarch.png ├── _modules │ ├── index.html │ └── switchyard │ │ ├── lib │ │ ├── address.html │ │ ├── debugging.html │ │ ├── interface.html │ │ ├── logging.html │ │ ├── packet │ │ │ ├── arp.html │ │ │ ├── common.html │ │ │ ├── ethernet.html │ │ │ ├── icmp.html │ │ │ ├── icmpv6.html │ │ │ ├── ipv4.html │ │ │ ├── ipv6.html │ │ │ ├── packet.html │ │ │ ├── tcp.html │ │ │ └── udp.html │ │ ├── socket │ │ │ └── socketemu.html │ │ └── testing.html │ │ └── llnetbase.html ├── _sources │ ├── advanced_api.rst.txt │ ├── index.rst.txt │ ├── installation.rst.txt │ ├── intro.rst.txt │ ├── live_execution.rst.txt │ ├── reference.rst.txt │ ├── release_notes.rst.txt │ ├── test_execution.rst.txt │ ├── test_scenario_creation.rst.txt │ ├── thanks.rst.txt │ └── writing_a_program.rst.txt ├── _static │ ├── ajax-loader.gif │ ├── basic.css │ ├── comment-bright.png │ ├── comment-close.png │ ├── comment.png │ ├── contents.png │ ├── doctools.js │ ├── down-pressed.png │ ├── down.png │ ├── file.png │ ├── jquery-3.1.0.js │ ├── jquery.js │ ├── minus.png │ ├── navigation.png │ ├── plus.png │ ├── pygments.css │ ├── searchtools.js │ ├── sphinxdoc.css │ ├── underscore-1.3.1.js │ ├── underscore.js │ ├── up-pressed.png │ ├── up.png │ └── websupport.js ├── advanced_api.html ├── genindex.html ├── index.html ├── installation.html ├── intro.html ├── live_execution.html ├── objects.inv ├── py-modindex.html ├── reference.html ├── release_notes.html ├── search.html ├── searchindex.js ├── test_execution.html ├── test_scenario_creation.html ├── thanks.html └── writing_a_program.html ├── documentation ├── .gitignore ├── Makefile ├── README.md ├── advanced_api.rst ├── applayer.graffle ├── applayer.pdf ├── applayer.png ├── applayer_detail.graffle ├── applayer_detail.pdf ├── applayer_detail.png ├── code │ ├── baaadhub.py │ ├── badscenario1.py │ ├── clientsocketapp.py │ ├── emptytestscenario.py │ ├── enterdebugger.py │ ├── failhub1.py │ ├── failhub2.py │ ├── failhub3.py │ ├── failhub4.py │ ├── failhub5.py │ ├── failhub6.py │ ├── failhub7.py │ ├── failhub8.py │ ├── fullhub.py │ ├── fullhub2.py │ ├── hubtests.py │ ├── inout1.py │ ├── inout2.py │ ├── inoutloop.py │ ├── inouttest.py │ ├── intfex.py │ ├── newheader.py │ ├── pkt_construction.py │ ├── protostackpattern.py │ ├── run_example.py │ ├── testscenario1.py │ ├── testscenario2.py │ └── udpappheader.py ├── conf.py ├── index.rst ├── installation.rst ├── intro.rst ├── live_execution.rst ├── packet.graffle ├── packet.pdf ├── packet.png ├── reference.rst ├── release_notes.rst ├── srpyarch.graffle ├── srpyarch.pdf ├── srpyarch.png ├── test_execution.rst ├── test_scenario_creation.rst ├── thanks.rst └── writing_a_program.rst ├── examples ├── README.rst ├── clientapp_udpstackex.py ├── exercises │ ├── README.rst │ ├── applayer │ │ ├── applayer.rst │ │ ├── blastee.py │ │ ├── blaster.py │ │ ├── middlebox.py │ │ ├── msgboardapp.rst │ │ ├── msgboarddiag.graffle │ │ ├── msgboarddiag.pdf │ │ ├── msgboarddiag.png │ │ ├── msgboardmiddlebox.rst │ │ ├── msgboardstack.rst │ │ └── start_mininet.py │ ├── firewall │ │ ├── firewall.py │ │ ├── firewall.rst │ │ ├── firewall_rules.txt │ │ ├── firewall_topology.graffle │ │ │ ├── data.plist │ │ │ ├── image1.pdf │ │ │ └── image2.pdf │ │ ├── firewall_topology.png │ │ ├── firewalltests.py │ │ ├── impairmenttest.py │ │ ├── ratelimittest.py │ │ ├── start_mininet.py │ │ └── www │ │ │ └── start_webserver.sh │ ├── learning_switch │ │ ├── learning_switch.rst │ │ ├── ls_diagram.graffle │ │ │ ├── data.plist │ │ │ └── image1.pdf │ │ ├── ls_diagram.png │ │ ├── ls_flowchart.graffle │ │ ├── ls_flowchart.png │ │ ├── myswitch.py │ │ └── switchtopo.py │ └── router │ │ ├── dvroute │ │ ├── dv_topology.graffle │ │ │ ├── data.plist │ │ │ └── image1.pdf │ │ ├── dv_topology.pdf │ │ ├── dv_topology.png │ │ ├── dvroute.rst │ │ └── rippkt1.png │ │ ├── forwarding_table.txt │ │ ├── lsroute │ │ ├── ls_topology.graffle │ │ │ ├── data.plist │ │ │ └── image1.pdf │ │ ├── ls_topology.pdf │ │ ├── ls_topology.png │ │ └── lsroute.rst │ │ ├── myrouter.py │ │ ├── router1.rst │ │ ├── router1_pcap1.png │ │ ├── router1_pcap2.png │ │ ├── router2.rst │ │ ├── router2_pcap.png │ │ ├── router2_topology.graffle │ │ ├── data.plist │ │ └── image1.pdf │ │ ├── router2_topology.png │ │ ├── router3.rst │ │ ├── router4.rst │ │ ├── router_topology.graffle │ │ ├── data.plist │ │ └── image1.pdf │ │ ├── router_topology.png │ │ └── start_mininet.py ├── hubtests.py ├── myhub.py ├── readpkt.py ├── sendpkt.py ├── server_udpstackex.py ├── sniff.py ├── start_mininet.py ├── sydump.py ├── udpstack.py └── udpstack_tests.py ├── forwarding_table.txt ├── lab_1 ├── 181860077佘帅杰_lab_1.docx ├── hubtests.py ├── lab_1.pcapng ├── myhub.py └── start_mininet.py ├── lab_2 ├── 181860077佘帅杰_lab_2.pdf ├── myswitch.py ├── myswitch_lru.py ├── myswitch_to.py ├── myswitch_traffic.py ├── mytests.py ├── mytests_lru.py ├── mytests_to.py ├── mytests_traffic.py ├── start_mininet.py ├── switchtests_lru.srpy ├── switchtests_to.srpy ├── switchtests_traffic.srpy └── switchtopo.py ├── lab_3 ├── 181860077佘帅杰_lab_3.pdf ├── myrouter.py ├── routertests1.srpy ├── routertests1full.srpy └── start_mininet.py ├── lab_4 ├── 181860077佘帅杰_lab_4.pdf ├── forwarding_table.txt ├── myrouter.py ├── routertests2.srpy ├── routertests2_template.py └── start_mininet.py ├── lab_5 ├── 181860077佘帅杰_lab_5.pdf ├── forwarding_table.txt ├── myrouter.py ├── routertests3.srpy ├── routertests3_template.py └── start_mininet.py ├── lab_6 ├── 181860077佘帅杰_lab_6.pdf ├── blastee.py ├── blastee_params.txt ├── blaster.py ├── blaster_params.txt ├── middlebox.py ├── middlebox_params.txt └── start_mininet.py ├── lab_7 ├── 181860077佘帅杰_lab_7.pdf ├── firewall.py ├── firewall_rules.txt ├── firewalltests.py ├── start_mininet.py └── www │ ├── 1.html │ ├── bigfile │ └── start_webserver.sh ├── requirements.txt ├── runtests.sh ├── setup.py ├── switchyard ├── __init__.py ├── hostfirewall.py ├── importcode.py ├── lib │ ├── .gitignore │ ├── __init__.py │ ├── address │ │ └── __init__.py │ ├── debugging.py │ ├── exceptions.py │ ├── interface.py │ ├── logging.py │ ├── openflow │ │ ├── __init__.py │ │ ├── ofswitch.py │ │ ├── openflow10.py │ │ └── openflow13.py │ ├── packet │ │ ├── .gitignore │ │ ├── __init__.py │ │ ├── arp.py │ │ ├── common.py │ │ ├── ethernet.py │ │ ├── icmp.py │ │ ├── icmpv6.py │ │ ├── ipv4.py │ │ ├── ipv6.py │ │ ├── null.py │ │ ├── packet.py │ │ ├── ripv2.py │ │ ├── tcp.py │ │ ├── udp.py │ │ └── util.py │ ├── socket │ │ ├── __init__.py │ │ └── socketemu.py │ ├── testing.py │ ├── topo │ │ ├── __init__.py │ │ ├── topobuild.py │ │ └── util.py │ └── userlib.py ├── llnetbase.py ├── llnetreal.py ├── llnettest.py ├── outputfmt.py ├── pcapffi.py ├── sim │ ├── __init__.py │ ├── cli.py │ ├── linkem.py │ ├── monitor.py │ └── nodeexec.py ├── swyard.py ├── syinit.py └── textcolor.py └── tests ├── test_addr.py ├── test_arp.py ├── test_color.py ├── test_ethernet.py ├── test_hostfirewall.py ├── test_icmp.py ├── test_importer.py ├── test_ipv4.py ├── test_ipv6.py ├── test_llnetdev.py ├── test_matcher.py ├── test_null.py ├── test_ofswitch.py ├── test_ofswitch_ext.py ├── test_openflow.py ├── test_packet.py ├── test_pcapffi.py ├── test_ripv2.py ├── test_rwimg.py ├── test_scenarios.py ├── test_socket.py ├── test_srpy.py ├── test_tcp.py ├── test_topo.py └── test_udp.py /README.md: -------------------------------------------------------------------------------- 1 | # NJU_ComputerNetWork 2 | 3 | ## 注意:本仓库只是为了学弟学妹可以参考相关实现,禁止任何形式的转载,更禁止任何形式的转载后收费(尤其是CSDN)!!!!!!!!!! 4 | 5 | **南京大学 计算机科学与技术系 2020 计算机网络实验** 6 | 7 | **switchyard-master 目录下是整个实验的全套代码** 8 | 9 | **实验包括实现Hub,switch,router以及配置router防火墙规则在内的实践** 10 | 11 | -------------------------------------------------------------------------------- /switchyard-master/.gitignore: -------------------------------------------------------------------------------- 1 | xenv 2 | *.pyc 3 | __pycache__ 4 | *.pcap 5 | .coverage 6 | htmlcov 7 | sandbox 8 | updatepypi.sh 9 | switchyard.egg-info 10 | build 11 | dist 12 | # venv 13 | syenv/ 14 | # vscode 15 | .vscode/ -------------------------------------------------------------------------------- /switchyard-master/.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | before_install: 5 | - sudo apt-get -qq update 6 | - sudo apt-get install -y libffi-dev libpcap-dev 7 | install: 8 | - python setup.py install 9 | script: 10 | - python tests/test_addr.py 11 | - python tests/test_ipv6.py 12 | - python tests/test_ripv2.py 13 | - python tests/test_addr.py 14 | - python tests/test_llnetdev.py 15 | - python tests/test_arp.py 16 | - python tests/test_matcher.py 17 | - python tests/test_scenarios.py 18 | - python tests/test_null.py 19 | - python tests/test_socket.py 20 | - python tests/test_ethernet.py 21 | - python tests/test_srpy.py 22 | - python tests/test_hostfirewall.py 23 | - python tests/test_tcp.py 24 | - python tests/test_icmp.py 25 | # temporarily remove uncritical apis 26 | # - python tests/test_topo.py 27 | - python tests/test_importer.py 28 | - python tests/test_packet.py 29 | - python tests/test_udp.py 30 | - python tests/test_ipv4.py 31 | -------------------------------------------------------------------------------- /switchyard-master/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | RUN apt-get -y update && apt-get -y install build-essential git-core vim make gcc clang libcurl3-gnutls-dev curl wget libxml2-dev libcurl4-gnutls-dev libssh2-1-dev libz-dev libssl-dev libreadline-dev automake libtool bison manpages-dev manpages-posix-dev net-tools man-db libffi-dev libpcap-dev python3-dev python3-pip python3-venv 3 | RUN pip3 install switchyard 4 | WORKDIR swyard 5 | COPY ./examples examples 6 | CMD bash 7 | -------------------------------------------------------------------------------- /switchyard-master/docs/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: a27858e10200e905f5b2ddc831d239d9 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /switchyard-master/docs/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/.nojekyll -------------------------------------------------------------------------------- /switchyard-master/docs/_images/applayer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_images/applayer.png -------------------------------------------------------------------------------- /switchyard-master/docs/_images/applayer_detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_images/applayer_detail.png -------------------------------------------------------------------------------- /switchyard-master/docs/_images/packet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_images/packet.png -------------------------------------------------------------------------------- /switchyard-master/docs/_images/srpyarch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_images/srpyarch.png -------------------------------------------------------------------------------- /switchyard-master/docs/_sources/index.rst.txt: -------------------------------------------------------------------------------- 1 | .. Switchyard documentation master file, created by 2 | sphinx-quickstart on Wed Dec 3 22:08:55 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Switchyard documentation 7 | ======================== 8 | 9 | .. Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | intro 15 | writing_a_program 16 | test_execution 17 | test_scenario_creation 18 | live_execution 19 | advanced_api 20 | installation 21 | reference 22 | release_notes 23 | thanks 24 | 25 | 26 | Indices and tables 27 | ================== 28 | 29 | * :ref:`genindex` 30 | * :ref:`modindex` 31 | * :ref:`search` 32 | 33 | I gratefully acknowledge support from the NSF. The materials here are based upon work supported by the National Science Foundation under grant CNS-1054985 ("CAREER: Expanding the functionality of Internet routers"). 34 | 35 | Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author and do not necessarily reflect the views of the National Science Foundation. 36 | 37 | .. todolist:: 38 | 39 | License 40 | ======= 41 | 42 | The Switchyard software is distributed under terms of the GNU General Public License, version 3. 43 | 44 | Switchyard's documentation is distributed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License: http://creativecommons.org/licenses/by-nc-sa/4.0/. 45 | -------------------------------------------------------------------------------- /switchyard-master/docs/_sources/installation.rst.txt: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | Installing Switchyard 4 | ********************* 5 | 6 | Switchyard has been tested and developed on the following operating systems: 7 | 8 | * macOS 10.10 and later 9 | * Ubuntu LTS releases from 14.04 and later 10 | * Fedora 21 11 | 12 | Note that these are all Unix-based systems. Switchyard may be enhanced in the future to support Windows-based systems. Ubuntu (current LTS) and macOS receive the most testing of Unix-based operating systems. 13 | 14 | --- 15 | 16 | The steps for getting Switchyard up and running are as follows: 17 | 18 | 0. Install Python 3.4 or later, if you don't already have it. 19 | 1. Install any necessary libraries for your operating system. 20 | 2. Create an Python "virtual environment" for installing Python modules (or install the modules to your system Python) 21 | 3. Install Switchyard. 22 | 23 | For step 0, you're on your own. Go to https://www.python.org/downloads/, or install packages via your OS'es package system, or use homebrew if you're on a Mac. Have fun. 24 | 25 | The specific libraries necessary for different OSes (step 1) are described below, but steps 2 and 3 are the same for all operating systems and are covered next. 26 | 27 | The recommended install procedure is to create a Python virtual environment for installing Switchyard and other required Python modules. One way to create a new virtual environment is to execute the following at a command line (in the folder in which you want to create the virtual environment):: 28 | 29 | $ python3 -m venv syenv 30 | 31 | This command will create a new virtual environment called ``syenv``. Once that's done, you can "activate" that environment and install Switchyard as follows:: 32 | 33 | $ source ./syenv/bin/activate 34 | (syenv)$ python3 -m pip install switchyard 35 | 36 | That's it. Once you've done that, the ``swyard`` program should be on your ``PATH`` (you can check by typing ``which swyard``). If you no longer want to use the Python virtual environment you've created, you can just type ``deactivate``. 37 | 38 | Operating system-specific instructions 39 | ====================================== 40 | 41 | MacOS X 42 | ------- 43 | 44 | The easiest way to get Switchyard running in macOS is to install homebrew. You can use ``brew`` to install Python 3. You should also ``brew`` to install the ``libpcap`` package. That should be all that is necessary. 45 | 46 | Ubuntu 47 | ------ 48 | 49 | For Ubuntu systems, you'll need to use ``apt-get`` or something similar to install the following packages:: 50 | 51 | libffi-dev libpcap-dev python3-dev python3-pip python3-venv 52 | 53 | Fedora/RedHat 54 | ------------- 55 | 56 | For Fedora and RedHat-based systems, you'll need to use ``yum`` or something similar to install a similar set of packages as with Ubuntu (but with the right name changes for the way packages are identified on Fedora):: 57 | 58 | libffi-devel libpcap-devel python3-devel python3-pip python3-virtualenv 59 | 60 | -------------------------------------------------------------------------------- /switchyard-master/docs/_sources/release_notes.rst.txt: -------------------------------------------------------------------------------- 1 | Release notes 2 | ************* 3 | 4 | The headings below refer either to branches on Switchyard's github repo (v1 and v2) or tags (2017.01.1). 5 | 6 | 2017.01.4 7 | --------- 8 | More bugfixes. 9 | 10 | 2017.01.3 11 | --------- 12 | Minor bugfixes. 13 | 14 | 2017.01.2 15 | --------- 16 | 17 | Add the capability to pass arguments to a Switchyard program via ``-g`` option to ``swyard``. 18 | Switchyard parses and assembles ``*args`` and ``**kwargs`` to pass into the user code, being careful to only pass them if the code can accept them. 19 | 20 | 2017.01.1 21 | --------- 22 | 23 | Major revision; expansion of types of exercises supported (notably application-layer programs via socket emulation) and several non-backward compatible API changes. Simplified user code import (single import of switchyard.lib.userlib). Installation via standard setuptools, so easily installed via easy_install or pip. Major revision of documentation. Lots of new tests were written, bringing test coverage above 90%. Expansion of exercises is still in progress. 24 | 25 | Some key API changes to be aware of: 26 | 27 | * the Scenario class is renamed TestScenario. The PacketOutputEvent previously allowed Openflow 1.0-like wildcard strings to specify wildcards for matching packets; these strings are no longer supported. To specify wildcards, a tuple of (classname,attribute) must be used; refer to :ref:`test-scenario-creation`, above. 28 | * ``recv_packet`` *always* returns a timestamp now; it returns a 3-tuple (named tuple) of timestamp, input_port and packet. 29 | * The only import required by user code is switchyard.lib.userlib, although individual imports are still fine (just more verbose). 30 | * Instead of invoking ``srpy.py``, a ``swyard`` program is installed during the new install process. ``swyard`` has a few command-line changes compared with ``srpy.py``. In particular, the ``-s`` option has gone away; to run Switchyard with a test, just use the ``-t`` option with the scenario file as the argument. 31 | 32 | 33 | v2 34 | -- 35 | 36 | Complete rewrite of v1. Moved to Python 3 and created packet parsing libraries, new libpcap interface library (pcapffi). Redesigned test scenario modules and an expanded of publicly available exercises. Used at Colgate twice and University of Wisconsin-Madison twice. Available on the ``v2`` branch on github. 37 | 38 | v1 39 | -- 40 | 41 | First version, which used the POX packet parsing libraries and had a variety of limitations. Implemented in Python 2 and used at Colgate once. Available on the ``v1`` branch on github, but very much obsolete. 42 | -------------------------------------------------------------------------------- /switchyard-master/docs/_sources/thanks.rst.txt: -------------------------------------------------------------------------------- 1 | Acknowledgments and thanks 2 | ************************** 3 | 4 | Once again, I gratefully acknowledge support from the NSF. The materials here are based upon work supported by the National Science Foundation under grant CNS-1054985 ("CAREER: Expanding the functionality of Internet routers"). 5 | Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author and do not necessarily reflect the views of the National Science Foundation. 6 | 7 | Thanks to Colgate COSC465 students from Spring 2014 and Spring 2015 for being guinea pigs and giving feedback for the very first versions of Switchyard. Thanks also to Prof. Paul Barford and CS640 students at the University of Wisconsin for using and providing feedback on Switchyard. 8 | 9 | Thanks to those students who have contributed fixes and made suggestions for improvements. In particular: 10 | 11 | * Thanks to Saul Shanabrook for several specific suggestions and bug reports that have led to improvements in Switchyard. 12 | * Thanks to Xuyi Ruan for identifying and suggesting a fix to bugs on one of the documentation diagrams. 13 | * Thanks to Sean Wilson for a bug fix on an infinitely recursive property setter. Oops, but this dumb bug motivated me to significantly improve test coverage, so there's that. 14 | * Thanks to Leon Yang for identifying a problem with kwarg processing for ICMP. 15 | 16 | -------------------------------------------------------------------------------- /switchyard-master/docs/_static/ajax-loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/ajax-loader.gif -------------------------------------------------------------------------------- /switchyard-master/docs/_static/comment-bright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/comment-bright.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/comment-close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/comment-close.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/comment.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/contents.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/contents.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/down-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/down-pressed.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/down.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/file.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/minus.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/navigation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/navigation.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/plus.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/up-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/up-pressed.png -------------------------------------------------------------------------------- /switchyard-master/docs/_static/up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/_static/up.png -------------------------------------------------------------------------------- /switchyard-master/docs/objects.inv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/docs/objects.inv -------------------------------------------------------------------------------- /switchyard-master/documentation/.gitignore: -------------------------------------------------------------------------------- 1 | _build 2 | x.txt 3 | -------------------------------------------------------------------------------- /switchyard-master/documentation/README.md: -------------------------------------------------------------------------------- 1 | # Switchyard documentation 2 | 3 | This directory contains Sphinx source (http://sphinx-doc.org/) for Switchyard documentation. 4 | 5 | ## License 6 | 7 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 8 | http://creativecommons.org/licenses/by-nc-sa/4.0/ 9 | -------------------------------------------------------------------------------- /switchyard-master/documentation/applayer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/applayer.pdf -------------------------------------------------------------------------------- /switchyard-master/documentation/applayer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/applayer.png -------------------------------------------------------------------------------- /switchyard-master/documentation/applayer_detail.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/applayer_detail.pdf -------------------------------------------------------------------------------- /switchyard-master/documentation/applayer_detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/applayer_detail.png -------------------------------------------------------------------------------- /switchyard-master/documentation/code/baaadhub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Ethernet hub in Switchyard. 5 | ''' 6 | from switchyard.lib.userlib import * 7 | 8 | def main(net): 9 | my_interfaces = net.interfaces() 10 | mymacs = [intf.ethaddr for intf in my_interfaces] 11 | 12 | while True: 13 | try: 14 | timestamp,dev,packet = net.recv_packet() 15 | except NoPackets: 16 | continue 17 | except Shutdown: 18 | return 19 | 20 | log_debug ("In {} received packet {} on {}".format(net.name, packet, dev)) 21 | eth = packet.get_header(Ethernet) 22 | if eth is None: 23 | log_info("Received a non-Ethernet packet?!") 24 | continue 25 | 26 | if eth.dst in mymacs: 27 | log_info ("Received a packet intended for me") 28 | else: 29 | for intf in my_interfaces: 30 | if dev != intf.name: 31 | log_info ("Flooding packet {} to {}".format(packet, intf.name)) 32 | eth.src = 'ba:ba:ba:ba:ba:ba' # sheep! 33 | net.send_packet(intf, packet) 34 | net.shutdown() 35 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/badscenario1.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | scenario = TestScenario("test example") 4 | scenario.add_interface('eth0', 'ab:cd:ef:ab:cd:ef', '1.2.3.4', '255.255.0.0', iftype=InterfaceType.Wired) 5 | 6 | scenario.expect(PacketInputEvent('eth1', Packet()), "A packet knocks on the door...") 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/clientsocketapp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # import socket 4 | import switchyard.lib.socket as socket 5 | 6 | HOST = '127.0.0.1' 7 | PORT = 10000 8 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 9 | s.settimeout(2.0) 10 | 11 | print("Sending message to server at {},{}".format(HOST,PORT)) 12 | s.sendto(b'Hello, stack', (HOST,PORT)) 13 | try: 14 | data,addr = s.recvfrom(1024) 15 | print('Client socket application received message from {}: {}'.format(repr(addr),data.decode('utf8'))) 16 | except: 17 | print("Timeout") 18 | 19 | s.close() 20 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/emptytestscenario.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | scenario = TestScenario("test example") 4 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/enterdebugger.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | while True: 5 | try: 6 | timestamp,input_port,packet = net.recv_packet(timeout=1.0) 7 | except NoPackets: 8 | # timeout waiting for packet arrival 9 | continue 10 | except Shutdown: 11 | # we're done; bail out of while loop 12 | break 13 | 14 | # invoke the debugger every time we get here, which 15 | # should be for every packet we receive! 16 | debugger() 17 | hdrs = packet.num_headers() 18 | 19 | # before exiting our main function, 20 | # perform shutdown on network 21 | net.shutdown() 22 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub1.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | net.send_packet('eth0', packet) 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub2.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | # net.send_packet('eth0', packet) 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub3.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | timestamp,input_port,packet = net.recv_packet() 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub4.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | net.clone_packet() 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub5.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | # add some informational text about ports on this device 5 | log_info ("Hub is starting up with these ports:") 6 | for port in net.ports(): 7 | log_info ("{}: ethernet address {}".format(port.name, port.ethaddr)) 8 | 9 | while True: 10 | try: 11 | timestamp,input_port,packet = net.recv_packet() 12 | except Shutdown: 13 | # got shutdown signal 14 | break 15 | except NoPackets: 16 | # try again... 17 | continue 18 | 19 | # send the packet out all ports *except* 20 | # the one on which it arrived 21 | for port in net.ports(): 22 | if port.name != input_port: 23 | net.send_packet(port.name, packet) 24 | 25 | # shutdown is the last thing we should do 26 | net.shutdown() 27 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub6.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | packet[Ethernet].src = "ba:aa:aa:ba:aa:aa" 7 | net.send_packet("eth0", packet) 8 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub7.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | packet[-1] = TCP() 7 | net.send_packet("eth0", packet) 8 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/failhub8.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | del packet[-1] 7 | net.send_packet("eth0", packet) 8 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/fullhub.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | # add some informational text about ports on this device 5 | log_info ("Hub is starting up with these ports:") 6 | for port in net.ports(): 7 | log_info ("{}: ethernet address {}".format(port.name, port.ethaddr)) 8 | 9 | while True: 10 | try: 11 | timestamp,input_port,packet = net.recv_packet() 12 | except Shutdown: 13 | # got shutdown signal 14 | break 15 | except NoPackets: 16 | # try again... 17 | continue 18 | 19 | # send the packet out all ports *except* 20 | # the one on which it arrived 21 | for port in net.ports(): 22 | if port.name != input_port: 23 | net.send_packet(port.name, packet) 24 | 25 | # shutdown is the last thing we should do 26 | net.shutdown() 27 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/fullhub2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Ethernet hub in Switchyard. 5 | ''' 6 | from switchyard.lib.userlib import * 7 | 8 | def main(net): 9 | my_interfaces = net.interfaces() 10 | mymacs = [intf.ethaddr for intf in my_interfaces] 11 | 12 | while True: 13 | try: 14 | timestamp,dev,packet = net.recv_packet() 15 | except NoPackets: 16 | continue 17 | except Shutdown: 18 | return 19 | 20 | log_debug ("In {} received packet {} on {}".format(net.name, packet, dev)) 21 | eth = packet.get_header(Ethernet) 22 | if eth is None: 23 | log_info("Received a non-Ethernet packet?!") 24 | continue 25 | 26 | if eth.dst in mymacs: 27 | log_info ("Received a packet intended for me") 28 | else: 29 | for intf in my_interfaces: 30 | if dev != intf.name: 31 | log_info ("Flooding packet {} to {}".format(packet, intf.name)) 32 | net.send_packet(intf, packet) 33 | net.shutdown() 34 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/hubtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.userlib import * 4 | 5 | def mk_pkt(hwsrc, hwdst, ipsrc, ipdst, reply=False): 6 | ether = Ethernet(src=hwsrc, dst=hwdst, ethertype=EtherType.IP) 7 | ippkt = IPv4(src=ipsrc, dst=ipdst, protocol=IPProtocol.ICMP, ttl=32) 8 | icmppkt = ICMP() 9 | if reply: 10 | icmppkt.icmptype = ICMPType.EchoReply 11 | else: 12 | icmppkt.icmptype = ICMPType.EchoRequest 13 | return ether + ippkt + icmppkt 14 | 15 | def hub_tests(): 16 | s = TestScenario("hub tests") 17 | s.add_interface('eth0', '10:00:00:00:00:01') 18 | s.add_interface('eth1', '10:00:00:00:00:02') 19 | s.add_interface('eth2', '10:00:00:00:00:03') 20 | 21 | # test case 1: a frame with broadcast destination should get sent out 22 | # all ports except ingress 23 | testpkt = mk_pkt("30:00:00:00:00:02", "ff:ff:ff:ff:ff:ff", "172.16.42.2", "255.255.255.255") 24 | s.expect(PacketInputEvent("eth1", testpkt), "An Ethernet frame with a broadcast destination address should arrive on eth1") 25 | s.expect(PacketOutputEvent("eth0", testpkt, "eth2", testpkt), "The Ethernet frame with a broadcast destination address should be forwarded out ports eth0 and eth2") 26 | 27 | # test case 2: a frame with any unicast address except one assigned to hub 28 | # interface should be sent out all ports except ingress 29 | reqpkt = mk_pkt("20:00:00:00:00:01", "30:00:00:00:00:02", '192.168.1.100','172.16.42.2') 30 | s.expect(PacketInputEvent("eth0", reqpkt), "An Ethernet frame from 20:00:00:00:00:01 to 30:00:00:00:00:02 should arrive on eth0") 31 | s.expect(PacketOutputEvent("eth1", reqpkt, "eth2", reqpkt), "Ethernet frame destined for 30:00:00:00:00:02 should be flooded out eth1 and eth2") 32 | 33 | resppkt = mk_pkt("30:00:00:00:00:02", "20:00:00:00:00:01", '172.16.42.2', '192.168.1.100', reply=True) 34 | s.expect(PacketInputEvent("eth1", resppkt), "An Ethernet frame from 30:00:00:00:00:02 to 20:00:00:00:00:01 should arrive on eth1") 35 | s.expect(PacketOutputEvent("eth0", resppkt, "eth2", resppkt), "Ethernet frame destined to 20:00:00:00:00:01 should be flooded out eth0 and eth2") 36 | 37 | # test case 3: a frame with dest address of one of the interfaces should 38 | # result in nothing happening 39 | reqpkt = mk_pkt("20:00:00:00:00:01", "10:00:00:00:00:03", '192.168.1.100','172.16.42.2') 40 | s.expect(PacketInputEvent("eth2", reqpkt), "An Ethernet frame should arrive on eth2 with destination address the same as eth2's MAC address") 41 | s.expect(PacketInputTimeoutEvent(1.0), "The hub should not do anything in response to a frame arriving with a destination address referring to the hub itself.") 42 | return s 43 | 44 | scenario = hub_tests() 45 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/inout1.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | timestamp,input_port,packet = net.recv_packet() 5 | print ("Received {} on {}".format(packet, input_port)) 6 | net.send_packet(input_port, packet) 7 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/inout2.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | # below, recvdata is a namedtuple 5 | recvdata = net.recv_packet() 6 | print ("At {}, received {} on {}".format( 7 | recvdata.timestamp, recvdata.packet, recvdata.input_port)) 8 | 9 | # alternatively, the above line could use indexing, although 10 | # readability suffers: 11 | # recvdata[0], recvdata[2], recvdata[1])) 12 | 13 | net.send_packet(recvdata.input_port, recvdata.packet) 14 | 15 | # likewise, the above line could be written using indexing 16 | # but, again, readability suffers: 17 | # net.send_packet(recvdata[1], recvdata[2]) 18 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/inoutloop.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | while True: 5 | try: 6 | timestamp,input_port,packet = net.recv_packet() 7 | except Shutdown: 8 | log_info ("Got shutdown signal; exiting") 9 | break 10 | except NoPackets: 11 | log_info ("No packets were available.") 12 | continue 13 | 14 | # if we get here, we must have received a packet 15 | log_info ("Received {} on {}".format(packet, input_port)) 16 | net.send_packet(input_port, packet) 17 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/inouttest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.userlib import * 4 | 5 | def mk_pkt(hwsrc, hwdst, ipsrc, ipdst, reply=False): 6 | ether = Ethernet(src=hwsrc, dst=hwdst, ethertype=EtherType.IP) 7 | ippkt = IPv4(src=ipsrc, dst=ipdst, protocol=IPProtocol.ICMP, ttl=32) 8 | icmppkt = ICMP() 9 | if reply: 10 | icmppkt.icmptype = ICMPType.EchoReply 11 | else: 12 | icmppkt.icmptype = ICMPType.EchoRequest 13 | return ether + ippkt + icmppkt 14 | 15 | def inouttests(): 16 | s = TestScenario("in/out basic tests") 17 | s.add_interface('eth0', '10:00:00:00:00:01', '172.16.42.1', '255.255.255.252') 18 | s.add_interface('eth1', '10:00:00:00:00:02', '10.10.0.1', '255.255.0.0') 19 | s.add_interface('eth2', '10:00:00:00:00:03', '192.168.1.1', '255.255.255.0') 20 | 21 | # test case 1: a frame with broadcast destination should get sent out 22 | # all ports except ingress 23 | testpkt = mk_pkt("30:00:00:00:00:02", "ff:ff:ff:ff:ff:ff", "172.16.42.2", "255.255.255.255") 24 | s.expect(PacketInputEvent("eth1", testpkt, display=Ethernet), "An Ethernet frame with a broadcast destination address should arrive on eth1") 25 | s.expect(PacketOutputEvent("eth1", testpkt, display=Ethernet), "The Ethernet frame should be forwarded back out eth1.") 26 | return s 27 | 28 | scenario = inouttests() 29 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/intfex.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | def main(net): 4 | for intf in net.interfaces(): 5 | log_info("{} has ethaddr {} and ipaddr {}/{} and is of type {}".format( 6 | intf.name, intf.ethaddr, intf.ipaddr, intf.netmask, intf.iftype.name)) 7 | 8 | # below, recvdata is a namedtuple 9 | recvdata = net.recv_packet() 10 | print ("At {}, received {} on {}".format( 11 | recvdata.timestamp, recvdata.packet, recvdata.input_port)) 12 | 13 | # alternatively, the above line could use indexing, although 14 | # readability suffers: 15 | # recvdata[0], recvdata[2], recvdata[1])) 16 | 17 | net.send_packet(recvdata.input_port, recvdata.packet) 18 | 19 | # likewise, the above line could be written using indexing 20 | # but, again, readability suffers: 21 | # net.send_packet(recvdata[1], recvdata[2]) 22 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/newheader.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | import struct 3 | 4 | class SpanningTreeMessage(PacketHeaderBase): 5 | _PACKFMT = "6sxB" 6 | 7 | def __init__(self, root="00:00:00:00:00:00", **kwargs): 8 | self._root = EthAddr(root) 9 | self._hops_to_root = 0 10 | PacketHeaderBase.__init__(self, **kwargs) 11 | 12 | def to_bytes(self): 13 | raw = struct.pack(self._PACKFMT, self._root.raw, self._hops_to_root) 14 | return raw 15 | 16 | def from_bytes(self, raw): 17 | packsize = struct.calcsize(self._PACKFMT) 18 | if len(raw) < packsize: 19 | raise ValueError("Not enough bytes to unpack SpanningTreeMessage") 20 | xroot,xhops = struct.unpack(self._PACKFMT, raw[:packsize]) 21 | self._root = EthAddr(xroot) 22 | self.hops_to_root = xhops 23 | return raw[packsize:] 24 | 25 | @property 26 | def hops_to_root(self): 27 | return self._hops_to_root 28 | 29 | @hops_to_root.setter 30 | def hops_to_root(self, value): 31 | self._hops_to_root = int(value) 32 | 33 | @property 34 | def root(self): 35 | return self._root 36 | 37 | def __str__(self): 38 | return "{} (root: {}, hops-to-root: {})".format( 39 | self.__class__.__name__, self.root, self.hops_to_root) 40 | 41 | 42 | if __name__ == '__main__': 43 | spm = SpanningTreeMessage("00:11:22:33:44:55", hops_to_root=1) 44 | print(spm) 45 | 46 | Ethernet.add_next_header_class(EtherType.SLOW, SpanningTreeMessage) 47 | pkt = Ethernet(src="11:22:11:22:11:22", 48 | dst="22:33:22:33:22:33", 49 | ethertype=EtherType.SLOW) + spm 50 | print(pkt) 51 | xbytes = pkt.to_bytes() 52 | p = Packet(raw=xbytes) 53 | print(p) 54 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/pkt_construction.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | p = Packet() # construct a packet object 3 | e = Ethernet() # construct Ethernet header 4 | ip = IPv4() # construct IPv4 header 5 | icmp = ICMP() # construct ICMP header 6 | p += e # add eth header to packet 7 | p += ip # add ip header to packet 8 | p += icmp # add icmp header to packet 9 | print (p) 10 | p = Ethernet() + IPv4() + ICMP() 11 | p.num_headers() 12 | len(p) 13 | p.size() 14 | 15 | p[0] 16 | p[0].src 17 | p[0].dst 18 | p[0].dst = "ab:cd:ef:00:11:22" 19 | str(p[0]) 20 | p[0].dst = EthAddr("00:11:22:33:44:55") 21 | str(p[0]) 22 | p[0].ethertype 23 | p[0].ethertype = EtherType.ARP 24 | print (p) 25 | p[0].ethertype = EtherType.IPv4 # set it back to sensible value 26 | 27 | p.has_header(IPv4) 28 | p.get_header_index(IPv4) 29 | str(p[1]) # access by index 30 | str(p[IPv4]) # access by header type 31 | p[IPv4].protocol 32 | p[IPv4].src 33 | p[IPv4].dst 34 | p[IPv4].dst = '149.43.80.13' 35 | 36 | p.has_header(ICMP) 37 | p.get_header_index(ICMP) 38 | p[2] # access by index; notice no conversion to string 39 | p[ICMP] # access by header type 40 | p[ICMP].icmptype 41 | p[ICMP].icmpcode 42 | p[ICMP].icmpdata 43 | icmp.icmpdata.sequence 44 | icmp.icmpdata.identifier 45 | icmp.icmpdata.identifier = 42 46 | icmp.icmpdata.sequence = 13 47 | print (p) 48 | 49 | icmp.icmpdata.data = "hello, world" 50 | print (p) 51 | 52 | p.to_bytes() 53 | 54 | e = Ethernet(src="11:22:33:44:55:66", dst="66:55:44:33:22:11", ethertype=EtherType.IP) 55 | ip = IPv4(src="1.2.3.4", dst="4.3.2.1", protocol=IPProtocol.UDP, ttl=32) 56 | udp = UDP(src=1234, dst=4321) 57 | p = e + ip + udp + b"this is some application payload!" 58 | print(p) 59 | 60 | 61 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/protostackpattern.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | class ProtocolStack(object): 4 | def __init__(self, net): 5 | self._net = net 6 | 7 | def handle_app_data(self, appdata): 8 | # do something to handle application data here, likely 9 | # resulting in an eventual call to self._net.send_packet() 10 | 11 | def handle_network_data(self, netdata): 12 | # do something with network data here, likely resulting 13 | # in an eventual call to ApplicationLayer.send_to_app() 14 | 15 | def main_loop(self): 16 | while True: 17 | appdata = None 18 | try: 19 | appdata = ApplicationLayer.recv_from_app(timeout=0.1) 20 | except NoPackets: 21 | pass 22 | except Shutdown: 23 | break 24 | if appdata is not None: 25 | handle_app_data(net, intf, appdata) 26 | 27 | netdata = None 28 | try: 29 | netdata = net.recv_packet(timeout=0.1) 30 | except NoPackets: 31 | pass 32 | except Shutdown: 33 | break 34 | if netdata is not None: 35 | handle_network_data(netdata) 36 | 37 | 38 | def main(net): 39 | stack = ProtocolStack(net) 40 | stack.main_loop() 41 | net.shutdown() 42 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/run_example.py: -------------------------------------------------------------------------------- 1 | from code import InteractiveConsole 2 | import sys 3 | 4 | console = InteractiveConsole() 5 | for line in sys.stdin: 6 | print(">>> {}".format(line.strip())) 7 | console.push(line.strip()) 8 | 9 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/testscenario1.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | scenario = TestScenario("in/out test scenario example") 4 | 5 | # only one interface on this imaginary device 6 | scenario.add_interface('eth0', 'ab:cd:ef:ab:cd:ef', '1.2.3.4', '255.255.0.0', 7 | iftype=InterfaceType.Wired) 8 | 9 | # construct a packet to be received 10 | p = Ethernet(src="00:11:22:33:44:55", dst="66:55:44:33:22:11") + \ 11 | IPv4(src="1.1.1.1", dst="2.2.2.2", protocol=IPProtocol.UDP) + \ 12 | UDP(src=5555, dst=8888) + b'some payload' 13 | 14 | # expect that the packet is received 15 | scenario.expect(PacketInputEvent('eth0', p), 16 | "A udp packet should arrive on eth0") 17 | 18 | # and expect that the packet is sent right back out 19 | scenario.expect(PacketOutputEvent('eth0', p, exact=True), 20 | "The udp packet should be emitted back out eth0") 21 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/testscenario2.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | 3 | scenario = TestScenario("packet forwarding example") 4 | 5 | # three interfaces on this device 6 | scenario.add_interface('eth0', 'ab:cd:ef:ab:cd:ef', '1.2.3.4', '255.255.0.0') 7 | scenario.add_interface('eth1', '00:11:22:ab:cd:ef', '5.6.7.8', '255.255.0.0') 8 | scenario.add_interface('eth2', 'ab:cd:ef:00:11:22', '9.10.11.12', '255.255.255.0') 9 | 10 | # add a forwarding table file to be written out when the test 11 | # scenario is executed 12 | scenario.add_file('forwarding_table.txt', ''' 13 | # network subnet-mask next-hop port 14 | 2.0.0.0 255.0.0.0 9.10.11.13 eth2 15 | 3.0.0.0 255.255.0.0 5.6.100.200 eth1 16 | ''') 17 | 18 | 19 | # construct a packet to be received 20 | p = Ethernet(src="00:11:22:33:44:55", dst="66:55:44:33:22:11") + \ 21 | IPv4(src="1.1.1.1", dst="2.2.2.2", protocol=IPProtocol.UDP, ttl=61) + \ 22 | UDP(src=5555, dst=8888) + b'some payload' 23 | 24 | # expect that the packet is received 25 | scenario.expect(PacketInputEvent('eth0', p), 26 | "A udp packet destined to 2.2.2.2 arrives on port eth0") 27 | 28 | # and subsequently forwarded out the correct port; employ 29 | # subset (exact=False) matching, along with a check that the 30 | # IPv4 TTL was decremented exactly by 1. 31 | scenario.expect(PacketOutputEvent('eth2', p, exact=False, 32 | predicate='''lambda pkt: pkt.has_header(IPv4) and pkt[IPv4].ttl == 60'''), 33 | "The udp packet destined to 2.2.2.2 should be forwarded out port eth2, with an appropriately decremented TTL.") 34 | -------------------------------------------------------------------------------- /switchyard-master/documentation/code/udpappheader.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | import struct 3 | 4 | class UDPPing(PacketHeaderBase): 5 | _PACKFMT = "!H" 6 | 7 | def __init__(self, seq=0, **kwargs): 8 | self._sequence = int(seq) 9 | PacketHeaderBase.__init__(self, **kwargs) 10 | 11 | def to_bytes(self): 12 | raw = struct.pack(self._PACKFMT, self._sequence) 13 | return raw 14 | 15 | def from_bytes(self, raw): 16 | packsize = struct.calcsize(self._PACKFMT) 17 | if len(raw) < packsize: 18 | raise ValueError("Not enough bytes to unpack UDPPing") 19 | attrs = struct.unpack(self._PACKFMT, raw[:packsize]) 20 | self.sequence = attrs[0] 21 | return raw[packsize:] 22 | 23 | @property 24 | def sequence(self): 25 | return self._sequence 26 | 27 | @sequence.setter 28 | def sequence(self, value): 29 | self._sequence = int(value) 30 | 31 | def __str__(self): 32 | return "{} seq: {}".format(self.__class__.__name__, self.sequence) 33 | 34 | 35 | if __name__ == '__main__': 36 | up1 = UDPPing() 37 | print(up1) 38 | 39 | up2 = UDPPing() 40 | up2.sequence = 13 41 | print(up2) 42 | 43 | up3 = UDPPing(sequence=42) 44 | print(up3) 45 | 46 | UDP_PING_PORT = 12345 47 | pkt = Ethernet(src="11:22:11:22:11:22", 48 | dst="22:33:22:33:22:33") + \ 49 | IPv4(src="1.2.3.4", dst="5.6.7.8", 50 | protocol=IPProtocol.UDP, ttl=64) + \ 51 | UDP(src=55555, dst=UDP_PING_PORT) + \ 52 | UDPPing(42) 53 | print("Before serialize/deserialize:", pkt) 54 | xbytes = pkt.to_bytes() 55 | reanimated_pkt = Packet(raw=xbytes) 56 | print("After deserialization:", reanimated_pkt) 57 | 58 | print("*" * 40) 59 | 60 | UDP.add_next_header_class(UDP_PING_PORT, UDPPing) 61 | UDP.set_next_header_class_key('dst') 62 | pkt = Ethernet(src="11:22:11:22:11:22", 63 | dst="22:33:22:33:22:33") + \ 64 | IPv4(src="1.2.3.4", dst="5.6.7.8", 65 | protocol=IPProtocol.UDP, ttl=64) + \ 66 | UDP(src=55555, dst=UDP_PING_PORT) + \ 67 | UDPPing(sequence=13) 68 | print("Before serialize/deserialize:", pkt) 69 | xbytes = pkt.to_bytes() 70 | reanimated_pkt = Packet(raw=xbytes) 71 | print("After deserialization:", reanimated_pkt) 72 | -------------------------------------------------------------------------------- /switchyard-master/documentation/index.rst: -------------------------------------------------------------------------------- 1 | .. Switchyard documentation master file, created by 2 | sphinx-quickstart on Wed Dec 3 22:08:55 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Switchyard documentation 7 | ======================== 8 | 9 | .. Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | intro 15 | writing_a_program 16 | test_execution 17 | test_scenario_creation 18 | live_execution 19 | advanced_api 20 | installation 21 | reference 22 | release_notes 23 | thanks 24 | 25 | 26 | Indices and tables 27 | ================== 28 | 29 | * :ref:`genindex` 30 | * :ref:`modindex` 31 | * :ref:`search` 32 | 33 | I gratefully acknowledge support from the NSF. The materials here are based upon work supported by the National Science Foundation under grant CNS-1054985 ("CAREER: Expanding the functionality of Internet routers"). 34 | 35 | Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author and do not necessarily reflect the views of the National Science Foundation. 36 | 37 | .. todolist:: 38 | 39 | License 40 | ======= 41 | 42 | The Switchyard software is distributed under terms of the GNU General Public License, version 3. 43 | 44 | Switchyard's documentation is distributed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License: http://creativecommons.org/licenses/by-nc-sa/4.0/. 45 | -------------------------------------------------------------------------------- /switchyard-master/documentation/installation.rst: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | Installing Switchyard 4 | ********************* 5 | 6 | Switchyard has been tested and developed on the following operating systems: 7 | 8 | * macOS 10.10 and later 9 | * Ubuntu LTS releases from 14.04 and later 10 | * Fedora 21 11 | 12 | Note that these are all Unix-based systems. Switchyard may be enhanced in the future to support Windows-based systems. Ubuntu (current LTS) and macOS receive the most testing of Unix-based operating systems. 13 | 14 | --- 15 | 16 | The steps for getting Switchyard up and running are as follows: 17 | 18 | 0. Install Python 3.4 or later, if you don't already have it. 19 | 1. Install any necessary libraries for your operating system. 20 | 2. Create an Python "virtual environment" for installing Python modules (or install the modules to your system Python) 21 | 3. Install Switchyard. 22 | 23 | For step 0, you're on your own. Go to https://www.python.org/downloads/, or install packages via your OS'es package system, or use homebrew if you're on a Mac. Have fun. 24 | 25 | The specific libraries necessary for different OSes (step 1) are described below, but steps 2 and 3 are the same for all operating systems and are covered next. 26 | 27 | The recommended install procedure is to create a Python virtual environment for installing Switchyard and other required Python modules. One way to create a new virtual environment is to execute the following at a command line (in the folder in which you want to create the virtual environment):: 28 | 29 | $ python3 -m venv syenv 30 | 31 | This command will create a new virtual environment called ``syenv``. Once that's done, you can "activate" that environment and install Switchyard as follows:: 32 | 33 | $ source ./syenv/bin/activate 34 | (syenv)$ python3 -m pip install switchyard 35 | 36 | That's it. Once you've done that, the ``swyard`` program should be on your ``PATH`` (you can check by typing ``which swyard``). If you no longer want to use the Python virtual environment you've created, you can just type ``deactivate``. 37 | 38 | Operating system-specific instructions 39 | ====================================== 40 | 41 | MacOS X 42 | ------- 43 | 44 | The easiest way to get Switchyard running in macOS is to install homebrew. You can use ``brew`` to install Python 3. You should also ``brew`` to install the ``libpcap`` package. That should be all that is necessary. 45 | 46 | Ubuntu 47 | ------ 48 | 49 | For Ubuntu systems, you'll need to use ``apt-get`` or something similar to install the following packages:: 50 | 51 | libffi-dev libpcap-dev python3-dev python3-pip python3-venv 52 | 53 | Fedora/RedHat 54 | ------------- 55 | 56 | For Fedora and RedHat-based systems, you'll need to use ``yum`` or something similar to install a similar set of packages as with Ubuntu (but with the right name changes for the way packages are identified on Fedora):: 57 | 58 | libffi-devel libpcap-devel python3-devel python3-pip python3-virtualenv 59 | 60 | -------------------------------------------------------------------------------- /switchyard-master/documentation/packet.graffle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/packet.graffle -------------------------------------------------------------------------------- /switchyard-master/documentation/packet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/packet.pdf -------------------------------------------------------------------------------- /switchyard-master/documentation/packet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/packet.png -------------------------------------------------------------------------------- /switchyard-master/documentation/release_notes.rst: -------------------------------------------------------------------------------- 1 | Release notes 2 | ************* 3 | 4 | The headings below refer either to branches on Switchyard's github repo (v1 and v2) or tags (2017.01.1). 5 | 6 | 2017.01.4 7 | --------- 8 | More bugfixes. 9 | 10 | 2017.01.3 11 | --------- 12 | Minor bugfixes. 13 | 14 | 2017.01.2 15 | --------- 16 | 17 | Add the capability to pass arguments to a Switchyard program via ``-g`` option to ``swyard``. 18 | Switchyard parses and assembles ``*args`` and ``**kwargs`` to pass into the user code, being careful to only pass them if the code can accept them. 19 | 20 | 2017.01.1 21 | --------- 22 | 23 | Major revision; expansion of types of exercises supported (notably application-layer programs via socket emulation) and several non-backward compatible API changes. Simplified user code import (single import of switchyard.lib.userlib). Installation via standard setuptools, so easily installed via easy_install or pip. Major revision of documentation. Lots of new tests were written, bringing test coverage above 90%. Expansion of exercises is still in progress. 24 | 25 | Some key API changes to be aware of: 26 | 27 | * the Scenario class is renamed TestScenario. The PacketOutputEvent previously allowed Openflow 1.0-like wildcard strings to specify wildcards for matching packets; these strings are no longer supported. To specify wildcards, a tuple of (classname,attribute) must be used; refer to :ref:`test-scenario-creation`, above. 28 | * ``recv_packet`` *always* returns a timestamp now; it returns a 3-tuple (named tuple) of timestamp, input_port and packet. 29 | * The only import required by user code is switchyard.lib.userlib, although individual imports are still fine (just more verbose). 30 | * Instead of invoking ``srpy.py``, a ``swyard`` program is installed during the new install process. ``swyard`` has a few command-line changes compared with ``srpy.py``. In particular, the ``-s`` option has gone away; to run Switchyard with a test, just use the ``-t`` option with the scenario file as the argument. 31 | 32 | 33 | v2 34 | -- 35 | 36 | Complete rewrite of v1. Moved to Python 3 and created packet parsing libraries, new libpcap interface library (pcapffi). Redesigned test scenario modules and an expanded of publicly available exercises. Used at Colgate twice and University of Wisconsin-Madison twice. Available on the ``v2`` branch on github. 37 | 38 | v1 39 | -- 40 | 41 | First version, which used the POX packet parsing libraries and had a variety of limitations. Implemented in Python 2 and used at Colgate once. Available on the ``v1`` branch on github, but very much obsolete. 42 | -------------------------------------------------------------------------------- /switchyard-master/documentation/srpyarch.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/srpyarch.pdf -------------------------------------------------------------------------------- /switchyard-master/documentation/srpyarch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/documentation/srpyarch.png -------------------------------------------------------------------------------- /switchyard-master/documentation/thanks.rst: -------------------------------------------------------------------------------- 1 | Acknowledgments and thanks 2 | ************************** 3 | 4 | Once again, I gratefully acknowledge support from the NSF. The materials here are based upon work supported by the National Science Foundation under grant CNS-1054985 ("CAREER: Expanding the functionality of Internet routers"). 5 | Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author and do not necessarily reflect the views of the National Science Foundation. 6 | 7 | Thanks to Colgate COSC465 students from Spring 2014 and Spring 2015 for being guinea pigs and giving feedback for the very first versions of Switchyard. Thanks also to Prof. Paul Barford and CS640 students at the University of Wisconsin for using and providing feedback on Switchyard. 8 | 9 | Thanks to those students who have contributed fixes and made suggestions for improvements. In particular: 10 | 11 | * Thanks to Saul Shanabrook for several specific suggestions and bug reports that have led to improvements in Switchyard. 12 | * Thanks to Xuyi Ruan for identifying and suggesting a fix to bugs on one of the documentation diagrams. 13 | * Thanks to Sean Wilson for a bug fix on an infinitely recursive property setter. Oops, but this dumb bug motivated me to significantly improve test coverage, so there's that. 14 | * Thanks to Leon Yang for identifying a problem with kwarg processing for ICMP. 15 | 16 | -------------------------------------------------------------------------------- /switchyard-master/examples/clientapp_udpstackex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # import socket 4 | import switchyard.lib.socket as socket 5 | 6 | HOST = '127.0.0.1' 7 | PORT = 10000 8 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 9 | s.settimeout(2.0) 10 | 11 | print("Sending message to server at {},{}".format(HOST,PORT)) 12 | s.sendto(b'Hello, stack', (HOST,PORT)) 13 | try: 14 | data,addr = s.recvfrom(1024) 15 | print('Client socket application received message from {}: {}'.format(repr(addr),data.decode('utf8'))) 16 | except: 17 | print("Timeout") 18 | 19 | s.close() 20 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/README.rst: -------------------------------------------------------------------------------- 1 | Sample Exercises 2 | **************** 3 | 4 | This folder contains sources for sample exercises. Each subfolder includes 5 | a project description and various support files. Note: if you're viewing this source through Github, it will render individual ``.rst`` files if you click on them. If you don't like ReStructuredText, use pandoc to convert to a format you like better. 6 | 7 | **Instructors**: if you'd like the Switchyard test files (and test source code), please email me. Any tests referred to in the project/exercise descriptions are intentionally excluded from this repo (except for the firewall, currently). 8 | 9 | An overview of existing and in-the-works exercises is as follows: 10 | 11 | Learning switch 12 | Build a simple Ethernet learning switch. This is a nice starter exercise for getting accustomed to the APIs and workflow in Switchyard. Some extensions and variants to this exercise are included in the description, such as a spanning-tree protocol-like capability. 13 | 14 | IP router 15 | This is really a set of 3 projects designed to gradually built up capabilities to implement an IPv4 router that uses a static forwarding table. Descriptions of extensions and variants such as dynamic routing are included. 16 | 17 | Firewall 18 | In this exercise, build a stand-alone firewall device with token bucket rate-limiting capability. 19 | 20 | UDP network stack + application 21 | This exercise is an introduction to using Switchyard's socket API emulation capabilities. The goal is to build the Ethernet/IP/UDP layers to support a UDP-based application, along with a basic windowed form of transport reliability. 22 | 23 | License 24 | ------- 25 | 26 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 27 | http://creativecommons.org/licenses/by-nc-sa/4.0/ 28 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/applayer.rst: -------------------------------------------------------------------------------- 1 | Application layer 2 | ----------------- 3 | 4 | Note: these exercises are a work in progress and some details may not be clear or correctly included yet. 5 | 6 | This exercise has three parts. In the first part, the goal is to create a Python socket-based client for a "message board" application. The server with this the client should communicate is already written; only the client needs to be created. This part of the project does *not* require any use of Switchyard --- only the built-in Python ``socket`` module is used. UDP is used as as the transport protocol. 7 | 8 | The goal of the second part of the exercise is to create a UDP-based network stack, which can be used by the client created in part 1 (and also by the server). The network stack will implement a static window-based form of reliable transport. 9 | 10 | The goal of the third and final part of the exercise is to create a simple middlebox device to introduce packet loss in the network. This part can either be done with "hard-coded" Ethernet address/IPv4 address mappings, or can implement ARP to operate in a more flexible manner. 11 | 12 | The three parts of this exercise are described in detail in three separate documents found in this folder: 13 | 14 | * ``msgboardapp.rst`` 15 | 16 | * ``msgboardstack.rst`` 17 | 18 | * ``msgboardmiddlebox.rst`` 19 | 20 | 21 | 22 | License 23 | ------- 24 | 25 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 26 | http://creativecommons.org/licenses/by-nc-sa/4.0/ 27 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/blastee.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.address import * 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.userlib import * 6 | from threading import * 7 | import time 8 | 9 | def switchy_main(net): 10 | my_interfaces = net.interfaces() 11 | mymacs = [intf.ethaddr for intf in my_interfaces] 12 | 13 | while True: 14 | gotpkt = True 15 | try: 16 | timestamp,dev,pkt = net.recv_packet() 17 | log_debug("Device is {}".format(dev)) 18 | except NoPackets: 19 | log_debug("No packets available in recv_packet") 20 | gotpkt = False 21 | except Shutdown: 22 | log_debug("Got shutdown signal") 23 | break 24 | 25 | if gotpkt: 26 | log_debug("I got a packet from {}".format(dev)) 27 | log_debug("Pkt: {}".format(pkt)) 28 | 29 | 30 | net.shutdown() 31 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/blaster.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.address import * 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.userlib import * 6 | from random import randint 7 | import time 8 | 9 | 10 | def switchy_main(net): 11 | my_intf = net.interfaces() 12 | mymacs = [intf.ethaddr for intf in my_intf] 13 | myips = [intf.ipaddr for intf in my_intf] 14 | 15 | while True: 16 | gotpkt = True 17 | try: 18 | #Timeout value will be parameterized! 19 | timestamp,dev,pkt = net.recv_packet(timeout=0.15) 20 | except NoPackets: 21 | log_debug("No packets available in recv_packet") 22 | gotpkt = False 23 | except Shutdown: 24 | log_debug("Got shutdown signal") 25 | break 26 | 27 | if gotpkt: 28 | log_debug("I got a packet") 29 | else: 30 | log_debug("Didn't receive anything") 31 | 32 | ''' 33 | Creating the headers for the packet 34 | ''' 35 | pkt = Ethernet() + IPv4() + UDP() 36 | pkt[1].protocol = IPProtocol.UDP 37 | 38 | ''' 39 | Do other things here and send packet 40 | ''' 41 | 42 | net.shutdown() 43 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/middlebox.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.address import * 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.userlib import * 6 | from threading import * 7 | from random import randint 8 | import time 9 | 10 | def switchy_main(net): 11 | 12 | my_intf = net.interfaces() 13 | mymacs = [intf.ethaddr for intf in my_intf] 14 | myips = [intf.ipaddr for intf in my_intf] 15 | 16 | while True: 17 | gotpkt = True 18 | try: 19 | timestamp,dev,pkt = net.recv_packet() 20 | log_debug("Device is {}".format(dev)) 21 | except NoPackets: 22 | log_debug("No packets available in recv_packet") 23 | gotpkt = False 24 | except Shutdown: 25 | log_debug("Got shutdown signal") 26 | break 27 | 28 | if gotpkt: 29 | log_debug("I got a packet {}".format(pkt)) 30 | 31 | if dev == "middlebox-eth0": 32 | log_debug("Received from blaster") 33 | ''' 34 | Received data packet 35 | Should I drop it? 36 | If not, modify headers & send to blastee 37 | ''' 38 | net.send_packet("middlebox-eth1", pkt) 39 | elif dev == "middlebox-eth1": 40 | log_debug("Received from blastee") 41 | ''' 42 | Received ACK 43 | Modify headers & send to blaster. Not dropping ACK packets! 44 | net.send_packet("middlebox-eth0", pkt) 45 | ''' 46 | else: 47 | log_debug("Oops :))") 48 | 49 | net.shutdown() 50 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/msgboarddiag.graffle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/applayer/msgboarddiag.graffle -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/msgboarddiag.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/applayer/msgboarddiag.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/msgboarddiag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/applayer/msgboarddiag.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/applayer/msgboardmiddlebox.rst: -------------------------------------------------------------------------------- 1 | Message board application middlebox 2 | ----------------------------------- 3 | 4 | The goal of the third and final part of the exercise is to create a simple middlebox device to introduce packet loss in the network. This part can either be done with "hard-coded" Ethernet address/IPv4 address mappings, or can implement ARP to operate in a more flexible manner. 5 | 6 | You'll implement this device using the Switchyard framework. It will only have two ports, with one port handling traffic to/from a MBclient, and the other port handling traffic to/from a MBserver. When ever a packet arrives on one port, it should be forwarded out the other port, and vice versa. There is no need for any explicit routing. 7 | 8 | Here's the "fun" part: although there's a pretty dumb forwarding mechanism used by the device, it will also be in charge of probabilistically dropping packets to simulate the evil sorts of things that can happen in a real network. Packet drops should only happen in the MBserver to MBclient direction, not the other way around. 9 | 10 | The ``main`` function of your middlebox device should accept, in addition to the ``net`` object, a floating point number between 0 and 1 which represents the probability of dropping a given packet. 11 | 12 | That's it! 13 | 14 | License 15 | ------- 16 | 17 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 18 | http://creativecommons.org/licenses/by-nc-sa/4.0/ 19 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.userlib import * 2 | import time 3 | 4 | def main(net): 5 | # assumes that there are exactly 2 ports 6 | portnames = [ p.name for p in net.ports() ] 7 | portpair = dict(zip(portnames, portnames[::-1])) 8 | 9 | while True: 10 | pkt = None 11 | try: 12 | timestamp,input_port,pkt = net.recv_packet(timeout=0.5) 13 | except NoPackets: 14 | pass 15 | except Shutdown: 16 | break 17 | 18 | if pkt is not None: 19 | 20 | # This is logically where you'd include some firewall 21 | # rule tests. It currently just forwards the packet 22 | # out the other port, but depending on the firewall rules 23 | # the packet may be dropped or mutilated. 24 | net.send_packet(portpair[input_port], pkt) 25 | 26 | 27 | net.shutdown() 28 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall_rules.txt: -------------------------------------------------------------------------------- 1 | 2 | # drop everything from an internal subnet which shouldn't be allowed 3 | # to communicate with rest of internet 4 | # rule 1 5 | deny ip src 192.168.42.0/24 dst any 6 | # rule 2 7 | deny ip src any dst 192.168.42.0/24 8 | 9 | # allow traffic to/from an internal web server that should 10 | # be accessible to external hosts 11 | # rule 3 12 | permit tcp src 192.168.13.13 srcport 80 dst any dstport any 13 | # rule 4 14 | permit tcp src any srcport any dst 192.168.13.13 dstport 80 15 | 16 | # allow DNS (udp port 53) traffic in/out of network 17 | # rule 5 18 | permit udp src 192.168.0.0/16 srcport any dst any dstport 53 19 | # rule 6 20 | permit udp src any srcport 53 dst 192.168.0.0/16 dstport any 21 | 22 | # allow internal hosts access to web (tcp ports 80 and 443) 23 | # rate limit http traffic to 100 kB/s (12500 bytes/sec), but 24 | # don't rate limit any encrypted HTTP traffic. 25 | # rule 7 26 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 80 ratelimit 12500 27 | # rule 8 28 | permit tcp src any srcport any dst 172.16.42.0/24 dstport 80 ratelimit 12500 29 | # rule 9 30 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 443 31 | # rule 10 32 | permit tcp src any srcport any dst 172.16.42.0/24 dstport 443 33 | 34 | # permit, but impair certain traffic flows 35 | # rule 11 36 | permit tcp src 192.168.0.0/24 srcport any dst any dstport 8000 impair 37 | 38 | # permit, but rate limit icmp to 100 bytes/sec 39 | # rule 12 40 | permit icmp src any dst any ratelimit 100 41 | 42 | # block everything else 43 | # rule 13 44 | deny ip src any dst any 45 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall_topology.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/firewall/firewall_topology.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall_topology.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/firewall/firewall_topology.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall_topology.graffle/image2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/firewall/firewall_topology.graffle/image2.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/firewall_topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/firewall/firewall_topology.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/impairmenttest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from copy import deepcopy 4 | import random 5 | 6 | from switchyard.lib.userlib import * 7 | 8 | firewall_rules = ''' 9 | # drop everything from an internal subnet which shouldn't be allowed 10 | # to communicate with rest of internet 11 | # rule 1 12 | deny ip src 192.168.42.0/24 dst any 13 | # rule 2 14 | deny ip src any dst 192.168.42.0/24 15 | 16 | # allow traffic to/from an internal web server that should 17 | # be accessible to external hosts 18 | # rule 3 19 | permit tcp src 192.168.13.13 srcport 80 dst any dstport any 20 | # rule 4 21 | permit tcp src any srcport any dst 192.168.13.13 dstport 80 22 | 23 | # allow DNS (udp port 53) traffic in/out of network 24 | # rule 5 25 | permit udp src 192.168.0.0/16 srcport any dst any dstport 53 26 | # rule 6 27 | permit udp src any srcport 53 dst 192.168.0.0/16 dstport any 28 | 29 | # allow internal hosts access to web (tcp ports 80 and 443) 30 | # rate limit http traffic to 100 kB/s (12500 bytes/sec), but 31 | # don't rate limit any encrypted HTTP traffic. 32 | # rule 7 33 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 80 ratelimit 12500 34 | # rule 8 35 | permit tcp src any srcport any dst 172.16.42.0/24 dstport 80 ratelimit 12500 36 | # rule 9 37 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 443 38 | # rule 10 39 | permit tcp src any srcport any dst 172.16.42.0/24 dstport 443 40 | 41 | # permit, but impair certain traffic flows 42 | # rule 11 43 | permit tcp src 192.168.0.0/24 srcport any dst any dstport 8000 impair 44 | 45 | # permit, but rate limit icmp to 100 bytes/sec 46 | # rule 12 47 | permit icmp src any dst any ratelimit 100 48 | 49 | # block everything else 50 | # rule 13 51 | deny ip src any dst any 52 | ''' 53 | 54 | def firewall_tests(): 55 | s = TestScenario("Firewall tests") 56 | s.add_file('firewall_rules.txt', firewall_rules) 57 | 58 | # two ethernet ports; no IP addresses assigned to 59 | # them. eth0 is internal network-facing, and eth1 60 | # is external network-facing. 61 | s.add_interface('eth0', '00:00:00:00:0b:01') 62 | s.add_interface('eth1', '00:00:00:00:0b:02') 63 | 64 | t = TCP() 65 | t.ACK = 1 66 | t.ack = random.randrange(0,2**32) 67 | t.seq = random.randrange(0,2**32) 68 | t.src = random.randrange(2**12,2**16) 69 | t.dst = 8000 70 | ip = IPv4() 71 | ip.src = '192.168.0.13' 72 | ip.dst = IPv4Address(random.randrange(2**16, 2**32)) 73 | ip.protocol = IPProtocol.TCP 74 | pkt = Ethernet() + ip + t + "This is some TCP data!".encode() 75 | # fill in any other packet headers or data to the constructed packet 76 | s.expect(PacketInputEvent('eth0',pkt), 77 | 'Packet that should be impaired arrives on eth0') 78 | 79 | # Modify the packet in the same way that you expect the firewall 80 | # to modify the packet. 81 | pkt = deepcopy(pkt) # make a full copy of the packet before modifying 82 | 83 | s.expect(PacketOutputEvent('eth1',pkt), 84 | 'Test description for a packet departure --- what should happen?') 85 | 86 | return s 87 | 88 | scenario = firewall_tests() 89 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet portion of pyrouter") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PyRouterTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PyRouterTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # external----firewall----internal 33 | # 34 | # external refers to the internet outside a given 35 | # enterprise's network. internal refers to the 36 | # enterprise's network. 37 | 38 | self.addHost('external') 39 | self.addHost('internal') 40 | self.addHost('firewall') 41 | 42 | for node in ['internal','external']: 43 | self.addLink(node, 'firewall', bw=1000, delay="10ms") 44 | 45 | def set_ip_pair(net, node1, node2, ip1, ip2): 46 | node1 = net.get(node1) 47 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 48 | intf = ilist[0] 49 | intf[0].setIP(ip1) 50 | intf[1].setIP(ip2) 51 | 52 | def set_ip(net, node, ifname, addr): 53 | node_object = net.get(node) 54 | intf = node_object.intf(ifname) 55 | intf.setIP(addr) 56 | 57 | def reset_macs(net, node, macbase): 58 | ifnum = 1 59 | node_object = net.get(node) 60 | for intf in node_object.intfList(): 61 | if node not in str(intf): 62 | continue # don't set lo or other interfaces 63 | node_object.setMAC(macbase.format(ifnum), intf) 64 | ifnum += 1 65 | 66 | for intf in node_object.intfList(): 67 | print node,intf,node_object.MAC(intf) 68 | 69 | def set_def_route(net, fromnode, gw): 70 | node_object = net.get(fromnode) 71 | node_object.cmdPrint("route add default gw {}".format(gw)) 72 | 73 | def setup_addressing(net): 74 | reset_macs(net, 'internal', '00:00:00:00:01:{:02x}') 75 | reset_macs(net, 'external', '00:00:00:00:10:{:02x}') 76 | reset_macs(net, 'firewall', '00:00:00:00:0b:{:02x}') 77 | 78 | set_ip(net,'internal','internal-eth0','192.168.0.1/24') 79 | set_ip(net,'external','external-eth0','192.168.0.2/24') 80 | 81 | def disable_ipv6(net): 82 | for v in net.values(): 83 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 84 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 85 | 86 | def stop_nodegrams(net): 87 | for nname in ['external','internal','firewall']: 88 | n = net.get(nname) 89 | n.cmd("killall python3") 90 | 91 | def main(): 92 | topo = PyRouterTopo(args) 93 | net = Mininet(topo=topo, link=TCLink, cleanup=True, autoSetMacs=True, controller=None) 94 | setup_addressing(net) 95 | disable_ipv6(net) 96 | net.staticArp() 97 | net.interact() 98 | 99 | if __name__ == '__main__': 100 | main() 101 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/firewall/www/start_webserver.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # assume we're running this from parent directory (within mininet) 4 | cd www 5 | 6 | # create a couple files for testing 7 | echo ' Test file 1 sneaky crackers wuz here! ' > 1.html 8 | dd if=/dev/zero of=bigfile bs=1k count=100 2>&1 > /dev/null 9 | 10 | if (( $# == 0 )) ; then 11 | port=80 12 | else 13 | port=$1 14 | fi 15 | 16 | python3 -m http.server ${port} & 17 | 18 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/ls_diagram.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/learning_switch/ls_diagram.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/ls_diagram.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/learning_switch/ls_diagram.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/ls_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/learning_switch/ls_diagram.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/ls_flowchart.graffle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/learning_switch/ls_flowchart.graffle -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/ls_flowchart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/learning_switch/ls_flowchart.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/myswitch.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Ethernet learning switch in Python. 3 | 4 | Note that this file currently has the code to implement a "hub" 5 | in it, not a learning switch. (I.e., it's currently a switch 6 | that doesn't learn.) 7 | ''' 8 | from switchyard.lib.userlib import * 9 | 10 | def main(net): 11 | my_interfaces = net.interfaces() 12 | mymacs = [intf.ethaddr for intf in my_interfaces] 13 | 14 | while True: 15 | try: 16 | timestamp,input_port,packet = net.recv_packet() 17 | except NoPackets: 18 | continue 19 | except Shutdown: 20 | return 21 | 22 | log_debug ("In {} received packet {} on {}".format(net.name, packet, input_port)) 23 | if packet[0].dst in mymacs: 24 | log_debug ("Packet intended for me") 25 | else: 26 | for intf in my_interfaces: 27 | if input_port != intf.name: 28 | log_debug ("Flooding packet {} to {}".format(packet, intf.name)) 29 | net.send_packet(intf.name, packet) 30 | net.shutdown() 31 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/learning_switch/switchtopo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet pyswitch topology") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PySwitchTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PySwitchTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # server1 34 | # \ 35 | # switch----client 36 | # / 37 | # server2 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('server1', **nodeconfig) 42 | self.addHost('server2', **nodeconfig) 43 | self.addHost('switch', **nodeconfig) 44 | self.addHost('client', **nodeconfig) 45 | 46 | for node in ['server1','server2','client']: 47 | # all links are 10Mb/s, 100 millisecond prop delay 48 | self.addLink(node, 'switch', bw=10, delay='100ms') 49 | 50 | def set_ip(net, node1, node2, ip): 51 | node1 = net.get(node1) 52 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 53 | intf = ilist[0] 54 | intf[0].setIP(ip) 55 | 56 | def reset_macs(net, node, macbase): 57 | ifnum = 1 58 | node_object = net.get(node) 59 | for intf in node_object.intfList(): 60 | node_object.setMAC(macbase.format(ifnum), intf) 61 | ifnum += 1 62 | 63 | for intf in node_object.intfList(): 64 | print node,intf,node_object.MAC(intf) 65 | 66 | def set_route(net, fromnode, prefix, nextnode): 67 | node_object = net.get(fromnode) 68 | ilist = node_object.connectionsTo(net.get(nextnode)) 69 | node_object.setDefaultRoute(ilist[0][0]) 70 | 71 | def setup_addressing(net): 72 | reset_macs(net, 'server1', '10:00:00:00:00:{:02x}') 73 | reset_macs(net, 'server2', '20:00:00:00:00:{:02x}') 74 | reset_macs(net, 'client', '30:00:00:00:00:{:02x}') 75 | reset_macs(net, 'switch', '40:00:00:00:00:{:02x}') 76 | set_ip(net, 'server1','switch','192.168.100.1/24') 77 | set_ip(net, 'server2','switch','192.168.100.2/24') 78 | set_ip(net, 'client','switch','192.168.100.3/24') 79 | 80 | def disable_ipv6(net): 81 | for v in net.values(): 82 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 83 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 84 | 85 | def main(): 86 | topo = PySwitchTopo(args) 87 | net = Mininet(controller=None, topo=topo, link=TCLink, cleanup=True) 88 | setup_addressing(net) 89 | disable_ipv6(net) 90 | net.interact() 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/dvroute/dv_topology.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/dvroute/dv_topology.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/dvroute/dv_topology.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/dvroute/dv_topology.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/dvroute/dv_topology.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/dvroute/dv_topology.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/dvroute/dv_topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/dvroute/dv_topology.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/dvroute/rippkt1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/dvroute/rippkt1.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/forwarding_table.txt: -------------------------------------------------------------------------------- 1 | 172.16.0.0 255.255.0.0 192.168.1.2 router-eth0 2 | 172.16.128.0 255.255.192.0 10.10.0.254 router-eth1 3 | 172.16.64.0 255.255.192.0 10.10.1.254 router-eth1 4 | 10.100.0.0 255.255.0.0 172.16.42.2 router-eth2 -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/lsroute/ls_topology.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/lsroute/ls_topology.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/lsroute/ls_topology.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/lsroute/ls_topology.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/lsroute/ls_topology.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/lsroute/ls_topology.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/lsroute/ls_topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/lsroute/ls_topology.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/myrouter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Basic IPv4 router (static routing) in Python. 5 | ''' 6 | 7 | import sys 8 | import os 9 | import time 10 | from switchyard.lib.userlib import * 11 | 12 | class Router(object): 13 | def __init__(self, net): 14 | self.net = net 15 | # other initialization stuff here 16 | 17 | 18 | def router_main(self): 19 | ''' 20 | Main method for router; we stay in a loop in this method, receiving 21 | packets until the end of time. 22 | ''' 23 | while True: 24 | gotpkt = True 25 | try: 26 | timestamp,dev,pkt = self.net.recv_packet(timeout=1.0) 27 | except NoPackets: 28 | log_debug("No packets available in recv_packet") 29 | gotpkt = False 30 | except Shutdown: 31 | log_debug("Got shutdown signal") 32 | break 33 | 34 | if gotpkt: 35 | log_debug("Got a packet: {}".format(str(pkt))) 36 | 37 | 38 | 39 | def main(net): 40 | ''' 41 | Main entry point for router. Just create Router 42 | object and get it going. 43 | ''' 44 | r = Router(net) 45 | r.router_main() 46 | net.shutdown() 47 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router1_pcap1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router1_pcap1.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router1_pcap2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router1_pcap2.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router2_pcap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router2_pcap.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router2_topology.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router2_topology.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router2_topology.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router2_topology.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router2_topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router2_topology.png -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router4.rst: -------------------------------------------------------------------------------- 1 | Router extensions 2 | ----------------- 3 | 4 | Here are three possible extensions to the router with exercise descriptions: 5 | 6 | * For a firewall extension:,see the ``firewall`` exercise folder. 7 | 8 | * For a RIPv2-like distance vector dynamic routing extension, see the ``dvroute`` folder. 9 | 10 | * For a link state (OSPF-like) dynamic routing extension, see the ``lsroute`` folder. 11 | 12 | Another idea, but without an exercise description: 13 | 14 | * Add a load balancing capability among 2 or more interfaces that are assumed to be connected to links leading to the same far-end destination (either to a single remote router or to multiple co-located routers). You could create a hash function that uses packet header attributes as input to make a decision about which interface on which to forward the packet. 15 | 16 | 17 | License 18 | ------- 19 | 20 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 21 | http://creativecommons.org/licenses/by-nc-sa/4.0/ 22 | -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router_topology.graffle/data.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router_topology.graffle/data.plist -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router_topology.graffle/image1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router_topology.graffle/image1.pdf -------------------------------------------------------------------------------- /switchyard-master/examples/exercises/router/router_topology.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/examples/exercises/router/router_topology.png -------------------------------------------------------------------------------- /switchyard-master/examples/hubtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.userlib import * 4 | 5 | def mk_pkt(hwsrc, hwdst, ipsrc, ipdst, reply=False): 6 | ether = Ethernet(src=hwsrc, dst=hwdst, ethertype=EtherType.IP) 7 | ippkt = IPv4(src=ipsrc, dst=ipdst, protocol=IPProtocol.ICMP, ttl=32) 8 | icmppkt = ICMP() 9 | if reply: 10 | icmppkt.icmptype = ICMPType.EchoReply 11 | else: 12 | icmppkt.icmptype = ICMPType.EchoRequest 13 | return ether + ippkt + icmppkt 14 | 15 | def hub_tests(): 16 | s = TestScenario("hub tests") 17 | s.add_interface('eth0', '10:00:00:00:00:01') 18 | s.add_interface('eth1', '10:00:00:00:00:02') 19 | s.add_interface('eth2', '10:00:00:00:00:03') 20 | 21 | # test case 1: a frame with broadcast destination should get sent out 22 | # all ports except ingress 23 | testpkt = mk_pkt("30:00:00:00:00:02", "ff:ff:ff:ff:ff:ff", "172.16.42.2", "255.255.255.255") 24 | s.expect(PacketInputEvent("eth1", testpkt, display=Ethernet), "An Ethernet frame with a broadcast destination address should arrive on eth1") 25 | s.expect(PacketOutputEvent("eth0", testpkt, "eth2", testpkt, display=Ethernet), "The Ethernet frame with a broadcast destination address should be forwarded out ports eth0 and eth2") 26 | 27 | # test case 2: a frame with any unicast address except one assigned to hub 28 | # interface should be sent out all ports except ingress 29 | reqpkt = mk_pkt("20:00:00:00:00:01", "30:00:00:00:00:02", '192.168.1.100','172.16.42.2') 30 | s.expect(PacketInputEvent("eth0", reqpkt, display=Ethernet), "An Ethernet frame from 20:00:00:00:00:01 to 30:00:00:00:00:02 should arrive on eth0") 31 | s.expect(PacketOutputEvent("eth1", reqpkt, "eth2", reqpkt, display=Ethernet), "Ethernet frame destined for 30:00:00:00:00:02 should be flooded out eth1 and eth2") 32 | 33 | resppkt = mk_pkt("30:00:00:00:00:02", "20:00:00:00:00:01", '172.16.42.2', '192.168.1.100', reply=True) 34 | s.expect(PacketInputEvent("eth1", resppkt, display=Ethernet), "An Ethernet frame from 30:00:00:00:00:02 to 20:00:00:00:00:01 should arrive on eth1") 35 | s.expect(PacketOutputEvent("eth0", resppkt, "eth2", resppkt, display=Ethernet), "Ethernet frame destined to 20:00:00:00:00:01 should be flooded out eth0 and eth2") 36 | 37 | #mytestcase 38 | testpkt = mk_pkt("20:00:00:00:00:01", "ff:ff:ff:ff:ff:ff", '192.168.1.100', "255.255.255.255") 39 | s.expect(PacketInputEvent("eth0", testpkt, display=Ethernet), "An Ethernet frame with a broadcast destination address should arrive on eth0") 40 | s.expect(PacketOutputEvent("eth1", testpkt, "eth2", testpkt, display=Ethernet), "The Ethernet frame with a broadcast destination address should be forwarded out ports eth1 and eth2") 41 | 42 | # test case 3: a frame with dest address of one of the interfaces should 43 | # result in nothing happening 44 | reqpkt = mk_pkt("20:00:00:00:00:01", "10:00:00:00:00:03", '192.168.1.100','172.16.42.2') 45 | s.expect(PacketInputEvent("eth2", reqpkt, display=Ethernet), "An Ethernet frame should arrive on eth2 with destination address the same as eth2's MAC address") 46 | s.expect(PacketInputTimeoutEvent(1.0), "The hub should not do anything in response to a frame arriving with a destination address referring to the hub itself.") 47 | return s 48 | 49 | scenario = hub_tests() 50 | -------------------------------------------------------------------------------- /switchyard-master/examples/myhub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ''' 3 | Ethernet hub in Switchyard. 4 | ''' 5 | from switchyard.lib.userlib import * 6 | 7 | 8 | def main(net): 9 | my_interfaces = net.interfaces() 10 | mymacs = [intf.ethaddr for intf in my_interfaces] 11 | in_num=0 12 | out_num=0 13 | while True: 14 | try: 15 | timestamp, dev, packet = net.recv_packet() 16 | in_num+=1 17 | except NoPackets: 18 | continue 19 | except Shutdown: 20 | return 21 | log_debug("In {} received packet {} on {}".format( 22 | net.name, packet, dev)) 23 | eth = packet.get_header(Ethernet) 24 | if eth is None: 25 | log_info("Received a non-Ethernet packet?!") 26 | continue 27 | 28 | if eth.dst in mymacs: 29 | log_info("Received a packet intended for me") 30 | else: 31 | #print("before loop") 32 | for intf in my_interfaces: 33 | #print("testcase1:",intf.name) 34 | #print("testcase2:",dev) 35 | if dev != intf.name: 36 | log_info("Flooding packet {} to {}".format( 37 | packet, intf.name)) 38 | net.send_packet(intf, packet) 39 | out_num+=1 40 | log_info("in:{} out:{}".format(in_num, out_num)) 41 | net.shutdown() 42 | -------------------------------------------------------------------------------- /switchyard-master/examples/readpkt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ''' 3 | Simple program that reads contents of a tcpdump tracefile 4 | and prints packets to stdout. 5 | ''' 6 | 7 | import sys 8 | from switchyard.pcapffi import * 9 | from switchyard.lib.packet import * 10 | 11 | files = ['sydump.pcap'] 12 | if len(sys.argv) > 1: 13 | files = sys.argv[1:] 14 | 15 | for infile in files: 16 | print("Opening {}.".format(infile)) 17 | reader = PcapReader(infile) 18 | count = 0 19 | while True: 20 | pkt = reader.recv_packet() 21 | if pkt is None: 22 | break 23 | p = Packet(raw=pkt.raw) 24 | print (p) 25 | count += 1 26 | print ("Got {} packets from {}.".format(count, infile)) 27 | reader.close() 28 | -------------------------------------------------------------------------------- /switchyard-master/examples/sendpkt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ''' 3 | Simple program that uses Switchyard libraries to emit a packet 4 | on every interface that can be opened. 5 | ''' 6 | 7 | from switchyard.lib.userlib import * 8 | 9 | def main(net): 10 | my_interfaces = net.interfaces() 11 | 12 | eth = Ethernet(dst='ff:ff:ff:ff:ff:ff') 13 | ip = IPv4(dst='192.168.100.100', ttl=16, protocol=IPProtocol.ICMP) 14 | icmp = ICMP(icmptype=ICMPType.EchoRequest) 15 | icmp.icmpdata.sequence = 1 16 | icmp.icmpdata.identifier = 13 17 | pkt = eth+ip+icmp 18 | for intf in my_interfaces: 19 | eth.src = intf.ethaddr 20 | ip.src = intf.ipaddr 21 | print("Sending {} out {}".format(pkt, intf.name)) 22 | try: 23 | net.send_packet(intf.name, pkt) 24 | except Exception as e: 25 | log_failure("Can't send packet: {}".format(str(e))) 26 | net.shutdown() 27 | -------------------------------------------------------------------------------- /switchyard-master/examples/server_udpstackex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import socket 3 | HOST = '127.0.0.1' 4 | PORT = 10000 5 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 6 | s.bind((HOST, PORT)) 7 | print("Server waiting on port {} for a message to echo back".format(PORT)) 8 | data,addr = s.recvfrom(1024) 9 | print("Received {} from {}".format(repr(data), repr(addr))) 10 | x = s.sendto(data, (addr[0],addr[1])) 11 | s.close() 12 | 13 | -------------------------------------------------------------------------------- /switchyard-master/examples/sniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Packet sniffer in Python 5 | ''' 6 | 7 | from switchyard.lib.userlib import * 8 | 9 | def main(net): 10 | my_interfaces = net.interfaces() 11 | log_info ("My interfaces: {}".format([intf.name for intf in my_interfaces])) 12 | count = 0 13 | while True: 14 | try: 15 | timestamp,dev,packet = net.recv_packet(timeout=1.0) 16 | except NoPackets: 17 | continue 18 | except Shutdown: 19 | return 20 | 21 | log_info("{:.3f}: {} {}".format(timestamp,dev,packet)) 22 | count += 1 23 | 24 | net.shutdown() 25 | print ("Got {} packets.".format(count)) 26 | -------------------------------------------------------------------------------- /switchyard-master/examples/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet pyswitch topology") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PySwitchTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PySwitchTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # server1 34 | # \ 35 | # hub----client 36 | # / 37 | # server2 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('server1', **nodeconfig) 42 | #self.addHost('server2', **nodeconfig) 43 | self.addHost('hub', **nodeconfig) 44 | self.addHost('client', **nodeconfig) 45 | ''' 46 | for node in ['server1','server2','client']: 47 | # all links are 10Mb/s, 100 millisecond prop delay 48 | self.addLink(node, 'hub', bw=10, delay='100ms') 49 | ''' 50 | for node in ['server1','client']: 51 | # all links are 10Mb/s, 100 millisecond prop delay 52 | self.addLink(node, 'hub', bw=10, delay='100ms') 53 | 54 | 55 | 56 | def set_ip(net, node1, node2, ip): 57 | node1 = net.get(node1) 58 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 59 | intf = ilist[0] 60 | intf[0].setIP(ip) 61 | 62 | def reset_macs(net, node, macbase): 63 | ifnum = 1 64 | node_object = net.get(node) 65 | for intf in node_object.intfList(): 66 | node_object.setMAC(macbase.format(ifnum), intf) 67 | ifnum += 1 68 | 69 | for intf in node_object.intfList(): 70 | print node,intf,node_object.MAC(intf) 71 | 72 | def set_route(net, fromnode, prefix, nextnode): 73 | node_object = net.get(fromnode) 74 | ilist = node_object.connectionsTo(net.get(nextnode)) 75 | node_object.setDefaultRoute(ilist[0][0]) 76 | 77 | def setup_addressing(net): 78 | reset_macs(net, 'server1', '10:00:00:00:00:{:02x}') 79 | #reset_macs(net, 'server2', '20:00:00:00:00:{:02x}') 80 | reset_macs(net, 'client', '30:00:00:00:00:{:02x}') 81 | reset_macs(net, 'hub', '40:00:00:00:00:{:02x}') 82 | set_ip(net, 'server1','hub','192.168.100.1/24') 83 | #set_ip(net, 'server2','hub','192.168.100.2/24') 84 | set_ip(net, 'client','hub','192.168.100.3/24') 85 | 86 | def disable_ipv6(net): 87 | for v in net.values(): 88 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 89 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 90 | 91 | def main(): 92 | topo = PySwitchTopo(args) 93 | net = Mininet(controller=None, topo=topo, link=TCLink, cleanup=True) 94 | setup_addressing(net) 95 | disable_ipv6(net) 96 | net.interact() 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /switchyard-master/examples/sydump.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ''' 3 | Simple tcpdump-like program that use Switchyard libraries for 4 | reading packets from a local device and dumping them to a file. 5 | ''' 6 | 7 | import sys 8 | from switchyard.pcapffi import * 9 | from switchyard.lib.packet import * 10 | 11 | interface = 'en0' 12 | if len(sys.argv) > 1: 13 | interface = sys.argv[1] 14 | 15 | reader = PcapLiveDevice(interface) 16 | writer = PcapDumper("sydump.pcap") 17 | print("Reading from {}".format(interface)) 18 | count = 0 19 | while True: 20 | pkt = reader.recv_packet(10.0) 21 | if pkt is None: 22 | break 23 | try: 24 | p = Packet(raw=pkt.raw) 25 | print (p) 26 | except Exception as e: 27 | print ("Failed to parse packet: {}".format(e)) 28 | 29 | writer.write_packet(pkt.raw) 30 | count += 1 31 | 32 | print ("Got {} packets".format(count)) 33 | reader.close() 34 | writer.close() 35 | -------------------------------------------------------------------------------- /switchyard-master/examples/udpstack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.userlib import * 4 | 5 | def main(net): 6 | intf = None 7 | 8 | for i in net.interfaces(): 9 | if i.iftype == InterfaceType.Loopback: 10 | intf = i 11 | break 12 | if intf is None: 13 | raise Exception("This example is designed to use the loopback interface but I didn't find one") 14 | 15 | while True: 16 | appdata = None 17 | try: 18 | appdata = ApplicationLayer.recv_from_app(timeout=0.1) 19 | except NoPackets: 20 | pass 21 | except Shutdown: 22 | break 23 | if appdata is not None: 24 | handle_app_data(net, intf, appdata) 25 | 26 | netdata = None 27 | try: 28 | netdata = net.recv_packet(timeout=0.1) 29 | except NoPackets: 30 | pass 31 | except Shutdown: 32 | break 33 | if netdata is not None: 34 | handle_network_data(netdata) 35 | 36 | net.shutdown() 37 | 38 | def handle_app_data(net, intf, appdata): 39 | flowaddr,message = appdata 40 | log_debug("Received data from app layer: <{}>".format(message)) 41 | log_debug("flowaddr: {}".format(flowaddr)) 42 | 43 | proto,srcip,srcport,dstip,dstport = flowaddr 44 | p = Null() + IPv4(protocol=proto, src=intf.ipaddr, dst=dstip, ipid=0xabcd, ttl=64, flags=IPFragmentFlag.DontFragment) + UDP(src=srcport,dst=dstport) + message 45 | 46 | log_debug("Sending {} to {}".format(p, intf.name)) 47 | net.send_packet(intf, p) 48 | 49 | def handle_network_data(netdata): 50 | timestamp, ingress, pkt = netdata 51 | log_debug("On {} received {}".format(ingress, pkt)) 52 | if pkt.has_header(IPv4): 53 | ipidx = pkt.get_header_index(IPv4) 54 | ip = pkt[ipidx] 55 | if pkt[ipidx].protocol == IPProtocol.UDP: 56 | udp = pkt.get_header(UDP) 57 | ApplicationLayer.send_to_app(IPProtocol.UDP, (ip.dst, udp.dst), 58 | (ip.src, udp.src), pkt[-1].data) 59 | elif pkt[ipidx].protocol == IPProtocol.ICMP: 60 | log_info("Received ICMP message: {}".format(pkt[ipidx+1])) 61 | else: 62 | log_info("Received an unexpected packet: {}".format(pkt[1:])) 63 | 64 | -------------------------------------------------------------------------------- /switchyard-master/examples/udpstack_tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from copy import deepcopy 4 | from switchyard.lib.userlib import * 5 | 6 | def udp_stack_tests(): 7 | s = TestScenario("UDP stack test (with pretend localhost)") 8 | s.add_interface('lo0', '00:00:00:00:00:00', '127.0.0.1', iftype=InterfaceType.Loopback) 9 | 10 | p = Null() + \ 11 | IPv4(src='127.0.0.1',dst='127.0.0.1',protocol=IPProtocol.UDP) + \ 12 | UDP(src=65535, dst=10000) + b'Hello stack' 13 | 14 | s.expect(PacketOutputEvent("lo0", p, exact=False, wildcards=[(UDP, 'src')]), "Emit UDP packet") 15 | 16 | reply = deepcopy(p) 17 | reply[1].src,reply[1].dst = reply[1].dst,reply[1].src 18 | reply[2].src,reply[2].dst = reply[2].dst,reply[2].src 19 | 20 | s.expect(PacketInputEvent('lo0', reply, 21 | copyfromlastout=('lo0',UDP,'src',UDP,'dst')), 22 | "Receive UDP packet") 23 | 24 | return s 25 | 26 | scenario = udp_stack_tests() 27 | -------------------------------------------------------------------------------- /switchyard-master/forwarding_table.txt: -------------------------------------------------------------------------------- 1 | 192.168.100.0 255.255.255.0 192.168.100.1 router-eth0 2 | 192.168.200.0 255.255.255.0 192.168.200.1 router-eth1 3 | 10.1.0.0 255.255.0.0 10.1.1.1 router-eth2 4 | -------------------------------------------------------------------------------- /switchyard-master/lab_1/181860077佘帅杰_lab_1.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_1/181860077佘帅杰_lab_1.docx -------------------------------------------------------------------------------- /switchyard-master/lab_1/hubtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.userlib import * 4 | 5 | def mk_pkt(hwsrc, hwdst, ipsrc, ipdst, reply=False): 6 | ether = Ethernet(src=hwsrc, dst=hwdst, ethertype=EtherType.IP) 7 | ippkt = IPv4(src=ipsrc, dst=ipdst, protocol=IPProtocol.ICMP, ttl=32) 8 | icmppkt = ICMP() 9 | if reply: 10 | icmppkt.icmptype = ICMPType.EchoReply 11 | else: 12 | icmppkt.icmptype = ICMPType.EchoRequest 13 | return ether + ippkt + icmppkt 14 | 15 | def hub_tests(): 16 | s = TestScenario("hub tests") 17 | s.add_interface('eth0', '10:00:00:00:00:01') 18 | s.add_interface('eth1', '10:00:00:00:00:02') 19 | s.add_interface('eth2', '10:00:00:00:00:03') 20 | 21 | # test case 1: a frame with broadcast destination should get sent out 22 | # all ports except ingress 23 | testpkt = mk_pkt("30:00:00:00:00:02", "ff:ff:ff:ff:ff:ff", "172.16.42.2", "255.255.255.255") 24 | s.expect(PacketInputEvent("eth1", testpkt, display=Ethernet), "An Ethernet frame with a broadcast destination address should arrive on eth1") 25 | s.expect(PacketOutputEvent("eth0", testpkt, "eth2", testpkt, display=Ethernet), "The Ethernet frame with a broadcast destination address should be forwarded out ports eth0 and eth2") 26 | 27 | # test case 2: a frame with any unicast address except one assigned to hub 28 | # interface should be sent out all ports except ingress 29 | reqpkt = mk_pkt("20:00:00:00:00:01", "30:00:00:00:00:02", '192.168.1.100','172.16.42.2') 30 | s.expect(PacketInputEvent("eth0", reqpkt, display=Ethernet), "An Ethernet frame from 20:00:00:00:00:01 to 30:00:00:00:00:02 should arrive on eth0") 31 | s.expect(PacketOutputEvent("eth1", reqpkt, "eth2", reqpkt, display=Ethernet), "Ethernet frame destined for 30:00:00:00:00:02 should be flooded out eth1 and eth2") 32 | 33 | resppkt = mk_pkt("30:00:00:00:00:02", "20:00:00:00:00:01", '172.16.42.2', '192.168.1.100', reply=True) 34 | s.expect(PacketInputEvent("eth1", resppkt, display=Ethernet), "An Ethernet frame from 30:00:00:00:00:02 to 20:00:00:00:00:01 should arrive on eth1") 35 | s.expect(PacketOutputEvent("eth0", resppkt, "eth2", resppkt, display=Ethernet), "Ethernet frame destined to 20:00:00:00:00:01 should be flooded out eth0 and eth2") 36 | 37 | #mytestcase 38 | testpkt = mk_pkt("20:00:00:00:00:01", "ff:ff:ff:ff:ff:ff", '192.168.1.100', "255.255.255.255") 39 | s.expect(PacketInputEvent("eth0", testpkt, display=Ethernet), "An Ethernet frame with a broadcast destination address should arrive on eth0") 40 | s.expect(PacketOutputEvent("eth1", testpkt, "eth2", testpkt, display=Ethernet), "The Ethernet frame with a broadcast destination address should be forwarded out ports eth1 and eth2") 41 | 42 | # test case 3: a frame with dest address of one of the interfaces should 43 | # result in nothing happening 44 | reqpkt = mk_pkt("20:00:00:00:00:01", "10:00:00:00:00:03", '192.168.1.100','172.16.42.2') 45 | s.expect(PacketInputEvent("eth2", reqpkt, display=Ethernet), "An Ethernet frame should arrive on eth2 with destination address the same as eth2's MAC address") 46 | s.expect(PacketInputTimeoutEvent(1.0), "The hub should not do anything in response to a frame arriving with a destination address referring to the hub itself.") 47 | return s 48 | 49 | scenario = hub_tests() 50 | -------------------------------------------------------------------------------- /switchyard-master/lab_1/lab_1.pcapng: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_1/lab_1.pcapng -------------------------------------------------------------------------------- /switchyard-master/lab_1/myhub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ''' 3 | Ethernet hub in Switchyard. 4 | ''' 5 | from switchyard.lib.userlib import * 6 | 7 | 8 | def main(net): 9 | my_interfaces = net.interfaces() 10 | mymacs = [intf.ethaddr for intf in my_interfaces] 11 | in_num=0 12 | out_num=0 13 | while True: 14 | try: 15 | timestamp, dev, packet = net.recv_packet() 16 | in_num+=1 17 | except NoPackets: 18 | continue 19 | except Shutdown: 20 | return 21 | log_debug("In {} received packet {} on {}".format( 22 | net.name, packet, dev)) 23 | eth = packet.get_header(Ethernet) 24 | if eth is None: 25 | log_info("Received a non-Ethernet packet?!") 26 | continue 27 | 28 | if eth.dst in mymacs: 29 | log_info("Received a packet intended for me") 30 | else: 31 | #print("before loop") 32 | for intf in my_interfaces: 33 | #print("testcase1:",intf.name) 34 | #print("testcase2:",dev) 35 | if dev != intf.name: 36 | log_info("Flooding packet {} to {}".format( 37 | packet, intf.name)) 38 | net.send_packet(intf, packet) 39 | out_num+=1 40 | log_info("in:{} out:{}".format(in_num, out_num)) 41 | net.shutdown() 42 | -------------------------------------------------------------------------------- /switchyard-master/lab_1/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet pyswitch topology") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PySwitchTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PySwitchTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # server1 34 | # \ 35 | # hub----client 36 | # / 37 | # server2 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('server1', **nodeconfig) 42 | #self.addHost('server2', **nodeconfig) 43 | self.addHost('hub', **nodeconfig) 44 | self.addHost('client', **nodeconfig) 45 | ''' 46 | for node in ['server1','server2','client']: 47 | # all links are 10Mb/s, 100 millisecond prop delay 48 | self.addLink(node, 'hub', bw=10, delay='100ms') 49 | ''' 50 | for node in ['server1','client']: 51 | # all links are 10Mb/s, 100 millisecond prop delay 52 | self.addLink(node, 'hub', bw=10, delay='100ms') 53 | 54 | 55 | 56 | def set_ip(net, node1, node2, ip): 57 | node1 = net.get(node1) 58 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 59 | intf = ilist[0] 60 | intf[0].setIP(ip) 61 | 62 | def reset_macs(net, node, macbase): 63 | ifnum = 1 64 | node_object = net.get(node) 65 | for intf in node_object.intfList(): 66 | node_object.setMAC(macbase.format(ifnum), intf) 67 | ifnum += 1 68 | 69 | for intf in node_object.intfList(): 70 | print node,intf,node_object.MAC(intf) 71 | 72 | def set_route(net, fromnode, prefix, nextnode): 73 | node_object = net.get(fromnode) 74 | ilist = node_object.connectionsTo(net.get(nextnode)) 75 | node_object.setDefaultRoute(ilist[0][0]) 76 | 77 | def setup_addressing(net): 78 | reset_macs(net, 'server1', '10:00:00:00:00:{:02x}') 79 | #reset_macs(net, 'server2', '20:00:00:00:00:{:02x}') 80 | reset_macs(net, 'client', '30:00:00:00:00:{:02x}') 81 | reset_macs(net, 'hub', '40:00:00:00:00:{:02x}') 82 | set_ip(net, 'server1','hub','192.168.100.1/24') 83 | #set_ip(net, 'server2','hub','192.168.100.2/24') 84 | set_ip(net, 'client','hub','192.168.100.3/24') 85 | 86 | def disable_ipv6(net): 87 | for v in net.values(): 88 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 89 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 90 | 91 | def main(): 92 | topo = PySwitchTopo(args) 93 | net = Mininet(controller=None, topo=topo, link=TCLink, cleanup=True) 94 | setup_addressing(net) 95 | disable_ipv6(net) 96 | net.interact() 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /switchyard-master/lab_2/181860077佘帅杰_lab_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_2/181860077佘帅杰_lab_2.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_2/myswitch.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Ethernet learning switch in Python. 3 | 4 | Note that this file currently has the code to implement a "hub" 5 | in it, not a learning switch. (I.e., it's currently a switch 6 | that doesn't learn.) 7 | ''' 8 | from switchyard.lib.userlib import * 9 | 10 | def main(net): 11 | boardcast_addr="ff:ff:ff:ff:ff:ff" 12 | my_interfaces = net.interfaces() 13 | mymacs = [intf.ethaddr for intf in my_interfaces] 14 | list_port=[] 15 | list_address=[] 16 | while True: 17 | try: 18 | timestamp,input_port,packet = net.recv_packet() 19 | except NoPackets: 20 | continue 21 | except Shutdown: 22 | return 23 | 24 | print("test info follows") 25 | for i in list_address: 26 | print(i) 27 | for i in list_port: 28 | print(i) 29 | print("test info end") 30 | 31 | log_debug ("In {} received packet {} on {}".format(net.name, packet, input_port)) 32 | 33 | log_info ("In {} received packet {} on {}".format(net.name, packet, input_port)) 34 | 35 | if packet[0].dst in mymacs: 36 | log_debug ("Packet intended for me") 37 | else: 38 | if packet[0].dst == boardcast_addr: 39 | if input_port in list_port: 40 | print("boardcast src port in list") 41 | else: 42 | print("boardcast src port not in list") 43 | list_port.append(input_port) 44 | list_address.append(packet[0].src) 45 | for intf in my_interfaces: 46 | if input_port != intf.name: 47 | log_debug ("Flooding packet {} to {}".format(packet, intf.name)) 48 | net.send_packet(intf.name, packet) 49 | log_info ("boardcast packet from {} to {}".format(input_port, intf.name)) 50 | else: 51 | if input_port in list_port: 52 | print("src port in list") 53 | else: 54 | print("src port not in list") 55 | list_port.append(input_port) 56 | list_address.append(packet[0].src) 57 | index=0 58 | send_flag=0 59 | for address in list_address: 60 | if address==packet[0].dst: 61 | net.send_packet(list_port[index], packet) 62 | log_info ("find port {} of address {}".format(list_port[index],packet[0].dst)) 63 | send_flag=1 64 | break 65 | index+=1 66 | if send_flag!=1: 67 | print("didn't find port") 68 | for intf in my_interfaces: 69 | if input_port != intf.name: 70 | log_debug ("Flooding packet {} to {}".format(packet, intf.name)) 71 | net.send_packet(intf.name, packet) 72 | log_info ("didnt find packet from {} to {}".format(input_port, intf.name)) 73 | 74 | 75 | net.shutdown() -------------------------------------------------------------------------------- /switchyard-master/lab_2/myswitch_to.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Ethernet learning switch in Python. 3 | 4 | Note that this file currently has the code to implement a "hub" 5 | in it, not a learning switch. (I.e., it's currently a switch 6 | that doesn't learn.) 7 | ''' 8 | from switchyard.lib.userlib import * 9 | import time 10 | class info: 11 | def __init__(self,create_times,ports,addresses): 12 | self.create_time=create_times 13 | self.port=ports 14 | self.address=addresses 15 | 16 | def main(net): 17 | boardcast_addr="ff:ff:ff:ff:ff:ff" 18 | my_interfaces = net.interfaces() 19 | mymacs = [intf.ethaddr for intf in my_interfaces] 20 | list_info=[] 21 | while True: 22 | try: 23 | timestamp,input_port,packet = net.recv_packet() 24 | except NoPackets: 25 | continue 26 | except Shutdown: 27 | return 28 | 29 | index=0 30 | while index=10: 33 | del(list_info[index]) 34 | else: 35 | index+=1 36 | 37 | log_debug ("In {} received packet {} on {}".format(net.name, packet, input_port)) 38 | 39 | log_info ("In {} received packet {} on {}".format(net.name, packet, input_port)) 40 | 41 | if packet[0].dst in mymacs: 42 | log_debug ("Packet intended for me") 43 | else: 44 | if packet[0].dst == boardcast_addr: 45 | flag=0 46 | for i in list_info: 47 | if i.address== packet[0].src: 48 | flag=1 49 | if i.port != input_port: 50 | i.port=input_port 51 | i.create_time=time.time() 52 | break 53 | if flag==0: 54 | cur_time=time.time() 55 | temp=info(cur_time,input_port,packet[0].src) 56 | list_info.append(temp) 57 | 58 | for intf in my_interfaces: 59 | if input_port != intf.name: 60 | log_debug ("Flooding packet {} to {}".format(packet, intf.name)) 61 | net.send_packet(intf.name, packet) 62 | log_info ("boardcast packet from {} to {}".format(input_port, intf.name)) 63 | else: 64 | flag=0 65 | for i in list_info: 66 | if i.address== packet[0].src: 67 | flag=1 68 | if i.port != input_port: 69 | i.port=input_port 70 | i.create_time=time.time() 71 | break 72 | if flag==0: 73 | cur_time=time.time() 74 | temp=info(cur_time,input_port,packet[0].src) 75 | list_info.append(temp) 76 | 77 | send_flag=0 78 | for i in list_info: 79 | if i.address==packet[0].dst: 80 | net.send_packet(i.port, packet) 81 | log_info ("find port {} of address {}".format(i.port,packet[0].dst)) 82 | send_flag=1 83 | break 84 | 85 | if send_flag!=1: 86 | print("didn't find port") 87 | for intf in my_interfaces: 88 | if input_port != intf.name: 89 | log_debug ("Flooding packet {} to {}".format(packet, intf.name)) 90 | net.send_packet(intf.name, packet) 91 | log_info ("didnt find packet from {} to {}".format(input_port, intf.name)) 92 | 93 | 94 | net.shutdown() -------------------------------------------------------------------------------- /switchyard-master/lab_2/mytests.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_2/mytests.py -------------------------------------------------------------------------------- /switchyard-master/lab_2/mytests_lru.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_2/mytests_lru.py -------------------------------------------------------------------------------- /switchyard-master/lab_2/mytests_to.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_2/mytests_to.py -------------------------------------------------------------------------------- /switchyard-master/lab_2/mytests_traffic.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_2/mytests_traffic.py -------------------------------------------------------------------------------- /switchyard-master/lab_2/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet pyswitch topology") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PySwitchTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PySwitchTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # server1 34 | # \ 35 | # switch----client 36 | # / 37 | # server2 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('server1', **nodeconfig) 42 | self.addHost('server2', **nodeconfig) 43 | self.addHost('switch', **nodeconfig) 44 | self.addHost('client', **nodeconfig) 45 | for node in ['server1','server2','client']: 46 | # all links are 10Mb/s, 100 millisecond prop delay 47 | self.addLink(node, 'switch', bw=10, delay='100ms') 48 | 49 | 50 | 51 | 52 | 53 | def set_ip(net, node1, node2, ip): 54 | node1 = net.get(node1) 55 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 56 | intf = ilist[0] 57 | intf[0].setIP(ip) 58 | 59 | def reset_macs(net, node, macbase): 60 | ifnum = 1 61 | node_object = net.get(node) 62 | for intf in node_object.intfList(): 63 | node_object.setMAC(macbase.format(ifnum), intf) 64 | ifnum += 1 65 | 66 | for intf in node_object.intfList(): 67 | print node,intf,node_object.MAC(intf) 68 | 69 | def set_route(net, fromnode, prefix, nextnode): 70 | node_object = net.get(fromnode) 71 | ilist = node_object.connectionsTo(net.get(nextnode)) 72 | node_object.setDefaultRoute(ilist[0][0]) 73 | 74 | def setup_addressing(net): 75 | reset_macs(net, 'server1', '10:00:00:00:00:{:02x}') 76 | reset_macs(net, 'server2', '20:00:00:00:00:{:02x}') 77 | reset_macs(net, 'client', '30:00:00:00:00:{:02x}') 78 | reset_macs(net, 'switch', '40:00:00:00:00:{:02x}') 79 | set_ip(net, 'server1','switch','192.168.100.1/24') 80 | set_ip(net, 'server2','switch','192.168.100.2/24') 81 | set_ip(net, 'client','switch','192.168.100.3/24') 82 | 83 | def disable_ipv6(net): 84 | for v in net.values(): 85 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 86 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 87 | 88 | def main(): 89 | topo = PySwitchTopo(args) 90 | net = Mininet(controller=None, topo=topo, link=TCLink, cleanup=True) 91 | setup_addressing(net) 92 | disable_ipv6(net) 93 | net.interact() 94 | 95 | if __name__ == '__main__': 96 | main() 97 | -------------------------------------------------------------------------------- /switchyard-master/lab_2/switchtests_lru.srpy: -------------------------------------------------------------------------------- 1 | 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 -------------------------------------------------------------------------------- /switchyard-master/lab_2/switchtests_to.srpy: -------------------------------------------------------------------------------- 1 | QlpoOTFBWSZTWSGGxYYAAen//////dfa8/0U+6/9wv/v///7/C6xCVdjJWxkhRBgOEjF0AWeALtkAKAAUgyUaaQ0mTUNqPEnoh6mmagzUzSNpNMmQGmRgQAPaoYgYQaeoGhkHqGgBofqj9JEGmI0YjTJpkwmCYmmJiGAgxNMRgJiYCAGjACMEaGQyYRkDTRoBEiQNGgGIxDTQ0aaYg0NGTTIaAaaYhk0ZDIMBMAJkGhpoAGmTQyaEGmI0YjTJpkwmCYmmJiGAgxNMRgJiYCAGjACMEaGQyYRkDTRoAkSIAgNBRiGjU2RMp5T0YmjFPUNA09I9R6gGmm1Mmmgeoeo9JoyepsRpGgBoBoNOALNxgGtlB7yChJe+92rJVLgbNnE1Wnivx2IBdBA0AsaYgvQdcOk5IPVmgyikLuipIkmuWJorU/UkC1CoX3ZTQxpPswdRMDEm8tYtgCpsoSKGtmCBdRh/7x4UxpjDhmN3ewgmqBgdpzkQdtwShQXoJfIkTZjMbVFKDsej6DPQX1vs2qiYasOO5+cFYzzV6RZMi20hkUk5wRTIULz+xRIGTpqni8onKIqtulfTcx1ZqhR3+4Ajnj6I/oLsFoSDwPnINaD0d8gwNQ3rFATmtlbiM+VfLQdcEaPmqsApCTPeZJjTOWNUKF11v+yu/UCOZ/roJG07jz/S6Xp2N4Oi6eyAoUbQgQb/Jb14HAmGzo6yHTQCQhETTwY+Gw4GIwgV6pHaGGGqwAEsosQETwCTbx66l2OIccBgAKU0gxGVijrBdpcDhAWi28I3MRQBZ87tcrzaenUCPcthIu7QflDywiR2zqhAbcdq3RIdikYGCtpcedWsYsfbooQ0XJ77URTTsZpoOdWLADjLC6qFw5QmgcYEeA94BDSoBoiaoNxlSayJMEpWMgLAUs148QuLvUmK+oUy9fM8O2dYaqb/VXwxWm8SUDUYDM7kKN7GqvpJO/pESVyBiIDNn32UuponqzCuJkMkKuVJ4zQOqiWcVpOuJY0jpfTrvx+cLTrD544NoHGDIDfoHhddcYiFpDvBaWE4rtuQwq4bEXgQ7XWB+YpmKkm66bxcwDAwabB6OH8Kgy1HC9oHVjHORt8HM9LqiTk8pnEbJtXHKw4DDlMDi7G3R6mClJOFy9HW9NvkEgg7fX8Qmbx1CDzPD3Q2fxnQvqKJYrSSFNBjVKxZCa4aJo5S6yYNOfTVG64VhUW0nJhvSXnCkgzlQeAJVhx9UH8t3KlIKw2wjdCYfbCW4bwYxVhUHrh3Q7wd8Pvh7AYB7IdkLw8YLw1h+kEsCBtK7XSoIEgG2uBfG4t9kJZvLawFWa9AaquhzlQobTJCUFdGi6jLiSL5IvNwQzm1eRcZ+Slz+7ONssyCsqtM/RplEBYpAdm1EFBjUOv4KmBQ6ai8mDrHBlAnCkyWbrFZRAqBkIx134zQ6rSHZRc5DoC4NjCW1zqcSoHdsO3QldlbUyQXaVjUGtcsIymK3XVbwcLck3bOebSRz5rNq0AZagN9myZq3WlkkI0AabE0SAjcLLxzmjNXjJuy0k369FWQMXilWiVObHkmleHx85lMnktLIMwYEJ43T8n8/reZ3CXIXR16S67EyerfxTr/VIntlQm00wkRXEq/LpnhpYxaw2KhG5sU0haC9YcyBQ34VgZdhXpWBt4WrJtbVRXoirRl3cKLMVeLRZlzlC8KCy0IoH6aXiNt4pI4hglXW4WIb9mA73CdW9S+tr16wxbQMjD3dAaq8yWyFZQLEwuXN0bEwDDfGELSDBSUvaJKT5FIH+WB4BTQNJbf/JgTPlP3JBoOGn7/oNHFdAFTBPqbMa2pGBFrlnhR7fVkEpwQxcwaufGa57/BT7d81OdMEjyYol5DsnHEHQlVAl3PKECAlAEQaZK9aPP5KE+tZTeTW7uFbrVfgpO+AClhB1wVxYFVMjJiynZHPqWAa106CA0iz4p7/d499NqzsUNEN/uQZFpMvGq7WPm9W2WizVnbu51UUcmnVq4NNROyDRTKvhOplpPRmNdMh1VpSifXYfzt/L8A/d6SC8dWC8+xqVHvjjVP8C3Zg7o4uHYUny/R4+A/LTmub2mJ8wgU36mqQHgQI51D/xdyRThQkCGGxYY -------------------------------------------------------------------------------- /switchyard-master/lab_2/switchtests_traffic.srpy: -------------------------------------------------------------------------------- 1 | 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 -------------------------------------------------------------------------------- /switchyard-master/lab_2/switchtopo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet pyswitch topology") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PySwitchTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PySwitchTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # server1 34 | # \ 35 | # switch----client 36 | # / 37 | # server2 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('server1', **nodeconfig) 42 | self.addHost('server2', **nodeconfig) 43 | self.addHost('switch', **nodeconfig) 44 | self.addHost('client', **nodeconfig) 45 | 46 | for node in ['server1','server2','client']: 47 | # all links are 10Mb/s, 100 millisecond prop delay 48 | self.addLink(node, 'switch', bw=10, delay='100ms') 49 | 50 | def set_ip(net, node1, node2, ip): 51 | node1 = net.get(node1) 52 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 53 | intf = ilist[0] 54 | intf[0].setIP(ip) 55 | 56 | def reset_macs(net, node, macbase): 57 | ifnum = 1 58 | node_object = net.get(node) 59 | for intf in node_object.intfList(): 60 | node_object.setMAC(macbase.format(ifnum), intf) 61 | ifnum += 1 62 | 63 | for intf in node_object.intfList(): 64 | print node,intf,node_object.MAC(intf) 65 | 66 | def set_route(net, fromnode, prefix, nextnode): 67 | node_object = net.get(fromnode) 68 | ilist = node_object.connectionsTo(net.get(nextnode)) 69 | node_object.setDefaultRoute(ilist[0][0]) 70 | 71 | def setup_addressing(net): 72 | reset_macs(net, 'server1', '10:00:00:00:00:{:02x}') 73 | reset_macs(net, 'server2', '20:00:00:00:00:{:02x}') 74 | reset_macs(net, 'client', '30:00:00:00:00:{:02x}') 75 | reset_macs(net, 'switch', '40:00:00:00:00:{:02x}') 76 | set_ip(net, 'server1','switch','192.168.100.1/24') 77 | set_ip(net, 'server2','switch','192.168.100.2/24') 78 | set_ip(net, 'client','switch','192.168.100.3/24') 79 | 80 | def disable_ipv6(net): 81 | for v in net.values(): 82 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 83 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 84 | 85 | def main(): 86 | topo = PySwitchTopo(args) 87 | net = Mininet(controller=None, topo=topo, link=TCLink, cleanup=True) 88 | setup_addressing(net) 89 | disable_ipv6(net) 90 | net.interact() 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /switchyard-master/lab_3/181860077佘帅杰_lab_3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_3/181860077佘帅杰_lab_3.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_3/myrouter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Basic IPv4 router (static routing) in Python. 5 | ''' 6 | 7 | import sys 8 | import os 9 | import time 10 | from switchyard.lib.userlib import * 11 | 12 | 13 | 14 | class Router(object): 15 | def __init__(self, net): 16 | self.net = net 17 | # other initialization stuff here 18 | self.interfaces = net.interfaces() 19 | self.ip_list=[intf.ipaddr for intf in self.interfaces] 20 | self.mac_list=[intf.ethaddr for intf in self.interfaces] 21 | self.arp_table={} 22 | 23 | def router_main(self): 24 | ''' 25 | Main method for router; we stay in a loop in this method, receiving 26 | packets until the end of time. 27 | ''' 28 | while True: 29 | gotpkt = True 30 | try: 31 | timestamp,dev,pkt = self.net.recv_packet(timeout=1.0) 32 | except NoPackets: 33 | log_debug("No packets available in recv_packet") 34 | gotpkt = False 35 | except Shutdown: 36 | log_debug("Got shutdown signal") 37 | break 38 | 39 | if gotpkt: 40 | log_debug("Got a packet: {}".format(str(pkt))) 41 | log_info("Got a packet: {}".format(str(pkt))) 42 | arp = pkt.get_header(Arp) 43 | if arp is None: 44 | log_info("Not arp Packet") 45 | else: 46 | log_info("operation kind {}".format(str(arp.operation))) 47 | self.arp_table[arp.senderprotoaddr]=arp.senderhwaddr 48 | if arp.operation == 1: 49 | log_info("recive arp requests") 50 | index=-1 51 | for i in range(len(self.ip_list)): 52 | if self.ip_list[i]==arp.targetprotoaddr: 53 | index=i 54 | break 55 | if index != -1: 56 | log_info("match the packet") 57 | answer=create_ip_arp_reply(self.mac_list[index], arp.senderhwaddr, self.ip_list[index],arp.senderprotoaddr) 58 | self.net.send_packet(dev, answer) 59 | log_info("send answer: {}".format(str(answer))) 60 | else: 61 | log_info("no match") 62 | else: 63 | if arp.operation == 2: 64 | log_info("recive arp reply") 65 | self.arp_table[arp.targetprotoaddr]=arp.targethwaddr 66 | else: 67 | log_info("recive unk arp") 68 | log_info("Table Shown as follows") 69 | for (k,v) in self.arp_table.items(): 70 | print ("%s " % k,v ) 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | def main(net): 80 | ''' 81 | Main entry point for router. Just create Router 82 | object and get it going. 83 | ''' 84 | r = Router(net) 85 | r.router_main() 86 | net.shutdown() 87 | -------------------------------------------------------------------------------- /switchyard-master/lab_3/routertests1.srpy: -------------------------------------------------------------------------------- 1 | QlpoOTFBWSZTWVhrYlAABKV///////Pad/3l6+//uv/v///j1l6AmmsQHUFTBEMBANQx0AS+dSmOtzuOzqruToMlGkwRppNTZTZT0maTT1NN6iMmajEyBk0B6mI0AaMjQNNDQxD1NGg0BoNA02mUGhBT00RT9U/aUzTUj1DQADQaNAA9QAAAAAANNNBoNAAAAAAJTRRMiGgjJkGgDQHqAMho0BoADIAAA0NAaAANBoAABoQYBDRiaAyaYTJpkAGEaNMAmAJhBoZAxMgDAACYmTATATQJFImFTGJNPU2k9INBo0A0ANNDQAAANAAAAAABpoAAD1ALqzbTGGPiEYevZUK1KTPO8aEbh12CNGy0QwwpUbglAYixQ07t34X3EDcnmJyZBasiJIDZFTgEkOf4QiVONCe47rQVrDv2KRFqVrErGuaQCuCjYizTqV4YyUUuogGUoioEzmP1HMSpQYiA0MwYBSsNZRoqCnQacTHATVjXLyyl1A5Ds5g8PwwSI4/RG5Ll8g6SuyTfq/ZLrqWG2qneJ5i/TTImmGoE23WbmqwZeURYALXsC5uCF8PfLMyxBPLdF61e0qKD2RKJjvGcevcZA6vL6qErEZwSla2ymZK+RsqJIZ20KgEmYsy0Q417dwKVsKXHVN61VRmwHmq1gWKOJ6aLGNVm2acoL33rX4moBnpVZdfWUEEgaW1nckJmp2zkxd5iYFmJ8Rslq48z+Vi0HFohGHt3cZESIR2UNg3lU+/htDilABCvmSefF38MyQhyopL3cxIgEx4NEOXeBpVGADGtVgeWhdzLREsOiofLH5j+QJd/VEbKNrG18taTeWckaxIbaarFL4MrA+8rVA9UUj9tsdhTgghZLcEhvsFaeicYMx8ESy+qiMUHHXaYEIOO3YF8Ut3XJsiF5wdBqcOOODjUL2XvMyp3Q8NXFihnYLKsHkxMlKKJTYIFCGdlAcRCYkcViqTS1M5HbmE3V+VgpVEDsJ7ZmItZCKZEwVYhVEKbFQEWdiNt0EWwdsmkiI4U5PAl2CAr2reEImigT+M3Sg1x1riWAQ0NDOMELlwxVkFdIwGXYHsPOWnIQsM7GtQoTRmBYQWOaJ7oYrJqkBC4LxeLwiqMoKEBG9G2CShRAvQ07Dl3Tq8xDWhl9dj4KYeICwU/WswMgsV2Fo+v2e2TuAbJ0RxGNvbvmexbR1JbKVCmsOy3AVwJBAlKlEqWjBUpKrGit0edRO1AckFLpIZt5Vvopy2YhE6lC3sm2iBSAjBhoE63srlFNOhvIrC0MNsNa8EyCyeQBjXAyAqyB93djmOoKBNFNWGOITzmS10urCXJwVJUkqkpaCjE0K3dajIBWpUZKaCYspYxDG1YBAlqtQqmQMtMZGGutGBh45WWIwSGa2QDxPqZrwLIDTzhwer1gVGU06LJO52e7vO9HdrDE89gy3Fi6tOFK1kUQ1IStLaUUOEQJxAogQulxEBgg6DQ0OuI2ViQKXEqU8vG6hcWc0jIy6hMTKFd+QNCMwRTxmNpoJ53cFyRoWA1ozEY+fBZSTJlgPSjFWFXoriuRqMDqMjYMAxEhgciZRVSQyhZNaoB0iqr4hSmGsEaBkwYblurAyTK456zyN1QwlbonenDPhbaGiRwJ4yZoJNbI4b5SK5k5UBEO4jaPOu6jiCgigadTIqMEHToEBCgCINyDXzh0BXXmcLPiNWlg39QUsvsAo/cFdiBp98xNBccoJctEQTMJyF2NiGLRlxsxkIkGaD4gsK57FDZ1b11LZpjqKsJcHDb21MfCJ72BUHsXLukeYaF+utGTJXj7v2qi/yk3SIgY9WmNd7qUa/W1g3YoMvPAvdW8A1vJc1epqyQGQtg1KYpPw9fZy8ynUA1wQLputNx/xdyRThQkFhrYlA= -------------------------------------------------------------------------------- /switchyard-master/lab_3/routertests1full.srpy: -------------------------------------------------------------------------------- 1 | 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 -------------------------------------------------------------------------------- /switchyard-master/lab_4/181860077佘帅杰_lab_4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_4/181860077佘帅杰_lab_4.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_4/forwarding_table.txt: -------------------------------------------------------------------------------- 1 | 172.16.0.0 255.255.0.0 192.168.1.2 router-eth0 2 | 172.16.128.0 255.255.192.0 10.10.0.254 router-eth1 3 | 172.16.64.0 255.255.192.0 10.10.1.254 router-eth1 4 | 10.100.0.0 255.255.0.0 172.16.42.2 router-eth2 -------------------------------------------------------------------------------- /switchyard-master/lab_4/routertests2.srpy: -------------------------------------------------------------------------------- 1 | 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 -------------------------------------------------------------------------------- /switchyard-master/lab_4/routertests2_template.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | from switchyard.lib.userlib import * 5 | 6 | def mk_arpreq(hwsrc, ipsrc, ipdst): 7 | return create_ip_arp_request(hwsrc, ipsrc, ipdst) 8 | 9 | def mk_arpresp(arpreq, hwsrc, arphwsrc=None, arphwdst=None): 10 | if arphwsrc is None: 11 | arphwsrc = hwsrc 12 | if arphwdst is None: 13 | arphwdst = arpreq[1].senderhwaddr 14 | srcip = arpreq[1].targetprotoaddr 15 | targetip = arpreq[1].senderprotoaddr 16 | return create_ip_arp_reply(hwsrc, arphwdst, srcip, targetip) 17 | 18 | def mk_ping(hwsrc, hwdst, ipsrc, ipdst, reply=False, ttl=64): 19 | ether = Ethernet() 20 | ether.src = hwsrc 21 | ether.dst = hwdst 22 | ippkt = IPv4() 23 | ippkt.src = ipsrc 24 | ippkt.dst = ipdst 25 | ippkt.ttl = ttl 26 | ippkt.ipid = 0 27 | icmppkt = ICMP() 28 | if reply: 29 | icmppkt.icmptype = ICMPType.EchoReply 30 | else: 31 | icmppkt.icmptype = ICMPType.EchoRequest 32 | icmppkt.icmpdata.sequence = 42 33 | icmppkt.icmpdata.data = b'stuff!' 34 | 35 | return ether + ippkt + icmppkt 36 | 37 | def write_table(): 38 | table = '''172.16.0.0 255.255.0.0 192.168.1.2 router-eth0 39 | 172.16.128.0 255.255.192.0 10.10.0.254 router-eth1 40 | 172.16.64.0 255.255.192.0 10.10.1.254 router-eth1 41 | 10.100.0.0 255.255.0.0 172.16.42.2 router-eth2 42 | ''' 43 | outfile = open('forwarding_table.txt', 'w') 44 | outfile.write(table) 45 | outfile.close() 46 | 47 | def router_stage2(): 48 | s = TestScenario("Router stage 2 additional test 1") 49 | s.add_interface('router-eth0', '10:00:00:00:00:01', '192.168.1.1', '255.255.255.0') 50 | s.add_interface('router-eth1', '10:00:00:00:00:02', '10.10.0.1', '255.255.0.0') 51 | s.add_interface('router-eth2', '10:00:00:00:00:03', '172.16.42.1', '255.255.255.252') 52 | 53 | otroarp = mk_arpreq("10:00:00:00:00:02", "10.10.0.1", "10.10.1.254") 54 | otroarpresponse = mk_arpresp(otroarp, "11:22:33:44:55:66") 55 | 56 | s.expect(PacketInputEvent("router-eth1", otroarpresponse, display=Arp), 57 | "Router should receive an unsolicited ARP response for 10.10.1.254 on router-eth1 and do nothing at all.") 58 | s.expect(PacketInputTimeoutEvent(0.1), 59 | "Application should try to receive a packet, but then timeout") 60 | return s 61 | 62 | write_table() 63 | scenario = router_stage2() 64 | -------------------------------------------------------------------------------- /switchyard-master/lab_5/181860077佘帅杰_lab_5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_5/181860077佘帅杰_lab_5.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_5/forwarding_table.txt: -------------------------------------------------------------------------------- 1 | 172.16.0.0 255.255.0.0 192.168.1.2 router-eth0 2 | 172.16.128.0 255.255.192.0 10.10.0.254 router-eth1 3 | 172.16.64.0 255.255.192.0 10.10.1.254 router-eth1 4 | 10.100.0.0 255.255.0.0 172.16.42.2 router-eth2 5 | -------------------------------------------------------------------------------- /switchyard-master/lab_5/routertests3.srpy: -------------------------------------------------------------------------------- 1 | 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 -------------------------------------------------------------------------------- /switchyard-master/lab_6/181860077佘帅杰_lab_6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_6/181860077佘帅杰_lab_6.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_6/blastee.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.address import * 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.userlib import * 6 | from threading import * 7 | import time 8 | 9 | def switchy_main(net): 10 | my_interfaces = net.interfaces() 11 | mymacs = [intf.ethaddr for intf in my_interfaces] 12 | file = open("blastee_params.txt") 13 | line = file.readline() 14 | line=line.strip('\n') 15 | d=line.split(" ") 16 | ip=d[1] 17 | num=d[3] 18 | while True: 19 | gotpkt = True 20 | try: 21 | timestamp,dev,pkt = net.recv_packet() 22 | log_debug("Device is {}".format(dev)) 23 | except NoPackets: 24 | log_debug("No packets available in recv_packet") 25 | gotpkt = False 26 | except Shutdown: 27 | log_debug("Got shutdown signal") 28 | break 29 | 30 | if gotpkt: 31 | #log_info("I got a packet from {}".format(dev)) 32 | #log_info("Pkt: {}".format(pkt)) 33 | #seq=int.from_bytes(pkt[3][0:4], byteorder='big', signed=False) 34 | #payload=int.from_bytes(pkt[3][6:14], byteorder='big', signed=False) 35 | #print(seq) 36 | #print(payload) 37 | seq2=pkt[3].to_bytes()[0:4] 38 | payload2=pkt[3].to_bytes()[6:14] 39 | #print(seq2) 40 | #print(payload2) 41 | seq=int.from_bytes(seq2, byteorder='big', signed=False) 42 | payload=int.from_bytes(payload2, byteorder='big', signed=False) 43 | print(seq) 44 | #print(payload) 45 | 46 | pkt = Ethernet() + IPv4() + UDP() 47 | pkt[1].protocol = IPProtocol.UDP 48 | pkt += seq2 49 | pkt += payload2 50 | pkt[Ethernet].src=EthAddr('20:00:00:00:00:01') 51 | pkt[IPv4].src=IPv4Address('192.168.200.1') 52 | pkt[Ethernet].dst=EthAddr('10:00:00:00:00:01') 53 | pkt[IPv4].dst=IPv4Address(ip) 54 | net.send_packet(my_interfaces[0],pkt) 55 | 56 | 57 | net.shutdown() 58 | -------------------------------------------------------------------------------- /switchyard-master/lab_6/blastee_params.txt: -------------------------------------------------------------------------------- 1 | -b 192.168.100.1 -n 100 2 | -------------------------------------------------------------------------------- /switchyard-master/lab_6/blaster_params.txt: -------------------------------------------------------------------------------- 1 | -b 192.168.200.1 -n 100 -l 30 -w 5 -t 300 -r 100 2 | -------------------------------------------------------------------------------- /switchyard-master/lab_6/middlebox.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from switchyard.lib.address import * 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.userlib import * 6 | from threading import * 7 | from random import randint 8 | import time 9 | 10 | def switchy_main(net): 11 | 12 | my_intf = net.interfaces() 13 | mymacs = [intf.ethaddr for intf in my_intf] 14 | myips = [intf.ipaddr for intf in my_intf] 15 | 16 | file = open("middlebox_params.txt") 17 | line = file.readline() 18 | line=line.strip('\n') 19 | d=line.split(" ") 20 | c=float(d[1]) 21 | c*=100 22 | print(c) 23 | while True: 24 | gotpkt = True 25 | try: 26 | timestamp,dev,pkt = net.recv_packet() 27 | log_debug("Device is {}".format(dev)) 28 | except NoPackets: 29 | log_debug("No packets available in recv_packet") 30 | gotpkt = False 31 | except Shutdown: 32 | log_debug("Got shutdown signal") 33 | break 34 | 35 | if gotpkt: 36 | log_debug("I got a packet {}".format(pkt)) 37 | 38 | if dev == "middlebox-eth0": 39 | log_debug("Received from blaster") 40 | ''' 41 | Received data packet 42 | Should I drop it? 43 | If not, modify headers & send to blastee 44 | ''' 45 | temp=randint(1,100) 46 | if temp <= c: 47 | print("Packet drop") 48 | else: 49 | pkt[Ethernet].dst=EthAddr('20:00:00:00:00:01') 50 | seq2=pkt[3].to_bytes()[0:4] 51 | seq3=int.from_bytes(seq2, byteorder='big', signed=False) 52 | net.send_packet("middlebox-eth1", pkt) 53 | print("send pac"," ",seq3) 54 | elif dev == "middlebox-eth1": 55 | log_debug("Received from blastee") 56 | ''' 57 | Received ACK 58 | Modify headers & send to blaster. Not dropping ACK packets! 59 | net.send_packet("middlebox-eth0", pkt) 60 | ''' 61 | pkt[Ethernet].dst=EthAddr('10:00:00:00:00:01') 62 | net.send_packet("middlebox-eth0", pkt) 63 | seq2=pkt[3].to_bytes()[0:4] 64 | seq3=int.from_bytes(seq2, byteorder='big', signed=False) 65 | print("send ACK ",seq3) 66 | else: 67 | log_debug("Oops :))") 68 | 69 | net.shutdown() 70 | -------------------------------------------------------------------------------- /switchyard-master/lab_6/middlebox_params.txt: -------------------------------------------------------------------------------- 1 | -d 0.59 2 | -------------------------------------------------------------------------------- /switchyard-master/lab_6/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet portion of pyrouter") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PyRouterTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PyRouterTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # 33 | # blaster 34 | # \ 35 | # middlebox 36 | # / 37 | # blastee 38 | # 39 | 40 | nodeconfig = {'cpu':-1} 41 | self.addHost('blaster', **nodeconfig) 42 | self.addHost('blastee', **nodeconfig) 43 | self.addHost('middlebox', **nodeconfig) 44 | 45 | linkconfig = { 46 | 'bw': 10, 47 | 'delay': '37.5ms', # Feel free to play with this value to see how it affects the communication 48 | 'loss': 0.0 49 | } 50 | 51 | for node in ['blaster','blastee']: 52 | self.addLink(node, 'middlebox', **linkconfig) 53 | 54 | def set_ip_pair(net, node1, node2, ip1, ip2): 55 | node1 = net.get(node1) 56 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 57 | intf = ilist[0] 58 | intf[0].setIP(ip1) 59 | intf[1].setIP(ip2) 60 | 61 | def reset_macs(net, node, macbase): 62 | ifnum = 1 63 | node_object = net.get(node) 64 | for intf in node_object.intfList(): 65 | node_object.setMAC(macbase.format(ifnum), intf) 66 | ifnum += 1 67 | 68 | for intf in node_object.intfList(): 69 | print node,intf,node_object.MAC(intf) 70 | 71 | def set_route(net, fromnode, prefix, gw): 72 | node_object = net.get(fromnode) 73 | node_object.cmdPrint("route add -net {} gw {}".format(prefix, gw)) 74 | 75 | def setup_addressing(net): 76 | ''' 77 | * reset_macs call sets the MAC address of the nodes in the network 78 | * blaster and blastee has a single port, hence the MAC address ends with :01 79 | * middlebox has two ports, MAC address ends with :01 and :02 respectively, that are connected to the blaster and blastee. 80 | ''' 81 | reset_macs(net, 'blaster', '10:00:00:00:00:{:02x}') 82 | reset_macs(net, 'blastee', '20:00:00:00:00:{:02x}') 83 | reset_macs(net, 'middlebox', '40:00:00:00:00:{:02x}') 84 | ''' 85 | * set_ip_pair call assigns IP addresses of the interfaces 86 | * convention is same as MAC address 87 | * middlebox has two IP addresses: 192.168.100.2 and 192.168.200.2 - connected to blaster and blastee respectively 88 | ''' 89 | set_ip_pair(net, 'blaster','middlebox','192.168.100.1/30','192.168.100.2/30') 90 | set_ip_pair(net, 'blastee','middlebox','192.168.200.1/30','192.168.200.2/30') 91 | set_route(net, 'blaster', '192.168.200.0/24', '192.168.100.2') 92 | set_route(net, 'blastee', '192.168.100.0/24', '192.168.200.2') 93 | 94 | def disable_ipv6(net): 95 | for v in net.values(): 96 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 97 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 98 | 99 | def main(): 100 | topo = PyRouterTopo(args) 101 | net = Mininet(topo=topo, link=TCLink, cleanup=True, controller=None) 102 | setup_addressing(net) 103 | disable_ipv6(net) 104 | net.interact() 105 | 106 | if __name__ == '__main__': 107 | main() 108 | -------------------------------------------------------------------------------- /switchyard-master/lab_7/181860077佘帅杰_lab_7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/lab_7/181860077佘帅杰_lab_7.pdf -------------------------------------------------------------------------------- /switchyard-master/lab_7/firewall_rules.txt: -------------------------------------------------------------------------------- 1 | 2 | # drop everything from an internal subnet which shouldn't be allowed 3 | # to communicate with rest of internet 4 | # rule 1 5 | deny ip src 192.168.42.0/24 dst any 6 | # rule 2 7 | deny ip src any dst 192.168.42.0/24 8 | 9 | # allow traffic to/from an internal web server that should 10 | # be accessible to external hosts 11 | # rule 3 12 | permit tcp src 192.168.13.13 srcport 80 dst any dstport any 13 | # rule 4 14 | permit tcp src any srcport any dst 192.168.13.13 dstport 80 15 | 16 | # allow DNS (udp port 53) traffic in/out of network 17 | # rule 5 18 | permit udp src 192.168.0.0/16 srcport any dst any dstport 53 19 | # rule 6 20 | permit udp src any srcport 53 dst 192.168.0.0/16 dstport any 21 | 22 | # allow internal hosts access to web (tcp ports 80 and 443) 23 | # rate limit http traffic to 100 kB/s (12500 bytes/sec), but 24 | # don't rate limit any encrypted HTTP traffic. 25 | # rule 7 26 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 80 ratelimit 12500 27 | # rule 8 28 | permit tcp src any srcport 80 dst 192.168.0.0/16 dstport any ratelimit 12500 29 | # rule 9 30 | permit tcp src 192.168.0.0/16 srcport any dst any dstport 443 31 | # rule 10 32 | permit tcp src any srcport 443 dst 192.168.0.0/16 dstport any 33 | 34 | # permit, but impair certain traffic flows 35 | # rule 11 36 | permit tcp src 192.168.0.0/24 srcport any dst any dstport 8000 impair 37 | # rule 12 38 | permit tcp src any srcport 8000 dst 192.168.0.0/24 dstport any impair 39 | 40 | # permit, but rate limit icmp to 150 bytes/sec. 41 | # NB: this includes *both* directions! 42 | # rule 13 43 | permit icmp src any dst any ratelimit 150 44 | 45 | # block everything else 46 | # rule 14 47 | deny ip src any dst any 48 | -------------------------------------------------------------------------------- /switchyard-master/lab_7/start_mininet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | 5 | from mininet.topo import Topo 6 | from mininet.net import Mininet 7 | from mininet.log import lg 8 | from mininet.node import CPULimitedHost 9 | from mininet.link import TCLink 10 | from mininet.util import irange, custom, quietRun, dumpNetConnections 11 | from mininet.cli import CLI 12 | 13 | from time import sleep, time 14 | from subprocess import Popen, PIPE 15 | import subprocess 16 | import argparse 17 | import os 18 | 19 | parser = argparse.ArgumentParser(description="Mininet portion of pyrouter") 20 | # no arguments needed as yet :-) 21 | args = parser.parse_args() 22 | lg.setLogLevel('info') 23 | 24 | class PyRouterTopo(Topo): 25 | 26 | def __init__(self, args): 27 | # Add default members to class. 28 | super(PyRouterTopo, self).__init__() 29 | 30 | # Host and link configuration 31 | # 32 | # external----firewall----internal 33 | # 34 | # external refers to the internet outside a given 35 | # enterprise's network. internal refers to the 36 | # enterprise's network. 37 | 38 | self.addHost('external') 39 | self.addHost('internal') 40 | self.addHost('firewall') 41 | 42 | for node in ['internal','external']: 43 | self.addLink(node, 'firewall', bw=1000, delay="10ms") 44 | 45 | def set_ip_pair(net, node1, node2, ip1, ip2): 46 | node1 = net.get(node1) 47 | ilist = node1.connectionsTo(net.get(node2)) # returns list of tuples 48 | intf = ilist[0] 49 | intf[0].setIP(ip1) 50 | intf[1].setIP(ip2) 51 | 52 | def set_ip(net, node, ifname, addr): 53 | node_object = net.get(node) 54 | intf = node_object.intf(ifname) 55 | intf.setIP(addr) 56 | 57 | def reset_macs(net, node, macbase): 58 | ifnum = 1 59 | node_object = net.get(node) 60 | for intf in node_object.intfList(): 61 | if node not in str(intf): 62 | continue # don't set lo or other interfaces 63 | node_object.setMAC(macbase.format(ifnum), intf) 64 | ifnum += 1 65 | 66 | for intf in node_object.intfList(): 67 | print node,intf,node_object.MAC(intf) 68 | 69 | def set_def_route(net, fromnode, gw): 70 | node_object = net.get(fromnode) 71 | node_object.cmdPrint("route add default gw {}".format(gw)) 72 | 73 | def setup_addressing(net): 74 | reset_macs(net, 'internal', '00:00:00:00:01:{:02x}') 75 | reset_macs(net, 'external', '00:00:00:00:10:{:02x}') 76 | reset_macs(net, 'firewall', '00:00:00:00:0b:{:02x}') 77 | 78 | set_ip(net,'internal','internal-eth0','192.168.0.1/24') 79 | set_ip(net,'external','external-eth0','192.168.0.2/24') 80 | 81 | def disable_ipv6(net): 82 | for v in net.values(): 83 | v.cmdPrint('sysctl -w net.ipv6.conf.all.disable_ipv6=1') 84 | v.cmdPrint('sysctl -w net.ipv6.conf.default.disable_ipv6=1') 85 | 86 | def stop_nodegrams(net): 87 | for nname in ['external','internal','firewall']: 88 | n = net.get(nname) 89 | n.cmd("killall python3") 90 | 91 | def main(): 92 | topo = PyRouterTopo(args) 93 | net = Mininet(topo=topo, link=TCLink, cleanup=True, autoSetMacs=True, controller=None) 94 | setup_addressing(net) 95 | disable_ipv6(net) 96 | net.staticArp() 97 | net.interact() 98 | 99 | if __name__ == '__main__': 100 | main() 101 | -------------------------------------------------------------------------------- /switchyard-master/lab_7/www/1.html: -------------------------------------------------------------------------------- 1 | Test file 1 sneaky crackers wuz here! 2 | -------------------------------------------------------------------------------- /switchyard-master/lab_7/www/start_webserver.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # assume we're running this from parent directory (within mininet) 4 | cd www 5 | 6 | # create a couple files for testing 7 | echo ' Test file 1 sneaky crackers wuz here! ' > 1.html 8 | dd if=/dev/zero of=bigfile bs=1k count=100 2>&1 > /dev/null 9 | 10 | if (( $# == 0 )) ; then 11 | port=80 12 | else 13 | port=$1 14 | fi 15 | 16 | python3 -m http.server ${port} & 17 | 18 | -------------------------------------------------------------------------------- /switchyard-master/requirements.txt: -------------------------------------------------------------------------------- 1 | cffi >=1.6.0 2 | colorama >=0.3.3 3 | coverage >=3.7.1 4 | docutils >=0.12 5 | networkx >=1.8.1 6 | matplotlib >=1.5.3 7 | Pygments >=1.6 8 | Sphinx >=1.2.3 9 | psutil >=5.2.0 10 | -------------------------------------------------------------------------------- /switchyard-master/runtests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | export PYTHONPATH=`pwd`/../..:`pwd` 4 | coverage erase 5 | rm -rf htmlcov 6 | 7 | PAT='switchyard/*','switchyard/switch*' 8 | EXCLPAT='*__init__.py','switchyard/sim/*','switchyard/lib/openflow/*' 9 | 10 | for f in tests/*.py 11 | do 12 | # python3 $f 13 | coverage run --source '.,switchyard' --include ${PAT} -a $f 14 | done 15 | 16 | coverage html --include ${PAT} --omit ${EXCLPAT} 17 | coverage report --include ${PAT} --omit ${EXCLPAT} 18 | 19 | -------------------------------------------------------------------------------- /switchyard-master/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | thisversion = '2019.01.01' 4 | 5 | setup(name="switchyard", 6 | version=thisversion, 7 | description="Switchyard is a framework for creating networked systems", 8 | author="Joel Sommers", 9 | author_email="jsommers@colgate.edu", 10 | url="https://github.com/jsommers/switchyard", 11 | keywords=['education', 'networked systems',], 12 | zip_safe=True, 13 | packages=find_packages(), 14 | python_requires='>=3.4', 15 | package_data={ '': ['*.txt', '*.rst'], }, 16 | exclude_package_data={'': ['README.rst','README.md']}, 17 | install_requires=["cffi >=1.10.0","colorama >=0.3.7","networkx >=1.11", "psutil >=5.2.0"], 18 | tests_require=['coverage >=3.7.1'], 19 | entry_points= { 20 | 'console_scripts': [ 'swyard = switchyard.swyard:main' ], 21 | }, 22 | license="This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. http://creativecommons.org/licenses/by-nc-sa/4.0/", 23 | classifiers=[ 24 | "Programming Language :: Python :: 3 :: Only", 25 | "Development Status :: 4 - Beta", 26 | "Topic :: Scientific/Engineering", 27 | "Topic :: Education", 28 | "Topic :: Software Development :: Libraries", 29 | "Topic :: System :: Networking", 30 | "Environment :: Console", 31 | "Intended Audience :: Education", 32 | "Intended Audience :: Science/Research", 33 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 34 | ], 35 | long_description=''' 36 | Switchyard is a library and framework for creating networked systems in Python. It is primarily intended for educational use and supports creating devices from layer 2 (Ethernet) all the way through the application layer. 37 | 38 | Documentation is available at http://jsommers.github.io/switchyard 39 | Documentation is written using the Python Sphinx package; doc sources are 40 | available in the documentation directory. 41 | 42 | The Switchyard software is distributed under terms of the GNU General Public License, version 3. 43 | 44 | Switchyard's documentation is distributed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License: http://creativecommons.org/licenses/by-nc-sa/4.0/. 45 | ''' 46 | ) 47 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/switchyard/__init__.py -------------------------------------------------------------------------------- /switchyard-master/switchyard/importcode.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import importlib 3 | import os 4 | 5 | from .lib.logging import log_failure, log_debug 6 | 7 | def import_or_die(module_name, entrypoint_names): 8 | ''' 9 | Import user code; return reference to usercode function. 10 | 11 | (str) -> function reference 12 | ''' 13 | log_debug("Importing {}".format(module_name)) 14 | module_name = os.path.abspath(module_name) 15 | if module_name.endswith('.py'): 16 | module_name,ext = os.path.splitext(module_name) 17 | modname = os.path.basename(module_name) 18 | dirname = os.path.dirname(module_name) 19 | if dirname and dirname not in sys.path: 20 | sys.path.append(dirname) 21 | 22 | # first, try to reload code 23 | if modname in sys.modules: 24 | user_module = sys.modules.get(modname) 25 | user_module = importlib.reload(user_module) 26 | # if it isn't in sys.modules, load it for the first time, or 27 | # try to. 28 | else: 29 | try: 30 | mypaths = [ x for x in sys.path if ("Cellar" not in x and "packages" not in x)] 31 | # print("Loading {} from {} ({})".format(modname, dirname, mypaths)) 32 | # user_module = importlib.import_module(modname) 33 | user_module = importlib.__import__(modname) 34 | except ImportError as e: 35 | log_failure("Fatal error: couldn't import module (error: {}) while executing {}".format(str(e), modname)) 36 | raise ImportError(e) 37 | 38 | # if there aren't any functions to call into, then the caller 39 | # just wanted the module/code to be imported, and that's it. 40 | if not entrypoint_names: 41 | return 42 | 43 | existing_names = dir(user_module) 44 | for method in entrypoint_names: 45 | if method in existing_names: 46 | return getattr(user_module, method) 47 | 48 | if len(entrypoint_names) > 1: 49 | entrypoints = "one of {}".format(', '.join(entrypoint_names)) 50 | else: 51 | entrypoints = entrypoint_names[0] 52 | raise ImportError("Required entrypoint function or symbol ({}) not found in your code".format(entrypoints)) 53 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/.gitignore: -------------------------------------------------------------------------------- 1 | testpcap.py 2 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/switchyard/lib/__init__.py -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/debugging.py: -------------------------------------------------------------------------------- 1 | # global: use in any timer callbacks 2 | # to decide whether to handle the timer or not. 3 | # if we're in the debugger, just drop it. 4 | 5 | from functools import wraps 6 | import pdb 7 | 8 | in_debugger = False 9 | def disable_timer(): 10 | global in_debugger 11 | in_debugger = True 12 | 13 | 14 | # decorate the "real" debugger entrypoint by 15 | # disabling any SIGALRM invocations -- just ignore 16 | # them if we're going into the debugger 17 | def setup_debugger(f): 18 | @wraps(f) 19 | def wrapper(*args, **kwargs): 20 | disable_timer() 21 | return f(*args, **kwargs) 22 | return wrapper 23 | 24 | @setup_debugger 25 | def debugger(): 26 | '''Invoke the interactive debugger. Can be used anywhere 27 | within a Switchyard program.''' 28 | pdb.Pdb(skip=['switchyard.lib.debugging']).set_trace() 29 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/exceptions.py: -------------------------------------------------------------------------------- 1 | class SwitchyardException(Exception): 2 | def __init__(self, message): 3 | self.message = message 4 | 5 | def __str__(self): 6 | return self.message 7 | 8 | def __repr__(self): 9 | return self.message 10 | 11 | class Shutdown(SwitchyardException): 12 | '''Exception that is raised in user Switchyard program when the 13 | framework is being shut down.''' 14 | def __init__(self, *args): 15 | SwitchyardException.__init__(self, "Framework shutdown") 16 | 17 | 18 | class NoPackets(SwitchyardException): 19 | '''Exception that is raised in user Switchyard program when 20 | the recv_packet() method is called on the net object and there 21 | are no packets available.''' 22 | def __init__(self, *args): 23 | SwitchyardException.__init__(self, "No packets available") 24 | 25 | class NotEnoughDataError(SwitchyardException): 26 | '''Exception that is raised when attempting to build a packet 27 | header object from a bytes object, but there aren't enough bytes 28 | to perform the reconstruction.''' 29 | pass 30 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/logging.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from ..textcolor import * 4 | from .debugging import debugger 5 | 6 | def setup_logging(debug, logfile=None): 7 | ''' 8 | Setup logging format and log level. 9 | ''' 10 | if debug: 11 | level = logging.DEBUG 12 | else: 13 | level = logging.INFO 14 | if logfile is not None: 15 | logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=level, filename=logfile) 16 | else: 17 | logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=level) 18 | 19 | def log_failure(s): 20 | '''Convenience function for failure message.''' 21 | with red(): 22 | logging.fatal("{}".format(s)) 23 | 24 | def log_debug(s): 25 | '''Convenience function for debugging message.''' 26 | logging.debug("{}".format(s)) 27 | 28 | def log_warn(s): 29 | '''Convenience function for warning message.''' 30 | with magenta(): 31 | logging.warning("{}".format(s)) 32 | 33 | def log_info(s): 34 | '''Convenience function for info message.''' 35 | logging.info("{}".format(s)) 36 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/openflow/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/switchyard/lib/openflow/__init__.py -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/packet/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/packet/__init__.py: -------------------------------------------------------------------------------- 1 | from .packet import * 2 | from .common import * 3 | 4 | from .ethernet import * 5 | from .arp import * 6 | 7 | from .ipv4 import * 8 | from .ipv6 import * 9 | from .icmpv6 import * 10 | 11 | from .udp import * 12 | from .tcp import * 13 | from .icmp import * 14 | 15 | from .ripv2 import * 16 | 17 | from .util import * 18 | 19 | from .null import * 20 | 21 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/packet/null.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import socket 3 | 4 | from .packet import PacketHeaderBase,Packet 5 | from .ipv4 import IPv4 6 | from .ipv6 import IPv6 7 | from ..exceptions import * 8 | 9 | AFTypeClasses = { 10 | socket.AF_INET: IPv4, 11 | socket.AF_INET6: IPv6 12 | } 13 | 14 | AFTypeNames = { 15 | socket.AF_INET: "AF_INET", 16 | socket.AF_INET6: "AF_INET6" 17 | } 18 | 19 | class Null(PacketHeaderBase): 20 | __slots__ = ['_af'] 21 | 22 | def __init__(self, af=socket.AF_INET): 23 | self._af = int(af) 24 | super().__init__() 25 | 26 | def size(self): 27 | return 4 28 | 29 | @property 30 | def af(self): 31 | return self._af 32 | 33 | @af.setter 34 | def af(self,value): 35 | self._af = int(value) 36 | 37 | def to_bytes(self): 38 | ''' 39 | Return packed byte representation of the Ethernet header. 40 | ''' 41 | return struct.pack('=I', self._af) 42 | 43 | def from_bytes(self, raw): 44 | '''Return a Null header object reconstructed from raw bytes, or an 45 | Exception if we can't resurrect the packet.''' 46 | if len(raw) < 4: 47 | raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw))) 48 | fields = struct.unpack('=I', raw[:4]) 49 | self._af = fields[0] 50 | return raw[4:] 51 | 52 | def next_header_class(self): 53 | cls = AFTypeClasses.get(self.af, None) 54 | if cls is None: 55 | raise Exception("No mapping from address family {} to a packet header class".format(self.af)) 56 | return cls 57 | 58 | def pre_serialize(self, raw, pkt, i): 59 | pass 60 | 61 | def __eq__(self, other): 62 | return self.af == other.af 63 | 64 | def __str__(self): 65 | return '{}: {}'.format(self.__class__.__name__, AFTypeNames.get(self.af, "?")) 66 | 67 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/packet/udp.py: -------------------------------------------------------------------------------- 1 | import struct 2 | 3 | from .packet import PacketHeaderBase 4 | from .common import checksum 5 | from ..exceptions import * 6 | 7 | ''' 8 | References: 9 | IETF RFC 768 10 | ''' 11 | 12 | # FIXME: checksum is broken for ip6 13 | 14 | class UDP(PacketHeaderBase): 15 | __slots__ = ['_src','_dst','_len','_checksum'] 16 | _PACKFMT = '!HHHH' 17 | _MINLEN = struct.calcsize(_PACKFMT) 18 | _next_header_map = {} 19 | _next_header_class_key = '' 20 | 21 | def __init__(self, **kwargs): 22 | self.src = self.dst = 0 23 | self._len = self.size() 24 | self._checksum = 0 25 | super().__init__(**kwargs) 26 | 27 | def size(self): 28 | return struct.calcsize(UDP._PACKFMT) 29 | 30 | def to_bytes(self): 31 | ''' 32 | Return packed byte representation of the UDP header. 33 | ''' 34 | return struct.pack(UDP._PACKFMT, self._src, self._dst, 35 | self._len, self._checksum) 36 | 37 | def from_bytes(self, raw): 38 | '''Return an Ethernet object reconstructed from raw bytes, or an 39 | Exception if we can't resurrect the packet.''' 40 | if len(raw) < UDP._MINLEN: 41 | raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an UDP object".format(len(raw))) 42 | fields = struct.unpack(UDP._PACKFMT, raw[:UDP._MINLEN]) 43 | self._src = fields[0] 44 | self._dst = fields[1] 45 | self._len = fields[2] 46 | self._checksum = fields[3] 47 | return raw[UDP._MINLEN:] 48 | 49 | def __eq__(self, other): 50 | return self.src == other.src and \ 51 | self.dst == other.dst 52 | 53 | @property 54 | def src(self): 55 | return self._src 56 | 57 | @property 58 | def dst(self): 59 | return self._dst 60 | 61 | @src.setter 62 | def src(self,value): 63 | self._src = value 64 | 65 | @dst.setter 66 | def dst(self,value): 67 | self._dst = value 68 | 69 | @property 70 | def checksum(self): 71 | return self._checksum 72 | 73 | @property 74 | def length(self): 75 | return self._len 76 | 77 | def __str__(self): 78 | return '{} {}->{}'.format(self.__class__.__name__, self.src, self.dst) 79 | 80 | def _compute_checksum_ipv4(self, ip4, xdata): 81 | if ip4 is None: 82 | return 0 83 | xhdr = struct.pack('!IIxBHHHHH', int(ip4.src), int(ip4.dst), 84 | ip4.protocol.value, self._len, 85 | self.src, self.dst, self._len, 0) 86 | return checksum(xhdr + xdata) 87 | 88 | def pre_serialize(self, raw, pkt, i): 89 | self._len = self.size() + len(raw) 90 | # checksum calc currently assumes we're only dealing with ipv4. 91 | # will need to be modified for ipv6 support... 92 | self._checksum = self._compute_checksum_ipv4(pkt.get_header_by_name('IPv4'), raw) 93 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/packet/util.py: -------------------------------------------------------------------------------- 1 | from . import * 2 | 3 | def create_ip_arp_reply(srchw, dsthw, srcip, targetip): 4 | ''' 5 | Create an ARP reply (just change what needs to be changed 6 | from a request) 7 | ''' 8 | pkt = create_ip_arp_request(srchw, srcip, targetip) 9 | pkt[0].dst = dsthw 10 | pkt[1].operation = ArpOperation.Reply 11 | pkt[1].targethwaddr = dsthw 12 | return pkt 13 | 14 | def create_ip_arp_request(srchw, srcip, targetip): 15 | ''' 16 | Create and return a packet containing an Ethernet header 17 | and ARP header. 18 | ''' 19 | ether = Ethernet() 20 | ether.src = srchw 21 | ether.dst = SpecialEthAddr.ETHER_BROADCAST.value 22 | ether.ethertype = EtherType.ARP 23 | arp = Arp() 24 | arp.operation = ArpOperation.Request 25 | arp.senderhwaddr = srchw 26 | arp.senderprotoaddr = srcip 27 | arp.targethwaddr = SpecialEthAddr.ETHER_BROADCAST.value 28 | arp.targetprotoaddr = targetip 29 | return ether + arp 30 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/socket/__init__.py: -------------------------------------------------------------------------------- 1 | from .socketemu import * 2 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/topo/__init__.py: -------------------------------------------------------------------------------- 1 | from .util import * 2 | from .topobuild import * 3 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/lib/userlib.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a wrapper module to facilitate easy import of the various modules, functions, classes, and other items needed from the perspective of a user program in Switchyard. 3 | ''' 4 | from .packet import * 5 | from .address import * 6 | from .exceptions import * 7 | from .logging import log_debug, log_info, log_failure, log_warn 8 | from .interface import Interface, InterfaceType 9 | from .testing import PacketInputEvent, PacketOutputEvent, PacketInputTimeoutEvent, TestScenario 10 | from .debugging import debugger 11 | from .socket.socketemu import ApplicationLayer 12 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/outputfmt.py: -------------------------------------------------------------------------------- 1 | class VerboseOutput(object): 2 | _on = False 3 | 4 | @staticmethod 5 | def enable(): 6 | VerboseOutput._on = True 7 | 8 | @staticmethod 9 | def disable(): 10 | VerboseOutput._on = False 11 | 12 | @staticmethod 13 | def enabled(): 14 | return VerboseOutput._on 15 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/sim/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ricardokevins/NJU_ComputerNetWork/88245a3a7d393d25f13f4e2edc23bb153857c3dd/switchyard-master/switchyard/sim/__init__.py -------------------------------------------------------------------------------- /switchyard-master/switchyard/sim/linkem.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import heapq 3 | from queue import Queue,Empty 4 | import time 5 | 6 | class LinkEmulator(object): 7 | def __init__(self, inqueue): 8 | self.expiryheap = [] 9 | self.inqueue = inqueue 10 | self.__shutdown = False 11 | 12 | def shutdown(self): 13 | self.__shutdown = True 14 | 15 | def run(self): 16 | while not self.__shutdown: 17 | 18 | now = time.time() 19 | while len(self.expiryheap) and self.expiryheap[0][0] <= now: 20 | expiretime,item,outqueue = heapq.heappop(self.expiryheap) 21 | outqueue.put(item) 22 | 23 | if len(self.expiryheap): 24 | expiretime,item,outqueue = self.expiryheap[0] 25 | timeout = expiretime - time.time() 26 | else: 27 | timeout = 0.1 28 | 29 | try: 30 | expiretime,item,outqueue = self.inqueue.get(timeout=timeout) 31 | except Empty: 32 | pass 33 | else: 34 | heapq.heappush(self.expiryheap, (expiretime, item, outqueue)) 35 | 36 | -------------------------------------------------------------------------------- /switchyard-master/switchyard/textcolor.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import atexit 3 | from contextlib import contextmanager 4 | from colorama import init, Fore, Back, Style 5 | 6 | class TextColor(object): 7 | _SETUP=False 8 | 9 | def __init__(self): 10 | raise Exception("Don't instantiate me.") 11 | 12 | @staticmethod 13 | def setup(): 14 | if TextColor._SETUP: 15 | return 16 | if sys.platform == 'win32': 17 | init(strip=True,convert=True,wrap=True) 18 | else: 19 | init() 20 | atexit.register(TextColor.reset) 21 | TextColor._SETUP=True 22 | 23 | @staticmethod 24 | def reset(): 25 | print(Fore.RESET + Back.RESET + Style.RESET_ALL) 26 | 27 | @staticmethod 28 | def green(): 29 | print(Fore.GREEN,end='') 30 | 31 | @staticmethod 32 | def red(): 33 | print(Fore.RED,end='') 34 | 35 | @staticmethod 36 | def blue(): 37 | print(Fore.BLUE,end='') 38 | 39 | @staticmethod 40 | def cyan(): 41 | print(Fore.CYAN,end='') 42 | 43 | @staticmethod 44 | def magenta(): 45 | print(Fore.MAGENTA,end='') 46 | 47 | @staticmethod 48 | def yellow(): 49 | print(Fore.YELLOW,end='') 50 | 51 | TextColor.setup() 52 | 53 | 54 | @contextmanager 55 | def red(): 56 | TextColor.red() 57 | yield 58 | TextColor.reset() 59 | 60 | @contextmanager 61 | def green(): 62 | TextColor.green() 63 | yield 64 | TextColor.reset() 65 | 66 | @contextmanager 67 | def blue(): 68 | TextColor.blue() 69 | yield 70 | TextColor.reset() 71 | 72 | @contextmanager 73 | def cyan(): 74 | TextColor.cyan() 75 | yield 76 | TextColor.reset() 77 | 78 | @contextmanager 79 | def magenta(): 80 | TextColor.magenta() 81 | yield 82 | TextColor.reset() 83 | 84 | @contextmanager 85 | def yellow(): 86 | TextColor.yellow() 87 | yield 88 | TextColor.reset() 89 | 90 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_addr.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | from switchyard.lib.address import * 3 | from ipaddress import AddressValueError 4 | import unittest 5 | 6 | class AddressTests(unittest.TestCase): 7 | def testEthAddr(self): 8 | e = EthAddr() 9 | self.assertEqual(e, SpecialEthAddr.ETHER_ANY.value) 10 | e1 = EthAddr("01-80-C2-00-00-0e") 11 | self.assertTrue(e1.is_bridge_filtered) 12 | e2 = EthAddr("e2-00-00-00-00-00") 13 | self.assertTrue(e2.is_local) 14 | self.assertFalse(e2.is_global) 15 | self.assertEqual(e2.raw, b'\xe2\x00\x00\x00\x00\x00') 16 | self.assertEqual(e2.toRaw(), b'\xe2\x00\x00\x00\x00\x00') 17 | self.assertEqual(e2.packed, b'\xe2\x00\x00\x00\x00\x00') 18 | self.assertEqual(e2.toStr('-'), "e2-00-00-00-00-00") 19 | self.assertEqual(str(e2), "e2:00:00:00:00:00") 20 | self.assertEqual(repr(e2), "EthAddr('e2:00:00:00:00:00')") 21 | self.assertEqual(e2.toTuple(), (0xe2, 0x0, 0x0, 0x0, 0x0, 0x0)) 22 | self.assertTrue(e1 < e2) 23 | 24 | def testSpecialEth(self): 25 | self.assertEqual(SpecialEthAddr.ETHER_ANY.value.raw, b'\x00'*6) 26 | self.assertTrue(SpecialEthAddr.LLDP_MULTICAST.value.is_multicast) 27 | self.assertEqual(str(SpecialEthAddr.PAE_MULTICAST.value), "01:80:c2:00:00:03") 28 | 29 | 30 | def testUtils(self): 31 | mask = IPv4Address("255.255.252.0") 32 | l = netmask_to_cidr(mask) 33 | self.assertEqual(l, 22) 34 | self.assertEqual(mask, cidr_to_netmask(l)) 35 | self.assertEqual(infer_netmask(IPAddr("10.0.0.1")), 8) 36 | self.assertEqual(infer_netmask(IPAddr("192.168.1.24")), 24) 37 | self.assertEqual(infer_netmask(IPAddr("149.43.80.25")), 16) 38 | self.assertEqual(infer_netmask(IPAddr("0.0.0.0")), 0) 39 | self.assertEqual(str(cidr_to_netmask(24)), "255.255.255.0") 40 | addr,netbits = parse_cidr("149.43.80.25/22", allow_host=True) 41 | self.assertEqual(addr, IPv4Address("149.43.80.25")) 42 | self.assertEqual(netbits, 22) 43 | self.assertEqual(netmask_to_cidr("255.255.0.0"), 16) 44 | with self.assertRaises(AddressValueError) as _: 45 | netmask_to_cidr("320.255.255.0") 46 | with self.assertRaises(RuntimeError) as _: 47 | netmask_to_cidr(2**32+1000) 48 | with self.assertRaises(RuntimeError) as _: 49 | parse_cidr("1.2.3.4/40") 50 | with self.assertRaises(RuntimeError) as _: 51 | parse_cidr("1.2.3.4/40") 52 | with self.assertRaises(RuntimeError) as _: 53 | parse_cidr("1.2.3.1/24") 54 | self.assertEqual(parse_cidr('149.43.80.1', infer=False), (IPv4Address("149.43.80.1"), 32)) 55 | self.assertEqual(parse_cidr('149.43.80.0', infer=False), (IPv4Address("149.43.80.0"), 32)) 56 | self.assertEqual(parse_cidr('149.43.80.0', infer=True), (IPv4Address("149.43.80.0"), 32)) 57 | self.assertEqual(parse_cidr('149.43.0.0', infer=True), (IPv4Address("149.43.0.0"), 16)) 58 | self.assertEqual(parse_cidr('149.43.80.0/255.255.252.0'), (IPv4Address("149.43.80.0"), 22)) 59 | self.assertEqual(parse_cidr('149.43.80.1/255.255.252.0', allow_host=True), 60 | (IPv4Address("149.43.80.1"), 22)) 61 | with self.assertRaises(RuntimeError) as _: 62 | parse_cidr('149.43.0.0/255.240.255.254') 63 | self.assertEqual(infer_netmask(IPv4Address("242.0.0.0")), 32) 64 | self.assertEqual(infer_netmask(IPv4Address("224.0.0.0")), 32) 65 | 66 | 67 | if __name__ == '__main__': 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_arp.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | from switchyard.lib.address import EthAddr, IPAddr 3 | import unittest 4 | 5 | class ArpTests(unittest.TestCase): 6 | def testArpRequest(self): 7 | p = create_ip_arp_request("00:00:00:11:22:33", "1.2.3.4", "10.11.12.13") 8 | self.assertEqual(p.num_headers(), 2) 9 | ether = p[0] 10 | arp = p[1] 11 | self.assertEqual(ether.src, "00:00:00:11:22:33") 12 | self.assertEqual(ether.dst, "ff:ff:ff:ff:ff:ff") 13 | self.assertEqual(ether.ethertype, EtherType.ARP) 14 | self.assertEqual(len(ether), 14) 15 | self.assertEqual(arp.operation, ArpOperation.Request) 16 | self.assertEqual(arp.hardwaretype, ArpHwType.Ethernet) 17 | self.assertEqual(arp.protocoltype, EtherType.IP) 18 | self.assertEqual(arp.senderhwaddr, EthAddr("00:00:00:11:22:33")) 19 | self.assertEqual(arp.targethwaddr, EthAddr("ff:ff:ff:ff:ff:ff")) 20 | self.assertEqual(arp.senderprotoaddr, IPv4Address("1.2.3.4")) 21 | self.assertEqual(arp.targetprotoaddr, IPv4Address("10.11.12.13")) 22 | serialized = arp.to_bytes() 23 | other = Arp() 24 | other.from_bytes(serialized) 25 | self.assertEqual(arp, other) 26 | self.assertEqual(len(arp), 28) 27 | with self.assertRaises(Exception): 28 | other.from_bytes(serialized[:-3]) 29 | xbytes = arp.to_bytes() 30 | # inject an invalid arp operation 31 | xbytes = xbytes[:6] + b'\xff\xff' + xbytes[8:] 32 | a = Arp() 33 | with self.assertRaises(Exception): 34 | a.from_bytes(xbytes) 35 | 36 | def testArpReply(self): 37 | p = create_ip_arp_reply("aa:bb:cc:dd:ee:ff", "00:00:00:11:22:33", "10.11.12.13", "1.2.3.4") 38 | self.assertEqual(p.num_headers(), 2) 39 | ether = p[0] 40 | arp = p[1] 41 | self.assertEqual(ether.dst, "00:00:00:11:22:33") 42 | self.assertEqual(ether.src, "aa:bb:cc:dd:ee:ff") 43 | self.assertEqual(ether.ethertype, EtherType.ARP) 44 | self.assertEqual(len(ether), 14) 45 | self.assertEqual(arp.operation, ArpOperation.Reply) 46 | self.assertEqual(arp.hardwaretype, ArpHwType.Ethernet) 47 | self.assertEqual(arp.protocoltype, EtherType.IP) 48 | self.assertEqual(arp.targethwaddr, EthAddr("00:00:00:11:22:33")) 49 | self.assertEqual(arp.senderhwaddr, EthAddr("aa:bb:cc:dd:ee:ff")) 50 | self.assertEqual(arp.targetprotoaddr, IPv4Address("1.2.3.4")) 51 | self.assertEqual(arp.senderprotoaddr, IPv4Address("10.11.12.13")) 52 | serialized = arp.to_bytes() 53 | other = Arp() 54 | other.from_bytes(serialized) 55 | self.assertEqual(arp, other) 56 | self.assertEqual(len(arp), 28) 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_color.py: -------------------------------------------------------------------------------- 1 | from switchyard.textcolor import green, red, blue, \ 2 | cyan, magenta, yellow, TextColor 3 | 4 | import unittest 5 | 6 | class ColorlibTests(unittest.TestCase): 7 | def testContext(self): 8 | print ("These tests need eyes...") 9 | with green(): 10 | print ("This should be green!") 11 | with red(): 12 | print ("This should be red!") 13 | with blue(): 14 | print ("This should be blue!") 15 | with cyan(): 16 | print ("This should be cyan!") 17 | with magenta(): 18 | print ("This should be magenta!") 19 | with yellow(): 20 | print ("This should be yellow!") 21 | print ("This should not be colored") 22 | 23 | def testOther(self): 24 | TextColor.setup() 25 | self.assertTrue(TextColor._SETUP) 26 | with self.assertRaises(Exception): 27 | TextColor() 28 | 29 | 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_ethernet.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | from switchyard.lib.address import EthAddr, IPAddr 3 | import unittest 4 | 5 | class EthernetPacketTests(unittest.TestCase): 6 | def setUp(self): 7 | self.e = Ethernet() 8 | 9 | def testBlankAddrs(self): 10 | self.assertEqual(self.e.src, EthAddr()) 11 | self.assertEqual(self.e.dst, EthAddr()) 12 | 13 | def testSetSrc(self): 14 | astr = '00:00:00:00:00:01' 15 | self.e.src = astr 16 | self.assertEqual(self.e.src, EthAddr(astr)) 17 | 18 | def testSetDst(self): 19 | astr = '00:00:00:00:00:01' 20 | self.e.dst = astr 21 | self.assertEqual(self.e.dst, EthAddr(astr)) 22 | 23 | def testBadSet(self): 24 | with self.assertRaises(Exception): 25 | self.e.xdst = EthAddr() 26 | 27 | def testBadEType(self): 28 | # try to set an invalid ethertype 29 | with self.assertRaises(ValueError): 30 | self.e.ethertype = 0x01 31 | 32 | def testBadAddr(self): 33 | with self.assertRaises(RuntimeError): 34 | x = EthAddr("a") 35 | 36 | def testParse(self): 37 | raw = b'\x01\x02\x03\x04\x05\x06\x06\x05\x04\x03\x02\x01\x08\x00' 38 | astr = '01:02:03:04:05:06' 39 | e = Ethernet() 40 | e.from_bytes(raw) 41 | self.assertEqual(e.dst, EthAddr(astr)) 42 | self.assertEqual(e.src, EthAddr(':'.join(astr.split(':')[::-1]))) 43 | self.assertEqual(e.ethertype, EtherType.IP) 44 | 45 | def testBadParse(self): 46 | raw = b'x\01' 47 | e = Ethernet() 48 | with self.assertRaises(Exception): 49 | e.from_bytes(raw) 50 | 51 | def testVlan(self): 52 | e = Ethernet() 53 | e.src = "00:11:22:33:44:55" 54 | e.dst = "aa:bb:cc:dd:ee:ff" 55 | e.ethertype = EtherType.x8021Q 56 | 57 | v = Vlan() 58 | v.vlanid = 42 59 | v.pcp = 2 60 | v.ethertype = EtherType.IP 61 | 62 | ip = IPv4() 63 | ip.src = "1.2.3.4" 64 | ip.dst = "5.6.7.8" 65 | icmp = ICMP() 66 | 67 | packet = e + v + ip + icmp 68 | self.assertEqual(packet.num_headers(), 4) 69 | self.assertEqual(packet[1].vlanid, 42) 70 | self.assertEqual(packet[1].pcp, 2) 71 | self.assertEqual(len(packet), 46) 72 | serialized = packet.to_bytes() 73 | 74 | other = Packet(raw=serialized) 75 | self.assertEqual(packet, other) 76 | 77 | if __name__ == '__main__': 78 | unittest.main() 79 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_importer.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import sys 3 | import os 4 | import tempfile 5 | import importlib 6 | 7 | import switchyard.importcode as imp 8 | 9 | class TestImporter(unittest.TestCase): 10 | def _writeFile(self, name): 11 | with open(name, "w") as outf: 12 | print("x = 1", file=outf) 13 | print("def fn():", file=outf) 14 | print(" print(x)", file=outf) 15 | 16 | def setUp(self): 17 | importlib.invalidate_caches() 18 | 19 | def testImporter1(self): 20 | name = "firsttest.py" 21 | self._writeFile(name) 22 | mod = imp.import_or_die(name, None) 23 | self.assertIsNone(mod) 24 | self.assertIn(name[:-3], sys.modules) 25 | os.unlink(name) 26 | 27 | def testImporter1b(self): 28 | name = "firsttwo_partdau.py" 29 | self._writeFile(name) 30 | mod = imp.import_or_die(name[:-3], None) 31 | self.assertIsNone(mod) 32 | self.assertIn(name[:-3], sys.modules) 33 | os.unlink(name) 34 | 35 | def testImporter2(self): 36 | name = "testimp2.py" 37 | self._writeFile(name) 38 | xfn = imp.import_or_die(name, ["fn"]) 39 | self.assertIsNotNone(xfn) 40 | self.assertEqual(xfn.__name__, "fn") 41 | self.assertIn(name[:-3], sys.modules) 42 | os.unlink(name) 43 | 44 | def testImporter3(self): 45 | name = "testimp3.py" 46 | self._writeFile(name) 47 | with self.assertRaises(ImportError): 48 | imp.import_or_die(name, ["ugh"]) 49 | os.unlink(name) 50 | 51 | def testImporter4(self): 52 | name = "testimp4.py" 53 | xfile = os.path.join(tempfile.gettempdir(), name) 54 | self._writeFile(xfile) 55 | xfn = imp.import_or_die(xfile, ["main","blob","fn"]) 56 | self.assertIsNotNone(xfn) 57 | self.assertEqual(xfn.__name__, "fn") 58 | self.assertIn(name[:-3], sys.modules) 59 | os.unlink(xfile) 60 | 61 | def testImporter5(self): 62 | with self.assertLogs() as cm: 63 | with self.assertRaises(ImportError): 64 | imp.import_or_die("/tmp/notafile.py", None) 65 | self.assertIn("couldn't import module", cm.output[0]) 66 | with self.assertLogs() as cm: 67 | with self.assertRaises(ImportError): 68 | imp.import_or_die("nothinghere.py", None) 69 | self.assertIn("couldn't import module", cm.output[0]) 70 | with self.assertLogs() as cm: 71 | with self.assertRaises(ImportError): 72 | imp.import_or_die("nothinghere", None) 73 | self.assertIn("couldn't import module", cm.output[0]) 74 | 75 | 76 | if __name__ == '__main__': 77 | unittest.main() 78 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_null.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from socket import AF_INET, AF_INET6, AF_DECnet 3 | 4 | from switchyard.lib.packet import * 5 | from switchyard.lib.address import EthAddr, IPAddr 6 | 7 | class NullPacketTests(unittest.TestCase): 8 | def testNullInstance(self): 9 | n = Null() 10 | b = n.to_bytes() 11 | self.assertEqual(len(b), 4) 12 | self.assertEqual(len(b), n.size()) 13 | self.assertEqual(b, b'\x02\x00\x00\x00') 14 | 15 | n2 = Null() 16 | self.assertEqual(n, n2) 17 | 18 | self.assertEqual(str(n), "Null: AF_INET") 19 | self.assertIsNone(n2.pre_serialize(None, None, None)) 20 | 21 | def testAf(self): 22 | n = Null() 23 | self.assertEqual(n.af, AF_INET) 24 | n.af = AF_INET6 25 | self.assertEqual(n.af, AF_INET6) 26 | self.assertEqual(n.next_header_class(), IPv6) 27 | n.af = AF_INET 28 | self.assertEqual(n.next_header_class(), IPv4) 29 | 30 | n.af = AF_DECnet 31 | with self.assertRaises(Exception): 32 | n.next_header_class() 33 | 34 | def testFromBytes(self): 35 | n = Null(AF_INET6) 36 | b = n.to_bytes() 37 | 38 | with self.assertRaises(Exception): 39 | n.from_bytes(b'\x00') 40 | 41 | x = n.from_bytes(b'\x02\x00\x00\x00') 42 | n2 = Null(AF_INET) 43 | self.assertEqual(n, n2) 44 | 45 | self.assertEqual(x, b'') 46 | 47 | 48 | if __name__ == '__main__': 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_ofswitch_ext.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ''' 4 | OF switch tests for use with an external controller. 5 | ''' 6 | 7 | import sys 8 | from switchyard.lib.address import * 9 | from switchyard.lib.packet import * 10 | from switchyard.lib.testing import * 11 | from switchyard.lib.openflow import * 12 | 13 | 14 | def mk_pkt(hwsrc, hwdst, ipsrc, ipdst, reply=False): 15 | ether = Ethernet() 16 | ether.src = EthAddr(hwsrc) 17 | ether.dst = EthAddr(hwdst) 18 | ether.ethertype = EtherType.IP 19 | 20 | ippkt = IPv4() 21 | ippkt.src = IPAddr(ipsrc) 22 | ippkt.dst = IPAddr(ipdst) 23 | ippkt.protocol = IPProtocol.ICMP 24 | ippkt.ttl = 32 25 | 26 | icmppkt = ICMP() 27 | if reply: 28 | icmppkt.icmptype = ICMPType.EchoReply 29 | else: 30 | icmppkt.icmptype = ICMPType.EchoRequest 31 | return ether + ippkt + icmppkt 32 | 33 | 34 | def ofswitch_tests(): 35 | s = TestScenario("Openflow Switch Tests") 36 | s.add_interface('eth0', '10:00:00:00:00:01') 37 | s.add_interface('eth1', '10:00:00:00:00:02') 38 | s.add_interface('eth2', '10:00:00:00:00:03') 39 | 40 | # test case 1: a frame with broadcast destination should get sent out 41 | # all ports except ingress 42 | testpkt = mk_pkt( 43 | "30:00:00:00:00:02", "ff:ff:ff:ff:ff:ff", "172.16.42.2", "255.255.255.255") 44 | s.expect(PacketInputEvent("eth1", testpkt, display=Ethernet), 45 | "An Ethernet frame with a broadcast destination address should arrive on eth1") 46 | s.expect(PacketInputTimeoutEvent(timeout=5), description="Wait for events to complete") 47 | s.expect(PacketOutputEvent("eth2", testpkt, "eth0", testpkt, display=Ethernet), 48 | "The Ethernet frame with a broadcast destination address should be forwarded out ports eth0 and eth2") 49 | # test case 2: frame with dest 30:...:02 should be sent out eth 1 (from where bcast frame arrived) 50 | testpkt2 = mk_pkt( 51 | "30:00:00:00:00:03", "30:00:00:00:00:02", "10.0.42.200", "172.16.42.2") 52 | s.expect(PacketInputEvent("eth2", testpkt2, display=Ethernet), 53 | "An Ethernet frame with a destination address 172.16.42.2 should arrive on eth2") 54 | s.expect(PacketInputTimeoutEvent(timeout=5), description="Wait for events to complete") 55 | s.expect(PacketOutputEvent("eth1", testpkt2, display=Ethernet), 56 | "An Ethernet frame with a destination address 172.16.42.2 should be forwarded out port eth1") 57 | s.expect(PacketInputTimeoutEvent(timeout=5), description="Wait for events to complete") 58 | 59 | # test case 3: dest port for 30::03 should have been learned from previous exchange 60 | testpkt3 = mk_pkt( 61 | "30:00:00:00:00:01", "30:00:00:00:00:03", "172.16.42.2", "10.1.13.13") 62 | s.expect(PacketInputEvent("eth0", testpkt3, display=Ethernet), 63 | "An Ethernet frame with a destination address 10.1.13.13 should arrive on eth0") 64 | s.expect(PacketInputTimeoutEvent(timeout=5), description="Wait for events to complete") 65 | s.expect(PacketOutputEvent("eth2", testpkt3, display=Ethernet), 66 | "An Ethernet frame with a destination address 10.1.13.13 should be forwarded out port eth2") 67 | 68 | return s 69 | 70 | 71 | scenario = ofswitch_tests() 72 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_ripv2.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from switchyard.lib.packet import * 4 | from switchyard.lib.address import EthAddr, IPAddr 5 | from switchyard.pcapffi import PcapDumper 6 | 7 | class RIPv2PacketTests(unittest.TestCase): 8 | def testRequest(self): 9 | p = Ethernet() + IPv4() + UDP() + RIPv2() 10 | p[0].src = '00:11:22:33:44:55' 11 | p[0].dst = '55:44:33:22:11:00' 12 | p[1].protocol = IPProtocol.UDP 13 | p[1].src = '192.168.100.42' 14 | p[1].dst = '192.168.100.255' 15 | p[2].src = 5000 16 | p[2].dst = 520 17 | xraw = p.to_bytes() 18 | pkt = Packet(raw=xraw) 19 | pkt[-1] = RIPv2(pkt[-1]) 20 | self.assertEqual(pkt, p) 21 | self.assertEqual(pkt[-1].size(), 4) 22 | 23 | self.assertIn("RIPv2 Request", str(pkt[-1])) 24 | 25 | def testReply(self): 26 | p = Ethernet() + IPv4() + UDP() + RIPv2() 27 | p[0].src = '00:11:22:33:44:55' 28 | p[0].dst = '55:44:33:22:11:00' 29 | p[1].protocol = IPProtocol.UDP 30 | p[1].src = '192.168.100.42' 31 | p[1].dst = '192.168.100.255' 32 | p[2].src = 5000 33 | p[2].dst = 520 34 | p[3].command = RIPCommand.Reply 35 | p[3].append(RIPRouteEntry('192.168.200.0','255.255.255.0','192.168.200.254',4)) 36 | p[3].append(RIPRouteEntry('192.168.100.0','255.255.252.0','192.168.100.254',3)) 37 | xraw = p.to_bytes() 38 | pkt = Packet(raw=xraw) 39 | pkt[-1] = RIPv2(pkt[-1]) 40 | self.assertEqual(pkt, p) 41 | s = str(pkt) 42 | self.assertIn('192.168.200.0/24', s) 43 | self.assertIn('192.168.100.0/22', s) 44 | self.assertEqual(pkt[-1][0].address, IPv4Address('192.168.200.0')) 45 | self.assertEqual(pkt[-1][0].netmask, IPv4Address('255.255.255.0')) 46 | self.assertEqual(pkt.size(), 44) 47 | self.assertEqual(pkt[3].size(), 44) 48 | 49 | pkt[-1][-1] = RIPRouteEntry('192.168.0.0','255.255.0.0','192.168.42.5',15) 50 | s = str(pkt) 51 | self.assertIn('192.168.0.0/16', s) 52 | self.assertNotIn('192.168.100.0/22', s) 53 | with self.assertRaises(ValueError): 54 | pkt[-1].append(1) 55 | with self.assertRaises(ValueError): 56 | pkt[-1][0] = 0 57 | with self.assertRaises(IndexError): 58 | pkt[-1][2] = RIPRouteEntry() 59 | with self.assertRaises(IndexError): 60 | x = pkt[-1][2] 61 | 62 | with self.assertRaises(TypeError): 63 | x = pkt[-1]["a"] 64 | lastentry = pkt[-1][-1] 65 | self.assertEqual(lastentry.address, IPv4Address("192.168.0.0")) 66 | self.assertEqual(lastentry.netmask, IPv4Address("255.255.0.0")) 67 | self.assertEqual(lastentry.nexthop, IPv4Address("192.168.42.5")) 68 | self.assertEqual(lastentry.metric, RIP_INFINITY) 69 | 70 | re = RIPRouteEntry('192.168.100.0','255.255.252.0','192.168.100.254',3) 71 | re2 = RIPRouteEntry.from_bytes(re.to_bytes()) 72 | self.assertEqual(re, re2) 73 | with self.assertRaises(Exception): 74 | re2.from_bytes(re.to_bytes()[:-1]) 75 | 76 | r1 = pkt[-1] 77 | b = r1.to_bytes() 78 | r2 = RIPv2() 79 | with self.assertRaises(Exception): 80 | r2.from_bytes(b[:3]) 81 | 82 | with self.assertLogs() as cm: 83 | b += b'\x11\x22\x33' 84 | r2.from_bytes(b) 85 | self.assertIn("payload isn't of expected size", cm.output[0]) 86 | 87 | with self.assertLogs() as cm: 88 | r2.from_bytes(b[:-9]) 89 | self.assertIn("payload isn't of expected size", cm.output[0]) 90 | 91 | self.assertIsNone(r1.next_header_class()) 92 | 93 | self.assertIn("RIPv2 Reply (2 routes", str(r1)) 94 | 95 | 96 | 97 | if __name__ == '__main__': 98 | unittest.main() 99 | 100 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_rwimg.py: -------------------------------------------------------------------------------- 1 | import os 2 | from switchyard.lib.topo import * 3 | 4 | t = Topology() 5 | h1 = t.addHost() 6 | h2 = t.addHost() 7 | s1 = t.addSwitch() 8 | s2 = t.addSwitch() 9 | t.addLink(h1,s1,1000000,0.1) 10 | t.addLink(h2,s2,1000000,0.1) 11 | t.addLink(s1,s2,1000000,"1 microsec") 12 | 13 | save_to_file(t, 'xtopo.txt') 14 | save_graph(t, 'xtopo.png', showaddrs=False, showintfs=True) 15 | 16 | os.unlink('xtopo.txt') 17 | os.unlink('xtopo.png') 18 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_tcp.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | from switchyard.lib.address import EthAddr, IPAddr, SpecialIPv4Addr 3 | import unittest 4 | 5 | class TCPPacketTests(unittest.TestCase): 6 | def setUp(self): 7 | self.t = TCP() 8 | 9 | def testReconstruct(self): 10 | self.t.ack = 1234 11 | self.t.ack = 5678 12 | self.t.PSH = True 13 | b = self.t.to_bytes() 14 | t2 = TCP() 15 | t2.from_bytes(b) 16 | self.assertEqual(self.t, t2) 17 | self.assertEqual(t2.size(), 20) 18 | self.assertIsNone(self.t.next_header_class()) 19 | 20 | def testFlags(self): 21 | self.assertEqual(self.t.flags, 0) 22 | self.t.SYN = 1 23 | self.t.FIN = True 24 | self.assertTrue(self.t.SYN) 25 | self.assertTrue(self.t.FIN) 26 | 27 | t2 = TCP(src=40, dst=80, seq=19, ack=47, SYN=1, ACK=1) 28 | self.assertIn("SA", str(t2)) 29 | t2.ACK = 0 30 | self.assertNotIn("SA", str(t2)) 31 | self.assertEqual(t2.ACK, 0) 32 | 33 | for f in TCPFlags: 34 | setattr(t2, f.name, 1) 35 | self.assertEqual(getattr(t2, f.name), 1) 36 | setattr(t2, f.name, 0) 37 | self.assertEqual(getattr(t2, f.name), 0) 38 | 39 | for f in TCPFlags: 40 | setattr(t2, f.name, 1) 41 | self.assertEqual(getattr(t2, f.name), 1) 42 | self.assertEqual(len(t2.flagstr), 9) 43 | 44 | def testBadSet(self): 45 | with self.assertRaises(Exception): 46 | self.t.srcport = 55 47 | 48 | def testChecksum(self): 49 | ip = IPv4(protocol=IPProtocol.TCP) 50 | t = TCP(src=40, dst=80, seq=19, ack=47, SYN=1) 51 | self.assertEqual(t.checksum, 0) 52 | p = Ethernet() + ip + t 53 | b = p.to_bytes() 54 | self.assertEqual("TCP 40->80 (S 19:47)", str(t)) 55 | self.assertEqual(t.checksum, 44841) 56 | 57 | with self.assertRaises(Exception): 58 | x = Packet(raw=b[:-2]) 59 | 60 | 61 | if __name__ == '__main__': 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /switchyard-master/tests/test_udp.py: -------------------------------------------------------------------------------- 1 | from switchyard.lib.packet import * 2 | from switchyard.lib.address import EthAddr, IPAddr 3 | import unittest 4 | 5 | class UDPPacketTests(unittest.TestCase): 6 | def testSerialize(self): 7 | ether = Ethernet() 8 | ether.src = '00:00:00:11:22:33' 9 | ether.dst = '11:22:33:00:00:00' 10 | ether.ethertype = EtherType.IP 11 | ippkt = IPv4() 12 | ippkt.src = '1.2.3.4' 13 | ippkt.dst = '4.5.6.7' 14 | ippkt.protocol = IPProtocol.UDP 15 | ippkt.ttl = 37 16 | ippkt.ipid = 0 17 | udppkt = UDP() 18 | udppkt.src = 10000 19 | udppkt.dst = 9999 20 | pkt = ether + ippkt + udppkt + RawPacketContents('hello, world') 21 | b = pkt.to_bytes() 22 | 23 | newpkt = Packet(raw=b) 24 | self.assertEqual(b, newpkt.to_bytes()) 25 | 26 | b = b[:-15] # slice into the udp header 27 | with self.assertRaises(Exception): 28 | newpkt = Packet(raw=b) 29 | 30 | def testChecksum(self): 31 | u = UDP() 32 | self.assertEqual(u.checksum, 0) 33 | 34 | p = IPv4() + u 35 | p[0].protocol = IPProtocol.UDP 36 | b = p.to_bytes() 37 | self.assertEqual(u.checksum, 65502) 38 | u = UDP(src=1234,dst=4567) 39 | u.pre_serialize(b'', Packet(), 0) 40 | self.assertEqual(u.checksum, 0) 41 | 42 | x = b'\x00\x00\xfe\xff\x00\x00' 43 | c = checksum(x, start=0, skip_word=1) 44 | self.assertEqual(c, 65535) 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | --------------------------------------------------------------------------------