Samesite - proxy that can cache partial transfers

Annotation For samesite.py
anonymous

Annotation For samesite.py

Lines of samesite.py from check-in 38b25713eb that are changed by the sequence of edits moving toward check-in 827033dd7e:

                         1: #!/usr/bin/env python3.1
                         2: 
                         3: import datetime, http.cookiejar, optparse, os, sys, shelve, re, urllib.request
                         4: 
                         5: parser = optparse.OptionParser()
                         6: parser.add_option('-v', '--verbose', action = 'store_true', dest = 'verbose', help = 'turns on verbose status notifications', metavar = 'bool', default = False)
                         7: parser.add_option('-d', '--dir', action = 'store', dest = 'dir', help = 'specify directory where the files should be stored', metavar = 'string', default = None)
                         8: parser.add_option('-r', '--root', action = 'store', dest = 'root', help = 'specify a site from which data should be mirrored', metavar = 'string', default = None)
                         9: parser.add_option('-l', '--log', action = 'store', dest = 'log', help = 'specify a log file to process', metavar = 'string', default = None)
                        10: parser.add_option('-e', '--skip-etag', action = 'store_true', dest = 'noetag', help = 'do not process etags', metavar = 'bool', default = False)
                        11: (options, args) = parser.parse_args()
                        12: 
                        13: assert options.dir, 'Directory not specified'
                        14: assert options.root, 'Server not specified'
                        15: assert options.log, 'Log file not specified'
                        16: assert os.access(options.log, os.R_OK), 'Log file unreadable'
                        17: 
                        18: # this is file index - everything is stored in this file
                        19: index = shelve.open(options.dir + '/.index')
                        20: desc_fields = ('Content-Length', 'Pragma', 'Last-Modified')
                        21: ignore_fields = ('Accept-Ranges', 'Age', 'Cache-Control', 'Connection', 'Content-Type', 'Date', 'Expires', 'Server', 'Via', 'X-Cache', 'X-Cache-Lookup', 'X-Powered-By')
                        22: 
                        23: if not options.noetag:
                        24: 	desc_fields += 'ETag',
                        25: else:
                        26: 	ignore_fields += 'ETag',
                        27: 
                        28: block_size = 32768
                        29: 
                        30: while True:
                        31: 	unchecked_files = set()
                        32: 	checked_files = 0
                        33: 
                        34: 	# reading log and storing found urls for processing
                        35: 	# check file mtime XXX
                        36: 	with open(options.log, 'r') as log_file:
                        37: 		log_line = re.compile('^[^ ]+ - - \[.*] "(GET|HEAD) (.*?)(\?.*)? HTTP/1.1" (\d+) \d+ "(.*)" "(.*)"$')
                        38: 		for line in log_file:
                        39: 			this_line = log_line.match(line.strip())
                        40: 			if this_line:
                        41: 				unchecked_files.add(this_line.group(2))
                        42: 
                        43: 	for url in unchecked_files:
                        44: 		reload = False
                        45: 		recheck = False
38b25713eb 2010-07-26   46: 		print('Checking file:', url)
                        47: 
                        48: 		# creating empty placeholder in index
                        49: 		if not url in index:
38b25713eb 2010-07-26   50: 			print('This one is new.')
                        51: 			index[url] = {}
                        52: 			reload = True
                        53: 
                        54: 		# creating file name from url
                        55: 		file_name = options.dir + re.compile('%20').sub(' ', url)
                        56: 
                        57: 		# forcibly checking file if no file present
                        58: 		if not reload and not os.access(file_name, os.R_OK):
38b25713eb 2010-07-26   59: 			print('File not found or inaccessible.')
                        60: 			reload = True
                        61: 
                        62: 		# forcibly checking file if file size doesn't match with index data
                        63: 		elif not reload and 'Content-Length' in index[url] and os.stat(file_name).st_size != int(index[url]['Content-Length']):
38b25713eb 2010-07-26   64: 			print('File size is ', os.stat(file_name).st_size, ' and stored file size is ', index[url]['Content-Length'], '.', sep='')
                        65: 			reload = True
                        66: 
                        67: 		# forcibly checking file if index hods Pragma header
                        68: 		if not reload and 'Pragma' in index[url] and index[url]['Pragma'] == 'no-cache':
38b25713eb 2010-07-26   69: 			print('Pragma on: recheck imminent.')
                        70: 			recheck = True
                        71: 
                        72: 		# skipping file processing if there's no need to recheck it and we have checked it at least 4 hours ago
                        73: 		if not recheck and not reload and '__time__' in index[url] and (datetime.datetime.now() - datetime.timedelta(hours = 4) - index[url]['__time__']).days < 0:
                        74: 			continue
                        75: 
                        76: 		try:
                        77: 			with urllib.request.urlopen(options.root + url) as source:
                        78: 				new_headers = {}
                        79: 				headers = source.info()
                        80: 
                        81: 				# stripping unneeded headers (XXX make this inplace?)
                        82: 				for header in headers:
                        83: 					if header in desc_fields:
                        84: 						if header == 'Pragma' and headers[header] != 'no-cache':
                        85: 							print('Pragma:', headers[header])
                        86: 						new_headers[header] = headers[header]
                        87: 					elif not header in ignore_fields:
                        88: 						print('Undefined header "', header, '": ', headers[header], sep='')
                        89: 
                        90: 				# comparing headers with data found in index
                        91: 				# if any header has changed (except Pragma) file is fully downloaded
                        92: 				# same if we get more or less headers
                        93: 				old_keys = set(index[url].keys())
                        94: 				old_keys.discard('__time__')
                        95: 				old_keys.discard('Pragma')
                        96: 				more_keys = set(new_headers.keys()) - old_keys
                        97: 				more_keys.discard('Pragma')
                        98: 				less_keys = old_keys - set(new_headers.keys())
                        99: 				if len(more_keys) > 0:
                       100: 					if not len(old_keys) == 0:
                       101: 						print('More headers appear:', more_keys)
                       102: 					reload = True
                       103: 				elif len(less_keys) > 0:
                       104: 					print('Less headers appear:', less_keys)
                       105: 				else:
                       106: 					for key in index[url].keys():
                       107: 						if key not in ('__time__', 'Pragma') and not index[url][key] == new_headers[key]:
                       108: 							print('Header "', key, '" changed from [', index[url][key], '] to [', new_headers[key], ']', sep='')
                       109: 							reload = True
                       110: 
                       111: 				# downloading file
                       112: 				if reload:
                       113: 					if 'Content-Length' in headers:
                       114: 						print('Downloading', headers['Content-Length'], 'bytes [', end='')
                       115: 					else:
                       116: 						print('Downloading [', end='')
                       117: 					sys.stdout.flush()
                       118: 
                       119: 					# file is created at temporary location and moved in place only when download completes
                       120: 					temp_file = open(options.dir + '/.tmp', 'wb')
                       121: 					buffer = source.read(block_size)
                       122: 					blocks = 0
                       123: 					megs = 0
                       124: 					while len(buffer) > 0:
                       125: 						temp_file.write(buffer)
                       126: 						print('.', end='')
                       127: 						sys.stdout.flush()
                       128: 						buffer = source.read(block_size)
                       129: 						blocks += 1
                       130: 						if blocks > 1024*1024/block_size:
                       131: 							blocks = blocks - 1024*1024/block_size
                       132: 							megs += 1
                       133: 							print('{}Mb'.format(megs), end='')
                       134: 					temp_file.close()
                       135: 					print(']')
                       136: 					os.renames(options.dir + '/.tmp', file_name)
                       137: 
                       138: 				checked_files += 1
                       139: 
                       140: 				# storing new time mark and storing new headers
                       141: 				new_headers['__time__'] = datetime.datetime.now()
                       142: 				index[url] = new_headers
                       143: 				index.sync()
                       144: 
                       145: 		except urllib.error.HTTPError as error:
                       146: 			# in case of error we don't need to do anything actually,
                       147: 			# if file download stalls or fails the file would not be moved to it's location
                       148: 			print(error)
                       149: 
38b25713eb 2010-07-26  150: 	print('[', len(unchecked_files), '/', checked_files, ']')
                       151: 
                       152: 	# checking if there were any files downloaded, if yes - restarting sequence
                       153: 	if checked_files == 0:
                       154: 		break