-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_tcp_client.py
237 lines (211 loc) · 7.42 KB
/
example_tcp_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import random
import sys
import socket
from enum import Enum
from typing import Iterable
import sockets
from ipv4 import IPv4Packet, IPv4Protocol, IPv4Address, IPV4TOS_NULL, IPv4Flags
from tcp import TCPPacket, TCP_FLAGS_SYN, TCP_FLAGS_ACK, TCP_FLAGS_PSH
def get_ipv4_packets(sock: socket.socket) -> Iterable[IPv4Packet | None]:
"""
Returns an iterable of the IPv4Packets incoming on the socket.
None will be inserted in the iterable if a socket timeout occurs.
"""
def result():
while True:
try:
data, _address = sock.recvfrom(sockets.RECV_SIZE)
yield IPv4Packet.deserialize(data)
except (BlockingIOError, TimeoutError):
yield None
return result()
def get_tcp_packets(
ipv4_packets: Iterable[IPv4Packet | None],
) -> Iterable[tuple[TCPPacket, IPv4Address] | None]:
"""
Returns an iterable of the TCP packets from the ipv4 packets.
If any of the ipv4 packets are None, they are left as-is.
"""
def result():
for ipv4_packet in ipv4_packets:
if ipv4_packet is None:
yield None
elif ipv4_packet.protocol == IPv4Protocol.TCP.value:
try:
yield (TCPPacket.deserialize(ipv4_packet.payload), ipv4_packet.source_address)
except AssertionError:
pass
return result()
WINDOW_SIZE: int = 33280
NUM_TCP_RETRIES: int = 3
TCP_TIMEOUT: float = 1.0 # Seconds
def tcp_roundtrip(
outgoing_pkt: TCPPacket,
source_address: IPv4Address,
peer_address: IPv4Address,
sock: socket.socket,
incoming_packets_on_connection: Iterable[TCPPacket | None],
) -> TCPPacket | None:
"""
Send a TCP packet and return the packet ACKing it.
If no ACK is sent within the timeout period, or a RST is received, return None
"""
for _ in range(NUM_TCP_RETRIES):
sock.sendto(
IPv4Packet.default(
source_address, peer_address, IPv4Protocol.TCP, outgoing_pkt.serialize()
).serialize(),
(str(peer_address), 0),
) # The 0 is ignored.
sock.settimeout(TCP_TIMEOUT)
incoming_pkt: TCPPacket | None = next(
filter(
lambda p: p is None
or (
p.acknowledgment_number
== (outgoing_pkt.sequence_number + len(outgoing_pkt.data) + outgoing_pkt.flags.syn)
% 2**32
)
or p.flags.rst,
incoming_packets_on_connection,
),
)
# Timeout occurred
if incoming_pkt is None:
continue
# Connection reset
if incoming_pkt.flags.rst:
incoming_pkt = None
break
sock.settimeout(None)
return incoming_pkt
def main() -> None:
if len(sys.argv) != 4:
print(
f"Usage: python3 {sys.argv[0]} <source_address> <desination_address> <destination_port>",
file=sys.stderr,
)
print(" source_address: The source address of the outgoing packets.", file=sys.stderr)
print(" destination_address: The desination address of the outgoing packets.")
print(" port: The destination port of the outgoing packets.", file=sys.stderr)
sys.exit(1)
source_address: IPv4Address = IPv4Address(sys.argv[1])
destination_address: IPv4Address = IPv4Address(sys.argv[1])
destination_port: int = int(sys.argv[3])
source_port: int = random.randint(1024, 65535) # If this collides, the client will fail.
sock: socket.socket = sockets.make_ethernet_socket(IPv4Protocol.TCP.value)
syn: TCPPacket = TCPPacket(
source_port,
destination_port, # Destination port
random.randint(0, 2**32 - 1), # Sequence number
0, # Acknowledgment number
0, # Data offset
0, # Reserved
TCP_FLAGS_SYN,
WINDOW_SIZE, # window
0, # checksum
0, # urgent_pointer
[],
b"",
)
syn.fix_padding()
syn.fix_data_offset()
syn.fix_checksum(source_address, destination_address)
sock.sendto(
IPv4Packet.default(
source_address, destination_address, IPv4Protocol.TCP, syn.serialize()
).serialize(),
(str(destination_address), 0),
)
for pkt_and_address in get_tcp_packets(get_ipv4_packets(sock)):
assert pkt_and_address is not None
pkt, address = pkt_and_address
if (
address == destination_address
and pkt.source_port == syn.destination_port
and pkt.destination_port == syn.source_port
):
synack = pkt
break
ack: TCPPacket = TCPPacket(
source_port,
destination_port, # Destination port
synack.acknowledgment_number,
(synack.sequence_number + 1) % 2**32, # Acknowledgment number
0, # Data offset
0, # Reserved
TCP_FLAGS_ACK,
WINDOW_SIZE, # window
0, # checksum
0, # urgent_pointer
[],
b"",
)
ack.fix_padding()
ack.fix_data_offset()
ack.fix_checksum(source_address, destination_address)
sock.sendto(
IPv4Packet.default(
source_address, destination_address, IPv4Protocol.TCP, ack.serialize()
).serialize(),
(str(destination_address), 0),
)
req: TCPPacket = TCPPacket(
source_port,
destination_port, # Destination port
ack.sequence_number,
ack.acknowledgment_number,
0, # Data offset
0, # Reserved
TCP_FLAGS_PSH | TCP_FLAGS_ACK,
WINDOW_SIZE, # window
0, # checksum
0, # urgent_pointer
[],
b"GET / HTTP/1.1\r\n\r\n",
)
req.fix_padding()
req.fix_data_offset()
req.fix_checksum(source_address, destination_address)
sock.sendto(
IPv4Packet.default(
source_address, destination_address, IPv4Protocol.TCP, req.serialize()
).serialize(),
(str(destination_address), 0),
)
for pkt_and_address in get_tcp_packets(get_ipv4_packets(sock)):
assert pkt_and_address is not None
pkt, address = pkt_and_address
if (
address == destination_address
and pkt.source_port == syn.destination_port
and pkt.destination_port == syn.source_port
):
if pkt.flags.fin:
break # Would be better to actually close the connection
sys.stdout.buffer.write(pkt.data)
data_ack: TCPPacket = TCPPacket(
source_port,
destination_port, # Destination port
(req.acknowledgment_number + len(req.data)) % 2**32,
(pkt.sequence_number + len(pkt.data)) % 2**32, # Acknowledgment number
0, # Data offset
0, # Reserved
TCP_FLAGS_ACK,
WINDOW_SIZE, # window
0, # checksum
0, # urgent_pointer
[],
b"",
)
data_ack.fix_padding()
data_ack.fix_data_offset()
data_ack.fix_checksum(source_address, destination_address)
sock.sendto(
IPv4Packet.default(
source_address, destination_address, IPv4Protocol.TCP, data_ack.serialize()
).serialize(),
(str(destination_address), 0),
)
if __name__ == "__main__":
main()