Samesite - proxy that can cache partial transfers

Annotation For samesite.py
anonymous

Annotation For samesite.py

Origin for each line in samesite.py from check-in 44aa59eb58:

d8731957ad 2012-08-07 arcade@b1t.na: #!/usr/bin/env python3.2
9a8a46bcf0 2011-09-06 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: from __future__ import unicode_literals, print_function
601ec56da6 2011-12-19 c.kworr@b84a3: 
82969b1fc2 2012-01-25 c.kworr@b84a3: #import gevent.monkey
82969b1fc2 2012-01-25 c.kworr@b84a3: #gevent.monkey.patch_all()
82969b1fc2 2012-01-25 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: import argparse, os
d8731957ad 2012-08-07 arcade@b1t.na: parser = argparse.ArgumentParser()
d8731957ad 2012-08-07 arcade@b1t.na: parser.add_argument('-c', '--config', dest = 'config', help = 'config file location', metavar = 'FILE', default = 'samesite.conf')
d8731957ad 2012-08-07 arcade@b1t.na: args = parser.parse_args()
d8731957ad 2012-08-07 arcade@b1t.na: assert os.access(args.config, os.R_OK), "Fatal error: can't read {}".format(args.config)
d8731957ad 2012-08-07 arcade@b1t.na: 
d8731957ad 2012-08-07 arcade@b1t.na: import configparser
d8731957ad 2012-08-07 arcade@b1t.na: config = configparser.ConfigParser({
d8731957ad 2012-08-07 arcade@b1t.na: 	'port': '8008',
d8731957ad 2012-08-07 arcade@b1t.na: 	'verbose': 'no',
d8731957ad 2012-08-07 arcade@b1t.na: 	'noetag': 'no',
d8731957ad 2012-08-07 arcade@b1t.na: 	'noparts': 'no',
d8731957ad 2012-08-07 arcade@b1t.na: 	'strip': '',
d8731957ad 2012-08-07 arcade@b1t.na: 	'sub': '',
d8731957ad 2012-08-07 arcade@b1t.na: 	'proto': 'http',
d8731957ad 2012-08-07 arcade@b1t.na: })
d8731957ad 2012-08-07 arcade@b1t.na: config.read(args.config)
d8731957ad 2012-08-07 arcade@b1t.na: 
d8731957ad 2012-08-07 arcade@b1t.na: cache_dir = os.path.realpath(os.path.dirname(args.config))
d8731957ad 2012-08-07 arcade@b1t.na: 
d8731957ad 2012-08-07 arcade@b1t.na: import re
d8731957ad 2012-08-07 arcade@b1t.na: for section in config.sections():
d8731957ad 2012-08-07 arcade@b1t.na: 	if section != 'DEFAULT':
d8731957ad 2012-08-07 arcade@b1t.na: 		if 'dir' in config[section]:
d8731957ad 2012-08-07 arcade@b1t.na: 			if not re.compile('^/.*').match(config[section]['dir']):
d8731957ad 2012-08-07 arcade@b1t.na: 				config[section]['dir'] = cache_dir + os.sep + section
d8731957ad 2012-08-07 arcade@b1t.na: 			thisDir = re.compile('^(.*)/$').match(config[section]['dir'])
d8731957ad 2012-08-07 arcade@b1t.na: 			if thisDir:
d8731957ad 2012-08-07 arcade@b1t.na: 				config[section]['dir'] = thisDir.group(1)
d8731957ad 2012-08-07 arcade@b1t.na: 			if not re.compile('^/(.*)$').match(config[section]['dir']):
d8731957ad 2012-08-07 arcade@b1t.na: 				config[section]['dir'] = cache_dir + os.sep + config[section]['dir']
d8731957ad 2012-08-07 arcade@b1t.na: 		else:
d8731957ad 2012-08-07 arcade@b1t.na: 			config[section]['dir'] = cache_dir + os.sep + section
d8731957ad 2012-08-07 arcade@b1t.na: 
d8731957ad 2012-08-07 arcade@b1t.na: 		if not 'root' in config[section]:
d8731957ad 2012-08-07 arcade@b1t.na: 			config[section]['root'] = section
cab908195f 2010-09-06 c.kworr@b84a3: 
cab908195f 2010-09-06 c.kworr@b84a3: #assert options.port or os.access(options.log, os.R_OK), 'Log file unreadable'
cab908195f 2010-09-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: const_desc_fields = set(['Content-Length', 'Last-Modified', 'Pragma'])
cab908195f 2010-09-06 c.kworr@b84a3: const_ignore_fields = set([
d8731957ad 2012-08-07 arcade@b1t.na: 	'Accept-Ranges', 'Age',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Cache-Control', 'Connection', 'Content-Type',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Date',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Expires',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Referer',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Server',
d8731957ad 2012-08-07 arcade@b1t.na: 	'Via',
d8731957ad 2012-08-07 arcade@b1t.na: 	'X-Cache', 'X-Cache-Lookup', 'X-Livetool', 'X-Powered-By',
90160dbf50 2011-03-06 c.kworr@b84a3: ])
90160dbf50 2011-03-06 c.kworr@b84a3: 
82969b1fc2 2012-01-25 c.kworr@b84a3: block_size = 8192
82969b1fc2 2012-01-25 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: import bsddb3.dbshelve, copy, datetime, http.server, spacemap, urllib.request, urllib.error
d8731957ad 2012-08-07 arcade@b1t.na: 
d8731957ad 2012-08-07 arcade@b1t.na: class MyRequestHandler(http.server.BaseHTTPRequestHandler):
90160dbf50 2011-03-06 c.kworr@b84a3: 	def __process(self):
90160dbf50 2011-03-06 c.kworr@b84a3: 		# reload means file needs to be reloaded to serve request
90160dbf50 2011-03-06 c.kworr@b84a3: 		reload = False
90160dbf50 2011-03-06 c.kworr@b84a3: 		# recheck means file needs to be checked, this also means that if file hav been modified we can serve older copy
90160dbf50 2011-03-06 c.kworr@b84a3: 		recheck = False
90160dbf50 2011-03-06 c.kworr@b84a3: 		# file_stat means file definitely exists
90160dbf50 2011-03-06 c.kworr@b84a3: 		file_stat = None
90160dbf50 2011-03-06 c.kworr@b84a3: 		# requested_ranges holds data about any range requested
90160dbf50 2011-03-06 c.kworr@b84a3: 		requested_ranges = None
90160dbf50 2011-03-06 c.kworr@b84a3: 		# records holds data from index locally, should be written back upon successfull completion
90160dbf50 2011-03-06 c.kworr@b84a3: 		record = None
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		myPath = re.compile('^(.*?)(\?.*)$').match(self.path)
90160dbf50 2011-03-06 c.kworr@b84a3: 		if myPath:
90160dbf50 2011-03-06 c.kworr@b84a3: 			my_path = myPath.group(1)
90160dbf50 2011-03-06 c.kworr@b84a3: 		else:
90160dbf50 2011-03-06 c.kworr@b84a3: 			my_path = self.path
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		config_host = config[self.headers['Host']]
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		if config_host['sub'] != None and config_host['strip'] != None and len(config_host['strip']) > 0:
d8731957ad 2012-08-07 arcade@b1t.na: 			string = re.compile(config_host['strip']).sub(config_host['sub'], my_path)
90160dbf50 2011-03-06 c.kworr@b84a3: 			my_path = string
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		my_path_b = my_path.encode('utf-8')
90160dbf50 2011-03-06 c.kworr@b84a3: 		info = 'Checking file: ' + my_path
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		if not os.access(config_host['dir'], os.X_OK):
d8731957ad 2012-08-07 arcade@b1t.na: 			os.mkdir(config_host['dir'])
90160dbf50 2011-03-06 c.kworr@b84a3: 		# this is file index - everything is stored in this file
90160dbf50 2011-03-06 c.kworr@b84a3: 		# _parts - list of stored parts of file
90160dbf50 2011-03-06 c.kworr@b84a3: 		# _time - last time the file was checked
90160dbf50 2011-03-06 c.kworr@b84a3: 		# everything else is just the headers
d8731957ad 2012-08-07 arcade@b1t.na: 		index = bsddb3.dbshelve.open(config_host['dir'] + os.sep + '.index')
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		desc_fields = const_desc_fields.copy()
90160dbf50 2011-03-06 c.kworr@b84a3: 		ignore_fields = const_ignore_fields.copy()
d8731957ad 2012-08-07 arcade@b1t.na: 		if config_host['noetag'] == 'no':
601ec56da6 2011-12-19 c.kworr@b84a3: 			desc_fields.add('etag')
90160dbf50 2011-03-06 c.kworr@b84a3: 		else:
601ec56da6 2011-12-19 c.kworr@b84a3: 			ignore_fields.add('etag')
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		proxy_ignored = set([
d8731957ad 2012-08-07 arcade@b1t.na: 			'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language',
d8731957ad 2012-08-07 arcade@b1t.na: 			'Cache-Control', 'Connection', 'Content-Length', 'Cookie',
d8731957ad 2012-08-07 arcade@b1t.na: 			'Host',
d8731957ad 2012-08-07 arcade@b1t.na: 			'If-Modified-Since', 'If-Unmodified-Since',
d8731957ad 2012-08-07 arcade@b1t.na: 			'Referer',
d8731957ad 2012-08-07 arcade@b1t.na: 			'Ua-Cpu', 'User-Agent',
d8731957ad 2012-08-07 arcade@b1t.na: 			'Via',
44aa59eb58 2012-08-09 arcade@b1t.na: 			'X-Forwarded-For', 'X-Last-HR', 'X-Last-HTTP-Status-Code', 'X-Old-UID', 'X-Removed', 'X-Real-IP', 'X-Retry-Count',
90160dbf50 2011-03-06 c.kworr@b84a3: 		])
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		print('===============[ {} request ]==='.format(self.command))
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		for header in self.headers:
90160dbf50 2011-03-06 c.kworr@b84a3: 			if header in proxy_ignored:
90160dbf50 2011-03-06 c.kworr@b84a3: 				pass
d8731957ad 2012-08-07 arcade@b1t.na: 			elif header in ('Range'):
90160dbf50 2011-03-06 c.kworr@b84a3: 				isRange = re.compile('bytes=(\d+)-(\d+)').match(self.headers[header])
90160dbf50 2011-03-06 c.kworr@b84a3: 				if isRange:
90160dbf50 2011-03-06 c.kworr@b84a3: 					requested_ranges = spacemap.SpaceMap({int(isRange.group(1)): int(isRange.group(2)) + 1})
90160dbf50 2011-03-06 c.kworr@b84a3: 				else:
90160dbf50 2011-03-06 c.kworr@b84a3: 					return()
d8731957ad 2012-08-07 arcade@b1t.na: 			elif header in ('Pragma'):
d8731957ad 2012-08-07 arcade@b1t.na: 				if my_path_b in index:
d8731957ad 2012-08-07 arcade@b1t.na: 					index[my_path_b][header] = self.headers[header]
90160dbf50 2011-03-06 c.kworr@b84a3: 			else:
90160dbf50 2011-03-06 c.kworr@b84a3: 				print('Unknown header - ', header, ': ', self.headers[header], sep='')
90160dbf50 2011-03-06 c.kworr@b84a3: 				return()
90160dbf50 2011-03-06 c.kworr@b84a3: 			print(header, self.headers[header])
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		# creating file name from my_path
d8731957ad 2012-08-07 arcade@b1t.na: 		file_name = config_host['dir'] + os.sep + re.compile('%20').sub(' ', my_path)
90160dbf50 2011-03-06 c.kworr@b84a3: 		# partial file or unfinished download
d8731957ad 2012-08-07 arcade@b1t.na: 		temp_name = config_host['dir'] + os.sep + '.parts' + re.compile('%20').sub(' ', my_path)
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		# creating empty placeholder in index
90160dbf50 2011-03-06 c.kworr@b84a3: 		# if there's no space map and there's no file in real directory - we have no file
90160dbf50 2011-03-06 c.kworr@b84a3: 		# if there's an empty space map - file is full
90160dbf50 2011-03-06 c.kworr@b84a3: 		# space map generally covers every bit of file we don't posess currently
d8731957ad 2012-08-07 arcade@b1t.na: 		if not my_path_b in index:
90160dbf50 2011-03-06 c.kworr@b84a3: 			info += '\nThis one is new.'
90160dbf50 2011-03-06 c.kworr@b84a3: 			reload = True
90160dbf50 2011-03-06 c.kworr@b84a3: 			record = {}
90160dbf50 2011-03-06 c.kworr@b84a3: 		else:
90160dbf50 2011-03-06 c.kworr@b84a3: 			# forcibly checking file if no file present
d8731957ad 2012-08-07 arcade@b1t.na: 			record = index[my_path_b]
90160dbf50 2011-03-06 c.kworr@b84a3: 			if os.access(file_name, os.R_OK):
90160dbf50 2011-03-06 c.kworr@b84a3: 				info += '\nFull file found.'
90160dbf50 2011-03-06 c.kworr@b84a3: 				file_stat = os.stat(file_name)
d8731957ad 2012-08-07 arcade@b1t.na: 			elif '_parts' in index[my_path_b] and os.access(temp_name, os.R_OK):
90160dbf50 2011-03-06 c.kworr@b84a3: 				info += '\nPartial file found.'
90160dbf50 2011-03-06 c.kworr@b84a3: 				file_stat = os.stat(temp_name)
d1fa9d0737 2012-01-16 c.kworr@b84a3: 				recheck = True
90160dbf50 2011-03-06 c.kworr@b84a3: 			else:
90160dbf50 2011-03-06 c.kworr@b84a3: 				info += '\nFile not found or inaccessible.'
90160dbf50 2011-03-06 c.kworr@b84a3: 				record['_parts'] = None
90160dbf50 2011-03-06 c.kworr@b84a3: 				reload = True
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		if not '_parts' in record:
90160dbf50 2011-03-06 c.kworr@b84a3: 			record['_parts'] = None
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		if record['_parts'] == None:
90160dbf50 2011-03-06 c.kworr@b84a3: 			recheck = True
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		# forcibly checking file if file size doesn't match with index data
90160dbf50 2011-03-06 c.kworr@b84a3: 		if not reload:
90160dbf50 2011-03-06 c.kworr@b84a3: 			if '_parts' in record and record['_parts'] == spacemap.SpaceMap():
601ec56da6 2011-12-19 c.kworr@b84a3: 				if 'content-length' in record and file_stat and file_stat.st_size != int(record['content-length']):
601ec56da6 2011-12-19 c.kworr@b84a3: 					info += '\nFile size is {} and stored file size is {}.'.format(file_stat.st_size, record['content-length'])
90160dbf50 2011-03-06 c.kworr@b84a3: 					record['_parts'] = None
90160dbf50 2011-03-06 c.kworr@b84a3: 					reload = True
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		# forcibly checking file if index holds Pragma header
601ec56da6 2011-12-19 c.kworr@b84a3: 		if not reload and 'pragma' in record and record['pragma'] == 'no-cache':
90160dbf50 2011-03-06 c.kworr@b84a3: 			info +='\nPragma on: recheck imminent.'
90160dbf50 2011-03-06 c.kworr@b84a3: 			recheck = True
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		# skipping file processing if there's no need to recheck it and we have checked it at least 4 hours ago
8425e2e393 2011-12-14 c.kworr@b84a3: 		if not recheck and not reload and '_time' in record and (record['_time'] - datetime.datetime.now() + datetime.timedelta(hours = 4)).days < 0:
8425e2e393 2011-12-14 c.kworr@b84a3: 			info += '\nFile is old - rechecking.'
90160dbf50 2011-03-06 c.kworr@b84a3: 			recheck = True
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		print(info)
90160dbf50 2011-03-06 c.kworr@b84a3: 		if reload or recheck:
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 			try:
d8731957ad 2012-08-07 arcade@b1t.na: 				request = config_host['proto'] + '://' + config_host['root'] + self.path
90160dbf50 2011-03-06 c.kworr@b84a3: 				my_headers = {}
44aa59eb58 2012-08-09 arcade@b1t.na: 				for header in ('Accept', 'Cache-Control', 'Cookie', 'Referer', 'User-Agent'):
90160dbf50 2011-03-06 c.kworr@b84a3: 					if header in self.headers:
90160dbf50 2011-03-06 c.kworr@b84a3: 						my_headers[header] = self.headers[header]
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 				needed = None
b5c328f916 2012-01-04 c.kworr@b84a3: 				if self.command not in ('HEAD'):
b5c328f916 2012-01-04 c.kworr@b84a3: 					if '_parts' in record and record['_parts'] != None:
d8731957ad 2012-08-07 arcade@b1t.na: 						if config_host['noparts'] != 'no' or requested_ranges == None or requested_ranges == spacemap.SpaceMap():
b5c328f916 2012-01-04 c.kworr@b84a3: 							needed = record['_parts']
b5c328f916 2012-01-04 c.kworr@b84a3: 						else:
b5c328f916 2012-01-04 c.kworr@b84a3: 							needed = record['_parts'] & requested_ranges
d8731957ad 2012-08-07 arcade@b1t.na: 					elif config_host['noparts'] =='no' and requested_ranges != None and requested_ranges != spacemap.SpaceMap():
b5c328f916 2012-01-04 c.kworr@b84a3: 						needed = requested_ranges
b5c328f916 2012-01-04 c.kworr@b84a3: 					ranges = ()
b5c328f916 2012-01-04 c.kworr@b84a3: 					print('Missing ranges: {}, requested ranges: {}, needed ranges: {}.'.format(record['_parts'], requested_ranges, needed))
b5c328f916 2012-01-04 c.kworr@b84a3: 					if needed != None and len(needed) > 0:
b5c328f916 2012-01-04 c.kworr@b84a3: 						needed.rewind()
b5c328f916 2012-01-04 c.kworr@b84a3: 						while True:
b5c328f916 2012-01-04 c.kworr@b84a3: 							range = needed.pop()
b5c328f916 2012-01-04 c.kworr@b84a3: 							if range[0] == None:
b5c328f916 2012-01-04 c.kworr@b84a3: 								break
b5c328f916 2012-01-04 c.kworr@b84a3: 							ranges += '{}-{}'.format(range[0], range[1] - 1),
d8731957ad 2012-08-07 arcade@b1t.na: 						my_headers['Range'] = 'bytes=' + ','.join(ranges)
b5c328f916 2012-01-04 c.kworr@b84a3: 
82969b1fc2 2012-01-25 c.kworr@b84a3: 				my_headers['Accept-Encoding'] = 'gzip, compress, deflate, identity; q=0'
d8731957ad 2012-08-07 arcade@b1t.na: 				request = urllib.request.Request(request, headers = my_headers)
b5c328f916 2012-01-04 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 				source = urllib.request.urlopen(request, timeout = 60)
601ec56da6 2011-12-19 c.kworr@b84a3: 				new_record = {}
601ec56da6 2011-12-19 c.kworr@b84a3: 				new_record['_parts'] = record['_parts']
601ec56da6 2011-12-19 c.kworr@b84a3: 				headers = source.info()
62e6d8a7ab 2012-01-16 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 				if 'Content-Encoding' in headers and headers['Content-Encoding'] == 'gzip':
a81f1a70fb 2012-01-16 c.kworr@b84a3: 					import gzip
a81f1a70fb 2012-01-16 c.kworr@b84a3: 					source = gzip.GzipFile(fileobj=source)
601ec56da6 2011-12-19 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: 				# stripping unneeded headers (XXX make this inplace?)
601ec56da6 2011-12-19 c.kworr@b84a3: 				for header in headers:
601ec56da6 2011-12-19 c.kworr@b84a3: 					if header in desc_fields:
601ec56da6 2011-12-19 c.kworr@b84a3: 						#if header == 'Pragma' and headers[header] != 'no-cache':
d8731957ad 2012-08-07 arcade@b1t.na: 						if header == 'Content-Length':
d8731957ad 2012-08-07 arcade@b1t.na: 							if 'Content-Range' not in headers:
601ec56da6 2011-12-19 c.kworr@b84a3: 								new_record[header] = int(headers[header])
601ec56da6 2011-12-19 c.kworr@b84a3: 						else:
601ec56da6 2011-12-19 c.kworr@b84a3: 							new_record[header] = headers[header]
d8731957ad 2012-08-07 arcade@b1t.na: 					elif header == 'Content-Range':
601ec56da6 2011-12-19 c.kworr@b84a3: 						range = re.compile('^bytes (\d+)-(\d+)/(\d+)$').match(headers[header])
601ec56da6 2011-12-19 c.kworr@b84a3: 						if range:
d8731957ad 2012-08-07 arcade@b1t.na: 							new_record['Content-Length'] = int(range.group(3))
601ec56da6 2011-12-19 c.kworr@b84a3: 						else:	
601ec56da6 2011-12-19 c.kworr@b84a3: 							assert False, 'Content-Range unrecognized.'
601ec56da6 2011-12-19 c.kworr@b84a3: 					elif not header in ignore_fields:
601ec56da6 2011-12-19 c.kworr@b84a3: 						print('Undefined header "', header, '": ', headers[header], sep='')
601ec56da6 2011-12-19 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: 				# comparing headers with data found in index
601ec56da6 2011-12-19 c.kworr@b84a3: 				# if any header has changed (except Pragma) file is fully downloaded
601ec56da6 2011-12-19 c.kworr@b84a3: 				# same if we get more or less headers
601ec56da6 2011-12-19 c.kworr@b84a3: 				old_keys = set(record.keys())
601ec56da6 2011-12-19 c.kworr@b84a3: 				old_keys.discard('_time')
d8731957ad 2012-08-07 arcade@b1t.na: 				old_keys.discard('Pragma')
601ec56da6 2011-12-19 c.kworr@b84a3: 				more_keys = set(new_record.keys()) - old_keys
d8731957ad 2012-08-07 arcade@b1t.na: 				more_keys.discard('Pragma')
601ec56da6 2011-12-19 c.kworr@b84a3: 				less_keys = old_keys - set(new_record.keys())
601ec56da6 2011-12-19 c.kworr@b84a3: 				if len(more_keys) > 0:
601ec56da6 2011-12-19 c.kworr@b84a3: 					if len(old_keys) != 0:
601ec56da6 2011-12-19 c.kworr@b84a3: 						print('More headers appear:', more_keys)
601ec56da6 2011-12-19 c.kworr@b84a3: 					reload = True
601ec56da6 2011-12-19 c.kworr@b84a3: 				elif len(less_keys) > 0:
601ec56da6 2011-12-19 c.kworr@b84a3: 					print('Less headers appear:', less_keys)
601ec56da6 2011-12-19 c.kworr@b84a3: 				else:
601ec56da6 2011-12-19 c.kworr@b84a3: 					for key in record.keys():
d8731957ad 2012-08-07 arcade@b1t.na: 						if key[0] != '_' and key != 'Pragma' and record[key] != new_record[key]:
601ec56da6 2011-12-19 c.kworr@b84a3: 							print('Header "', key, '" changed from [', record[key], '] to [', new_record[key], ']', sep='')
601ec56da6 2011-12-19 c.kworr@b84a3: 							print(type(record[key]), type(new_record[key]))
601ec56da6 2011-12-19 c.kworr@b84a3: 							reload = True
601ec56da6 2011-12-19 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: 				if reload:
601ec56da6 2011-12-19 c.kworr@b84a3: 					print('Reloading.')
601ec56da6 2011-12-19 c.kworr@b84a3: 					if os.access(temp_name, os.R_OK):
601ec56da6 2011-12-19 c.kworr@b84a3: 						os.unlink(temp_name)
601ec56da6 2011-12-19 c.kworr@b84a3: 					if os.access(file_name, os.R_OK):
601ec56da6 2011-12-19 c.kworr@b84a3: 						os.unlink(file_name)
d8731957ad 2012-08-07 arcade@b1t.na: 					if 'Content-Length' in new_record:
d8731957ad 2012-08-07 arcade@b1t.na: 						new_record['_parts'] = spacemap.SpaceMap({0: int(new_record['Content-Length'])})
601ec56da6 2011-12-19 c.kworr@b84a3: 				if not new_record['_parts']:
601ec56da6 2011-12-19 c.kworr@b84a3: 					new_record['_parts'] = spacemap.SpaceMap()
601ec56da6 2011-12-19 c.kworr@b84a3: 				print(new_record)
601ec56da6 2011-12-19 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: 				# downloading file or segment
d8731957ad 2012-08-07 arcade@b1t.na: 				if 'Content-Length' in new_record:
601ec56da6 2011-12-19 c.kworr@b84a3: 					if needed == None:
601ec56da6 2011-12-19 c.kworr@b84a3: 						needed = new_record['_parts']
601ec56da6 2011-12-19 c.kworr@b84a3: 					else:
601ec56da6 2011-12-19 c.kworr@b84a3: 						if len(needed) > 1:
601ec56da6 2011-12-19 c.kworr@b84a3: 							print("Multipart requests currently not supported.")
601ec56da6 2011-12-19 c.kworr@b84a3: 							assert False, 'Skip this one for now.'
601ec56da6 2011-12-19 c.kworr@b84a3: 				#else:
601ec56da6 2011-12-19 c.kworr@b84a3: 					#assert False, 'No content-length or Content-Range header.'
601ec56da6 2011-12-19 c.kworr@b84a3: 
601ec56da6 2011-12-19 c.kworr@b84a3: 				new_record['_time'] = datetime.datetime.now()
601ec56da6 2011-12-19 c.kworr@b84a3: 				if self.command not in ('HEAD'):
601ec56da6 2011-12-19 c.kworr@b84a3: 					# file is created at temporary location and moved in place only when download completes
601ec56da6 2011-12-19 c.kworr@b84a3: 					if not os.access(temp_name, os.R_OK):
d8731957ad 2012-08-07 arcade@b1t.na: 						empty_name = config_host['dir'] + os.sep + '.tmp'
601ec56da6 2011-12-19 c.kworr@b84a3: 						with open(empty_name, 'w+b') as some_file:
601ec56da6 2011-12-19 c.kworr@b84a3: 							pass
601ec56da6 2011-12-19 c.kworr@b84a3: 						os.renames(empty_name, temp_name)
601ec56da6 2011-12-19 c.kworr@b84a3: 					temp_file = open(temp_name, 'r+b')
601ec56da6 2011-12-19 c.kworr@b84a3: 					if requested_ranges == None and needed == None:
601ec56da6 2011-12-19 c.kworr@b84a3: 						needed = new_record['_parts']
601ec56da6 2011-12-19 c.kworr@b84a3: 					needed.rewind()
601ec56da6 2011-12-19 c.kworr@b84a3: 					while True:
62e6d8a7ab 2012-01-16 c.kworr@b84a3: 						# XXX can make this implicit - one request per range
601ec56da6 2011-12-19 c.kworr@b84a3: 						(start, end) = needed.pop()
601ec56da6 2011-12-19 c.kworr@b84a3: 						if start == None:
601ec56da6 2011-12-19 c.kworr@b84a3: 							break
601ec56da6 2011-12-19 c.kworr@b84a3: 						stream_last = start
601ec56da6 2011-12-19 c.kworr@b84a3: 						old_record = copy.copy(new_record)
601ec56da6 2011-12-19 c.kworr@b84a3: 						if end - start < block_size:
601ec56da6 2011-12-19 c.kworr@b84a3: 							req_block_size = end - start
601ec56da6 2011-12-19 c.kworr@b84a3: 						else:
601ec56da6 2011-12-19 c.kworr@b84a3: 							req_block_size = block_size
601ec56da6 2011-12-19 c.kworr@b84a3: 						buffer = source.read(req_block_size)
601ec56da6 2011-12-19 c.kworr@b84a3: 						length = len(buffer)
601ec56da6 2011-12-19 c.kworr@b84a3: 						while length > 0 and stream_last < end:
601ec56da6 2011-12-19 c.kworr@b84a3: 							stream_pos = stream_last + length
601ec56da6 2011-12-19 c.kworr@b84a3: 							assert stream_pos <= end, 'Received more data then requested: pos:{} start:{} end:{}.'.format(stream_pos, start, end)
601ec56da6 2011-12-19 c.kworr@b84a3: 							temp_file.seek(stream_last)
601ec56da6 2011-12-19 c.kworr@b84a3: 							temp_file.write(buffer)
601ec56da6 2011-12-19 c.kworr@b84a3: 							x = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
601ec56da6 2011-12-19 c.kworr@b84a3: 							new_record['_parts'] = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
d8731957ad 2012-08-07 arcade@b1t.na: 							index[my_path_b] = old_record
601ec56da6 2011-12-19 c.kworr@b84a3: 							index.sync()
601ec56da6 2011-12-19 c.kworr@b84a3: 							old_record = copy.copy(new_record)
601ec56da6 2011-12-19 c.kworr@b84a3: 							stream_last = stream_pos
601ec56da6 2011-12-19 c.kworr@b84a3: 							if end - stream_last < block_size:
601ec56da6 2011-12-19 c.kworr@b84a3: 								req_block_size = end - stream_last
601ec56da6 2011-12-19 c.kworr@b84a3: 							buffer = source.read(req_block_size)
601ec56da6 2011-12-19 c.kworr@b84a3: 							length = len(buffer)
601ec56da6 2011-12-19 c.kworr@b84a3: 					# moving downloaded data to real file
601ec56da6 2011-12-19 c.kworr@b84a3: 					temp_file.close()
601ec56da6 2011-12-19 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 				index[my_path_b] = new_record
601ec56da6 2011-12-19 c.kworr@b84a3: 				index.sync()
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 			except urllib.error.HTTPError as error:
90160dbf50 2011-03-06 c.kworr@b84a3: 				# in case of error we don't need to do anything actually,
90160dbf50 2011-03-06 c.kworr@b84a3: 				# if file download stalls or fails the file would not be moved to it's location
44aa59eb58 2012-08-09 arcade@b1t.na: 				print(error, repr(my_headers))
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		print(index[my_path_b])
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		if not os.access(file_name, os.R_OK) and os.access(temp_name, os.R_OK) and '_parts' in index[my_path_b] and index[my_path_b]['_parts'] == spacemap.SpaceMap():
90160dbf50 2011-03-06 c.kworr@b84a3: 			# just moving
90160dbf50 2011-03-06 c.kworr@b84a3: 			# drop old dirs XXX
90160dbf50 2011-03-06 c.kworr@b84a3: 			print('Moving temporary file to new destination.')
90160dbf50 2011-03-06 c.kworr@b84a3: 			os.renames(temp_name, file_name)
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: 		if not my_path_b in index:
90160dbf50 2011-03-06 c.kworr@b84a3: 			self.send_response(502)
90160dbf50 2011-03-06 c.kworr@b84a3: 			self.end_headers()
90160dbf50 2011-03-06 c.kworr@b84a3: 			return
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 		if self.command == 'HEAD':
90160dbf50 2011-03-06 c.kworr@b84a3: 			self.send_response(200)
d8731957ad 2012-08-07 arcade@b1t.na: 			if 'Content-Length' in index[my_path_b]:
d8731957ad 2012-08-07 arcade@b1t.na: 				self.send_header('Content-Length', index[my_path_b]['Content-Length'])
d8731957ad 2012-08-07 arcade@b1t.na: 			self.send_header('Accept-Ranges', 'bytes')
d8731957ad 2012-08-07 arcade@b1t.na: 			self.send_header('Content-Type', 'application/octet-stream')
d8731957ad 2012-08-07 arcade@b1t.na: 			if 'Last-Modified' in index[my_path_b]:
d8731957ad 2012-08-07 arcade@b1t.na: 				self.send_header('Last-Modified', index[my_path_b]['Last-Modified'])
90160dbf50 2011-03-06 c.kworr@b84a3: 			self.end_headers()
90160dbf50 2011-03-06 c.kworr@b84a3: 		else:
d8731957ad 2012-08-07 arcade@b1t.na: 			if ('_parts' in index[my_path_b] and index[my_path_b]['_parts'] != spacemap.SpaceMap()) or not os.access(file_name, os.R_OK):
90160dbf50 2011-03-06 c.kworr@b84a3: 				file_name = temp_name
90160dbf50 2011-03-06 c.kworr@b84a3: 
90160dbf50 2011-03-06 c.kworr@b84a3: 			with open(file_name, 'rb') as real_file:
90160dbf50 2011-03-06 c.kworr@b84a3: 				file_stat = os.stat(file_name)
d8731957ad 2012-08-07 arcade@b1t.na: 				if 'Range' in self.headers:
90160dbf50 2011-03-06 c.kworr@b84a3: 					self.send_response(206)
90160dbf50 2011-03-06 c.kworr@b84a3: 					ranges = ()
90160dbf50 2011-03-06 c.kworr@b84a3: 					requested_ranges.rewind()
90160dbf50 2011-03-06 c.kworr@b84a3: 					while True:
90160dbf50 2011-03-06 c.kworr@b84a3: 						pair = requested_ranges.pop()
90160dbf50 2011-03-06 c.kworr@b84a3: 						if pair[0] == None:
90160dbf50 2011-03-06 c.kworr@b84a3: 							break
90160dbf50 2011-03-06 c.kworr@b84a3: 						ranges += '{}-{}'.format(pair[0], str(pair[1] - 1)),
d8731957ad 2012-08-07 arcade@b1t.na: 					self.send_header('Content-Range', 'bytes {}/{}'.format(','.join(ranges), index[my_path_b]['Content-Length']))
90160dbf50 2011-03-06 c.kworr@b84a3: 				else:
90160dbf50 2011-03-06 c.kworr@b84a3: 					self.send_response(200)
d8731957ad 2012-08-07 arcade@b1t.na: 					self.send_header('Content-Length', str(file_stat.st_size))
90160dbf50 2011-03-06 c.kworr@b84a3: 					requested_ranges = spacemap.SpaceMap({0: file_stat.st_size})
d8731957ad 2012-08-07 arcade@b1t.na: 				if 'Last-Modified' in index[my_path_b]:
d8731957ad 2012-08-07 arcade@b1t.na: 					self.send_header('Last-Modified', index[my_path_b]['Last-Modified'])
d8731957ad 2012-08-07 arcade@b1t.na: 				self.send_header('Content-Type', 'application/octet-stream')
90160dbf50 2011-03-06 c.kworr@b84a3: 				self.end_headers()
90160dbf50 2011-03-06 c.kworr@b84a3: 				if self.command in ('GET'):
90160dbf50 2011-03-06 c.kworr@b84a3: 					if len(requested_ranges) > 0:
90160dbf50 2011-03-06 c.kworr@b84a3: 						requested_ranges.rewind()
90160dbf50 2011-03-06 c.kworr@b84a3: 						(start, end) = requested_ranges.pop()
90160dbf50 2011-03-06 c.kworr@b84a3: 					else:
90160dbf50 2011-03-06 c.kworr@b84a3: 						start = 0
9a8a46bcf0 2011-09-06 c.kworr@b84a3: 						# XXX ugly hack
d8731957ad 2012-08-07 arcade@b1t.na: 						if 'Content-Length' in index[my_path_b]:
d8731957ad 2012-08-07 arcade@b1t.na: 							end = index[my_path_b]['Content-Length']
9a8a46bcf0 2011-09-06 c.kworr@b84a3: 						else:
9a8a46bcf0 2011-09-06 c.kworr@b84a3: 							end = 0
90160dbf50 2011-03-06 c.kworr@b84a3: 					real_file.seek(start)
90160dbf50 2011-03-06 c.kworr@b84a3: 					if block_size > end - start:
90160dbf50 2011-03-06 c.kworr@b84a3: 						req_block_size = end - start
90160dbf50 2011-03-06 c.kworr@b84a3: 					else:
90160dbf50 2011-03-06 c.kworr@b84a3: 						req_block_size = block_size
90160dbf50 2011-03-06 c.kworr@b84a3: 					buffer = real_file.read(req_block_size)
90160dbf50 2011-03-06 c.kworr@b84a3: 					length = len(buffer)
90160dbf50 2011-03-06 c.kworr@b84a3: 					while length > 0:
90160dbf50 2011-03-06 c.kworr@b84a3: 						self.wfile.write(buffer)
90160dbf50 2011-03-06 c.kworr@b84a3: 						start += len(buffer)
90160dbf50 2011-03-06 c.kworr@b84a3: 						if req_block_size > end - start:
90160dbf50 2011-03-06 c.kworr@b84a3: 							req_block_size = end - start
90160dbf50 2011-03-06 c.kworr@b84a3: 						if req_block_size == 0:
90160dbf50 2011-03-06 c.kworr@b84a3: 							break
90160dbf50 2011-03-06 c.kworr@b84a3: 						buffer = real_file.read(req_block_size)
90160dbf50 2011-03-06 c.kworr@b84a3: 						length = len(buffer)
90160dbf50 2011-03-06 c.kworr@b84a3: 				
90160dbf50 2011-03-06 c.kworr@b84a3: 	def do_HEAD(self):
90160dbf50 2011-03-06 c.kworr@b84a3: 		return self.__process()
90160dbf50 2011-03-06 c.kworr@b84a3: 	def do_GET(self):
90160dbf50 2011-03-06 c.kworr@b84a3: 		return self.__process()
90160dbf50 2011-03-06 c.kworr@b84a3: 
d8731957ad 2012-08-07 arcade@b1t.na: server = http.server.HTTPServer(('127.0.0.1', int(config['DEFAULT']['port'])), MyRequestHandler)
90160dbf50 2011-03-06 c.kworr@b84a3: server.serve_forever()
82969b1fc2 2012-01-25 c.kworr@b84a3: 
82969b1fc2 2012-01-25 c.kworr@b84a3: #gevent.joinall()