forked from rxcomm/smmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·88 lines (81 loc) · 2.62 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
#!/usr/bin/env python
"""
A simple echo server for axochat
"""
import binascii
import socket
import threading
import sys
from time import time
from random import randint
HOST = '0.0.0.0'
PORT = 50000
BACKLOG = 10
while True:
try:
PORT = raw_input('TCP port (1 for random choice, 50000 is default): ')
PORT = int(PORT)
break
except ValueError:
PORT = 50000
break
if PORT >= 1025 and PORT <= 65535:
pass
elif PORT == 1:
PORT = 1025 + randint(0, 64510)
print 'PORT is ' + str(PORT)
ans = raw_input('Keep a log of the (encrypted) traffic? y/N ')
if ans == 'y' or ans == 'Y' or ans == 'yes':
LOGTRAFFIC = True
else:
LOGTRAFFIC = False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen(BACKLOG)
client_list = {}
client_list_index = 0
address_list = []
def receiveData(client, address, index):
global client_list
global address_list
for i, item in client_list.iteritems():
item.send('SYSMSG' + str(len(client_list)) + ' users connected\nEOP')
while True:
data = ''
while data[-3:] != 'EOP':
rcv = client.recv(1024)
if not rcv:
del client_list[index]
address_list.remove(address)
for i, item in client_list.iteritems():
item.send('SYSMSG' + 'Disconnection: only ' + str(len(client_list)) + ' users connected\nEOP')
print str(address) + ' disconnected'
sys.exit()
data = data + rcv
data_list = data.split('EOP')
for data in data_list:
if data != '':
if LOGTRAFFIC:
with open('server.traffic.log', 'a') as f:
f.write(binascii.b2a_base64(data[3:]))
for i, item in client_list.iteritems():
try:
if (data[:3] != '998' and client != item) and (data[:3] == '999' or int(data[:3]) == i):
item.send(data[3:] + 'EOP')
except ValueError:
pass
try:
while True:
client, address = s.accept()
data = ''
while data[-5:] != 'START':
rcv = client.recv(1024)
data = data + rcv
my_index = int(data[:-5])
client_list[my_index] = client
address_list = address_list + [address]
threading.Thread(target=receiveData,args=(client,address,my_index)).start()
print str(my_index) + ': ' +str(address) + ' connected'
except KeyboardInterrupt:
print 'Server stopped'