-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.py
239 lines (211 loc) · 7.22 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
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
238
239
import sys, socket, re
connected = True
def parse501(message,token,parsedText,socket):
mail = re.match("MAIL\s+FROM:\s*<([a-zA-Z0-9!#$%&'*+/=?~^_`}{|~-]{1,61}@(?:(?:[a-zA-Z])(?:[a-zA$
rcpt = re.match("RCPT\s+TO:\s*<([a-zA-Z0-9!#$%&'*+/=?~^_`}{|~-]{1,61}@(?:(?:[a-zA-Z])(?:[a-zA-Z$
data = re.match('DATA\s*$', message)
if(token not in {'mail','rcpt','data'}):
return True
if(token == 'mail'):
if mail:
socket.send('250 OK\r\n'.encode())
parsedText.append(mail.group(0))
return False
else:
socket.send('501 Syntax error in parameters or arguments\r\n'.encode())
return True
elif(token == 'rcpt'):
if rcpt:
socket.send('250 OK\r\n'.encode())
parsedText.append(rcpt.group(0))
parsedText.append(rcpt.group(1))
return False
else:
socket.send('501 Syntax error in parameters or arguments\r\n'.encode())
return True
elif(token == 'data'):
if data:
socket.send('354 Start mail input; end with . on a line by itself\r\n'.encode())
parsedText.append(data.group(0))
return False
else:
socket.send('501 Syntax error in parameters or arguments\r\n'.encode())
return True
def parseToken(token, message, socket):
global connected
if connected == False:
return False
if(token not in {'mail','rcpt','data'}):
return False
mail = re.match('MAIL\s+FROM:\s*', message)
rcpt = re.match('RCPT\s+TO:\s*', message)
data = re.match('DATA\s*', message)
if(token == 'mail'):
if(rcpt or data):
socket.send('503 Bad sequence of commands\r\n'.encode())
return False
elif(mail):
return True
elif(token == 'data'):
if(rcpt or mail):
socket.send('503 Bad sequence of commands\r\n'.encode())
return False
elif(data):
return True
elif(token == 'rcpt'):
if(mail or data):
socket.send('503 Bad sequence of commands\r\n'.encode())
return False
elif(rcpt):
return True
socket.send('500 Syntax error: command unrecognized\r\n'.encode())
return False
def parseInput(inputSocket):
global connected
try:
message = inputSocket.recv(4096).decode()
sys.stdout.write(message)
if(message == 'QUIT\r\n'):
inputSocket.send(f'221 {socket.getfqdn()} closing connection\r\n'.encode())
connected = False
inputSocket.close()
return message
except socket.error as err:
inputSocket.close()
connected = False
def parseMail(parsedText, socket):
global connected
while(True):
message = parseInput(socket)
if not connected:
return False
if not parseToken('mail', message, socket):
continue
else:
if not parse501(message,'mail',parsedText, socket):
return True
else:
continue
def parseRcpt(parsedText,socket):
global connected
while(True):
message = parseInput(socket)
if not connected:
return False
#parse if token is out of order
if not parseToken('rcpt', message, socket):
continue
else:
if not parse501(message, 'rcpt',parsedText, socket):
return True
else:
continue
def parseData(parsedText, socket):
global connected
while(True):
message = parseInput(socket)
if not parseToken('data', message, socket):
continue
else:
if not parse501(message,'data',parsedText, socket):
messageData = []
EOF = False
while not EOF:
inputMessage = socket.recv(4096).decode()
message = inputMessage.splitlines()
for line in message:
print(line, end = '\r\n')
messageData.append(line)
if(line =='.\r\n'or line =='.'):
socket.send('250 OK\r\n'.encode())
EOF = True
break
parsedText.append(messageData)
return True
else:
continue
def writer(parsedText):
domain = parsedText[2].split('@',1)[1]
# new file's name doesnt need angle brackets
fileName = "forward/"+ domain
# a+ creates a new file if one doesnt already exist
newFile = open((fileName), "a+")
newFile.write(parsedText[0])
newFile.write(parsedText[1])
newFile.write(parsedText[3])
for i in range(len(parsedText[4])):
receiver = parsedText[4][i]
newFile.write(receiver+ "\r\n")
def mail(socket):
temp = []
while(True):
# parsedText[0] = MAIL, parsedText[1] = RCPT, parsedText[3] = DATA
parsedText = []
mailFromstatus = parseMail(parsedText, socket)
if mailFromstatus:
rcptStatus = parseRcpt(parsedText, socket)
if rcptStatus:
parseData(parsedText, socket)
temp.append(parsedText)
writer(parsedText)
if not connected:
return False
else:
if not connected:
return False
continue
return False
def connect(csocket):
global connected
try:
host = socket.getfqdn()
csocket.send(f"220 {host}\r\n".encode())
while(True):
parsed = parseInput(csocket)
if connected:
if(parsed[0:5] == 'HELO '):
parsed = re.match('HELO\s+((?:(?:[a-zA-Z])(?:[a-zA-Z0-9-])*\.)+(?:[a-zA-Z])(?:[$
if parsed:
serverHand = f"250 Hello {parsed.group(1)} pleased to meet you\r\n"
csocket.send(serverHand.encode())
return True
else:
csocket.send('501 Syntax error in parameters or arguments\r\n'.encode())
continue
else:
csocket.send('500 Syntax error: command unrecognized\r\n'.encode())
continue
else:
return False
except socket.error as err:
print(err)
csocket.close()
connected = False
def server():
global connected
#port = int(input())
port = int(sys.argv[1])
try:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print(err)
try:
serversocket.bind((socket.getfqdn(), port))
except socket.error as err:
print(err)
quit()
#listen with a max queue of 5
serversocket.listen(5)
while True:
csocket, address = serversocket.accept()
connected = True
startProcessing = connect(csocket)
if (startProcessing == True):
mail(csocket)
server()
# todo:
# create a new file
# remove string splitting and replace with a better way
# implement regex to decrease overhead per TA's advice
# create message abstractions
# clean up code