pydiode 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pydiode-0.0.1/.gitignore +3 -0
- pydiode-0.0.1/LICENSE +21 -0
- pydiode-0.0.1/PKG-INFO +61 -0
- pydiode-0.0.1/README.md +47 -0
- pydiode-0.0.1/pyproject.toml +25 -0
- pydiode-0.0.1/src/pydiode/__init__.py +0 -0
- pydiode-0.0.1/src/pydiode/common.py +32 -0
- pydiode-0.0.1/src/pydiode/generator.py +49 -0
- pydiode-0.0.1/src/pydiode/main.py +148 -0
- pydiode-0.0.1/src/pydiode/receive.py +79 -0
- pydiode-0.0.1/src/pydiode/send.py +245 -0
- pydiode-0.0.1/tests/tests.py +82 -0
pydiode-0.0.1/.gitignore
ADDED
pydiode-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Peter Story
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pydiode-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: pydiode
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Transfer data through a unidirectional network (i.e., a data diode)
|
|
5
|
+
Project-URL: Homepage, https://github.com/ClarkuCSCI/pydiode
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/ClarkuCSCI/pydiode/issues
|
|
7
|
+
Author-email: Peter Story <peter.garth.story@gmail.com>
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# pydiode
|
|
16
|
+
|
|
17
|
+
Transfer data through a unidirectional network (i.e., a data diode).
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
Install from PyPI:
|
|
22
|
+
```
|
|
23
|
+
pip install pydiode
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
To install from source, clone the repo then run:
|
|
27
|
+
```
|
|
28
|
+
pip install .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
Documentation:
|
|
34
|
+
```
|
|
35
|
+
pydiode --help
|
|
36
|
+
pydiode send --help
|
|
37
|
+
pydiode receive --help
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Start a receiver on localhost:
|
|
41
|
+
```
|
|
42
|
+
pydiode --debug receive 127.0.0.1
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Send data to the receiver, from localhost to localhost:
|
|
46
|
+
```
|
|
47
|
+
pydiode --debug send 127.0.0.1 127.0.0.1
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Type some information into the receiver. When finished, press enter, then type Control-D to signal the end-of-file. The receiver should print the received information.
|
|
51
|
+
|
|
52
|
+
With debug-level logging, you will see details about each packet sent and received. Omit the `--debug` paramater when sending large amount of data, since debug-level logging incurs significant CPU usage.
|
|
53
|
+
|
|
54
|
+
## Development
|
|
55
|
+
|
|
56
|
+
Run unit tests:
|
|
57
|
+
```
|
|
58
|
+
python -m unittest tests.tests
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Since [the unit tests run on the installed code](https://blog.ionelmc.ro/2014/05/25/python-packaging/), remember to install the latest version of the code before running the unit tests.
|
pydiode-0.0.1/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# pydiode
|
|
2
|
+
|
|
3
|
+
Transfer data through a unidirectional network (i.e., a data diode).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
Install from PyPI:
|
|
8
|
+
```
|
|
9
|
+
pip install pydiode
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
To install from source, clone the repo then run:
|
|
13
|
+
```
|
|
14
|
+
pip install .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Documentation:
|
|
20
|
+
```
|
|
21
|
+
pydiode --help
|
|
22
|
+
pydiode send --help
|
|
23
|
+
pydiode receive --help
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Start a receiver on localhost:
|
|
27
|
+
```
|
|
28
|
+
pydiode --debug receive 127.0.0.1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Send data to the receiver, from localhost to localhost:
|
|
32
|
+
```
|
|
33
|
+
pydiode --debug send 127.0.0.1 127.0.0.1
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Type some information into the receiver. When finished, press enter, then type Control-D to signal the end-of-file. The receiver should print the received information.
|
|
37
|
+
|
|
38
|
+
With debug-level logging, you will see details about each packet sent and received. Omit the `--debug` paramater when sending large amount of data, since debug-level logging incurs significant CPU usage.
|
|
39
|
+
|
|
40
|
+
## Development
|
|
41
|
+
|
|
42
|
+
Run unit tests:
|
|
43
|
+
```
|
|
44
|
+
python -m unittest tests.tests
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Since [the unit tests run on the installed code](https://blog.ionelmc.ro/2014/05/25/python-packaging/), remember to install the latest version of the code before running the unit tests.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pydiode"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Peter Story", email="peter.garth.story@gmail.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "Transfer data through a unidirectional network (i.e., a data diode)"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
"Homepage" = "https://github.com/ClarkuCSCI/pydiode"
|
|
22
|
+
"Bug Tracker" = "https://github.com/ClarkuCSCI/pydiode/issues"
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
pydiode = "pydiode.main:main"
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import struct
|
|
3
|
+
|
|
4
|
+
# How much data will fit in each packet we send?
|
|
5
|
+
# Experimentally, this is the maximum UDP payload I can send on macOS.
|
|
6
|
+
UDP_MAX_BYTES = 9216
|
|
7
|
+
|
|
8
|
+
# Number of bits in a byte
|
|
9
|
+
BYTE = 8
|
|
10
|
+
|
|
11
|
+
# Color, represented as a character: Red, Blue, and blacK (1 byte).
|
|
12
|
+
# Number of packets, represented as an unsigned short (2 bytes)
|
|
13
|
+
# Sequence number, represented as an unsigned short (2 bytes)
|
|
14
|
+
# The payload, represented as an array of bytes
|
|
15
|
+
PACKET_HEADER = struct.Struct("<cHH")
|
|
16
|
+
|
|
17
|
+
# Maximum payload length
|
|
18
|
+
MAX_PAYLOAD = UDP_MAX_BYTES - PACKET_HEADER.size
|
|
19
|
+
|
|
20
|
+
# Whether to log details about each packet sent/received.
|
|
21
|
+
# Only log packet details when debugging, due to CPU overhead.
|
|
22
|
+
LOG_PACKETS = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def log_packet(prefix, data):
|
|
26
|
+
if LOG_PACKETS:
|
|
27
|
+
color, n_packets, seq = PACKET_HEADER.unpack(data[: PACKET_HEADER.size])
|
|
28
|
+
payload_length = len(data) - PACKET_HEADER.size
|
|
29
|
+
logging.debug(
|
|
30
|
+
f"{prefix} <Packet color={color} n_packets={n_packets} "
|
|
31
|
+
f"seq={seq} payload_length={payload_length}>"
|
|
32
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import hashlib
|
|
3
|
+
import random
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def generate_data(byte_count, seed, output):
|
|
7
|
+
"""
|
|
8
|
+
:param byte_count: Number of bytes
|
|
9
|
+
:param seed: Seed used to generate the data
|
|
10
|
+
:param output: Output file name
|
|
11
|
+
:returns: A checksum of the data
|
|
12
|
+
"""
|
|
13
|
+
# It's faster to generate data in chunks, instead of one byte at a time
|
|
14
|
+
WRITE_CHUNK = 1000
|
|
15
|
+
random.seed(seed)
|
|
16
|
+
with open(output, "wb") as f:
|
|
17
|
+
for i in range(int(byte_count / WRITE_CHUNK)):
|
|
18
|
+
f.write(random.randbytes(WRITE_CHUNK))
|
|
19
|
+
f.write(random.randbytes(byte_count % WRITE_CHUNK))
|
|
20
|
+
with open(output, "rb") as f:
|
|
21
|
+
return hashlib.file_digest(f, "sha256").hexdigest()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main():
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
description="Generate a file containing random data."
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"output",
|
|
30
|
+
help="Output file name",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--byte-count",
|
|
34
|
+
help="Number of bytes to generate",
|
|
35
|
+
type=int,
|
|
36
|
+
default=125000,
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--seed",
|
|
40
|
+
help="Random seed for generating data",
|
|
41
|
+
type=int,
|
|
42
|
+
default=random.randint(0, 1000000),
|
|
43
|
+
)
|
|
44
|
+
args = parser.parse_args()
|
|
45
|
+
print(generate_data(args.byte_count, args.seed, args.output))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
if __name__ == "__main__":
|
|
49
|
+
main()
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
import pydiode.common
|
|
6
|
+
from .common import BYTE, MAX_PAYLOAD, PACKET_HEADER, UDP_MAX_BYTES
|
|
7
|
+
from .send import read_data, send_data
|
|
8
|
+
from .receive import AsyncWriter, receive_data
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def async_main():
|
|
12
|
+
parser = argparse.ArgumentParser(
|
|
13
|
+
description="Send and receive data through a data diode via UDP."
|
|
14
|
+
)
|
|
15
|
+
subparsers = parser.add_subparsers(
|
|
16
|
+
help="Whether to run in send or receive mode"
|
|
17
|
+
)
|
|
18
|
+
parser.add_argument(
|
|
19
|
+
"--debug",
|
|
20
|
+
help="Print DEBUG logging",
|
|
21
|
+
action="store_const",
|
|
22
|
+
dest="loglevel",
|
|
23
|
+
const=logging.DEBUG,
|
|
24
|
+
default=logging.WARNING,
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"--verbose",
|
|
28
|
+
help="Print INFO logging",
|
|
29
|
+
action="store_const",
|
|
30
|
+
dest="loglevel",
|
|
31
|
+
const=logging.INFO,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
send_parser = subparsers.add_parser("send", help="Send data")
|
|
35
|
+
send_parser.add_argument(
|
|
36
|
+
"read_ip", help="The IP of the interface data is read from"
|
|
37
|
+
)
|
|
38
|
+
send_parser.add_argument(
|
|
39
|
+
"write_ip",
|
|
40
|
+
help="The IP of the interface data is written to",
|
|
41
|
+
)
|
|
42
|
+
send_parser.add_argument(
|
|
43
|
+
"--port",
|
|
44
|
+
type=int,
|
|
45
|
+
help="Send and receive data using this port",
|
|
46
|
+
default=1234,
|
|
47
|
+
)
|
|
48
|
+
send_parser.add_argument(
|
|
49
|
+
"--max-bitrate",
|
|
50
|
+
type=int,
|
|
51
|
+
help="Maximum number of bits transferred per second",
|
|
52
|
+
default=1000000000,
|
|
53
|
+
)
|
|
54
|
+
send_parser.add_argument(
|
|
55
|
+
"--chunk-duration",
|
|
56
|
+
type=float,
|
|
57
|
+
help="Send each chunk for this many seconds",
|
|
58
|
+
)
|
|
59
|
+
send_parser.add_argument(
|
|
60
|
+
"--chunk-max-packets",
|
|
61
|
+
type=int,
|
|
62
|
+
help="The maximum number of packets a chunk should contain",
|
|
63
|
+
)
|
|
64
|
+
send_parser.add_argument(
|
|
65
|
+
"--redundancy",
|
|
66
|
+
type=int,
|
|
67
|
+
help="How many times to send each chunk",
|
|
68
|
+
default=2,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
receive_parser = subparsers.add_parser("receive", help="Receive data")
|
|
72
|
+
receive_parser.add_argument(
|
|
73
|
+
"read_ip", help="The IP of the interface data is read from"
|
|
74
|
+
)
|
|
75
|
+
receive_parser.add_argument(
|
|
76
|
+
"--port",
|
|
77
|
+
type=int,
|
|
78
|
+
help="Send and receive data using this port",
|
|
79
|
+
default=1234,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
args = parser.parse_args()
|
|
83
|
+
logging.basicConfig(level=args.loglevel)
|
|
84
|
+
# Only log packet details when debugging, due to CPU overhead
|
|
85
|
+
if args.loglevel == logging.DEBUG:
|
|
86
|
+
pydiode.common.LOG_PACKETS = True
|
|
87
|
+
|
|
88
|
+
# If we are sending data
|
|
89
|
+
if "write_ip" in args:
|
|
90
|
+
if args.chunk_duration and args.chunk_max_packets:
|
|
91
|
+
raise ValueError(
|
|
92
|
+
"Supply either --chunk-duration or --chunk-max-packets"
|
|
93
|
+
)
|
|
94
|
+
elif not args.chunk_duration and not args.chunk_max_packets:
|
|
95
|
+
args.chunk_max_packets = 100
|
|
96
|
+
|
|
97
|
+
# Calculate chunk_duration based on chunk_max_packets, or vice versa
|
|
98
|
+
if args.chunk_max_packets:
|
|
99
|
+
# How many seconds do we need to send this many fully loaded
|
|
100
|
+
# packets without exceeding max_bitrate?
|
|
101
|
+
args.chunk_duration = (
|
|
102
|
+
args.chunk_max_packets * UDP_MAX_BYTES * BYTE / args.max_bitrate
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
# How many fully loaded packets can be sent per second without
|
|
106
|
+
# exceeding max_bitrate?
|
|
107
|
+
# TODO Consider whether to account for UDP and IPv4 headers.
|
|
108
|
+
args.chunk_max_packets = (
|
|
109
|
+
args.chunk_duration * args.max_bitrate / BYTE / UDP_MAX_BYTES
|
|
110
|
+
)
|
|
111
|
+
logging.debug(f"chunk_max_packets={args.chunk_max_packets}")
|
|
112
|
+
logging.debug(f"chunk_duration={args.chunk_duration}")
|
|
113
|
+
|
|
114
|
+
# How much data will fit in these packets?
|
|
115
|
+
chunk_max_data_bytes = int(args.chunk_max_packets * MAX_PAYLOAD)
|
|
116
|
+
logging.debug(f"PACKET_HEADER.size={PACKET_HEADER.size}")
|
|
117
|
+
logging.debug(f"MAX_PAYLOAD={MAX_PAYLOAD}")
|
|
118
|
+
logging.debug(f"chunk_max_data_bytes={chunk_max_data_bytes}")
|
|
119
|
+
|
|
120
|
+
# Queue of chunks to be sent
|
|
121
|
+
chunks = []
|
|
122
|
+
# Read and send data concurrently
|
|
123
|
+
await asyncio.gather(
|
|
124
|
+
read_data(chunks, chunk_max_data_bytes, args.chunk_duration),
|
|
125
|
+
send_data(
|
|
126
|
+
chunks,
|
|
127
|
+
args.chunk_duration,
|
|
128
|
+
args.redundancy,
|
|
129
|
+
args.read_ip,
|
|
130
|
+
args.write_ip,
|
|
131
|
+
args.port,
|
|
132
|
+
),
|
|
133
|
+
)
|
|
134
|
+
# If we are receiving data
|
|
135
|
+
else:
|
|
136
|
+
queue = asyncio.Queue()
|
|
137
|
+
writer = AsyncWriter(queue)
|
|
138
|
+
await asyncio.gather(
|
|
139
|
+
receive_data(queue, args.read_ip, args.port), writer.write()
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def main():
|
|
144
|
+
asyncio.run(async_main())
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
main()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from .common import log_packet, PACKET_HEADER
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AsyncWriter:
|
|
9
|
+
def __init__(self, queue):
|
|
10
|
+
self.queue = queue
|
|
11
|
+
# TODO If connected to a terminal, display output immediately
|
|
12
|
+
|
|
13
|
+
async def write(self):
|
|
14
|
+
"""
|
|
15
|
+
Write data asynchronously to STDOUT.
|
|
16
|
+
"""
|
|
17
|
+
while True:
|
|
18
|
+
data = await self.queue.get()
|
|
19
|
+
self.queue.task_done()
|
|
20
|
+
if data is None:
|
|
21
|
+
break
|
|
22
|
+
else:
|
|
23
|
+
await asyncio.get_event_loop().run_in_executor(
|
|
24
|
+
None, sys.stdout.buffer.write, data
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DiodeReceiveProtocol(asyncio.DatagramProtocol):
|
|
29
|
+
def __init__(self, queue, on_con_lost):
|
|
30
|
+
self.queue = queue
|
|
31
|
+
self.on_con_lost = on_con_lost
|
|
32
|
+
# Completed chunks
|
|
33
|
+
self.completed = {b"R": False, b"B": False}
|
|
34
|
+
# Packets for the chunks
|
|
35
|
+
self.packets = {b"R": {}, b"B": {}}
|
|
36
|
+
|
|
37
|
+
def datagram_received(self, data, addr):
|
|
38
|
+
color, n_packets, seq = PACKET_HEADER.unpack(data[: PACKET_HEADER.size])
|
|
39
|
+
log_packet("Received", data)
|
|
40
|
+
# If EOF (blacK) packet
|
|
41
|
+
if color == b"K":
|
|
42
|
+
self.queue.put_nowait(None)
|
|
43
|
+
self.on_con_lost.set_result(True)
|
|
44
|
+
# Is this packet for an incomplete chunk?
|
|
45
|
+
elif not self.completed[color]:
|
|
46
|
+
# Record the payload
|
|
47
|
+
self.packets[color][seq] = data[PACKET_HEADER.size :]
|
|
48
|
+
# Did we complete the chunk?
|
|
49
|
+
if len(self.packets[color]) == n_packets:
|
|
50
|
+
logging.debug(f"Packet completed the {color} chunk")
|
|
51
|
+
# Write each packet to STDOUT
|
|
52
|
+
for seq in range(n_packets):
|
|
53
|
+
self.queue.put_nowait(self.packets[color][seq])
|
|
54
|
+
# Mark this chunk as completed
|
|
55
|
+
self.completed[color] = True
|
|
56
|
+
self.packets[color] = {}
|
|
57
|
+
# Mark the other chunk as incomplete
|
|
58
|
+
other_color = b"B" if color == b"R" else b"R"
|
|
59
|
+
self.completed[other_color] = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
async def receive_data(queue, read_ip, port):
|
|
63
|
+
"""
|
|
64
|
+
Receive chunks over the network.
|
|
65
|
+
|
|
66
|
+
:queue: Store received data onto this queue
|
|
67
|
+
:param read_ip: Listen for data on this IP address
|
|
68
|
+
:param port: Listen for data on this port
|
|
69
|
+
"""
|
|
70
|
+
loop = asyncio.get_running_loop()
|
|
71
|
+
on_con_lost = loop.create_future()
|
|
72
|
+
transport, protocol = await loop.create_datagram_endpoint(
|
|
73
|
+
lambda: DiodeReceiveProtocol(queue, on_con_lost),
|
|
74
|
+
local_addr=(read_ip, port),
|
|
75
|
+
)
|
|
76
|
+
try:
|
|
77
|
+
await on_con_lost
|
|
78
|
+
finally:
|
|
79
|
+
transport.close()
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import stat
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .common import log_packet, MAX_PAYLOAD, PACKET_HEADER
|
|
10
|
+
|
|
11
|
+
# Number of EOF packets to send per chunk duration
|
|
12
|
+
N_EOF = 4
|
|
13
|
+
|
|
14
|
+
# Sleep after sending this many packets
|
|
15
|
+
PACKET_BURST = 10
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Chunk:
|
|
19
|
+
def __init__(self, data):
|
|
20
|
+
self.data = data
|
|
21
|
+
self.n_packets = math.ceil(len(data) / MAX_PAYLOAD)
|
|
22
|
+
|
|
23
|
+
def __iter__(self):
|
|
24
|
+
for i in range(self.n_packets):
|
|
25
|
+
yield self.data[i * MAX_PAYLOAD : ((i + 1) * MAX_PAYLOAD)]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AsyncReader:
|
|
29
|
+
def __init__(self, chunk_max_data_bytes):
|
|
30
|
+
self.chunk_max_data_bytes = chunk_max_data_bytes
|
|
31
|
+
self.regular_file = stat.S_ISREG(os.fstat(sys.stdin.fileno()).st_mode)
|
|
32
|
+
self.stream_reader = None
|
|
33
|
+
|
|
34
|
+
async def read(self):
|
|
35
|
+
"""
|
|
36
|
+
Read data asynchronously from STDIN.
|
|
37
|
+
|
|
38
|
+
:returns: Bytes read from STDIN
|
|
39
|
+
"""
|
|
40
|
+
if self.regular_file:
|
|
41
|
+
# If connected to a regular file, there's no need for a
|
|
42
|
+
# StreamReader: we can quickly read the maximum amount of data for
|
|
43
|
+
# a chunk.
|
|
44
|
+
return await asyncio.get_event_loop().run_in_executor(
|
|
45
|
+
None, sys.stdin.buffer.read, self.chunk_max_data_bytes
|
|
46
|
+
)
|
|
47
|
+
else:
|
|
48
|
+
# If STDIN is a pipe or character device, data may become available
|
|
49
|
+
# incrementally. StreamReader lets us read the input incrementally,
|
|
50
|
+
# instead of waiting for a fixed number of bytes to become
|
|
51
|
+
# available.
|
|
52
|
+
# StreamReader doesn't work (and isn't necessary) with file
|
|
53
|
+
# redirection.
|
|
54
|
+
# https://stackoverflow.com/a/71627449
|
|
55
|
+
if not self.stream_reader:
|
|
56
|
+
loop = asyncio.get_event_loop()
|
|
57
|
+
self.stream_reader = asyncio.StreamReader()
|
|
58
|
+
protocol = asyncio.StreamReaderProtocol(self.stream_reader)
|
|
59
|
+
await loop.connect_read_pipe(lambda: protocol, sys.stdin.buffer)
|
|
60
|
+
# Read up to the maximum amount of data in a chunk
|
|
61
|
+
return await self.stream_reader.read(self.chunk_max_data_bytes)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def append_to_chunks(chunks, data, chunk_max_data_bytes):
|
|
65
|
+
"""
|
|
66
|
+
Append data to the end of the chunks array, filling chunks that have
|
|
67
|
+
space.
|
|
68
|
+
|
|
69
|
+
:param chunks: An array of bytes and bytearrays
|
|
70
|
+
:param data: bytes, to be store in chunks
|
|
71
|
+
:param chunk_max_data_bytes: The maximum number of bytes stored in a chunk.
|
|
72
|
+
We assume the data parameter never exceeds
|
|
73
|
+
this value.
|
|
74
|
+
"""
|
|
75
|
+
# If there are no chunks, or if the last chunk is full
|
|
76
|
+
if (len(chunks) == 0) or (len(chunks[-1]) == chunk_max_data_bytes):
|
|
77
|
+
if len(data) == chunk_max_data_bytes:
|
|
78
|
+
# There's no room for additional data, so immutable suffices
|
|
79
|
+
chunks.append(data)
|
|
80
|
+
else:
|
|
81
|
+
# Append a mutable bytearray, so we can add data later
|
|
82
|
+
chunks.append(bytearray(data))
|
|
83
|
+
# If the last chunk has room for data
|
|
84
|
+
else:
|
|
85
|
+
# How much data can fit in the last chunk?
|
|
86
|
+
remaining_space = chunk_max_data_bytes - len(chunks[-1])
|
|
87
|
+
chunks[-1].extend(data[:remaining_space])
|
|
88
|
+
# If some of the data didn't fit in the last chunk
|
|
89
|
+
if remaining_space < len(data):
|
|
90
|
+
chunks.append(data[remaining_space:])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def read_data(chunks, chunk_max_data_bytes, chunk_duration):
|
|
94
|
+
"""
|
|
95
|
+
Read data from STDIN, and store it into the chunks queue.
|
|
96
|
+
|
|
97
|
+
:param chunks: An array of bytes and bytearrays
|
|
98
|
+
:param chunk_max_data_bytes: The maximum number of bytes stored in a chunk
|
|
99
|
+
:param chunk_duration: Amount of time taken to send each chunk
|
|
100
|
+
"""
|
|
101
|
+
reader = AsyncReader(chunk_max_data_bytes)
|
|
102
|
+
data = await reader.read()
|
|
103
|
+
# Until EOF is encountered
|
|
104
|
+
while data:
|
|
105
|
+
logging.debug(f"Read {len(data)} bytes of data")
|
|
106
|
+
append_to_chunks(chunks, data, chunk_max_data_bytes)
|
|
107
|
+
while len(chunks) > 3:
|
|
108
|
+
# At least the first and second chunks will be full.
|
|
109
|
+
# Wait for chunks to be sent.
|
|
110
|
+
await asyncio.sleep(chunk_duration)
|
|
111
|
+
data = await reader.read()
|
|
112
|
+
# Signal there won't be more data
|
|
113
|
+
chunks.append(None)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class AsyncSleeper:
|
|
117
|
+
def __init__(self, n_sleeps, duration):
|
|
118
|
+
# The number of sleeps we've performed so far
|
|
119
|
+
self.n = 0
|
|
120
|
+
# We will eventually sleep this many times
|
|
121
|
+
self.n_sleeps = n_sleeps
|
|
122
|
+
# Eventually, this much time should pass
|
|
123
|
+
self.duration = duration
|
|
124
|
+
self.start = time.time()
|
|
125
|
+
|
|
126
|
+
async def sleep(self):
|
|
127
|
+
self.n += 1
|
|
128
|
+
if self.n > self.n_sleeps:
|
|
129
|
+
raise IndexError(f"Already slept {self.n_sleeps} times")
|
|
130
|
+
# How much time should elapse from start by the end of this sleep?
|
|
131
|
+
target_elapsed = (self.n / self.n_sleeps) * self.duration
|
|
132
|
+
already_elapsed = time.time() - self.start
|
|
133
|
+
sleep_duration = target_elapsed - already_elapsed
|
|
134
|
+
logging.debug(f"Sleeping {sleep_duration:.5f} seconds")
|
|
135
|
+
await asyncio.sleep(sleep_duration)
|
|
136
|
+
|
|
137
|
+
async def sleep_remainder(self):
|
|
138
|
+
# If we haven't yet slept for the specified number of times, we will
|
|
139
|
+
# perform one big sleep to fill the remaining time
|
|
140
|
+
if self.n < self.n_sleeps:
|
|
141
|
+
# How much time should elapse from start by the end of this sleep?
|
|
142
|
+
already_elapsed = time.time() - self.start
|
|
143
|
+
sleep_duration = self.duration - already_elapsed
|
|
144
|
+
logging.debug(f"Sleeping remaining {sleep_duration:.5f} seconds")
|
|
145
|
+
await asyncio.sleep(sleep_duration)
|
|
146
|
+
# Record that we have met our "sleep quota"
|
|
147
|
+
self.n = self.n_sleeps
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def _send_eof(chunk_duration, transport):
|
|
151
|
+
sleeper = AsyncSleeper(N_EOF, chunk_duration)
|
|
152
|
+
for seq in range(N_EOF):
|
|
153
|
+
data = PACKET_HEADER.pack(b"K", N_EOF, seq)
|
|
154
|
+
transport.sendto(data)
|
|
155
|
+
log_packet("Sent", data)
|
|
156
|
+
await sleeper.sleep()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
async def _send_chunk(chunk, color, redundancy, chunk_duration, transport):
|
|
160
|
+
start = time.time()
|
|
161
|
+
# Wrap the chunk bytes in a helper class
|
|
162
|
+
c = Chunk(chunk)
|
|
163
|
+
# Sleep after sending this many packets to avoid sending large bursts
|
|
164
|
+
packet_burst = min(c.n_packets, PACKET_BURST)
|
|
165
|
+
# Send the data over the network
|
|
166
|
+
logging.debug(f"{c.n_packets} packets needed to send {color} chunk")
|
|
167
|
+
for r in range(redundancy):
|
|
168
|
+
sleeper = AsyncSleeper(
|
|
169
|
+
math.ceil(c.n_packets / packet_burst), chunk_duration
|
|
170
|
+
)
|
|
171
|
+
logging.debug(f"Send iteration {r + 1}/{redundancy}")
|
|
172
|
+
for seq, payload in enumerate(c):
|
|
173
|
+
header = PACKET_HEADER.pack(color, c.n_packets, seq)
|
|
174
|
+
data = header + payload
|
|
175
|
+
transport.sendto(data)
|
|
176
|
+
log_packet("Sent", data)
|
|
177
|
+
# Sleep after "packet_burst" packets have been sent
|
|
178
|
+
if ((seq + 1) % packet_burst) == 0:
|
|
179
|
+
await sleeper.sleep()
|
|
180
|
+
# Sleep for any remaining time (i.e., if the number of packets isn't a
|
|
181
|
+
# multiple of packet_burst)
|
|
182
|
+
await sleeper.sleep_remainder()
|
|
183
|
+
logging.debug(
|
|
184
|
+
f"Sent {color} chunk of length {len(chunk)} "
|
|
185
|
+
f"in {time.time() - start:.5f} seconds"
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class DiodeSendProtocol(asyncio.DatagramProtocol):
|
|
190
|
+
def __init__(self, on_con_lost):
|
|
191
|
+
self.on_con_lost = on_con_lost
|
|
192
|
+
|
|
193
|
+
def connection_lost(self, exc):
|
|
194
|
+
self.on_con_lost.set_result(True)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def send_data(
|
|
198
|
+
chunks, chunk_duration, redundancy, read_ip, write_ip, port
|
|
199
|
+
):
|
|
200
|
+
"""
|
|
201
|
+
Send chunks over the network.
|
|
202
|
+
|
|
203
|
+
:param chunks: An array of bytes and bytearrays
|
|
204
|
+
:param chunk_duration: Amount of time taken to send each chunk
|
|
205
|
+
:param redundancy: How many times to transfer the data
|
|
206
|
+
:param read_ip: Send data to this IP address
|
|
207
|
+
:param write_ip: Send data from this IP address
|
|
208
|
+
:param port: Send data using this port
|
|
209
|
+
"""
|
|
210
|
+
# The current chunk color
|
|
211
|
+
color = b"R"
|
|
212
|
+
|
|
213
|
+
# Open a UDP "connection"
|
|
214
|
+
loop = asyncio.get_event_loop()
|
|
215
|
+
on_con_lost = loop.create_future()
|
|
216
|
+
transport, _ = await loop.create_datagram_endpoint(
|
|
217
|
+
lambda: DiodeSendProtocol(on_con_lost),
|
|
218
|
+
remote_addr=(read_ip, port),
|
|
219
|
+
# Don't specify the send port: the OS will choose an available port
|
|
220
|
+
local_addr=(write_ip, None),
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# Send data until a None chunk is encountered, indicating EOF
|
|
224
|
+
while True:
|
|
225
|
+
if len(chunks) > 0:
|
|
226
|
+
chunk = chunks.pop(0)
|
|
227
|
+
# There will never be more data
|
|
228
|
+
if chunk is None:
|
|
229
|
+
await _send_eof(chunk_duration, transport)
|
|
230
|
+
break
|
|
231
|
+
# We have a chunk of data to send
|
|
232
|
+
else:
|
|
233
|
+
await _send_chunk(
|
|
234
|
+
chunk, color, redundancy, chunk_duration, transport
|
|
235
|
+
)
|
|
236
|
+
# Switch the color
|
|
237
|
+
color = b"B" if color == b"R" else b"R"
|
|
238
|
+
# Wait for more data
|
|
239
|
+
else:
|
|
240
|
+
await asyncio.sleep(chunk_duration)
|
|
241
|
+
|
|
242
|
+
# Close the UDP "connection"
|
|
243
|
+
transport.close()
|
|
244
|
+
# Wait for the buffer to flush before returning
|
|
245
|
+
await on_con_lost
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import tempfile
|
|
5
|
+
import unittest
|
|
6
|
+
|
|
7
|
+
from pydiode.generator import generate_data
|
|
8
|
+
from pydiode.send import append_to_chunks
|
|
9
|
+
|
|
10
|
+
# Number of bytes in a 1 Mbit
|
|
11
|
+
MBIT_BYTES = 125000
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TestPyDiode(unittest.TestCase):
|
|
15
|
+
def test_diode_file_io(self):
|
|
16
|
+
with tempfile.TemporaryDirectory() as tempdir:
|
|
17
|
+
RANDOM_DATA = os.path.join(tempdir, "random_data")
|
|
18
|
+
# Generate 1Mbit of random data
|
|
19
|
+
expected_checksum = generate_data(MBIT_BYTES, 42, RANDOM_DATA)
|
|
20
|
+
# Send the data through localhost
|
|
21
|
+
receive = subprocess.Popen(
|
|
22
|
+
f"pydiode receive 127.0.0.1",
|
|
23
|
+
stdout=subprocess.PIPE,
|
|
24
|
+
shell=True,
|
|
25
|
+
)
|
|
26
|
+
checksum = subprocess.Popen(
|
|
27
|
+
"shasum -a 256",
|
|
28
|
+
stdin=receive.stdout,
|
|
29
|
+
stdout=subprocess.PIPE,
|
|
30
|
+
shell=True,
|
|
31
|
+
)
|
|
32
|
+
send = subprocess.Popen(
|
|
33
|
+
f"pydiode send 127.0.0.1 127.0.0.1 < {RANDOM_DATA}",
|
|
34
|
+
shell=True,
|
|
35
|
+
)
|
|
36
|
+
send.communicate()
|
|
37
|
+
receive.communicate()
|
|
38
|
+
checksum_stdout, _ = checksum.communicate()
|
|
39
|
+
actual_checksum = checksum_stdout.decode("utf-8").split(" ")[0]
|
|
40
|
+
# Check whether the received data matches the sent data
|
|
41
|
+
self.assertEqual(expected_checksum, actual_checksum)
|
|
42
|
+
|
|
43
|
+
def test_diode_pipe_io(self):
|
|
44
|
+
expected_hasher = hashlib.sha256()
|
|
45
|
+
expected_hasher.update(b"Hello\n")
|
|
46
|
+
# Send "Hello" through localhost
|
|
47
|
+
receive = subprocess.Popen(
|
|
48
|
+
f"pydiode receive 127.0.0.1",
|
|
49
|
+
stdout=subprocess.PIPE,
|
|
50
|
+
shell=True,
|
|
51
|
+
)
|
|
52
|
+
send = subprocess.Popen(
|
|
53
|
+
"echo Hello | pydiode send 127.0.0.1 127.0.0.1",
|
|
54
|
+
shell=True,
|
|
55
|
+
)
|
|
56
|
+
send.communicate()
|
|
57
|
+
receive_stdout, _ = receive.communicate()
|
|
58
|
+
actual_hasher = hashlib.sha256()
|
|
59
|
+
actual_hasher.update(receive_stdout)
|
|
60
|
+
# Check whether the received data matches the sent data
|
|
61
|
+
self.assertEqual(expected_hasher.hexdigest(), actual_hasher.hexdigest())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TestChunks(unittest.TestCase):
|
|
65
|
+
def test_empty_chunks(self):
|
|
66
|
+
chunks = []
|
|
67
|
+
append_to_chunks(chunks, b"Hello", 10)
|
|
68
|
+
self.assertEqual([b"Hello"], chunks)
|
|
69
|
+
|
|
70
|
+
def test_full_chunks(self):
|
|
71
|
+
chunks = []
|
|
72
|
+
append_to_chunks(chunks, b"I am full!", 10)
|
|
73
|
+
self.assertEqual([b"I am full!"], chunks)
|
|
74
|
+
append_to_chunks(chunks, b"Hello", 10)
|
|
75
|
+
self.assertEqual([b"I am full!", b"Hello"], chunks)
|
|
76
|
+
|
|
77
|
+
def test_partial_chunks(self):
|
|
78
|
+
chunks = []
|
|
79
|
+
append_to_chunks(chunks, b"Not full", 10)
|
|
80
|
+
self.assertEqual([b"Not full"], chunks)
|
|
81
|
+
append_to_chunks(chunks, b"Hello", 10)
|
|
82
|
+
self.assertEqual([b"Not fullHe", b"llo"], chunks)
|