Squid url redirector

Annotation For squid-tagger.py
anonymous

Annotation For squid-tagger.py

Origin for each line in squid-tagger.py from check-in 6c8b368359:

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)
26fc9b34d9 2010-08-07   83: 			return(True)
7e3418d94f 2009-10-12   84: 		else:
7e3418d94f 2009-10-12   85: 			self._log.info('bad request\n')
b93dc49210 2009-10-13   86: 			self.writeline(line)
26fc9b34d9 2010-08-07   87: 			return(False)
b93dc49210 2009-10-13   88: 
b93dc49210 2009-10-13   89: 	def writeline(self, string):
b93dc49210 2009-10-13   90: 		self._log.info('sending: ' + string)
b93dc49210 2009-10-13   91: 		sys.stdout.write(string)
b93dc49210 2009-10-13   92: 		sys.stdout.flush()
b93dc49210 2009-10-13   93: 
ed7808827d 2009-10-14   94: 	def loop(self):
ed7808827d 2009-10-14   95: 		while True:
ed7808827d 2009-10-14   96: 			line = sys.stdin.readline()
ed7808827d 2009-10-14   97: 			if len(line) == 0:
ed7808827d 2009-10-14   98: 				break
ed7808827d 2009-10-14   99: 			self.check(line)
ed7808827d 2009-10-14  100: 
b93dc49210 2009-10-13  101: # threaded checking facility
b93dc49210 2009-10-13  102: class CheckerThread(Checker):
ed7808827d 2009-10-14  103: 	__slots__ = frozenset(['_lock', '_lock_exit', '_lock_queue', '_queue'])
b93dc49210 2009-10-13  104: 
b93dc49210 2009-10-13  105: 	def __init__(self):
ed7808827d 2009-10-14  106: 		# basic initialisation
b93dc49210 2009-10-13  107: 		Checker.__init__(self)
ed7808827d 2009-10-14  108: 
b93dc49210 2009-10-13  109: 		# Spin lock. Loop acquires it on start then releases it when holding queue
b93dc49210 2009-10-13  110: 		# lock. This way the thread proceeds without stops while queue has data and
b93dc49210 2009-10-13  111: 		# gets stalled when no data present. The lock is released by queue writer
b93dc49210 2009-10-13  112: 		# after storing something into the queue
b93dc49210 2009-10-13  113: 		self._lock = _thread.allocate_lock()
ed7808827d 2009-10-14  114: 		self._lock_exit = _thread.allocate_lock()
b93dc49210 2009-10-13  115: 		self._lock_queue = _thread.allocate_lock()
b93dc49210 2009-10-13  116: 		self._lock.acquire()
b93dc49210 2009-10-13  117: 		self._queue = []
b93dc49210 2009-10-13  118: 		_thread.start_new_thread(self._start, ())
b93dc49210 2009-10-13  119: 
b93dc49210 2009-10-13  120: 	def _start(self):
b93dc49210 2009-10-13  121: 		while True:
b93dc49210 2009-10-13  122: 			self._lock.acquire()
ed7808827d 2009-10-14  123: 			with self._lock_queue:
ed7808827d 2009-10-14  124: 				# yes this should be written this way, and yes, this is why I hate threading
ed7808827d 2009-10-14  125: 				if len(self._queue) > 1:
ed7808827d 2009-10-14  126: 					if self._lock.locked():
ed7808827d 2009-10-14  127: 						self._lock.release()
ed7808827d 2009-10-14  128: 				req = self._queue.pop(0)
ed7808827d 2009-10-14  129: 			Checker.process(self, req[0], req[1], req[2], req[3])
ed7808827d 2009-10-14  130: 			with self._lock_queue:
ed7808827d 2009-10-14  131: 				if len(self._queue) == 0:
ed7808827d 2009-10-14  132: 					if self._lock_exit.locked():
ed7808827d 2009-10-14  133: 						self._lock_exit.release()
ed7808827d 2009-10-14  134: 
ed7808827d 2009-10-14  135: 	def process(self, id, site, ip_address, url_path, line):
ed7808827d 2009-10-14  136: 		with self._lock_queue:
ed7808827d 2009-10-14  137: 			self._queue.append((id, site, ip_address, url_path))
ed7808827d 2009-10-14  138: 			self._log.info('request {} queued ({})\n'.format(id, line))
ed7808827d 2009-10-14  139: 			if not self._lock_exit.locked():
ed7808827d 2009-10-14  140: 				self._lock_exit.acquire()
ed7808827d 2009-10-14  141: 			if self._lock.locked():
ed7808827d 2009-10-14  142: 				self._lock.release()
ed7808827d 2009-10-14  143: 
ed7808827d 2009-10-14  144: 	def loop(self):
ed7808827d 2009-10-14  145: 		while True:
ed7808827d 2009-10-14  146: 			line = sys.stdin.readline()
ed7808827d 2009-10-14  147: 			if len(line) == 0:
ed7808827d 2009-10-14  148: 				break
ed7808827d 2009-10-14  149: 			self.check(line)
ed7808827d 2009-10-14  150: 		self._lock_exit.acquire()
ed7808827d 2009-10-14  151: 
26fc9b34d9 2010-08-07  152: # kqueue enabled class for BSD's
ed7808827d 2009-10-14  153: class CheckerKqueue(Checker):
ed7808827d 2009-10-14  154: 	__slots__ = frozenset(['_kq', '_select', '_queue'])
ed7808827d 2009-10-14  155: 
ed7808827d 2009-10-14  156: 	def __init__(self):
ed7808827d 2009-10-14  157: 		# basic initialisation
ed7808827d 2009-10-14  158: 		Checker.__init__(self)
ed7808827d 2009-10-14  159: 
ed7808827d 2009-10-14  160: 		# importing select module
ed7808827d 2009-10-14  161: 		import select
ed7808827d 2009-10-14  162: 		self._select = select
ed7808827d 2009-10-14  163: 
ed7808827d 2009-10-14  164: 		# kreating kqueue
ed7808827d 2009-10-14  165: 		self._kq = self._select.kqueue()
ed7808827d 2009-10-14  166: 		assert (self._kq.fileno() != -1)
ed7808827d 2009-10-14  167: 
ed7808827d 2009-10-14  168: 		# watching sys.stdin for data
ed7808827d 2009-10-14  169: 		self._kq.control([self._select.kevent(sys.stdin, self._select.KQ_FILTER_READ, self._select.KQ_EV_ADD)], 0)
ed7808827d 2009-10-14  170: 
ed7808827d 2009-10-14  171: 		# creating data queue
ed7808827d 2009-10-14  172: 		self._queue = []
ed7808827d 2009-10-14  173: 
ed7808827d 2009-10-14  174: 	def loop(self):
ed7808827d 2009-10-14  175: 		# Wait for data by default
ed7808827d 2009-10-14  176: 		timeout = None
26fc9b34d9 2010-08-07  177: 		eof = False
26fc9b34d9 2010-08-07  178: 		buffer = ''
ed7808827d 2009-10-14  179: 		while True:
26fc9b34d9 2010-08-07  180: 			# checking if there is any data or witing for data to arrive
ed7808827d 2009-10-14  181: 			kevs = self._kq.control(None, 1, timeout)
26fc9b34d9 2010-08-07  182: 			if len(kevs) > 0 and kevs[0].filter == self._select.KQ_FILTER_READ and kevs[0].data > 0:
6c8b368359 2010-08-07  183: 				# reading data in
6c8b368359 2010-08-07  184: 				new_buffer = sys.stdin.read(kevs[0].data)
6c8b368359 2010-08-07  185: 				# if no data was sent - we have reached and of file
6c8b368359 2010-08-07  186: 				if len(new_buffer) == 0:
6c8b368359 2010-08-07  187: 					eof = True
6c8b368359 2010-08-07  188: 				else:
6c8b368359 2010-08-07  189: 					# adding current buffer to old buffer remains
6c8b368359 2010-08-07  190: 					buffer += new_buffer
6c8b368359 2010-08-07  191: 					# splitting to lines
6c8b368359 2010-08-07  192: 					lines = buffer.split('\n')
6c8b368359 2010-08-07  193: 					# last line that was not terminate by newline returns to buffer
6c8b368359 2010-08-07  194: 					buffer = lines[-1]
6c8b368359 2010-08-07  195: 					# an only if there was at least one newline
6c8b368359 2010-08-07  196: 					if len(lines) > 1:
6c8b368359 2010-08-07  197: 						for line in lines[:-1]:
6c8b368359 2010-08-07  198: 							# add data to the queue
6c8b368359 2010-08-07  199: 							if self.check(line + '\n'):
6c8b368359 2010-08-07  200: 								# don't wait for more data, start processing
6c8b368359 2010-08-07  201: 								timeout = 0
26fc9b34d9 2010-08-07  202: 				# if kq reports en of stream refuse to read more of it
26fc9b34d9 2010-08-07  203: 				if kevs[0].flags >> 15 == 1:
26fc9b34d9 2010-08-07  204: 					eof = True
ed7808827d 2009-10-14  205: 			else:
26fc9b34d9 2010-08-07  206: 				if len(self._queue) > 0:
26fc9b34d9 2010-08-07  207: 					req = self._queue.pop(0)
26fc9b34d9 2010-08-07  208: 					Checker.process(self, req[0], req[1], req[2], req[3])
26fc9b34d9 2010-08-07  209: 					if len(self._queue) == 0:
26fc9b34d9 2010-08-07  210: 						# wait for data - we have nothing to process
26fc9b34d9 2010-08-07  211: 						timeout = None
26fc9b34d9 2010-08-07  212: 				elif eof:
26fc9b34d9 2010-08-07  213: 					break
ed7808827d 2009-10-14  214: 
ed7808827d 2009-10-14  215: 	def process(self, id, site, ip_address, url_path, line):
26fc9b34d9 2010-08-07  216: 		# simply adding data to the queue
ed7808827d 2009-10-14  217: 		self._queue.append((id, site, ip_address, url_path))
ed7808827d 2009-10-14  218: 		self._log.info('request {} queued ({})\n'.format(id, line))
7e3418d94f 2009-10-12  219: 
fc934cead1 2009-10-13  220: # this classes processes config file and substitutes default values
d500448801 2009-10-05  221: class Config:
b93dc49210 2009-10-13  222: 	__slots__ = frozenset(['_config', '_default', '_section'])
b93dc49210 2009-10-13  223: 	_default = {
b93dc49210 2009-10-13  224: 		'reactor': {
b93dc49210 2009-10-13  225: 			'reactor': 'thread',
b93dc49210 2009-10-13  226: 		},
fc934cead1 2009-10-13  227: 		'log': {
fc934cead1 2009-10-13  228: 			'silent': 'no',
fc934cead1 2009-10-13  229: 		},
fc934cead1 2009-10-13  230: 		'database': {
fc934cead1 2009-10-13  231: 			'host': 'localhost',
fc934cead1 2009-10-13  232: 			'database': 'squidTag',
fc934cead1 2009-10-13  233: 	},}
d500448801 2009-10-05  234: 
fc934cead1 2009-10-13  235: 	# function to read in config file
d500448801 2009-10-05  236: 	def __init__(self):
d500448801 2009-10-05  237: 		parser = optparse.OptionParser()
d500448801 2009-10-05  238: 		parser.add_option('-c', '--config', dest = 'config',
d500448801 2009-10-05  239: 			help = 'config file location', metavar = 'FILE',
d500448801 2009-10-05  240: 			default = '/usr/local/etc/squid-tagger.conf')
d500448801 2009-10-05  241: 
d500448801 2009-10-05  242: 		(options, args) = parser.parse_args()
d500448801 2009-10-05  243: 
d500448801 2009-10-05  244: 		if not os.access(options.config, os.R_OK):
d500448801 2009-10-05  245: 			print("Can't read {}: exitting".format(options.config))
d500448801 2009-10-05  246: 			sys.exit(2)
d500448801 2009-10-05  247: 
d500448801 2009-10-05  248: 		self._config = configparser.ConfigParser()
d500448801 2009-10-05  249: 		self._config.readfp(open(options.config))
d500448801 2009-10-05  250: 
fc934cead1 2009-10-13  251: 	# function to select config file section or create one
d500448801 2009-10-05  252: 	def section(self, section):
fc934cead1 2009-10-13  253: 		if not self._config.has_section(section):
fc934cead1 2009-10-13  254: 			self._config.add_section(section)
d500448801 2009-10-05  255: 		self._section = section
d500448801 2009-10-05  256: 
fc934cead1 2009-10-13  257: 	# function to get config parameter, if parameter doesn't exists the default
fc934cead1 2009-10-13  258: 	# value or None is substituted
d500448801 2009-10-05  259: 	def __getitem__(self, name):
fc934cead1 2009-10-13  260: 		if not self._config.has_option(self._section, name):
b93dc49210 2009-10-13  261: 			if self._section in self._default:
b93dc49210 2009-10-13  262: 				if name in self._default[self._section]:
fc934cead1 2009-10-13  263: 					self._config.set(self._section, name, self._default[self._section][name])
fc934cead1 2009-10-13  264: 				else:
fc934cead1 2009-10-13  265: 					self._config.set(self._section, name, None)
fc934cead1 2009-10-13  266: 			else:
fc934cead1 2009-10-13  267: 				self._config.set(self._section, name, None)
b93dc49210 2009-10-13  268: 		return(self._config.get(self._section, name))
d500448801 2009-10-05  269: 
fc934cead1 2009-10-13  270: # initializing and reading in config file
d500448801 2009-10-05  271: config = Config()
d500448801 2009-10-05  272: 
b93dc49210 2009-10-13  273: config.section('reactor')
b93dc49210 2009-10-13  274: if config['reactor'] == 'thread':
b93dc49210 2009-10-13  275: 	checker = CheckerThread()
ed7808827d 2009-10-14  276: elif config['reactor'] == 'plain':
ed7808827d 2009-10-14  277: 	checker = Checker()
ed7808827d 2009-10-14  278: elif config['reactor'] == 'kqueue':
ed7808827d 2009-10-14  279: 	checker = CheckerKqueue()
b93dc49210 2009-10-13  280: 
ed7808827d 2009-10-14  281: checker.loop()