Add IP blacklist support
This commit is contained in:
parent
42d7b2d61d
commit
0d092f83c3
45
gophersrv.py
45
gophersrv.py
|
@ -34,8 +34,9 @@ import subprocess
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
# Config
|
# Config
|
||||||
port = 7070
|
port = 7070
|
||||||
gopherroot = os.environ['HOME']+'/gopher'
|
gopherroot = os.environ['HOME']+'/gopher'
|
||||||
|
blacklistfile = os.environ['HOME']+'/gopher_blacklist'
|
||||||
|
|
||||||
# Set up socket
|
# Set up socket
|
||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
@ -269,6 +270,44 @@ class Serve(threading.Thread):
|
||||||
except socket.error:
|
except socket.error:
|
||||||
self.conn.close()
|
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:
|
while True:
|
||||||
conn, addr = sock.accept()
|
conn, addr = sock.accept()
|
||||||
Serve(conn).start()
|
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