Samesite - proxy that can cache partial transfers

Annotation For samesite.py
anonymous

Annotation For samesite.py

Lines of samesite.py from check-in 601ec56da6 that are changed by the sequence of edits moving toward check-in 5d16a125ab:

                         1: #!/usr/bin/env python
                         2: 
                         3: from __future__ import unicode_literals, print_function
                         4: 
                         5: import bsddb.dbshelve, copy, datetime, os, BaseHTTPServer, sys, spacemap, re, urllib2
                         6: 
                         7: class Config:
                         8: 	__slots__ = frozenset(['_config', '_default', '_section', 'options', 'root'])
                         9: 	_default = {
                        10: 		'general': {
                        11: 			'port': '8008',
                        12: 		},
                        13: 		'_other': {
                        14: 			'verbose': 'no',
                        15: 			'noetag': 'no',
                        16: 			'noparts': 'no',
                        17: 			'strip': '',
                        18: 			'sub': '',
                        19: 	},}
                        20: 
                        21: 	# function to read in config file
                        22: 	def __init__(self):
                        23: 		import ConfigParser, optparse
                        24: 
                        25: 		parser = optparse.OptionParser()
                        26: 		parser.add_option('-c', '--config', dest = 'config', help = 'config file location', metavar = 'FILE', default = 'samesite.conf')
                        27: 		(self.options, args) = parser.parse_args()
                        28: 
                        29: 		assert os.access(self.options.config, os.R_OK), "Fatal error: can't read {}".format(self.options.config)
                        30: 
                        31: 		configDir = re.compile('^(.*)/[^/]+$').match(self.options.config)
                        32: 		if configDir:
                        33: 			self.root = configDir.group(1)
                        34: 		else:
                        35: 			self.root = os.getcwd()
                        36: 
                        37: 		self._config = ConfigParser.ConfigParser()
                        38: 		self._config.readfp(open(self.options.config))
                        39: 
                        40: 		for section in self._config.sections():
                        41: 			if section != 'general':
                        42: 				if self._config.has_option(section, 'dir'):
                        43: 					if re.compile('^/$').match(self._config.get(section, 'dir')):
                        44: 						self._config.set(section, 'dir', self.root + os.sep + section)
                        45: 					thisDir = re.compile('^(.*)/$').match(self._config.get(section, 'dir'))
                        46: 					if thisDir:
                        47: 						self._config.set(section, 'dir', thisDir.group(1))
                        48: 					if not re.compile('^/(.*)$').match(self._config.get(section, 'dir')):
                        49: 						self._config.set(section, 'dir', self.root + os.sep + self._config.get(section, 'dir'))
                        50: 				else:
                        51: 					self._config.set(section, 'dir', self.root + os.sep + section)
                        52: 
                        53: 				if not self._config.has_option(section, 'root'):
                        54: 					self._config.set(section, 'root', section)
                        55: 
                        56: 	# function to select config file section or create one
                        57: 	def section(self, section):
                        58: 		if not self._config.has_section(section):
                        59: 			self._config.add_section(section)
                        60: 		self._section = section
                        61: 
                        62: 	# function to get config parameter, if parameter doesn't exists the default
                        63: 	# value or None is substituted
                        64: 	def __getitem__(self, name):
                        65: 		if not self._config.has_option(self._section, name):
                        66: 			if self._section in self._default:
                        67: 				if name in self._default[self._section]:
                        68: 					self._config.set(self._section, name, self._default[self._section][name])
                        69: 				else:
                        70: 					self._config.set(self._section, name, None)
                        71: 			elif name in self._default['_other']:
                        72: 				self._config.set(self._section, name, self._default['_other'][name])
                        73: 			else:
                        74: 				self._config.set(self._section, name, None)
                        75: 		return(self._config.get(self._section, name))
                        76: 
                        77: config = Config()
                        78: 
                        79: #assert options.port or os.access(options.log, os.R_OK), 'Log file unreadable'
                        80: 
                        81: const_desc_fields = set(['content-length', 'last-modified', 'pragma'])
                        82: const_ignore_fields = set([
                        83: 	'accept-ranges', 'age',
                        84: 	'cache-control', 'connection', 'content-type',
                        85: 	'date',
                        86: 	'expires',
                        87: 	'referer',
                        88: 	'server',
                        89: 	'via',
                        90: 	'x-cache', 'x-cache-lookup', 'x-livetool', 'x-powered-by',
                        91: ])
                        92: 
                        93: block_size = 4096
                        94: 
                        95: class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
                        96: 	def __process(self):
                        97: 		# reload means file needs to be reloaded to serve request
                        98: 		reload = False
                        99: 		# recheck means file needs to be checked, this also means that if file hav been modified we can serve older copy
                       100: 		recheck = False
                       101: 		# file_stat means file definitely exists
                       102: 		file_stat = None
                       103: 		# requested_ranges holds data about any range requested
                       104: 		requested_ranges = None
                       105: 		# records holds data from index locally, should be written back upon successfull completion
                       106: 		record = None
                       107: 
                       108: 		myPath = re.compile('^(.*?)(\?.*)$').match(self.path)
                       109: 		if myPath:
                       110: 			my_path = myPath.group(1)
                       111: 		else:
                       112: 			my_path = self.path
                       113: 
                       114: 		config.section(self.headers['host'])
                       115: 
                       116: 		if config['sub'] != None and config['strip'] != None and len(config['strip']) > 0:
                       117: 			string = re.compile(config['strip']).sub(config['sub'], my_path)
                       118: 			my_path = string
                       119: 
                       120: 		info = 'Checking file: ' + my_path
                       121: 
                       122: 		if not os.access(config['dir'], os.X_OK):
                       123: 			os.mkdir(config['dir'])
                       124: 		# this is file index - everything is stored in this file
                       125: 		# _parts - list of stored parts of file
                       126: 		# _time - last time the file was checked
                       127: 		# everything else is just the headers
                       128: 		index = bsddb.dbshelve.open(config['dir'] + os.sep + '.index')
                       129: 
                       130: 		desc_fields = const_desc_fields.copy()
                       131: 		ignore_fields = const_ignore_fields.copy()
                       132: 		if config['noetag'] == 'no':
                       133: 			desc_fields.add('etag')
                       134: 		else:
                       135: 			ignore_fields.add('etag')
                       136: 
                       137: 		proxy_ignored = set([
                       138: 			'accept', 'accept-charset', 'accept-encoding', 'accept-language',
                       139: 			'cache-control', 'connection', 'content-length', 'cookie',
                       140: 			'host',
                       141: 			'if-modified-since', 'if-unmodified-since',
                       142: 			'referer',
                       143: 			'user-agent',
                       144: 			'via',
                       145: 			'x-forwarded-for', 'x-last-hr', 'x-last-http-status-code', 'x-removed', 'x-real-ip', 'x-retry-count',
                       146: 		])
                       147: 
                       148: 		print('===============[ {} request ]==='.format(self.command))
                       149: 
                       150: 		for header in self.headers:
                       151: 			if header in proxy_ignored:
                       152: 				pass
                       153: 			elif header in ('range'):
                       154: 				isRange = re.compile('bytes=(\d+)-(\d+)').match(self.headers[header])
                       155: 				if isRange:
                       156: 					requested_ranges = spacemap.SpaceMap({int(isRange.group(1)): int(isRange.group(2)) + 1})
                       157: 				else:
                       158: 					return()
                       159: 			elif header in ('pragma'):
                       160: 				if my_path in index:
                       161: 					index[my_path][header] = self.headers[header]
                       162: 			else:
                       163: 				print('Unknown header - ', header, ': ', self.headers[header], sep='')
                       164: 				return()
                       165: 			print(header, self.headers[header])
                       166: 
                       167: 		# creating file name from my_path
                       168: 		file_name = config['dir'] + os.sep + re.compile('%20').sub(' ', my_path)
                       169: 		# partial file or unfinished download
                       170: 		temp_name = config['dir'] + os.sep + '.parts' + re.compile('%20').sub(' ', my_path)
                       171: 
                       172: 		# creating empty placeholder in index
                       173: 		# if there's no space map and there's no file in real directory - we have no file
                       174: 		# if there's an empty space map - file is full
                       175: 		# space map generally covers every bit of file we don't posess currently
                       176: 		if not my_path in index:
                       177: 			info += '\nThis one is new.'
                       178: 			reload = True
                       179: 			record = {}
                       180: 		else:
                       181: 			# forcibly checking file if no file present
                       182: 			record = index[my_path]
                       183: 			if os.access(file_name, os.R_OK):
                       184: 				info += '\nFull file found.'
                       185: 				file_stat = os.stat(file_name)
                       186: 			elif '_parts' in index[my_path] and os.access(temp_name, os.R_OK):
                       187: 				info += '\nPartial file found.'
                       188: 				file_stat = os.stat(temp_name)
                       189: 				recheck = True
                       190: 			else:
                       191: 				info += '\nFile not found or inaccessible.'
                       192: 				record['_parts'] = None
                       193: 				reload = True
                       194: 
                       195: 		if not '_parts' in record:
                       196: 			record['_parts'] = None
                       197: 
                       198: 		if record['_parts'] == None:
                       199: 			recheck = True
                       200: 
                       201: 		# forcibly checking file if file size doesn't match with index data
                       202: 		if not reload:
                       203: 			if '_parts' in record and record['_parts'] == spacemap.SpaceMap():
                       204: 				if 'content-length' in record and file_stat and file_stat.st_size != int(record['content-length']):
                       205: 					info += '\nFile size is {} and stored file size is {}.'.format(file_stat.st_size, record['content-length'])
                       206: 					record['_parts'] = None
                       207: 					reload = True
                       208: 
                       209: 		# forcibly checking file if index holds Pragma header
                       210: 		if not reload and 'pragma' in record and record['pragma'] == 'no-cache':
                       211: 			info +='\nPragma on: recheck imminent.'
                       212: 			recheck = True
                       213: 
                       214: 		# skipping file processing if there's no need to recheck it and we have checked it at least 4 hours ago
                       215: 		if not recheck and not reload and '_time' in record and (record['_time'] - datetime.datetime.now() + datetime.timedelta(hours = 4)).days < 0:
                       216: 			info += '\nFile is old - rechecking.'
                       217: 			recheck = True
                       218: 
                       219: 		print(info)
                       220: 		if reload or recheck:
                       221: 
                       222: 			try:
                       223: 				request = 'http://' + config['root'] + self.path
                       224: 				my_headers = {}
                       225: 				for header in ('cache-control', 'cookie', 'referer', 'user-agent'):
                       226: 					if header in self.headers:
                       227: 						my_headers[header] = self.headers[header]
                       228: 
                       229: 				needed = None
                       230: 				if '_parts' in record and record['_parts'] != None:
                       231: 					if config['noparts'] != 'no' or requested_ranges == None or requested_ranges == spacemap.SpaceMap():
                       232: 						needed = record['_parts']
                       233: 					else:
                       234: 						needed = record['_parts'] & requested_ranges
                       235: 				elif config['noparts'] =='no' and requested_ranges != None and requested_ranges != spacemap.SpaceMap():
                       236: 					needed = requested_ranges
                       237: 				ranges = ()
                       238: 				print('Missing ranges: {}, requested ranges: {}, needed ranges: {}.'.format(record['_parts'], requested_ranges, needed))
                       239: 				if needed != None and len(needed) > 0:
                       240: 					needed.rewind()
                       241: 					while True:
                       242: 						range = needed.pop()
                       243: 						if range[0] == None:
                       244: 							break
                       245: 						ranges += '{}-{}'.format(range[0], range[1] - 1),
601ec56da6 2011-12-19  246: 					my_headers['range'] = 'bytes=' + ','.join(ranges)
                       247: 
                       248: 				request = urllib2.Request(request, headers = my_headers)
                       249: 
                       250: 				source = urllib2.urlopen(request)
                       251: 				new_record = {}
                       252: 				new_record['_parts'] = record['_parts']
                       253: 				headers = source.info()
                       254: 
                       255: 				# stripping unneeded headers (XXX make this inplace?)
                       256: 				for header in headers:
                       257: 					if header in desc_fields:
                       258: 						#if header == 'Pragma' and headers[header] != 'no-cache':
                       259: 						if header == 'content-length':
                       260: 							if 'content-range' not in headers:
                       261: 								new_record[header] = int(headers[header])
                       262: 						else:
                       263: 							new_record[header] = headers[header]
                       264: 					elif header == 'content-range':
                       265: 						range = re.compile('^bytes (\d+)-(\d+)/(\d+)$').match(headers[header])
                       266: 						if range:
                       267: 							new_record['content-length'] = int(range.group(3))
                       268: 						else:	
                       269: 							assert False, 'Content-Range unrecognized.'
                       270: 					elif not header in ignore_fields:
                       271: 						print('Undefined header "', header, '": ', headers[header], sep='')
                       272: 
                       273: 				# comparing headers with data found in index
                       274: 				# if any header has changed (except Pragma) file is fully downloaded
                       275: 				# same if we get more or less headers
                       276: 				old_keys = set(record.keys())
                       277: 				old_keys.discard('_time')
                       278: 				old_keys.discard('pragma')
                       279: 				more_keys = set(new_record.keys()) - old_keys
                       280: 				more_keys.discard('pragma')
                       281: 				less_keys = old_keys - set(new_record.keys())
                       282: 				if len(more_keys) > 0:
                       283: 					if len(old_keys) != 0:
                       284: 						print('More headers appear:', more_keys)
                       285: 					reload = True
                       286: 				elif len(less_keys) > 0:
                       287: 					print('Less headers appear:', less_keys)
                       288: 				else:
                       289: 					for key in record.keys():
                       290: 						if key[0] != '_' and key != 'pragma' and record[key] != new_record[key]:
                       291: 							print('Header "', key, '" changed from [', record[key], '] to [', new_record[key], ']', sep='')
                       292: 							print(type(record[key]), type(new_record[key]))
                       293: 							reload = True
                       294: 
                       295: 				if reload:
                       296: 					print('Reloading.')
                       297: 					if os.access(temp_name, os.R_OK):
                       298: 						os.unlink(temp_name)
                       299: 					if os.access(file_name, os.R_OK):
                       300: 						os.unlink(file_name)
                       301: 					if 'content-length' in new_record:
                       302: 						new_record['_parts'] = spacemap.SpaceMap({0: int(new_record['content-length'])})
                       303: 				if not new_record['_parts']:
                       304: 					new_record['_parts'] = spacemap.SpaceMap()
                       305: 				print(new_record)
                       306: 
                       307: 				# downloading file or segment
                       308: 				if 'content-length' in new_record:
                       309: 					if needed == None:
                       310: 						needed = new_record['_parts']
                       311: 					else:
                       312: 						if len(needed) > 1:
                       313: 							print("Multipart requests currently not supported.")
                       314: 							assert False, 'Skip this one for now.'
                       315: 				#else:
                       316: 					#assert False, 'No content-length or Content-Range header.'
                       317: 
                       318: 				new_record['_time'] = datetime.datetime.now()
                       319: 				if self.command not in ('HEAD'):
                       320: 					# file is created at temporary location and moved in place only when download completes
                       321: 					if not os.access(temp_name, os.R_OK):
                       322: 						empty_name = config['dir'] + os.sep + '.tmp'
                       323: 						with open(empty_name, 'w+b') as some_file:
                       324: 							pass
                       325: 						os.renames(empty_name, temp_name)
                       326: 					temp_file = open(temp_name, 'r+b')
                       327: 					if requested_ranges == None and needed == None:
                       328: 						needed = new_record['_parts']
                       329: 					needed.rewind()
                       330: 					while True:
                       331: 						(start, end) = needed.pop()
                       332: 						if start == None:
                       333: 							break
                       334: 						stream_last = start
                       335: 						old_record = copy.copy(new_record)
                       336: 						if end - start < block_size:
                       337: 							req_block_size = end - start
                       338: 						else:
                       339: 							req_block_size = block_size
                       340: 						buffer = source.read(req_block_size)
                       341: 						length = len(buffer)
                       342: 						while length > 0 and stream_last < end:
                       343: 							stream_pos = stream_last + length
                       344: 							assert stream_pos <= end, 'Received more data then requested: pos:{} start:{} end:{}.'.format(stream_pos, start, end)
                       345: 							temp_file.seek(stream_last)
                       346: 							temp_file.write(buffer)
                       347: 							x = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
                       348: 							new_record['_parts'] = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
                       349: 							index[my_path] = old_record
                       350: 							index.sync()
                       351: 							old_record = copy.copy(new_record)
                       352: 							stream_last = stream_pos
                       353: 							if end - stream_last < block_size:
                       354: 								req_block_size = end - stream_last
                       355: 							buffer = source.read(req_block_size)
                       356: 							length = len(buffer)
                       357: 					# moving downloaded data to real file
                       358: 					temp_file.close()
                       359: 
                       360: 				index[my_path] = new_record
                       361: 				index.sync()
                       362: 
                       363: 			except urllib2.HTTPError as error:
                       364: 				# in case of error we don't need to do anything actually,
                       365: 				# if file download stalls or fails the file would not be moved to it's location
                       366: 				print(error)
                       367: 
                       368: 		print(index[my_path])
                       369: 
                       370: 		if not os.access(file_name, os.R_OK) and os.access(temp_name, os.R_OK) and '_parts' in index[my_path] and index[my_path]['_parts'] == spacemap.SpaceMap():
                       371: 			# just moving
                       372: 			# drop old dirs XXX
                       373: 			print('Moving temporary file to new destination.')
                       374: 			os.renames(temp_name, file_name)
                       375: 
                       376: 		if not my_path in index:
                       377: 			self.send_response(502)
                       378: 			self.end_headers()
                       379: 			return
                       380: 
                       381: 		if self.command == 'HEAD':
                       382: 			self.send_response(200)
                       383: 			if 'content-length' in index[my_path]:
                       384: 				self.send_header('content-length', index[my_path]['content-length'])
                       385: 			self.send_header('accept-ranges', 'bytes')
                       386: 			self.send_header('content-type', 'application/octet-stream')
                       387: 			if 'last-modified' in index[my_path]:
                       388: 				self.send_header('last-modified', index[my_path]['last-modified'])
                       389: 			self.end_headers()
                       390: 		else:
                       391: 			if ('_parts' in index[my_path] and index[my_path]['_parts'] != spacemap.SpaceMap()) or not os.access(file_name, os.R_OK):
                       392: 				file_name = temp_name
                       393: 
                       394: 			with open(file_name, 'rb') as real_file:
                       395: 				file_stat = os.stat(file_name)
                       396: 				if 'range' in self.headers:
                       397: 					self.send_response(206)
                       398: 					ranges = ()
                       399: 					requested_ranges.rewind()
                       400: 					while True:
                       401: 						pair = requested_ranges.pop()
                       402: 						if pair[0] == None:
                       403: 							break
                       404: 						ranges += '{}-{}'.format(pair[0], str(pair[1] - 1)),
                       405: 					self.send_header('content-range', 'bytes {}/{}'.format(','.join(ranges), index[my_path]['content-length']))
                       406: 				else:
                       407: 					self.send_response(200)
                       408: 					self.send_header('content-length', str(file_stat.st_size))
                       409: 					requested_ranges = spacemap.SpaceMap({0: file_stat.st_size})
                       410: 				if 'last-modified' in index[my_path]:
                       411: 					self.send_header('last-modified', index[my_path]['last-modified'])
                       412: 				self.send_header('content-type', 'application/octet-stream')
                       413: 				self.end_headers()
                       414: 				if self.command in ('GET'):
                       415: 					if len(requested_ranges) > 0:
                       416: 						requested_ranges.rewind()
                       417: 						(start, end) = requested_ranges.pop()
                       418: 					else:
                       419: 						start = 0
                       420: 						# XXX ugly hack
                       421: 						if 'content-length' in index[my_path]:
                       422: 							end = index[my_path]['content-length']
                       423: 						else:
                       424: 							end = 0
                       425: 					real_file.seek(start)
                       426: 					if block_size > end - start:
                       427: 						req_block_size = end - start
                       428: 					else:
                       429: 						req_block_size = block_size
                       430: 					buffer = real_file.read(req_block_size)
                       431: 					length = len(buffer)
                       432: 					while length > 0:
                       433: 						self.wfile.write(buffer)
                       434: 						start += len(buffer)
                       435: 						if req_block_size > end - start:
                       436: 							req_block_size = end - start
                       437: 						if req_block_size == 0:
                       438: 							break
                       439: 						buffer = real_file.read(req_block_size)
                       440: 						length = len(buffer)
                       441: 				
                       442: 	def do_HEAD(self):
                       443: 		return self.__process()
                       444: 	def do_GET(self):
                       445: 		return self.__process()
                       446: 
                       447: config.section('general')
                       448: server = BaseHTTPServer.HTTPServer(('127.0.0.1', int(config['port'])), MyRequestHandler)
                       449: server.serve_forever()