Lines of
samesite.py
from check-in a81f1a70fb
that are changed by the sequence of edits moving toward
check-in d1fa9d0737:
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: else:
190: info += '\nFile not found or inaccessible.'
191: record['_parts'] = None
192: reload = True
193:
194: if not '_parts' in record:
195: record['_parts'] = None
196:
197: if record['_parts'] == None:
198: recheck = True
199:
200: # forcibly checking file if file size doesn't match with index data
201: if not reload:
202: if '_parts' in record and record['_parts'] == spacemap.SpaceMap():
203: if 'content-length' in record and file_stat and file_stat.st_size != int(record['content-length']):
204: info += '\nFile size is {} and stored file size is {}.'.format(file_stat.st_size, record['content-length'])
205: record['_parts'] = None
206: reload = True
207:
208: # forcibly checking file if index holds Pragma header
209: if not reload and 'pragma' in record and record['pragma'] == 'no-cache':
210: info +='\nPragma on: recheck imminent.'
211: recheck = True
212:
213: # skipping file processing if there's no need to recheck it and we have checked it at least 4 hours ago
214: if not recheck and not reload and '_time' in record and (record['_time'] - datetime.datetime.now() + datetime.timedelta(hours = 4)).days < 0:
215: info += '\nFile is old - rechecking.'
216: recheck = True
217:
218: print(info)
219: if reload or recheck:
220:
221: try:
222: request = 'http://' + config['root'] + self.path
223: my_headers = {}
224: for header in ('cache-control', 'cookie', 'referer', 'user-agent'):
225: if header in self.headers:
226: my_headers[header] = self.headers[header]
227:
228: needed = None
229: if self.command not in ('HEAD'):
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),
246: my_headers['range'] = 'bytes=' + ','.join(ranges)
247:
248: my_headers['Accept-Encoding'] = 'gzip'
249: request = urllib2.Request(request, headers = my_headers)
250:
251: source = urllib2.urlopen(request, timeout = 60)
252: new_record = {}
253: new_record['_parts'] = record['_parts']
254: headers = source.info()
255:
256: if 'content-encoding' in headers and headers['content-encoding'] == 'gzip':
257: import gzip
258: source = gzip.GzipFile(fileobj=source)
259:
260: # stripping unneeded headers (XXX make this inplace?)
261: for header in headers:
262: if header in desc_fields:
263: #if header == 'Pragma' and headers[header] != 'no-cache':
264: if header == 'content-length':
265: if 'content-range' not in headers:
266: new_record[header] = int(headers[header])
267: else:
268: new_record[header] = headers[header]
269: elif header == 'content-range':
270: range = re.compile('^bytes (\d+)-(\d+)/(\d+)$').match(headers[header])
271: if range:
272: new_record['content-length'] = int(range.group(3))
273: else:
274: assert False, 'Content-Range unrecognized.'
275: elif not header in ignore_fields:
276: print('Undefined header "', header, '": ', headers[header], sep='')
277:
278: # comparing headers with data found in index
279: # if any header has changed (except Pragma) file is fully downloaded
280: # same if we get more or less headers
281: old_keys = set(record.keys())
282: old_keys.discard('_time')
283: old_keys.discard('pragma')
284: more_keys = set(new_record.keys()) - old_keys
285: more_keys.discard('pragma')
286: less_keys = old_keys - set(new_record.keys())
287: if len(more_keys) > 0:
288: if len(old_keys) != 0:
289: print('More headers appear:', more_keys)
290: reload = True
291: elif len(less_keys) > 0:
292: print('Less headers appear:', less_keys)
293: else:
294: for key in record.keys():
295: if key[0] != '_' and key != 'pragma' and record[key] != new_record[key]:
296: print('Header "', key, '" changed from [', record[key], '] to [', new_record[key], ']', sep='')
297: print(type(record[key]), type(new_record[key]))
298: reload = True
299:
300: if reload:
301: print('Reloading.')
302: if os.access(temp_name, os.R_OK):
303: os.unlink(temp_name)
304: if os.access(file_name, os.R_OK):
305: os.unlink(file_name)
306: if 'content-length' in new_record:
307: new_record['_parts'] = spacemap.SpaceMap({0: int(new_record['content-length'])})
308: if not new_record['_parts']:
309: new_record['_parts'] = spacemap.SpaceMap()
310: print(new_record)
311:
312: # downloading file or segment
313: if 'content-length' in new_record:
314: if needed == None:
315: needed = new_record['_parts']
316: else:
317: if len(needed) > 1:
318: print("Multipart requests currently not supported.")
319: assert False, 'Skip this one for now.'
320: #else:
321: #assert False, 'No content-length or Content-Range header.'
322:
323: new_record['_time'] = datetime.datetime.now()
324: if self.command not in ('HEAD'):
325: # file is created at temporary location and moved in place only when download completes
326: if not os.access(temp_name, os.R_OK):
327: empty_name = config['dir'] + os.sep + '.tmp'
328: with open(empty_name, 'w+b') as some_file:
329: pass
330: os.renames(empty_name, temp_name)
331: temp_file = open(temp_name, 'r+b')
332: if requested_ranges == None and needed == None:
333: needed = new_record['_parts']
334: needed.rewind()
335: while True:
336: # XXX can make this implicit - one request per range
337: (start, end) = needed.pop()
338: if start == None:
339: break
340: stream_last = start
341: old_record = copy.copy(new_record)
342: if end - start < block_size:
343: req_block_size = end - start
344: else:
345: req_block_size = block_size
346: buffer = source.read(req_block_size)
347: length = len(buffer)
348: while length > 0 and stream_last < end:
349: stream_pos = stream_last + length
350: assert stream_pos <= end, 'Received more data then requested: pos:{} start:{} end:{}.'.format(stream_pos, start, end)
351: temp_file.seek(stream_last)
352: temp_file.write(buffer)
353: x = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
354: new_record['_parts'] = new_record['_parts'] - spacemap.SpaceMap({stream_last: stream_pos})
355: index[my_path] = old_record
356: index.sync()
357: old_record = copy.copy(new_record)
358: stream_last = stream_pos
359: if end - stream_last < block_size:
360: req_block_size = end - stream_last
361: buffer = source.read(req_block_size)
362: length = len(buffer)
363: # moving downloaded data to real file
364: temp_file.close()
365:
366: index[my_path] = new_record
367: index.sync()
368:
369: except urllib2.HTTPError as error:
370: # in case of error we don't need to do anything actually,
371: # if file download stalls or fails the file would not be moved to it's location
372: print(error)
373:
374: print(index[my_path])
375:
376: 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():
377: # just moving
378: # drop old dirs XXX
379: print('Moving temporary file to new destination.')
380: os.renames(temp_name, file_name)
381:
382: if not my_path in index:
383: self.send_response(502)
384: self.end_headers()
385: return
386:
387: if self.command == 'HEAD':
388: self.send_response(200)
389: if 'content-length' in index[my_path]:
390: self.send_header('content-length', index[my_path]['content-length'])
391: self.send_header('accept-ranges', 'bytes')
392: self.send_header('content-type', 'application/octet-stream')
393: if 'last-modified' in index[my_path]:
394: self.send_header('last-modified', index[my_path]['last-modified'])
395: self.end_headers()
396: else:
397: if ('_parts' in index[my_path] and index[my_path]['_parts'] != spacemap.SpaceMap()) or not os.access(file_name, os.R_OK):
398: file_name = temp_name
399:
400: with open(file_name, 'rb') as real_file:
401: file_stat = os.stat(file_name)
402: if 'range' in self.headers:
403: self.send_response(206)
404: ranges = ()
405: requested_ranges.rewind()
406: while True:
407: pair = requested_ranges.pop()
408: if pair[0] == None:
409: break
410: ranges += '{}-{}'.format(pair[0], str(pair[1] - 1)),
411: self.send_header('content-range', 'bytes {}/{}'.format(','.join(ranges), index[my_path]['content-length']))
412: else:
413: self.send_response(200)
414: self.send_header('content-length', str(file_stat.st_size))
415: requested_ranges = spacemap.SpaceMap({0: file_stat.st_size})
416: if 'last-modified' in index[my_path]:
417: self.send_header('last-modified', index[my_path]['last-modified'])
418: self.send_header('content-type', 'application/octet-stream')
419: self.end_headers()
420: if self.command in ('GET'):
421: if len(requested_ranges) > 0:
422: requested_ranges.rewind()
423: (start, end) = requested_ranges.pop()
424: else:
425: start = 0
426: # XXX ugly hack
427: if 'content-length' in index[my_path]:
428: end = index[my_path]['content-length']
429: else:
430: end = 0
431: real_file.seek(start)
432: if block_size > end - start:
433: req_block_size = end - start
434: else:
435: req_block_size = block_size
436: buffer = real_file.read(req_block_size)
437: length = len(buffer)
438: while length > 0:
439: self.wfile.write(buffer)
440: start += len(buffer)
441: if req_block_size > end - start:
442: req_block_size = end - start
443: if req_block_size == 0:
444: break
445: buffer = real_file.read(req_block_size)
446: length = len(buffer)
447:
448: def do_HEAD(self):
449: return self.__process()
450: def do_GET(self):
451: return self.__process()
452:
453: config.section('general')
454: server = BaseHTTPServer.HTTPServer(('127.0.0.1', int(config['port'])), MyRequestHandler)
455: server.serve_forever()