-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp2c.py
More file actions
234 lines (213 loc) · 8.91 KB
/
p2c.py
File metadata and controls
234 lines (213 loc) · 8.91 KB
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
from random import randint
import os
import platform
import socket
import threading
import time
import argparse
from email.utils import formatdate
from utilities import parse_request
class PeerToClient:
def __init__(self, peer_ip, peer_port=None, rfc_store=None):
self.peer_ip = peer_ip
self.peer_port = peer_port if peer_port else randint(1024, 65535)
self.client_connections = []
self.rfc_store = {str(k): v for k, v in (rfc_store or {}).items()}
self.socket_info = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._shutdown_event = threading.Event()
self.client_threads = []
def add_rfc_file(self, rfc_number, file_path):
self.rfc_store[str(rfc_number)] = file_path
def _find_rfc_path(self, rfc_number):
rnum = str(rfc_number)
path = self.rfc_store.get(rnum)
if path and os.path.isfile(path):
return path
candidates = [
os.path.join('resources', f'{rnum}.txt'),
os.path.join('resources', f'rfc{rnum}.txt'),
os.path.join('rfc_files', f'{rnum}.txt'),
os.path.join('downloads', f'{rnum}.txt'),
]
for c in candidates:
if os.path.isfile(c):
return c
return None
def _response_headers(self, status_code, phrase, extra_headers=None, content_length=0):
headers = []
headers.append(f"P2P-CI/1.0 {status_code} {phrase}\r\n")
headers.append(f"Date: {formatdate(timeval=None, usegmt=True)}\r\n")
headers.append(f"OS: {platform.system()} {platform.release()}\r\n")
if extra_headers:
for k, v in extra_headers.items():
headers.append(f"{k}: {v}\r\n")
if content_length:
headers.append(f"Content-Length: {content_length}\r\n")
headers.append("Content-Type: text/plain\r\n")
headers.append("\r\n")
return ''.join(headers)
def handle_client_connection(self, client_socket):
try:
client_socket.settimeout(1.0)
except Exception:
pass
with client_socket:
while not self._shutdown_event.is_set():
try:
data = client_socket.recv(4096)
except socket.timeout:
continue
except OSError:
break
if not data:
break
request = data.decode('utf-8', errors='replace')
print(f"\n[Peer Upload] Received request:\n{request}")
try:
method, version, parameters, headers, body = parse_request(request)
except Exception:
resp = self._response_headers(400, "Bad Request")
client_socket.sendall(resp.encode('utf-8'))
continue
if version != 'P2P-CI/1.0':
resp = self._response_headers(505, "P2P-CI Version Not Supported")
client_socket.sendall(resp.encode('utf-8'))
continue
if method != 'GET' or len(parameters) < 2 or parameters[0] != 'RFC':
resp = self._response_headers(400, "Bad Request")
client_socket.sendall(resp.encode('utf-8'))
continue
rfc_number = parameters[1]
path = self._find_rfc_path(rfc_number)
if not path:
resp = self._response_headers(404, "Not Found")
client_socket.sendall(resp.encode('utf-8'))
continue
try:
with open(path, 'rb') as f:
content = f.read()
st = os.stat(path)
extra = {
'Last-Modified': formatdate(st.st_mtime, usegmt=True),
}
resp = self._response_headers(200, "OK", extra_headers=extra, content_length=len(content))
client_socket.sendall(resp.encode('utf-8') + content)
except FileNotFoundError:
resp = self._response_headers(404, "Not Found")
client_socket.sendall(resp.encode('utf-8'))
except Exception:
resp = self._response_headers(400, "Bad Request")
client_socket.sendall(resp.encode('utf-8'))
break
def spin_up(self):
print(f"Peer upload server listening on {self.peer_ip}:{self.peer_port}")
try:
self.socket_info.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
self.socket_info.bind((self.peer_ip, self.peer_port))
self.socket_info.listen()
try:
self.socket_info.settimeout(1.0)
except Exception:
pass
while not self._shutdown_event.is_set():
try:
client_socket, client_address = self.socket_info.accept()
except socket.timeout:
continue
except OSError:
break
print(f"Accepted connection from {client_address}")
self.client_connections.append(client_socket)
t = threading.Thread(target=self.handle_client_connection, args=(client_socket,), daemon=True)
self.client_threads.append(t)
t.start()
def shutdown(self):
if self._shutdown_event.is_set():
return
print("Shutting down peer upload server...")
self._shutdown_event.set()
try:
self.socket_info.close()
except Exception:
pass
for conn in list(self.client_connections):
try:
try:
conn.shutdown(socket.SHUT_RDWR)
except Exception:
pass
conn.close()
except Exception:
pass
for t in list(self.client_threads):
if t.is_alive():
t.join(timeout=1.0)
print("Peer upload server stopped.")
def _load_peer_details(peer_number):
path = os.path.join('peer_details', f'peer{peer_number}.txt')
if not os.path.isfile(path):
raise FileNotFoundError(f"Peer details file not found: {path}")
with open(path, 'r', encoding='utf-8') as f:
lines = [ln.strip() for ln in f.readlines() if ln.strip()]
if len(lines) < 2:
raise ValueError(f"Invalid peer details in {path}; expected at least IP and port")
ip = lines[0]
try:
port = int(lines[1])
except ValueError:
raise ValueError(f"Invalid port in {path}: {lines[1]}")
rfcs = []
for ln in lines[2:]:
parts = ln.split(' ', 1)
if not parts:
continue
number = parts[0]
title = parts[1] if len(parts) > 1 else ''
rfcs.append((number, title))
return ip, port, rfcs
def _build_rfc_store_from_rfcs(rfcs, search_dirs=None):
search_dirs = search_dirs or ['resources', 'rfc_files']
store = {}
for number, _title in rfcs:
candidates = []
for d in search_dirs:
candidates.append(os.path.join(d, f"{number}.txt"))
candidates.append(os.path.join(d, f"rfc{number}.txt"))
for c in candidates:
if os.path.isfile(c):
store[str(number)] = c
break
return store
def main():
parser = argparse.ArgumentParser(description='Peer upload server (P2P-CI GET).')
parser.add_argument('-n', '--peer', type=int, help='Peer number to load from peer_details/peer<N>.txt')
parser.add_argument('--ip', type=str, help='Override IP address (if not using --peer)')
parser.add_argument('--port', type=int, help='Override port (if not using --peer)')
parser.add_argument('--resources', type=str, nargs='*', help='Directories to search for RFC text files')
args = parser.parse_args()
if args.peer is not None:
ip, port, rfcs = _load_peer_details(args.peer)
search_dirs = args.resources or ['resources', 'rfc_files']
rfc_store = _build_rfc_store_from_rfcs(rfcs, search_dirs)
if not rfc_store:
print(f"Warning: No RFC text files found for peer{args.peer} in {search_dirs}. GET may return 404.")
server = PeerToClient(ip, port, rfc_store=rfc_store)
print(f"Starting peer{args.peer} upload server at {ip}:{port}")
print(f"Serving RFCs: {', '.join(sorted(rfc_store.keys())) or '(none found)'}")
else:
ip = args.ip or '127.0.0.1'
port = args.port or 9000
search_dirs = args.resources or ['resources', 'rfc_files']
server = PeerToClient(ip, port)
print(f"Starting upload server at {ip}:{port}")
print(f"Search directories: {search_dirs}")
try:
server.spin_up()
except KeyboardInterrupt:
print("\nKeyboardInterrupt received. Stopping peer upload server...")
finally:
server.shutdown()
if __name__ == "__main__":
main()