d500448801 2009-10-05 1: #!/usr/bin/env python3.1
d500448801 2009-10-05 2:
d500448801 2009-10-05 3: import configparser, optparse, os, postgresql.api, re, sys, _thread
d500448801 2009-10-05 4:
b93dc49210 2009-10-13 5: # wrapper around syslog, can be muted
d500448801 2009-10-05 6: class Logger:
d500448801 2009-10-05 7: __slots__ = frozenset(['_syslog'])
d500448801 2009-10-05 8:
d500448801 2009-10-05 9: def __init__(self):
d500448801 2009-10-05 10: config.section('log')
d500448801 2009-10-05 11: if config['silent'] == 'yes':
d500448801 2009-10-05 12: self._syslog = None
d500448801 2009-10-05 13: else:
d500448801 2009-10-05 14: import syslog
d500448801 2009-10-05 15: self._syslog = syslog
d500448801 2009-10-05 16: self._syslog.openlog('squidTag')
d500448801 2009-10-05 17:
d500448801 2009-10-05 18: def info(self, message):
4b22e25f24 2009-10-07 19: if self._syslog:
d500448801 2009-10-05 20: self._syslog.syslog(self._syslog.LOG_INFO, message)
d500448801 2009-10-05 21:
d500448801 2009-10-05 22: def notice(self, message):
4b22e25f24 2009-10-07 23: if self._syslog:
d500448801 2009-10-05 24: self._syslog.syslog(self._syslog.LOG_NOTICE, message)
d500448801 2009-10-05 25:
b93dc49210 2009-10-13 26: # wrapper around database
d500448801 2009-10-05 27: class tagDB:
9450c03d41 2010-08-07 28: __slots__ = frozenset(('_check_stmt', '_db'))
b93dc49210 2009-10-13 29:
b93dc49210 2009-10-13 30: def __init__(self):
9450c03d41 2010-08-07 31: config.section('database')
9450c03d41 2010-08-07 32: self._db = postgresql.open(
9450c03d41 2010-08-07 33: 'pq://{}:{}@{}/{}'.format(
9450c03d41 2010-08-07 34: config['user'],
9450c03d41 2010-08-07 35: config['password'],
9450c03d41 2010-08-07 36: config['host'],
9450c03d41 2010-08-07 37: config['database'],
9450c03d41 2010-08-07 38: ) )
9450c03d41 2010-08-07 39: self._check_stmt = self._db.prepare("select redirect_url, regexp from site_rule where site <@ tripdomain($1) and netmask >> $2::text::inet order by array_length(site, 1) desc")
b93dc49210 2009-10-13 40:
b93dc49210 2009-10-13 41: def check(self, site, ip_address):
b93dc49210 2009-10-13 42: return(self._check_stmt(site, ip_address))
b93dc49210 2009-10-13 43:
b93dc49210 2009-10-13 44: # abstract class with basic checking functionality
b93dc49210 2009-10-13 45: class Checker:
ed7808827d 2009-10-14 46: __slots__ = frozenset(['_db', '_log'])
7e3418d94f 2009-10-12 47:
7e3418d94f 2009-10-12 48: def __init__(self):
b93dc49210 2009-10-13 49: self._db = tagDB()
b93dc49210 2009-10-13 50: self._log = Logger()
b93dc49210 2009-10-13 51:
ed7808827d 2009-10-14 52: def process(self, id, site, ip_address, url_path, line = None):
b93dc49210 2009-10-13 53: self._log.info('trying {}\n'.format(site))
b93dc49210 2009-10-13 54: result = self._db.check(site, ip_address)
b93dc49210 2009-10-13 55: #reply = '{}://{}/{}'.format(req[4], req[1], req[3])
b93dc49210 2009-10-13 56: reply = '-'
b93dc49210 2009-10-13 57: for row in result:
b93dc49210 2009-10-13 58: if row != None and row[0] != None:
b93dc49210 2009-10-13 59: if row[1] != None:
b93dc49210 2009-10-13 60: self._log.info('trying regexp "{}" versus "{}"\n'.format(row[1], url_path))
d2c54d0451 2010-03-01 61: try:
d2c54d0451 2010-03-01 62: if re.compile(row[1]).match(url_path):
1fa8a88371 2010-07-14 63: reply = row[0].format(url_path)
d2c54d0451 2010-03-01 64: break
d2c54d0451 2010-03-01 65: else:
d2c54d0451 2010-03-01 66: continue
d2c54d0451 2010-03-01 67: except:
d2c54d0451 2010-03-01 68: self._log.info("can't compile regexp")
b93dc49210 2009-10-13 69: else:
1fa8a88371 2010-07-14 70: reply = row[0].format(url_path)
b93dc49210 2009-10-13 71: break
b93dc49210 2009-10-13 72: self.writeline('{} {}\n'.format(id, reply))
7e3418d94f 2009-10-12 73:
7e3418d94f 2009-10-12 74: def check(self, line):
7e3418d94f 2009-10-12 75: request = re.compile('^([0-9]+)\ (http|ftp):\/\/([-\w.:]+)\/([^ ]*)\ ([0-9.]+)\/(-|[\w\.]+)\ (-|\w+)\ (-|GET|HEAD|POST).*$').match(line)
7e3418d94f 2009-10-12 76: if request:
7e3418d94f 2009-10-12 77: id = request.group(1)
7e3418d94f 2009-10-12 78: #proto = request.group(2)
7e3418d94f 2009-10-12 79: site = request.group(3)
7e3418d94f 2009-10-12 80: url_path = request.group(4)
7e3418d94f 2009-10-12 81: ip_address = request.group(5)
ed7808827d 2009-10-14 82: self.process(id, site, ip_address, url_path, line)
7e3418d94f 2009-10-12 83: else:
7e3418d94f 2009-10-12 84: self._log.info('bad request\n')
b93dc49210 2009-10-13 85: self.writeline(line)
b93dc49210 2009-10-13 86:
b93dc49210 2009-10-13 87: def writeline(self, string):
b93dc49210 2009-10-13 88: self._log.info('sending: ' + string)
b93dc49210 2009-10-13 89: sys.stdout.write(string)
b93dc49210 2009-10-13 90: sys.stdout.flush()
b93dc49210 2009-10-13 91:
ed7808827d 2009-10-14 92: def loop(self):
ed7808827d 2009-10-14 93: while True:
ed7808827d 2009-10-14 94: line = sys.stdin.readline()
ed7808827d 2009-10-14 95: if len(line) == 0:
ed7808827d 2009-10-14 96: break
ed7808827d 2009-10-14 97: self.check(line)
ed7808827d 2009-10-14 98:
b93dc49210 2009-10-13 99: # threaded checking facility
b93dc49210 2009-10-13 100: class CheckerThread(Checker):
ed7808827d 2009-10-14 101: __slots__ = frozenset(['_lock', '_lock_exit', '_lock_queue', '_queue'])
b93dc49210 2009-10-13 102:
b93dc49210 2009-10-13 103: def __init__(self):
ed7808827d 2009-10-14 104: # basic initialisation
b93dc49210 2009-10-13 105: Checker.__init__(self)
ed7808827d 2009-10-14 106:
b93dc49210 2009-10-13 107: # Spin lock. Loop acquires it on start then releases it when holding queue
b93dc49210 2009-10-13 108: # lock. This way the thread proceeds without stops while queue has data and
b93dc49210 2009-10-13 109: # gets stalled when no data present. The lock is released by queue writer
b93dc49210 2009-10-13 110: # after storing something into the queue
b93dc49210 2009-10-13 111: self._lock = _thread.allocate_lock()
ed7808827d 2009-10-14 112: self._lock_exit = _thread.allocate_lock()
b93dc49210 2009-10-13 113: self._lock_queue = _thread.allocate_lock()
b93dc49210 2009-10-13 114: self._lock.acquire()
b93dc49210 2009-10-13 115: self._queue = []
b93dc49210 2009-10-13 116: _thread.start_new_thread(self._start, ())
b93dc49210 2009-10-13 117:
b93dc49210 2009-10-13 118: def _start(self):
b93dc49210 2009-10-13 119: while True:
b93dc49210 2009-10-13 120: self._lock.acquire()
ed7808827d 2009-10-14 121: with self._lock_queue:
ed7808827d 2009-10-14 122: # yes this should be written this way, and yes, this is why I hate threading
ed7808827d 2009-10-14 123: if len(self._queue) > 1:
ed7808827d 2009-10-14 124: if self._lock.locked():
ed7808827d 2009-10-14 125: self._lock.release()
ed7808827d 2009-10-14 126: req = self._queue.pop(0)
ed7808827d 2009-10-14 127: Checker.process(self, req[0], req[1], req[2], req[3])
ed7808827d 2009-10-14 128: with self._lock_queue:
ed7808827d 2009-10-14 129: if len(self._queue) == 0:
ed7808827d 2009-10-14 130: if self._lock_exit.locked():
ed7808827d 2009-10-14 131: self._lock_exit.release()
ed7808827d 2009-10-14 132:
ed7808827d 2009-10-14 133: def process(self, id, site, ip_address, url_path, line):
ed7808827d 2009-10-14 134: with self._lock_queue:
ed7808827d 2009-10-14 135: self._queue.append((id, site, ip_address, url_path))
ed7808827d 2009-10-14 136: self._log.info('request {} queued ({})\n'.format(id, line))
ed7808827d 2009-10-14 137: if not self._lock_exit.locked():
ed7808827d 2009-10-14 138: self._lock_exit.acquire()
ed7808827d 2009-10-14 139: if self._lock.locked():
ed7808827d 2009-10-14 140: self._lock.release()
ed7808827d 2009-10-14 141:
ed7808827d 2009-10-14 142: def loop(self):
ed7808827d 2009-10-14 143: while True:
ed7808827d 2009-10-14 144: line = sys.stdin.readline()
ed7808827d 2009-10-14 145: if len(line) == 0:
ed7808827d 2009-10-14 146: break
ed7808827d 2009-10-14 147: self.check(line)
ed7808827d 2009-10-14 148: self._lock_exit.acquire()
ed7808827d 2009-10-14 149:
ed7808827d 2009-10-14 150: # kqueue enable class for BSD's XXX broken for now
ed7808827d 2009-10-14 151: class CheckerKqueue(Checker):
ed7808827d 2009-10-14 152: __slots__ = frozenset(['_kq', '_select', '_queue'])
ed7808827d 2009-10-14 153:
ed7808827d 2009-10-14 154: def __init__(self):
ed7808827d 2009-10-14 155: # basic initialisation
ed7808827d 2009-10-14 156: Checker.__init__(self)
ed7808827d 2009-10-14 157:
ed7808827d 2009-10-14 158: # importing select module
ed7808827d 2009-10-14 159: import select
ed7808827d 2009-10-14 160: self._select = select
ed7808827d 2009-10-14 161:
ed7808827d 2009-10-14 162: # kreating kqueue
ed7808827d 2009-10-14 163: self._kq = self._select.kqueue()
ed7808827d 2009-10-14 164: assert (self._kq.fileno() != -1)
ed7808827d 2009-10-14 165:
ed7808827d 2009-10-14 166: # watching sys.stdin for data
ed7808827d 2009-10-14 167: self._kq.control([self._select.kevent(sys.stdin, self._select.KQ_FILTER_READ, self._select.KQ_EV_ADD)], 0)
ed7808827d 2009-10-14 168:
ed7808827d 2009-10-14 169: # creating data queue
ed7808827d 2009-10-14 170: self._queue = []
ed7808827d 2009-10-14 171:
ed7808827d 2009-10-14 172: def loop(self):
ed7808827d 2009-10-14 173: # Wait for data by default
ed7808827d 2009-10-14 174: timeout = None
ed7808827d 2009-10-14 175: while True:
ed7808827d 2009-10-14 176: # checking if there is any data
ed7808827d 2009-10-14 177: kevs = self._kq.control(None, 1, timeout)
ed7808827d 2009-10-14 178: if len(kevs) > 0:
ed7808827d 2009-10-14 179: #kev = kevs[0]
ed7808827d 2009-10-14 180: # XXX add some code to read only known data size and check for newlines
ed7808827d 2009-10-14 181: line = sys.stdin.readline()
ed7808827d 2009-10-14 182: # add data to the queue
ed7808827d 2009-10-14 183: self.check(line)
ed7808827d 2009-10-14 184: # don't wait for data, start processing
ed7808827d 2009-10-14 185: timeout = 0
ed7808827d 2009-10-14 186: else:
ed7808827d 2009-10-14 187: req = self._queue.pop(0)
ed7808827d 2009-10-14 188: Checker.process(self, req[0], req[1], req[2], req[3])
ed7808827d 2009-10-14 189: if len(self._queue) == 0:
ed7808827d 2009-10-14 190: # wait for data - we have nothing to process
ed7808827d 2009-10-14 191: timeout = None
ed7808827d 2009-10-14 192:
ed7808827d 2009-10-14 193: def process(self, id, site, ip_address, url_path, line):
ed7808827d 2009-10-14 194: self._queue.append((id, site, ip_address, url_path))
ed7808827d 2009-10-14 195: self._log.info('request {} queued ({})\n'.format(id, line))
7e3418d94f 2009-10-12 196:
fc934cead1 2009-10-13 197: # this classes processes config file and substitutes default values
d500448801 2009-10-05 198: class Config:
b93dc49210 2009-10-13 199: __slots__ = frozenset(['_config', '_default', '_section'])
b93dc49210 2009-10-13 200: _default = {
b93dc49210 2009-10-13 201: 'reactor': {
b93dc49210 2009-10-13 202: 'reactor': 'thread',
b93dc49210 2009-10-13 203: },
fc934cead1 2009-10-13 204: 'log': {
fc934cead1 2009-10-13 205: 'silent': 'no',
fc934cead1 2009-10-13 206: },
fc934cead1 2009-10-13 207: 'database': {
fc934cead1 2009-10-13 208: 'host': 'localhost',
fc934cead1 2009-10-13 209: 'database': 'squidTag',
fc934cead1 2009-10-13 210: },}
d500448801 2009-10-05 211:
fc934cead1 2009-10-13 212: # function to read in config file
d500448801 2009-10-05 213: def __init__(self):
d500448801 2009-10-05 214: parser = optparse.OptionParser()
d500448801 2009-10-05 215: parser.add_option('-c', '--config', dest = 'config',
d500448801 2009-10-05 216: help = 'config file location', metavar = 'FILE',
d500448801 2009-10-05 217: default = '/usr/local/etc/squid-tagger.conf')
d500448801 2009-10-05 218:
d500448801 2009-10-05 219: (options, args) = parser.parse_args()
d500448801 2009-10-05 220:
d500448801 2009-10-05 221: if not os.access(options.config, os.R_OK):
d500448801 2009-10-05 222: print("Can't read {}: exitting".format(options.config))
d500448801 2009-10-05 223: sys.exit(2)
d500448801 2009-10-05 224:
d500448801 2009-10-05 225: self._config = configparser.ConfigParser()
d500448801 2009-10-05 226: self._config.readfp(open(options.config))
d500448801 2009-10-05 227:
fc934cead1 2009-10-13 228: # function to select config file section or create one
d500448801 2009-10-05 229: def section(self, section):
fc934cead1 2009-10-13 230: if not self._config.has_section(section):
fc934cead1 2009-10-13 231: self._config.add_section(section)
d500448801 2009-10-05 232: self._section = section
d500448801 2009-10-05 233:
fc934cead1 2009-10-13 234: # function to get config parameter, if parameter doesn't exists the default
fc934cead1 2009-10-13 235: # value or None is substituted
d500448801 2009-10-05 236: def __getitem__(self, name):
fc934cead1 2009-10-13 237: if not self._config.has_option(self._section, name):
b93dc49210 2009-10-13 238: if self._section in self._default:
b93dc49210 2009-10-13 239: if name in self._default[self._section]:
fc934cead1 2009-10-13 240: self._config.set(self._section, name, self._default[self._section][name])
fc934cead1 2009-10-13 241: else:
fc934cead1 2009-10-13 242: self._config.set(self._section, name, None)
fc934cead1 2009-10-13 243: else:
fc934cead1 2009-10-13 244: self._config.set(self._section, name, None)
b93dc49210 2009-10-13 245: return(self._config.get(self._section, name))
d500448801 2009-10-05 246:
fc934cead1 2009-10-13 247: # initializing and reading in config file
d500448801 2009-10-05 248: config = Config()
d500448801 2009-10-05 249:
b93dc49210 2009-10-13 250: config.section('reactor')
b93dc49210 2009-10-13 251: if config['reactor'] == 'thread':
b93dc49210 2009-10-13 252: checker = CheckerThread()
ed7808827d 2009-10-14 253: elif config['reactor'] == 'plain':
ed7808827d 2009-10-14 254: checker = Checker()
ed7808827d 2009-10-14 255: elif config['reactor'] == 'kqueue':
ed7808827d 2009-10-14 256: checker = CheckerKqueue()
b93dc49210 2009-10-13 257:
ed7808827d 2009-10-14 258: checker.loop()