-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
189 lines (163 loc) · 6.24 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
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
import socket
import shutil
import os
from functools import wraps
import codes
def configure_connection(host, port):
"""Создание соединения."""
print(f'run server on {host}:{port}')
sock = bind_socket(host, port)
while True:
try:
conn, addr = sock.accept()
print(f'user: {addr}, connected')
with FTPServer(conn, addr) as ftp:
ftp.run_server()
except KeyboardInterrupt:
break
sock.close()
def bind_socket(host, port):
"""Привязать слушающий сокет к ip и порту."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen()
return sock
def to_bytes(msg):
return bytes(msg, encoding='utf-8')
class FTPServer:
def __init__(
self,
connection,
address,
):
self.connection = connection
self.address = address
self.is_logged = False
self.pasv = False
self.data_connection = False
self.buffer_size = 1024
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if self.data_connection:
self.data_connection.close()
self.connection.close()
def run_server(self):
while True:
data = self.connection.recv(self.buffer_size)
if not data:
break
decoded = data.decode('utf-8').split(' ', 1)
command = decoded[0]
arg = decoded[1].lstrip(' ') if len(decoded) > 1 else None
if not self.command_exists(command):
self.send_message(codes.SYNTAX_ERROR)
else:
ftp_command = getattr(self, command)
ftp_command(arg)
def argument_checker(check, message):
"""Проверка аргументов класса."""
def decorate(func):
@wraps(func)
def wrap(self, *args, **kwargs):
res = None
if getattr(self, check, None):
res = func(self, *args, **kwargs)
else:
self.send_message(message)
return res
return wrap
return decorate
def send_message(self, msg):
if not isinstance(msg, bytes):
msg = to_bytes(msg)
self.connection.send(msg)
def command_exists(self, command):
return bool(getattr(self, command, None))
def USER(self, username):
"""Проверка пользователя."""
if username:
self.send_message(codes.LOGGED_IN)
self.is_logged = True
else:
self.send_message(codes.NOT_LOGGED_IN)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def PASV(self, *args):
"""Перевести сервер в пассивный режим."""
sock = bind_socket(HOST, 0)
port = sock.getsockname()[1]
hbytes = HOST.split('.')
pbytes = [repr(port//256), repr(port%256)]
port_bytes = hbytes + pbytes
cmd = ','.join(port_bytes)
self.connection.sendall(to_bytes(cmd))
self.data_connection, _ = sock.accept()
self.pasv = True
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def PWD(self, *args):
"""Показать путь."""
path = os.getcwdb()
self.data_connection.send(path)
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def LIST(self, path):
"""Вывести список файлов."""
if os.path.exists(path):
list_dir = '\n'.join(os.listdir(path))
self.data_connection.send(to_bytes(list_dir))
else:
self.data_connection.send(codes.REQUESTED_ACTION_NOT_TAKEN)
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def MKD(self, dirname):
"""Создание дирректории."""
os.makedirs(dirname)
msg = codes.PATHNAME_CREATED.decode('utf-8').replace("PATHNAME", f"{dirname}")
self.data_connection.send(to_bytes(msg))
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def DELE(self, filename):
"""Удалить файл."""
path = os.path.join(os.getcwd(), filename)
if os.path.exists(path):
try:
os.remove(path)
self.data_connection.send(codes.REQUESTED_ACTION_COMPLETED)
except OSError:
self.data_connection.send(codes.REQUEST_FILE_ACTION_ABORTED)
else:
self.data_connection.send(codes.REQUESTED_ACTION_NOT_TAKEN)
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def RMD(self, dirname):
"""Удалить папку."""
path = os.path.join(os.getcwd(), dirname)
if os.path.exists(path):
try:
shutil.rmtree(path)
self.data_connection.send(codes.REQUESTED_ACTION_COMPLETED)
except OSError:
self.data_connection.send(codes.REQUEST_FILE_ACTION_ABORTED)
else:
self.data_connection.send(codes.REQUESTED_ACTION_NOT_TAKEN)
@argument_checker('pasv', codes.CANT_OPEN_DATA_CONNECTION)
@argument_checker('is_logged', codes.NOT_LOGGED_IN)
def RETR(self, pathname):
"""Отправка файла."""
path = os.path.join(os.getcwd(), pathname)
if os.path.exists(path):
with open(pathname, 'rb') as f:
while True:
chunk = f.read(self.buffer_size)
if not chunk:
break
self.data_connection.send(chunk)
self.data_connection.send(codes.REQUESTED_ACTION_COMPLETED)
else:
self.data_connection.send(codes.REQUESTED_ACTION_NOT_TAKEN)
if __name__ == '__main__':
HOST = '127.0.0.1'
PORT = 8080
configure_connection(HOST, PORT)