Add IP blacklist support
This commit is contained in:
parent
42d7b2d61d
commit
0d092f83c3
39
gophersrv.py
39
gophersrv.py
|
@ -36,6 +36,7 @@ import threading
|
|||
# Config
|
||||
port = 7070
|
||||
gopherroot = os.environ['HOME']+'/gopher'
|
||||
blacklistfile = os.environ['HOME']+'/gopher_blacklist'
|
||||
|
||||
# Set up socket
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
@ -269,6 +270,44 @@ class Serve(threading.Thread):
|
|||
except socket.error:
|
||||
self.conn.close()
|
||||
|
||||
def toint(addr):
|
||||
a1, a2, a3, a4 = [int(i) for i in addr.split('.')]
|
||||
return a1<<24 | a2<<16 | a3<<8 | a4
|
||||
|
||||
try:
|
||||
f = open(blacklistfile, 'r')
|
||||
except IOError:
|
||||
blacklist = []
|
||||
else:
|
||||
blacklist = []
|
||||
for line in f:
|
||||
if len(line) > 0 and line[-1] == '\n':
|
||||
line = line[:-1]
|
||||
|
||||
line = line.split('/')
|
||||
if len(line) == 1:
|
||||
addr = toint(line[0])
|
||||
upto = 32
|
||||
elif len(line) == 2:
|
||||
addr = toint(line[0])
|
||||
upto = int(line[1])
|
||||
else:
|
||||
assert(not 'Invalid line format')
|
||||
|
||||
blacklist.append((addr, upto))
|
||||
|
||||
f.close()
|
||||
|
||||
def matchaddr(addr, blacklist_entry):
|
||||
blacklist_addr, upto = blacklist_entry
|
||||
shift = 32 - upto
|
||||
return addr >> shift == blacklist_addr >> shift
|
||||
|
||||
while True:
|
||||
conn, addr = sock.accept()
|
||||
ip, port = addr
|
||||
if not any(map(lambda x: matchaddr(toint(ip), x), blacklist)):
|
||||
print ip, blacklist#debg
|
||||
Serve(conn).start()
|
||||
else:
|
||||
conn.close()
|
||||
|
|
Loading…
Reference in New Issue