d8731957ad 2012-08-07 1: #!/usr/bin/env python3.2
9a8a46bcf0 2011-09-06 2:
601ec56da6 2011-12-19 3: from __future__ import unicode_literals, print_function
601ec56da6 2011-12-19 4:
82969b1fc2 2012-01-25 5: #import gevent.monkey
82969b1fc2 2012-01-25 6: #gevent.monkey.patch_all()
82969b1fc2 2012-01-25 7:
d8731957ad 2012-08-07 8: import argparse, os
d8731957ad 2012-08-07 9: parser = argparse.ArgumentParser()
d8731957ad 2012-08-07 10: parser.add_argument('-c', '--config', dest = 'config', help = 'config file location', metavar = 'FILE', default = 'samesite.conf')
d8731957ad 2012-08-07 11: args = parser.parse_args()
d8731957ad 2012-08-07 12: assert os.access(args.config, os.R_OK), "Fatal error: can't read {}".format(args.config)
d8731957ad 2012-08-07 13:
d8731957ad 2012-08-07 14: import configparser
d8731957ad 2012-08-07 15: config = configparser.ConfigParser({
d8731957ad 2012-08-07 16: 'port': '8008',
d8731957ad 2012-08-07 17: 'verbose': 'no',
d8731957ad 2012-08-07 18: 'noetag': 'no',
d8731957ad 2012-08-07 19: 'noparts': 'no',
d8731957ad 2012-08-07 20: 'strip': '',
d8731957ad 2012-08-07 21: 'sub': '',
d8731957ad 2012-08-07 22: 'proto': 'http',
d8731957ad 2012-08-07 23: })
d8731957ad 2012-08-07 24: config.read(args.config)
d8731957ad 2012-08-07 25:
d8731957ad 2012-08-07 26: cache_dir = os.path.realpath(os.path.dirname(args.config))
d8731957ad 2012-08-07 27:
d8731957ad 2012-08-07 28: import re
d8731957ad 2012-08-07 29: for section in config.sections():
d8731957ad 2012-08-07 30: if section != 'DEFAULT':
d8731957ad 2012-08-07 31: if 'dir' in config[section]:
d8731957ad 2012-08-07 32: if not re.compile('^/.*').match(config[section]['dir']):
d8731957ad 2012-08-07 33: config[section]['dir'] = cache_dir + os.sep + section
d8731957ad 2012-08-07 34: thisDir = re.compile('^(.*)/$').match(config[section]['dir'])
d8731957ad 2012-08-07 35: if thisDir:
d8731957ad 2012-08-07 36: config[section]['dir'] = thisDir.group(1)
d8731957ad 2012-08-07 37: if not re.compile('^/(.*)$').match(config[section]['dir']):
d8731957ad 2012-08-07 38: config[section]['dir'] = cache_dir + os.sep + config[section]['dir']
d8731957ad 2012-08-07 39: else:
d8731957ad 2012-08-07 40: config[section]['dir'] = cache_dir + os.sep + section
d8731957ad 2012-08-07 41:
d8731957ad 2012-08-07 42: if not 'root' in config[section]:
d8731957ad 2012-08-07 43: config[section]['root'] = section
b0975a28fb 2010-08-26 44:
b0975a28fb 2010-08-26 45: #assert options.port or os.access(options.log, os.R_OK), 'Log file unreadable'
b0975a28fb 2010-08-26 46:
d8731957ad 2012-08-07 47: const_desc_fields = set(['Content-Length', 'Last-Modified', 'Pragma'])
cab908195f 2010-09-06 48: const_ignore_fields = set([
d8731957ad 2012-08-07 49: 'Accept-Ranges', 'Age',
d8731957ad 2012-08-07 50: 'Cache-Control', 'Connection', 'Content-Type',
d8731957ad 2012-08-07 51: 'Date',
d8731957ad 2012-08-07 52: 'Expires',
d8731957ad 2012-08-07 53: 'Referer',
d8731957ad 2012-08-07 54: 'Server',
d8731957ad 2012-08-07 55: 'Via',
d8731957ad 2012-08-07 56: 'X-Cache', 'X-Cache-Lookup', 'X-Livetool', 'X-Powered-By',
90160dbf50 2011-03-06 57: ])
90160dbf50 2011-03-06 58:
82969b1fc2 2012-01-25 59: block_size = 8192
82969b1fc2 2012-01-25 60:
d8731957ad 2012-08-07 61: import bsddb3.dbshelve, copy, datetime, http.server, spacemap, urllib.request, urllib.error
d8731957ad 2012-08-07 62:
d8731957ad 2012-08-07 63: class MyRequestHandler(http.server.BaseHTTPRequestHandler):
90160dbf50 2011-03-06 64: def __process(self):
90160dbf50 2011-03-06 65: # reload means file needs to be reloaded to serve request
90160dbf50 2011-03-06 66: reload = False
90160dbf50 2011-03-06 67: # 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 68: recheck = False
90160dbf50 2011-03-06 69: # file_stat means file definitely exists
90160dbf50 2011-03-06 70: file_stat = None
90160dbf50 2011-03-06 71: # requested_ranges holds data about any range requested
90160dbf50 2011-03-06 72: requested_ranges = None
90160dbf50 2011-03-06 73: # records holds data from index locally, should be written back upon successfull completion
90160dbf50 2011-03-06 74: record = None
90160dbf50 2011-03-06 75:
90160dbf50 2011-03-06 76: myPath = re.compile('^(.*?)(\?.*)$').match(self.path)
90160dbf50 2011-03-06 77: if myPath:
90160dbf50 2011-03-06 78: my_path = myPath.group(1)
90160dbf50 2011-03-06 79: else:
90160dbf50 2011-03-06 80: my_path = self.path
90160dbf50 2011-03-06 81:
d8731957ad 2012-08-07 82: config_host = config[self.headers['Host']]
90160dbf50 2011-03-06 83:
d8731957ad 2012-08-07 84: if config_host['sub'] != None and config_host['strip'] != None and len(config_host['strip']) > 0:
d8731957ad 2012-08-07 85: string = re.compile(config_host['strip']).sub(config_host['sub'], my_path)
90160dbf50 2011-03-06 86: my_path = string
90160dbf50 2011-03-06 87:
d8731957ad 2012-08-07 88: my_path_b = my_path.encode('utf-8')
90160dbf50 2011-03-06 89: info = 'Checking file: ' + my_path
90160dbf50 2011-03-06 90:
d8731957ad 2012-08-07 91: if not os.access(config_host['dir'], os.X_OK):
d8731957ad 2012-08-07 92: os.mkdir(config_host['dir'])
90160dbf50 2011-03-06 93: # this is file index - everything is stored in this file
90160dbf50 2011-03-06 94: # _parts - list of stored parts of file
90160dbf50 2011-03-06 95: # _time - last time the file was checked
90160dbf50 2011-03-06 96: # everything else is just the headers
d8731957ad 2012-08-07 97: index = bsddb3.dbshelve.open(config_host['dir'] + os.sep + '.index')
90160dbf50 2011-03-06 98:
90160dbf50 2011-03-06 99: desc_fields = const_desc_fields.copy()
90160dbf50 2011-03-06 100: ignore_fields = const_ignore_fields.copy()
d8731957ad 2012-08-07 101: if config_host['noetag'] == 'no':
601ec56da6 2011-12-19 102: desc_fields.add('etag')
90160dbf50 2011-03-06 103: else:
601ec56da6 2011-12-19 104: ignore_fields.add('etag')
90160dbf50 2011-03-06 105:
90160dbf50 2011-03-06 106: proxy_ignored = set([
d8731957ad 2012-08-07 107: 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language',
d8731957ad 2012-08-07 108: 'Cache-Control', 'Connection', 'Content-Length', 'Cookie',
d8731957ad 2012-08-07 109: 'Host',
d8731957ad 2012-08-07 110: 'If-Modified-Since', 'If-Unmodified-Since',
d8731957ad 2012-08-07 111: 'Referer',
d8731957ad 2012-08-07 112: 'Ua-Cpu', 'User-Agent',
d8731957ad 2012-08-07 113: 'Via',
d8731957ad 2012-08-07 114: 'X-Forwarded-For', 'X-Last-Hr', 'X-Last-Http-Status-Code', 'X-Removed', 'X-Real-Ip', 'X-Retry-Count',
90160dbf50 2011-03-06 115: ])
90160dbf50 2011-03-06 116:
90160dbf50 2011-03-06 117: print('===============[ {} request ]==='.format(self.command))
90160dbf50 2011-03-06 118:
90160dbf50 2011-03-06 119: for header in self.headers:
90160dbf50 2011-03-06 120: if header in proxy_ignored:
90160dbf50 2011-03-06 121: pass
d8731957ad 2012-08-07 122: elif header in ('Range'):
90160dbf50 2011-03-06 123: isRange = re.compile('bytes=(\d+)-(\d+)').match(self.headers[header])
90160dbf50 2011-03-06 124: if isRange:
90160dbf50 2011-03-06 125: requested_ranges = spacemap.SpaceMap({int(isRange.group(1)): int(isRange.group(2)) + 1})
90160dbf50 2011-03-06 126: else:
90160dbf50 2011-03-06 127: return()
d8731957ad 2012-08-07 128: elif header in ('Pragma'):
d8731957ad 2012-08-07 129: if my_path_b in index:
d8731957ad 2012-08-07 130: index[my_path_b][header] = self.headers[header]
90160dbf50 2011-03-06 131: else:
90160dbf50 2011-03-06 132: print('Unknown header - ', header, ': ', self.headers[header], sep='')
90160dbf50 2011-03-06 133: return()
90160dbf50 2011-03-06 134: print(header, self.headers[header])
90160dbf50 2011-03-06 135:
90160dbf50 2011-03-06 136: # creating file name from my_path
d8731957ad 2012-08-07 137: file_name = config_host['dir'] + os.sep + re.compile('%20').sub(' ', my_path)
90160dbf50 2011-03-06 138: # partial file or unfinished download
d8731957ad 2012-08-07 139: temp_name = config_host['dir'] + os.sep + '.parts' + re.compile('%20').sub(' ', my_path)
90160dbf50 2011-03-06 140:
90160dbf50 2011-03-06 141: # creating empty placeholder in index
90160dbf50 2011-03-06 142: # if there's no space map and there's no file in real directory - we have no file
90160dbf50 2011-03-06 143: # if there's an empty space map - file is full
90160dbf50 2011-03-06 144: # space map generally covers every bit of file we don't posess currently
d8731957ad 2012-08-07 145: if not my_path_b in index:
90160dbf50 2011-03-06 146: info += '\nThis one is new.'
90160dbf50 2011-03-06 147: reload = True
90160dbf50 2011-03-06 148: record = {}
90160dbf50 2011-03-06 149: else:
90160dbf50 2011-03-06 150: # forcibly checking file if no file present
d8731957ad 2012-08-07 151: record = index[my_path_b]
90160dbf50 2011-03-06 152: if os.access(file_name, os.R_OK):
90160dbf50 2011-03-06 153: info += '\nFull file found.'
90160dbf50 2011-03-06 154: file_stat = os.stat(file_name)
d8731957ad 2012-08-07 155: elif '_parts' in index[my_path_b] and os.access(temp_name, os.R_OK):
90160dbf50 2011-03-06 156: info += '\nPartial file found.'
90160dbf50 2011-03-06 157: file_stat = os.stat(temp_name)
d1fa9d0737 2012-01-16 158: recheck = True
90160dbf50 2011-03-06 159: else:
90160dbf50 2011-03-06 160: info += '\nFile not found or inaccessible.'
90160dbf50 2011-03-06 161: record['_parts'] = None
90160dbf50 2011-03-06 162: reload = True
90160dbf50 2011-03-06 163:
90160dbf50 2011-03-06 164: if not '_parts' in record:
90160dbf50 2011-03-06 165: record['_parts'] = None
90160dbf50 2011-03-06 166:
90160dbf50 2011-03-06 167: if record['_parts'] == None:
90160dbf50 2011-03-06 168: recheck = True
90160dbf50 2011-03-06 169:
90160dbf50 2011-03-06 170: # forcibly checking file if file size doesn't match with index data
90160dbf50 2011-03-06 171: if not reload:
90160dbf50 2011-03-06 172: if '_parts' in record and record['_parts'] == spacemap.SpaceMap():
601ec56da6 2011-12-19 173: if 'content-length' in record and file_stat and file_stat.st_size != int(record['content-length']):
601ec56da6 2011-12-19 174: info += '\nFile size is {} and stored file size is {}.'.format(file_stat.st_size, record['content-length'])
90160dbf50 2011-03-06 175: record['_parts'] = None
90160dbf50 2011-03-06 176: reload = True
90160dbf50 2011-03-06 177:
90160dbf50 2011-03-06 178: # forcibly checking file if index holds Pragma header
601ec56da6 2011-12-19 179: if not reload and 'pragma' in record and record['pragma'] == 'no-cache':
90160dbf50 2011-03-06 180: info +='\nPragma on: recheck imminent.'
90160dbf50 2011-03-06 181: recheck = True
90160dbf50 2011-03-06 182:
90160dbf50 2011-03-06 183: # 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 184: 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 185: info += '\nFile is old - rechecking.'
90160dbf50 2011-03-06 186: recheck = True
90160dbf50 2011-03-06 187:
90160dbf50 2011-03-06 188: print(info)
90160dbf50 2011-03-06 189: if reload or recheck:
90160dbf50 2011-03-06 190:
90160dbf50 2011-03-06 191: try:
d8731957ad 2012-08-07 192: request = config_host['proto'] + '://' + config_host['root'] + self.path
90160dbf50 2011-03-06 193: my_headers = {}
d8731957ad 2012-08-07 194: for header in ('Cache-Control', 'Cookie', 'Referer', 'User-Agent'):
90160dbf50 2011-03-06 195: if header in self.headers:
90160dbf50 2011-03-06 196: my_headers[header] = self.headers[header]
90160dbf50 2011-03-06 197:
90160dbf50 2011-03-06 198: needed = None
b5c328f916 2012-01-04 199: if self.command not in ('HEAD'):
b5c328f916 2012-01-04 200: if '_parts' in record and record['_parts'] != None:
d8731957ad 2012-08-07 201: if config_host['noparts'] != 'no' or requested_ranges == None or requested_ranges == spacemap.SpaceMap():
b5c328f916 2012-01-04 202: needed = record['_parts']
b5c328f916 2012-01-04 203: else:
b5c328f916 2012-01-04 204: needed = record['_parts'] & requested_ranges
d8731957ad 2012-08-07 205: elif config_host['noparts'] =='no' and requested_ranges != None and requested_ranges != spacemap.SpaceMap():
b5c328f916 2012-01-04 206: needed = requested_ranges
b5c328f916 2012-01-04 207: ranges = ()
b5c328f916 2012-01-04 208: print('Missing ranges: {}, requested ranges: {}, needed ranges: {}.'.format(record['_parts'], requested_ranges, needed))
b5c328f916 2012-01-04 209: if needed != None and len(needed) > 0:
b5c328f916 2012-01-04 210: needed.rewind()
b5c328f916 2012-01-04 211: while True:
b5c328f916 2012-01-04 212: range = needed.pop()
b5c328f916 2012-01-04 213: if range[0] == None:
b5c328f916 2012-01-04 214: break
b5c328f916 2012-01-04 215: ranges += '{}-{}'.format(range[0], range[1] - 1),
d8731957ad 2012-08-07 216: my_headers['Range'] = 'bytes=' + ','.join(ranges)
b5c328f916 2012-01-04 217:
82969b1fc2 2012-01-25 218: my_headers['Accept-Encoding'] = 'gzip, compress, deflate, identity; q=0'
d8731957ad 2012-08-07 219: request = urllib.request.Request(request, headers = my_headers)
b5c328f916 2012-01-04 220:
d8731957ad 2012-08-07 221: source = urllib.request.urlopen(request, timeout = 60)
601ec56da6 2011-12-19 222: new_record = {}
601ec56da6 2011-12-19 223: new_record['_parts'] = record['_parts']
601ec56da6 2011-12-19 224: headers = source.info()
62e6d8a7ab 2012-01-16 225:
d8731957ad 2012-08-07 226: if 'Content-Encoding' in headers and headers['Content-Encoding'] == 'gzip':
a81f1a70fb 2012-01-16 227: import gzip
a81f1a70fb 2012-01-16 228: source = gzip.GzipFile(fileobj=source)
601ec56da6 2011-12-19 229:
601ec56da6 2011-12-19 230: # stripping unneeded headers (XXX make this inplace?)
601ec56da6 2011-12-19 231: for header in headers:
601ec56da6 2011-12-19 232: if header in desc_fields:
601ec56da6 2011-12-19 233: #if header == 'Pragma' and headers[header] != 'no-cache':
d8731957ad 2012-08-07 234: if header == 'Content-Length':
d8731957ad 2012-08-07 235: if 'Content-Range' not in headers:
601ec56da6 2011-12-19 236: new_record[header] = int(headers[header])
601ec56da6 2011-12-19 237: else:
601ec56da6 2011-12-19 238: new_record[header] = headers[header]
d8731957ad 2012-08-07 239: elif header == 'Content-Range':
601ec56da6 2011-12-19 240: range = re.compile('^bytes (\d+)-(\d+)/(\d+)$').match(headers[header])
601ec56da6 2011-12-19 241: if range:
d8731957ad 2012-08-07 242: new_record['Content-Length'] = int(range.group(3))
601ec56da6 2011-12-19 243: else:
601ec56da6 2011-12-19 244: assert False, 'Content-Range unrecognized.'
601ec56da6 2011-12-19 245: elif not header in ignore_fields:
601ec56da6 2011-12-19 246: print('Undefined header "', header, '": ', headers[header], sep='')
601ec56da6 2011-12-19 247:
601ec56da6 2011-12-19 248: # comparing headers with data found in index
601ec56da6 2011-12-19 249: # if any header has changed (except Pragma) file is fully downloaded
601ec56da6 2011-12-19 250: # same if we get more or less headers
601ec56da6 2011-12-19 251: old_keys = set(record.keys())
601ec56da6 2011-12-19 252: old_keys.discard('_time')
d8731957ad 2012-08-07 253: old_keys.discard('Pragma')
601ec56da6 2011-12-19 254: more_keys = set(new_record.keys()) - old_keys
d8731957ad 2012-08-07 255: more_keys.discard('Pragma')
601ec56da6 2011-12-19 256: less_keys = old_keys - set(new_record.keys())
601ec56da6 2011-12-19 257: if len(more_keys) > 0:
601ec56da6 2011-12-19 258: if len(old_keys) != 0:
601ec56da6 2011-12-19 259: print('More headers appear:', more_keys)
601ec56da6 2011-12-19 260: reload = True
601ec56da6 2011-12-19 261: elif len(less_keys) > 0:
601ec56da6 2011-12-19 262: print('Less headers appear:', less_keys)
601ec56da6 2011-12-19 263: else:
601ec56da6 2011-12-19 264: for key in record.keys():
d8731957ad 2012-08-07 265: if key[0] != '_' and key != 'Pragma' and record[key] != new_record[key]:
601ec56da6 2011-12-19 266: print('Header "', key, '" changed from [', record[key], '] to [', new_record[key], ']', sep='')
601ec56da6 2011-12-19 267: print(type(record[key]), type(new_record[key]))
601ec56da6 2011-12-19 268: reload = True
601ec56da6 2011-12-19 269:
601ec56da6 2011-12-19 270: if reload:
601ec56da6 2011-12-19 271: print('Reloading.')
601ec56da6 2011-12-19 272: if os.access(temp_name, os.R_OK):
601ec56da6 2011-12-19 273: os.unlink(temp_name)
601ec56da6 2011-12-19 274: if os.access(file_name, os.R_OK):
601ec56da6 2011-12-19 275: os.unlink(file_name)
d8731957ad 2012-08-07 276: if 'Content-Length' in new_record:
d8731957ad 2012-08-07 277: new_record['_parts'] = spacemap.SpaceMap({0: int(new_record['Content-Length'])})
601ec56da6 2011-12-19 278: if not new_record['_parts']:
601ec56da6 2011-12-19 279: new_record['_parts'] = spacemap.SpaceMap()
601ec56da6 2011-12-19 280: print(new_record)
601ec56da6 2011-12-19 281:
601ec56da6 2011-12-19 282: # downloading file or segment
d8731957ad 2012-08-07 283: if 'Content-Length' in new_record:
601ec56da6 2011-12-19 284: if needed == None:
601ec56da6 2011-12-19 285: needed = new_record['_parts']
601ec56da6 2011-12-19 286: else:
601ec56da6 2011-12-19 287: if len(needed) > 1:
601ec56da6 2011-12-19 288: print("Multipart requests currently not supported.")
601ec56da6 2011-12-19 289: assert False, 'Skip this one for now.'
601ec56da6 2011-12-19 290: #else:
601ec56da6 2011-12-19 291: #assert False, 'No content-length or Content-Range header.'
601ec56da6 2011-12-19 292:
601ec56da6 2011-12-19 293: new_record['_time'] = datetime.datetime.now()
601ec56da6 2011-12-19 294: if self.command not in ('HEAD'):
601ec56da6 2011-12-19 295: # file is created at temporary location and moved in place only when download completes
601ec56da6 2011-12-19 296: if not os.access(temp_name, os.R_OK):
d8731957ad 2012-08-07 297: empty_name = config_host['dir'] + os.sep + '.tmp'
601ec56da6 2011-12-19 298: with open(empty_name, 'w+b') as some_file:
601ec56da6 2011-12-19 299: pass
601ec56da6 2011-12-19 300: os.renames(empty_name, temp_name)
601ec56da6 2011-12-19 301: temp_file = open(temp_name, 'r+b')
601ec56da6 2011-12-19 302: if requested_ranges == None and needed == None:
601ec56da6 2011-12-19 303: needed = new_record['_parts']
601ec56da6 2011-12-19 304: needed.rewind()
601ec56da6 2011-12-19 305: while True:
62e6d8a7ab 2012-01-16 306: # XXX can make this implicit - one request per range
601ec56da6 2011-12-19 307: (start, end) = needed.pop()
601ec56da6 2011-12-19 308: if start == None:
601ec56da6 2011-12-19 309: break
601ec56da6 2011-12-19 310: stream_last = start
601ec56da6 2011-12-19 311: old_record = copy.copy(new_record)
601ec56da6 2011-12-19 312: if end - start < block_size:
601ec56da6 2011-12-19 313: req_block_size = end - start
601ec56da6 2011-12-19 314: else:
601ec56da6 2011-12-19 315: req_block_size = block_size
601ec56da6 2011-12-19 316: buffer = source.read(req_block_size)
601ec56da6 2011-12-19 317: length = len(buffer)
601ec56da6 2011-12-19 318: while length > 0 and stream_last < end:
601ec56da6 2011-12-19 319: stream_pos = stream_last + length
601ec56da6 2011-12-19 320: assert stream_pos <= end, 'Received more data then requested: pos:{} start:{} end:{}.'.format(stream_pos, start, end)
601ec56da6 2011-12-19 321: temp_file.seek(stream_last)
601ec56da6 2011-12-19 322: temp_file.write(buffer)
601ec56da6 2011-12-19 323: x = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
601ec56da6 2011-12-19 324: new_record['_parts'] = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
d8731957ad 2012-08-07 325: index[my_path_b] = old_record
601ec56da6 2011-12-19 326: index.sync()
601ec56da6 2011-12-19 327: old_record = copy.copy(new_record)
601ec56da6 2011-12-19 328: stream_last = stream_pos
601ec56da6 2011-12-19 329: if end - stream_last < block_size:
601ec56da6 2011-12-19 330: req_block_size = end - stream_last
601ec56da6 2011-12-19 331: buffer = source.read(req_block_size)
601ec56da6 2011-12-19 332: length = len(buffer)
601ec56da6 2011-12-19 333: # moving downloaded data to real file
601ec56da6 2011-12-19 334: temp_file.close()
601ec56da6 2011-12-19 335:
d8731957ad 2012-08-07 336: index[my_path_b] = new_record
601ec56da6 2011-12-19 337: index.sync()
38b25713eb 2010-07-26 338:
d8731957ad 2012-08-07 339: except urllib.error.HTTPError as error:
80f8e3804a 2010-08-20 340: # in case of error we don't need to do anything actually,
80f8e3804a 2010-08-20 341: # if file download stalls or fails the file would not be moved to it's location
80f8e3804a 2010-08-20 342: print(error)
80f8e3804a 2010-08-20 343:
d8731957ad 2012-08-07 344: print(index[my_path_b])
90160dbf50 2011-03-06 345:
d8731957ad 2012-08-07 346: 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 347: # just moving
90160dbf50 2011-03-06 348: # drop old dirs XXX
90160dbf50 2011-03-06 349: print('Moving temporary file to new destination.')
90160dbf50 2011-03-06 350: os.renames(temp_name, file_name)
90160dbf50 2011-03-06 351:
d8731957ad 2012-08-07 352: if not my_path_b in index:
90160dbf50 2011-03-06 353: self.send_response(502)
90160dbf50 2011-03-06 354: self.end_headers()
90160dbf50 2011-03-06 355: return
90160dbf50 2011-03-06 356:
90160dbf50 2011-03-06 357: if self.command == 'HEAD':
90160dbf50 2011-03-06 358: self.send_response(200)
d8731957ad 2012-08-07 359: if 'Content-Length' in index[my_path_b]:
d8731957ad 2012-08-07 360: self.send_header('Content-Length', index[my_path_b]['Content-Length'])
d8731957ad 2012-08-07 361: self.send_header('Accept-Ranges', 'bytes')
d8731957ad 2012-08-07 362: self.send_header('Content-Type', 'application/octet-stream')
d8731957ad 2012-08-07 363: if 'Last-Modified' in index[my_path_b]:
d8731957ad 2012-08-07 364: self.send_header('Last-Modified', index[my_path_b]['Last-Modified'])
90160dbf50 2011-03-06 365: self.end_headers()
90160dbf50 2011-03-06 366: else:
d8731957ad 2012-08-07 367: 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 368: file_name = temp_name
90160dbf50 2011-03-06 369:
90160dbf50 2011-03-06 370: with open(file_name, 'rb') as real_file:
90160dbf50 2011-03-06 371: file_stat = os.stat(file_name)
d8731957ad 2012-08-07 372: if 'Range' in self.headers:
90160dbf50 2011-03-06 373: self.send_response(206)
90160dbf50 2011-03-06 374: ranges = ()
90160dbf50 2011-03-06 375: requested_ranges.rewind()
90160dbf50 2011-03-06 376: while True:
90160dbf50 2011-03-06 377: pair = requested_ranges.pop()
90160dbf50 2011-03-06 378: if pair[0] == None:
90160dbf50 2011-03-06 379: break
90160dbf50 2011-03-06 380: ranges += '{}-{}'.format(pair[0], str(pair[1] - 1)),
d8731957ad 2012-08-07 381: self.send_header('Content-Range', 'bytes {}/{}'.format(','.join(ranges), index[my_path_b]['Content-Length']))
90160dbf50 2011-03-06 382: else:
90160dbf50 2011-03-06 383: self.send_response(200)
d8731957ad 2012-08-07 384: self.send_header('Content-Length', str(file_stat.st_size))
90160dbf50 2011-03-06 385: requested_ranges = spacemap.SpaceMap({0: file_stat.st_size})
d8731957ad 2012-08-07 386: if 'Last-Modified' in index[my_path_b]:
d8731957ad 2012-08-07 387: self.send_header('Last-Modified', index[my_path_b]['Last-Modified'])
d8731957ad 2012-08-07 388: self.send_header('Content-Type', 'application/octet-stream')
90160dbf50 2011-03-06 389: self.end_headers()
90160dbf50 2011-03-06 390: if self.command in ('GET'):
90160dbf50 2011-03-06 391: if len(requested_ranges) > 0:
90160dbf50 2011-03-06 392: requested_ranges.rewind()
90160dbf50 2011-03-06 393: (start, end) = requested_ranges.pop()
90160dbf50 2011-03-06 394: else:
90160dbf50 2011-03-06 395: start = 0
9a8a46bcf0 2011-09-06 396: # XXX ugly hack
d8731957ad 2012-08-07 397: if 'Content-Length' in index[my_path_b]:
d8731957ad 2012-08-07 398: end = index[my_path_b]['Content-Length']
9a8a46bcf0 2011-09-06 399: else:
9a8a46bcf0 2011-09-06 400: end = 0
90160dbf50 2011-03-06 401: real_file.seek(start)
90160dbf50 2011-03-06 402: if block_size > end - start:
90160dbf50 2011-03-06 403: req_block_size = end - start
90160dbf50 2011-03-06 404: else:
90160dbf50 2011-03-06 405: req_block_size = block_size
90160dbf50 2011-03-06 406: buffer = real_file.read(req_block_size)
90160dbf50 2011-03-06 407: length = len(buffer)
90160dbf50 2011-03-06 408: while length > 0:
90160dbf50 2011-03-06 409: self.wfile.write(buffer)
90160dbf50 2011-03-06 410: start += len(buffer)
90160dbf50 2011-03-06 411: if req_block_size > end - start:
90160dbf50 2011-03-06 412: req_block_size = end - start
90160dbf50 2011-03-06 413: if req_block_size == 0:
90160dbf50 2011-03-06 414: break
90160dbf50 2011-03-06 415: buffer = real_file.read(req_block_size)
90160dbf50 2011-03-06 416: length = len(buffer)
90160dbf50 2011-03-06 417:
90160dbf50 2011-03-06 418: def do_HEAD(self):
90160dbf50 2011-03-06 419: return self.__process()
90160dbf50 2011-03-06 420: def do_GET(self):
90160dbf50 2011-03-06 421: return self.__process()
90160dbf50 2011-03-06 422:
d8731957ad 2012-08-07 423: server = http.server.HTTPServer(('127.0.0.1', int(config['DEFAULT']['port'])), MyRequestHandler)
90160dbf50 2011-03-06 424: server.serve_forever()
82969b1fc2 2012-01-25 425:
82969b1fc2 2012-01-25 426: #gevent.joinall()