-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
64 lines (51 loc) · 2.06 KB
/
server.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
from fbtftp.base_handler import BaseHandler
from fbtftp.base_handler import ResponseData
from fbtftp.base_server import BaseServer
import os
class FileResponseData(ResponseData):
def __init__(self, path):
self._size = os.stat(path).st_size
self._reader = open(path, 'rb')
def read(self, n):
return self._reader.read(n)
def size(self):
return self._size
def close(self):
self._reader.close()
def print_session_stats(stats):
print(stats)
def print_server_stats(stats):
counters = stats.get_and_reset_all_counters()
print('Server stats - every {} seconds'.format(stats.interval))
print(counters)
class StaticHandler(BaseHandler):
def __init__(self, server_addr, peer, path, options, root, stats_callback):
self._root = root
super().__init__(server_addr, peer, path, options, stats_callback)
def get_response_data(self):
return FileResponseData(self._root + self._path)
class StaticServer(BaseServer):
def __init__(self, address, port, retries, timeout, root,
handler_stats_callback, server_stats_callback=None):
self._root = root
self._handler_stats_callback = handler_stats_callback
super().__init__(address, port, retries, timeout, server_stats_callback)
def get_handler(self, server_addr, peer, path, options):
if path == "/jos-grub":
path = path + "-" + peer[0]
elif (path == "/boot/grub/grub.cfg") and os.path.exists("shutdown-" + peer[0]):
path = "/boot/grub/grub-shutdown.cfg"
print("get %s" % path)
return StaticHandler(
server_addr, peer, path, options, self._root,
self._handler_stats_callback)
def main():
server = StaticServer(address='0.0.0.0', port=69, retries=3, timeout=5,
root='.', handler_stats_callback=print_session_stats,
server_stats_callback=print_server_stats)
try:
server.run()
except KeyboardInterrupt:
server.close()
if __name__ == '__main__':
main()