desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Process a NEWNEWS command. Arguments: - group: group name or \'*\' - date: string \'yymmdd\' indicating the date - time: string \'hhmmss\' indicating the time Return: - resp: server response if successful - list: list of message ids'
def newnews(self, group, date, time, file=None):
cmd = ((((('NEWNEWS ' + group) + ' ') + date) + ' ') + time) return self.longcmd(cmd, file)
'Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)'
def list(self, file=None):
(resp, list) = self.longcmd('LIST', file) for i in range(len(list)): list[i] = tuple(list[i].split()) return (resp, list)
'Get a description for a single group. If more than one group matches (\'group\' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be \'215\' or \'285\' (for xgtitle) anyway. If the response code is needed, use the \'descriptions\' method. NOTE: This neither checks for a wildcard in \'group\' nor does it check whether the group actually exists.'
def description(self, group):
(resp, lines) = self.descriptions(group) if (len(lines) == 0): return '' else: return lines[0][1]
'Get descriptions for a range of groups.'
def descriptions(self, group_pattern):
line_pat = re.compile('^(?P<group>[^ DCTB ]+)[ DCTB ]+(.*)$') (resp, raw_lines) = self.longcmd(('LIST NEWSGROUPS ' + group_pattern)) if (resp[:3] != '215'): (resp, raw_lines) = self.longcmd(('XGTITLE ' + group_pattern)) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return (resp, lines)
'Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles (string) - first: first article number (string) - last: last article number (string) - name: the group name'
def group(self, name):
resp = self.shortcmd(('GROUP ' + name)) if (resp[:3] != '211'): raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if (n > 1): count = words[1] if (n > 2): first = words[2] if (n > 3): last = words[3] if (n > 4): name = words[4].lower() return (resp, count, first, last, name)
'Process a HELP command. Returns: - resp: server response if successful - list: list of strings'
def help(self, file=None):
return self.longcmd('HELP', file)
'Internal: parse the response of a STAT, NEXT or LAST command.'
def statparse(self, resp):
if (resp[:2] != '22'): raise NNTPReplyError(resp) words = resp.split() nr = 0 id = '' n = len(words) if (n > 1): nr = words[1] if (n > 2): id = words[2] return (resp, nr, id)
'Internal: process a STAT, NEXT or LAST command.'
def statcmd(self, line):
resp = self.shortcmd(line) return self.statparse(resp)
'Process a STAT command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: the article number - id: the message id'
def stat(self, id):
return self.statcmd(('STAT ' + id))
'Process a NEXT command. No arguments. Return as for STAT.'
def next(self):
return self.statcmd('NEXT')
'Process a LAST command. No arguments. Return as for STAT.'
def last(self):
return self.statcmd('LAST')
'Internal: process a HEAD, BODY or ARTICLE command.'
def artcmd(self, line, file=None):
(resp, list) = self.longcmd(line, file) (resp, nr, id) = self.statparse(resp) return (resp, nr, id, list)
'Process a HEAD command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article\'s header'
def head(self, id):
return self.artcmd(('HEAD ' + id))
'Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article\'s body or an empty list if file was used'
def body(self, id, file=None):
return self.artcmd(('BODY ' + id), file)
'Process an ARTICLE command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article'
def article(self, id):
return self.artcmd(('ARTICLE ' + id))
'Process a SLAVE command. Returns: - resp: server response if successful'
def slave(self):
return self.shortcmd('SLAVE')
'Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. \'subject\') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings'
def xhdr(self, hdr, str, file=None):
pat = re.compile('^([0-9]+) ?(.*)\n?') (resp, lines) = self.longcmd(((('XHDR ' + hdr) + ' ') + str), file) for i in range(len(lines)): line = lines[i] m = pat.match(line) if m: lines[i] = m.group(1, 2) return (resp, lines)
'Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)'
def xover(self, start, end, file=None):
(resp, lines) = self.longcmd(((('XOVER ' + start) + '-') + end), file) xover_lines = [] for line in lines: elem = line.split(' DCTB ') try: xover_lines.append((elem[0], elem[1], elem[2], elem[3], elem[4], elem[5].split(), elem[6], elem[7])) except IndexError: raise NNTPDataError(line) return (resp, xover_lines)
'Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings'
def xgtitle(self, group, file=None):
line_pat = re.compile('^([^ DCTB ]+)[ DCTB ]+(.*)$') (resp, raw_lines) = self.longcmd(('XGTITLE ' + group), file) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return (resp, lines)
'Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article'
def xpath(self, id):
resp = self.shortcmd(('XPATH ' + id)) if (resp[:3] != '223'): raise NNTPReplyError(resp) try: [resp_num, path] = resp.split() except ValueError: raise NNTPReplyError(resp) else: return (resp, path)
'Process the DATE command. Arguments: None Returns: resp: server response if successful date: Date suitable for newnews/newgroups commands etc. time: Time suitable for newnews/newgroups commands etc.'
def date(self):
resp = self.shortcmd('DATE') if (resp[:3] != '111'): raise NNTPReplyError(resp) elem = resp.split() if (len(elem) != 2): raise NNTPDataError(resp) date = elem[1][2:8] time = elem[1][(-6):] if ((len(date) != 6) or (len(time) != 6)): raise NNTPDataError(resp) return (resp, date, time)
'Process a POST command. Arguments: - f: file containing the article Returns: - resp: server response if successful'
def post(self, f):
resp = self.shortcmd('POST') if (resp[0] != '3'): raise NNTPReplyError(resp) while 1: line = f.readline() if (not line): break if (line[(-1)] == '\n'): line = line[:(-1)] if (line[:1] == '.'): line = ('.' + line) self.putline(line) self.putline('.') return self.getresp()
'Process an IHAVE command. Arguments: - id: message-id of the article - f: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.'
def ihave(self, id, f):
resp = self.shortcmd(('IHAVE ' + id)) if (resp[0] != '3'): raise NNTPReplyError(resp) while 1: line = f.readline() if (not line): break if (line[(-1)] == '\n'): line = line[:(-1)] if (line[:1] == '.'): line = ('.' + line) self.putline(line) self.putline('.') return self.getresp()
'Process a QUIT command and close the socket. Returns: - resp: server response if successful'
def quit(self):
resp = self.shortcmd('QUIT') self.file.close() self.sock.close() del self.file, self.sock return resp
'Serve a GET request.'
def do_GET(self):
f = self.send_head() if f: try: self.copyfile(f, self.wfile) finally: f.close()
'Serve a HEAD request.'
def do_HEAD(self):
f = self.send_head() if f: f.close()
'Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do.'
def send_head(self):
path = self.translate_path(self.path) f = None if os.path.isdir(path): parts = urlparse.urlsplit(self.path) if (not parts.path.endswith('/')): self.send_response(301) new_parts = (parts[0], parts[1], (parts[2] + '/'), parts[3], parts[4]) new_url = urlparse.urlunsplit(new_parts) self.send_header('Location', new_url) self.end_headers() return None for index in ('index.html', 'index.htm'): index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: f = open(path, 'rb') except IOError: self.send_error(404, 'File not found') return None try: self.send_response(200) self.send_header('Content-type', ctype) fs = os.fstat(f.fileno()) self.send_header('Content-Length', str(fs[6])) self.send_header('Last-Modified', self.date_time_string(fs.st_mtime)) self.end_headers() return f except: f.close() raise
'Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head().'
def list_directory(self, path):
try: list = os.listdir(path) except os.error: self.send_error(404, 'No permission to list directory') return None list.sort(key=(lambda a: a.lower())) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') f.write(('<html>\n<title>Directory listing for %s</title>\n' % displaypath)) f.write(('<body>\n<h2>Directory listing for %s</h2>\n' % displaypath)) f.write('<hr>\n<ul>\n') for name in list: fullname = os.path.join(path, name) displayname = linkname = name if os.path.isdir(fullname): displayname = (name + '/') linkname = (name + '/') if os.path.islink(fullname): displayname = (name + '@') f.write(('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname)))) f.write('</ul>\n<hr>\n</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header('Content-type', ('text/html; charset=%s' % encoding)) self.send_header('Content-Length', str(length)) self.end_headers() return f
'Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)'
def translate_path(self, path):
path = path.split('?', 1)[0] path = path.split('#', 1)[0] trailing_slash = path.rstrip().endswith('/') path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: if (os.path.dirname(word) or (word in (os.curdir, os.pardir))): continue path = os.path.join(path, word) if trailing_slash: path += '/' return path
'Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well.'
def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)
'Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file\'s extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess.'
def guess_type(self, path):
(base, ext) = posixpath.splitext(path) if (ext in self.extensions_map): return self.extensions_map[ext] ext = ext.lower() if (ext in self.extensions_map): return self.extensions_map[ext] else: return self.extensions_map['']
'Returns a dialect (or None) corresponding to the sample'
def sniff(self, sample, delimiters=None):
(quotechar, doublequote, delimiter, skipinitialspace) = self._guess_quote_and_delimiter(sample, delimiters) if (not delimiter): (delimiter, skipinitialspace) = self._guess_delimiter(sample, delimiters) if (not delimiter): raise Error, 'Could not determine delimiter' class dialect(Dialect, ): _name = 'sniffed' lineterminator = '\r\n' quoting = QUOTE_MINIMAL dialect.doublequote = doublequote dialect.delimiter = delimiter dialect.quotechar = (quotechar or '"') dialect.skipinitialspace = skipinitialspace return dialect
'Looks for text enclosed between two identical quotes (the probable quotechar) which are preceded and followed by the same character (the probable delimiter). For example: ,\'some text\', The quote with the most wins, same with the delimiter. If there is no quotechar the delimiter can\'t be determined this way.'
def _guess_quote_and_delimiter(self, data, delimiters):
matches = [] for restr in ('(?P<delim>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\\w\n"\'])(?P<space> ?)', '(?P<delim>>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): regexp = re.compile(restr, (re.DOTALL | re.MULTILINE)) matches = regexp.findall(data) if matches: break if (not matches): return ('', False, None, 0) quotes = {} delims = {} spaces = 0 for m in matches: n = (regexp.groupindex['quote'] - 1) key = m[n] if key: quotes[key] = (quotes.get(key, 0) + 1) try: n = (regexp.groupindex['delim'] - 1) key = m[n] except KeyError: continue if (key and ((delimiters is None) or (key in delimiters))): delims[key] = (delims.get(key, 0) + 1) try: n = (regexp.groupindex['space'] - 1) except KeyError: continue if m[n]: spaces += 1 quotechar = reduce((lambda a, b, quotes=quotes: (((quotes[a] > quotes[b]) and a) or b)), quotes.keys()) if delims: delim = reduce((lambda a, b, delims=delims: (((delims[a] > delims[b]) and a) or b)), delims.keys()) skipinitialspace = (delims[delim] == spaces) if (delim == '\n'): delim = '' else: delim = '' skipinitialspace = 0 dq_regexp = re.compile(('((%(delim)s)|^)\\W*%(quote)s[^%(delim)s\\n]*%(quote)s[^%(delim)s\\n]*%(quote)s\\W*((%(delim)s)|$)' % {'delim': re.escape(delim), 'quote': quotechar}), re.MULTILINE) if dq_regexp.search(data): doublequote = True else: doublequote = False return (quotechar, doublequote, delim, skipinitialspace)
'The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don\'t want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) build a table of frequencies of this frequency (meta-frequency?), e.g. \'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows\' 3) use the mode of the meta-frequency to determine the /expected/ frequency for that character 4) find out how often the character actually meets that goal 5) the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary.'
def _guess_delimiter(self, data, delimiters):
data = filter(None, data.split('\n')) ascii = [chr(c) for c in range(127)] chunkLength = min(10, len(data)) iteration = 0 charFrequency = {} modes = {} delims = {} (start, end) = (0, min(chunkLength, len(data))) while (start < len(data)): iteration += 1 for line in data[start:end]: for char in ascii: metaFrequency = charFrequency.get(char, {}) freq = line.count(char) metaFrequency[freq] = (metaFrequency.get(freq, 0) + 1) charFrequency[char] = metaFrequency for char in charFrequency.keys(): items = charFrequency[char].items() if ((len(items) == 1) and (items[0][0] == 0)): continue if (len(items) > 1): modes[char] = reduce((lambda a, b: (((a[1] > b[1]) and a) or b)), items) items.remove(modes[char]) modes[char] = (modes[char][0], (modes[char][1] - reduce((lambda a, b: (0, (a[1] + b[1]))), items)[1])) else: modes[char] = items[0] modeList = modes.items() total = float((chunkLength * iteration)) consistency = 1.0 threshold = 0.9 while ((len(delims) == 0) and (consistency >= threshold)): for (k, v) in modeList: if ((v[0] > 0) and (v[1] > 0)): if (((v[1] / total) >= consistency) and ((delimiters is None) or (k in delimiters))): delims[k] = v consistency -= 0.01 if (len(delims) == 1): delim = delims.keys()[0] skipinitialspace = (data[0].count(delim) == data[0].count(('%c ' % delim))) return (delim, skipinitialspace) start = end end += chunkLength if (not delims): return ('', 0) if (len(delims) > 1): for d in self.preferred: if (d in delims.keys()): skipinitialspace = (data[0].count(d) == data[0].count(('%c ' % d))) return (d, skipinitialspace) items = [(v, k) for (k, v) in delims.items()] items.sort() delim = items[(-1)][1] skipinitialspace = (data[0].count(delim) == data[0].count(('%c ' % delim))) return (delim, skipinitialspace)
'Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch(\'add\',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an \'_\' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an \'_\'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module\'s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.'
def register_instance(self, instance, allow_dotted_names=False):
self.instance = instance self.allow_dotted_names = allow_dotted_names
'Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function.'
def register_function(self, function, name=None):
if (name is None): name = function.__name__ self.funcs[name] = function
'Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html'
def register_introspection_functions(self):
self.funcs.update({'system.listMethods': self.system_listMethods, 'system.methodSignature': self.system_methodSignature, 'system.methodHelp': self.system_methodHelp})
'Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208'
def register_multicall_functions(self):
self.funcs.update({'system.multicall': self.system_multicall})
'Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior.'
def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
try: (params, method) = xmlrpclib.loads(data) if (dispatch_method is not None): response = dispatch_method(method, params) else: response = self._dispatch(method, params) response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: (exc_type, exc_value, exc_tb) = sys.exc_info() response = xmlrpclib.dumps(xmlrpclib.Fault(1, ('%s:%s' % (exc_type, exc_value))), encoding=self.encoding, allow_none=self.allow_none) return response
'system.listMethods() => [\'add\', \'subtract\', \'multiple\'] Returns a list of the methods supported by the server.'
def system_listMethods(self):
methods = self.funcs.keys() if (self.instance is not None): if hasattr(self.instance, '_listMethods'): methods = remove_duplicates((methods + self.instance._listMethods())) elif (not hasattr(self.instance, '_dispatch')): methods = remove_duplicates((methods + list_public_methods(self.instance))) methods.sort() return methods
'system.methodSignature(\'add\') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.'
def system_methodSignature(self, method_name):
return 'signatures not supported'
'system.methodHelp(\'add\') => "Adds two integers together" Returns a string containing documentation for the specified method.'
def system_methodHelp(self, method_name):
method = None if (method_name in self.funcs): method = self.funcs[method_name] elif (self.instance is not None): if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) elif (not hasattr(self.instance, '_dispatch')): try: method = resolve_dotted_attribute(self.instance, method_name, self.allow_dotted_names) except AttributeError: pass if (method is None): return '' else: import pydoc return pydoc.getdoc(method)
'system.multicall([{\'methodName\': \'add\', \'params\': [2, 2]}, ...]) => [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208'
def system_multicall(self, call_list):
results = [] for call in call_list: method_name = call['methodName'] params = call['params'] try: results.append([self._dispatch(method_name, params)]) except Fault as fault: results.append({'faultCode': fault.faultCode, 'faultString': fault.faultString}) except: (exc_type, exc_value, exc_tb) = sys.exc_info() results.append({'faultCode': 1, 'faultString': ('%s:%s' % (exc_type, exc_value))}) return results
'Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch(\'add\',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an \'_\' are considered private and will not be called.'
def _dispatch(self, method, params):
func = None try: func = self.funcs[method] except KeyError: if (self.instance is not None): if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: try: func = resolve_dotted_attribute(self.instance, method, self.allow_dotted_names) except AttributeError: pass if (func is not None): return func(*params) else: raise Exception(('method "%s" is not supported' % method))
'Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server\'s _dispatch method for handling.'
def do_POST(self):
if (not self.is_rpc_path_valid()): self.report_404() return try: max_chunk_size = ((10 * 1024) * 1024) size_remaining = int(self.headers['content-length']) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if (not chunk): break L.append(chunk) size_remaining -= len(L[(-1)]) data = ''.join(L) data = self.decode_request_content(data) if (data is None): return response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None), self.path) except Exception as e: self.send_response(500) if (hasattr(self.server, '_send_traceback_header') and self.server._send_traceback_header): self.send_header('X-exception', str(e)) self.send_header('X-traceback', traceback.format_exc()) self.send_header('Content-length', '0') self.end_headers() else: self.send_response(200) self.send_header('Content-type', 'text/xml') if (self.encode_threshold is not None): if (len(response) > self.encode_threshold): q = self.accept_encodings().get('gzip', 0) if q: try: response = xmlrpclib.gzip_encode(response) self.send_header('Content-Encoding', 'gzip') except NotImplementedError: pass self.send_header('Content-length', str(len(response))) self.end_headers() self.wfile.write(response)
'Selectively log an accepted request.'
def log_request(self, code='-', size='-'):
if self.server.logRequests: BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
'Handle a single XML-RPC request'
def handle_xmlrpc(self, request_text):
response = self._marshaled_dispatch(request_text) print 'Content-Type: text/xml' print ('Content-Length: %d' % len(response)) print sys.stdout.write(response)
'Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method.'
def handle_get(self):
code = 400 (message, explain) = BaseHTTPServer.BaseHTTPRequestHandler.responses[code] response = (BaseHTTPServer.DEFAULT_ERROR_MESSAGE % {'code': code, 'message': message, 'explain': explain}) print ('Status: %d %s' % (code, message)) print ('Content-Type: %s' % BaseHTTPServer.DEFAULT_ERROR_CONTENT_TYPE) print ('Content-Length: %d' % len(response)) print sys.stdout.write(response)
'Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers.'
def handle_request(self, request_text=None):
if ((request_text is None) and (os.environ.get('REQUEST_METHOD', None) == 'GET')): self.handle_get() else: try: length = int(os.environ.get('CONTENT_LENGTH', None)) except (TypeError, ValueError): length = (-1) if (request_text is None): request_text = sys.stdin.read(length) self.handle_xmlrpc(request_text)
'Initialize a new instance, passing the time and delay functions'
def __init__(self, timefunc, delayfunc):
self._queue = [] self.timefunc = timefunc self.delayfunc = delayfunc
'Enter a new event in the queue at an absolute time. Returns an ID for the event which can be used to remove it, if necessary.'
def enterabs(self, time, priority, action, argument):
event = Event(time, priority, action, argument) heapq.heappush(self._queue, event) return event
'A variant that specifies the time as a relative time. This is actually the more commonly used interface.'
def enter(self, delay, priority, action, argument):
time = (self.timefunc() + delay) return self.enterabs(time, priority, action, argument)
'Remove an event from the queue. This must be presented the ID as returned by enter(). If the event is not in the queue, this raises ValueError.'
def cancel(self, event):
self._queue.remove(event) heapq.heapify(self._queue)
'Check whether the queue is empty.'
def empty(self):
return (not self._queue)
'Execute events until the queue is empty. When there is a positive delay until the first event, the delay function is called and the event is left in the queue; otherwise, the event is removed from the queue and executed (its action function is called, passing it the argument). If the delay function returns prematurely, it is simply restarted. It is legal for both the delay function and the action function to modify the queue or to raise an exception; exceptions are not caught but the scheduler\'s state remains well-defined so run() may be called again. A questionable hack is added to allow other threads to run: just after an event is executed, a delay of 0 is executed, to avoid monopolizing the CPU when other threads are also runnable.'
def run(self):
q = self._queue delayfunc = self.delayfunc timefunc = self.timefunc pop = heapq.heappop while q: (time, priority, action, argument) = checked_event = q[0] now = timefunc() if (now < time): delayfunc((time - now)) else: event = pop(q) if (event is checked_event): action(*argument) delayfunc(0) else: heapq.heappush(q, event)
'An ordered list of upcoming events. Events are named tuples with fields for: time, priority, action, arguments'
@property def queue(self):
events = self._queue[:] return map(heapq.heappop, ([events] * len(events)))
'Return the name (ID) of the current chunk.'
def getname(self):
return self.chunkname
'Return the size of the current chunk.'
def getsize(self):
return self.chunksize
'Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error.'
def seek(self, pos, whence=0):
if self.closed: raise ValueError, 'I/O operation on closed file' if (not self.seekable): raise IOError, 'cannot seek' if (whence == 1): pos = (pos + self.size_read) elif (whence == 2): pos = (pos + self.chunksize) if ((pos < 0) or (pos > self.chunksize)): raise RuntimeError self.file.seek((self.offset + pos), 0) self.size_read = pos
'Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk.'
def read(self, size=(-1)):
if self.closed: raise ValueError, 'I/O operation on closed file' if (self.size_read >= self.chunksize): return '' if (size < 0): size = (self.chunksize - self.size_read) if (size > (self.chunksize - self.size_read)): size = (self.chunksize - self.size_read) data = self.file.read(size) self.size_read = (self.size_read + len(data)) if ((self.size_read == self.chunksize) and self.align and (self.chunksize & 1)): dummy = self.file.read(1) self.size_read = (self.size_read + len(dummy)) return data
'Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk.'
def skip(self):
if self.closed: raise ValueError, 'I/O operation on closed file' if self.seekable: try: n = (self.chunksize - self.size_read) if (self.align and (self.chunksize & 1)): n = (n + 1) self.file.seek(n, 1) self.size_read = (self.size_read + n) return except IOError: pass while (self.size_read < self.chunksize): n = min(8192, (self.chunksize - self.size_read)) dummy = self.read(n) if (not dummy): raise EOFError
'Go to the location of the first blank on the given line, returning the index of the last non-blank character.'
def _end_of_line(self, y):
last = self.maxx while True: if (curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP): last = min(self.maxx, (last + 1)) break elif (last == 0): break last = (last - 1) return last
'Process a single editing command.'
def do_command(self, ch):
(y, x) = self.win.getyx() self.lastcmd = ch if curses.ascii.isprint(ch): if ((y < self.maxy) or (x < self.maxx)): self._insert_printable_char(ch) elif (ch == curses.ascii.SOH): self.win.move(y, 0) elif (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY_BACKSPACE)): if (x > 0): self.win.move(y, (x - 1)) elif (y == 0): pass elif self.stripspaces: self.win.move((y - 1), self._end_of_line((y - 1))) else: self.win.move((y - 1), self.maxx) if (ch in (curses.ascii.BS, curses.KEY_BACKSPACE)): self.win.delch() elif (ch == curses.ascii.EOT): self.win.delch() elif (ch == curses.ascii.ENQ): if self.stripspaces: self.win.move(y, self._end_of_line(y)) else: self.win.move(y, self.maxx) elif (ch in (curses.ascii.ACK, curses.KEY_RIGHT)): if (x < self.maxx): self.win.move(y, (x + 1)) elif (y == self.maxy): pass else: self.win.move((y + 1), 0) elif (ch == curses.ascii.BEL): return 0 elif (ch == curses.ascii.NL): if (self.maxy == 0): return 0 elif (y < self.maxy): self.win.move((y + 1), 0) elif (ch == curses.ascii.VT): if ((x == 0) and (self._end_of_line(y) == 0)): self.win.deleteln() else: self.win.move(y, x) self.win.clrtoeol() elif (ch == curses.ascii.FF): self.win.refresh() elif (ch in (curses.ascii.SO, curses.KEY_DOWN)): if (y < self.maxy): self.win.move((y + 1), x) if (x > self._end_of_line((y + 1))): self.win.move((y + 1), self._end_of_line((y + 1))) elif (ch == curses.ascii.SI): self.win.insertln() elif (ch in (curses.ascii.DLE, curses.KEY_UP)): if (y > 0): self.win.move((y - 1), x) if (x > self._end_of_line((y - 1))): self.win.move((y - 1), self._end_of_line((y - 1))) return 1
'Collect and return the contents of the window.'
def gather(self):
result = '' for y in range((self.maxy + 1)): self.win.move(y, 0) stop = self._end_of_line(y) if ((stop == 0) and self.stripspaces): continue for x in range((self.maxx + 1)): if (self.stripspaces and (x > stop)): break result = (result + chr(curses.ascii.ascii(self.win.inch(y, x)))) if (self.maxy > 0): result = (result + '\n') return result
'Edit in the widget window and collect the results.'
def edit(self, validate=None):
while 1: ch = self.win.getch() if validate: ch = validate(ch) if (not ch): continue if (not self.do_command(ch)): break self.win.refresh() return self.gather()
'Constructor.'
def __init__(self, path=None, profile=None):
if (profile is None): profile = MH_PROFILE self.profile = os.path.expanduser(profile) if (path is None): path = self.getprofile('Path') if (not path): path = PATH if ((not os.path.isabs(path)) and (path[0] != '~')): path = os.path.join('~', path) path = os.path.expanduser(path) if (not os.path.isdir(path)): raise Error, 'MH() path not found' self.path = path
'String representation.'
def __repr__(self):
return ('MH(%r, %r)' % (self.path, self.profile))
'Routine to print an error. May be overridden by a derived class.'
def error(self, msg, *args):
sys.stderr.write(('MH error: %s\n' % (msg % args)))
'Return a profile entry, None if not found.'
def getprofile(self, key):
return pickline(self.profile, key)
'Return the path (the name of the collection\'s directory).'
def getpath(self):
return self.path
'Return the name of the current folder.'
def getcontext(self):
context = pickline(os.path.join(self.getpath(), 'context'), 'Current-Folder') if (not context): context = 'inbox' return context
'Set the name of the current folder.'
def setcontext(self, context):
fn = os.path.join(self.getpath(), 'context') f = open(fn, 'w') f.write(('Current-Folder: %s\n' % context)) f.close()
'Return the names of the top-level folders.'
def listfolders(self):
folders = [] path = self.getpath() for name in os.listdir(path): fullname = os.path.join(path, name) if os.path.isdir(fullname): folders.append(name) folders.sort() return folders
'Return the names of the subfolders in a given folder (prefixed with the given folder name).'
def listsubfolders(self, name):
fullname = os.path.join(self.path, name) nlinks = os.stat(fullname).st_nlink if (nlinks <= 2): return [] subfolders = [] subnames = os.listdir(fullname) for subname in subnames: fullsubname = os.path.join(fullname, subname) if os.path.isdir(fullsubname): name_subname = os.path.join(name, subname) subfolders.append(name_subname) nlinks = (nlinks - 1) if (nlinks <= 2): break subfolders.sort() return subfolders
'Return the names of all folders and subfolders, recursively.'
def listallfolders(self):
return self.listallsubfolders('')
'Return the names of subfolders in a given folder, recursively.'
def listallsubfolders(self, name):
fullname = os.path.join(self.path, name) nlinks = os.stat(fullname).st_nlink if (nlinks <= 2): return [] subfolders = [] subnames = os.listdir(fullname) for subname in subnames: if ((subname[0] == ',') or isnumeric(subname)): continue fullsubname = os.path.join(fullname, subname) if os.path.isdir(fullsubname): name_subname = os.path.join(name, subname) subfolders.append(name_subname) if (not os.path.islink(fullsubname)): subsubfolders = self.listallsubfolders(name_subname) subfolders = (subfolders + subsubfolders) nlinks = (nlinks - 1) if (nlinks <= 2): break subfolders.sort() return subfolders
'Return a new Folder object for the named folder.'
def openfolder(self, name):
return Folder(self, name)
'Create a new folder (or raise os.error if it cannot be created).'
def makefolder(self, name):
protect = pickline(self.profile, 'Folder-Protect') if (protect and isnumeric(protect)): mode = int(protect, 8) else: mode = FOLDER_PROTECT os.mkdir(os.path.join(self.getpath(), name), mode)
'Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.'
def deletefolder(self, name):
fullname = os.path.join(self.getpath(), name) for subname in os.listdir(fullname): fullsubname = os.path.join(fullname, subname) try: os.unlink(fullsubname) except os.error: self.error(('%s not deleted, continuing...' % fullsubname)) os.rmdir(fullname)
'Constructor.'
def __init__(self, mh, name):
self.mh = mh self.name = name if (not os.path.isdir(self.getfullname())): raise Error, ('no folder %s' % name)
'String representation.'
def __repr__(self):
return ('Folder(%r, %r)' % (self.mh, self.name))
'Error message handler.'
def error(self, *args):
self.mh.error(*args)
'Return the full pathname of the folder.'
def getfullname(self):
return os.path.join(self.mh.path, self.name)
'Return the full pathname of the folder\'s sequences file.'
def getsequencesfilename(self):
return os.path.join(self.getfullname(), MH_SEQUENCES)
'Return the full pathname of a message in the folder.'
def getmessagefilename(self, n):
return os.path.join(self.getfullname(), str(n))
'Return list of direct subfolders.'
def listsubfolders(self):
return self.mh.listsubfolders(self.name)
'Return list of all subfolders.'
def listallsubfolders(self):
return self.mh.listallsubfolders(self.name)
'Return the list of messages currently present in the folder. As a side effect, set self.last to the last message (or 0).'
def listmessages(self):
messages = [] match = numericprog.match append = messages.append for name in os.listdir(self.getfullname()): if match(name): append(name) messages = map(int, messages) messages.sort() if messages: self.last = messages[(-1)] else: self.last = 0 return messages
'Return the set of sequences for the folder.'
def getsequences(self):
sequences = {} fullname = self.getsequencesfilename() try: f = open(fullname, 'r') except IOError: return sequences while 1: line = f.readline() if (not line): break fields = line.split(':') if (len(fields) != 2): self.error(('bad sequence in %s: %s' % (fullname, line.strip()))) key = fields[0].strip() value = IntSet(fields[1].strip(), ' ').tolist() sequences[key] = value return sequences
'Write the set of sequences back to the folder.'
def putsequences(self, sequences):
fullname = self.getsequencesfilename() f = None for (key, seq) in sequences.iteritems(): s = IntSet('', ' ') s.fromlist(seq) if (not f): f = open(fullname, 'w') f.write(('%s: %s\n' % (key, s.tostring()))) if (not f): try: os.unlink(fullname) except os.error: pass else: f.close()
'Return the current message. Raise Error when there is none.'
def getcurrent(self):
seqs = self.getsequences() try: return max(seqs['cur']) except (ValueError, KeyError): raise Error, 'no cur message'
'Set the current message.'
def setcurrent(self, n):
updateline(self.getsequencesfilename(), 'cur', str(n), 0)
'Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.'
def parsesequence(self, seq):
all = self.listmessages() if (not all): raise Error, ('no messages in %s' % self.name) if (seq == 'all'): return all i = seq.find(':') if (i >= 0): (head, dir, tail) = (seq[:i], '', seq[(i + 1):]) if (tail[:1] in '-+'): (dir, tail) = (tail[:1], tail[1:]) if (not isnumeric(tail)): raise Error, ('bad message list %s' % seq) try: count = int(tail) except (ValueError, OverflowError): count = len(all) try: anchor = self._parseindex(head, all) except Error as msg: seqs = self.getsequences() if (not (head in seqs)): if (not msg): msg = ('bad message list %s' % seq) raise Error, msg, sys.exc_info()[2] msgs = seqs[head] if (not msgs): raise Error, ('sequence %s empty' % head) if (dir == '-'): return msgs[(- count):] else: return msgs[:count] else: if (not dir): if (head in ('prev', 'last')): dir = '-' if (dir == '-'): i = bisect(all, anchor) return all[max(0, (i - count)):i] else: i = bisect(all, (anchor - 1)) return all[i:(i + count)] i = seq.find('-') if (i >= 0): begin = self._parseindex(seq[:i], all) end = self._parseindex(seq[(i + 1):], all) i = bisect(all, (begin - 1)) j = bisect(all, end) r = all[i:j] if (not r): raise Error, ('bad message list %s' % seq) return r try: n = self._parseindex(seq, all) except Error as msg: seqs = self.getsequences() if (not (seq in seqs)): if (not msg): msg = ('bad message list %s' % seq) raise Error, msg return seqs[seq] else: if (n not in all): if isnumeric(seq): raise Error, ("message %d doesn't exist" % n) else: raise Error, ('no %s message' % seq) else: return [n]
'Internal: parse a message number (or cur, first, etc.).'
def _parseindex(self, seq, all):
if isnumeric(seq): try: return int(seq) except (OverflowError, ValueError): return sys.maxint if (seq in ('cur', '.')): return self.getcurrent() if (seq == 'first'): return all[0] if (seq == 'last'): return all[(-1)] if (seq == 'next'): n = self.getcurrent() i = bisect(all, n) try: return all[i] except IndexError: raise Error, 'no next message' if (seq == 'prev'): n = self.getcurrent() i = bisect(all, (n - 1)) if (i == 0): raise Error, 'no prev message' try: return all[(i - 1)] except IndexError: raise Error, 'no prev message' raise Error, None
'Open a message -- returns a Message object.'
def openmessage(self, n):
return Message(self, n)
'Remove one or more messages -- may raise os.error.'
def removemessages(self, list):
errors = [] deleted = [] for n in list: path = self.getmessagefilename(n) commapath = self.getmessagefilename((',' + str(n))) try: os.unlink(commapath) except os.error: pass try: os.rename(path, commapath) except os.error as msg: errors.append(msg) else: deleted.append(n) if deleted: self.removefromallsequences(deleted) if errors: if (len(errors) == 1): raise os.error, errors[0] else: raise os.error, ('multiple errors:', errors)
'Refile one or more messages -- may raise os.error. \'tofolder\' is an open folder object.'
def refilemessages(self, list, tofolder, keepsequences=0):
errors = [] refiled = {} for n in list: ton = (tofolder.getlast() + 1) path = self.getmessagefilename(n) topath = tofolder.getmessagefilename(ton) try: os.rename(path, topath) except os.error: try: shutil.copy2(path, topath) os.unlink(path) except (IOError, os.error) as msg: errors.append(msg) try: os.unlink(topath) except os.error: pass continue tofolder.setlast(ton) refiled[n] = ton if refiled: if keepsequences: tofolder._copysequences(self, refiled.items()) self.removefromallsequences(refiled.keys()) if errors: if (len(errors) == 1): raise os.error, errors[0] else: raise os.error, ('multiple errors:', errors)
'Helper for refilemessages() to copy sequences.'
def _copysequences(self, fromfolder, refileditems):
fromsequences = fromfolder.getsequences() tosequences = self.getsequences() changed = 0 for (name, seq) in fromsequences.items(): try: toseq = tosequences[name] new = 0 except KeyError: toseq = [] new = 1 for (fromn, ton) in refileditems: if (fromn in seq): toseq.append(ton) changed = 1 if (new and toseq): tosequences[name] = toseq if changed: self.putsequences(tosequences)
'Move one message over a specific destination message, which may or may not already exist.'
def movemessage(self, n, tofolder, ton):
path = self.getmessagefilename(n) f = open(path) f.close() del f topath = tofolder.getmessagefilename(ton) backuptopath = tofolder.getmessagefilename((',%d' % ton)) try: os.rename(topath, backuptopath) except os.error: pass try: os.rename(path, topath) except os.error: ok = 0 try: tofolder.setlast(None) shutil.copy2(path, topath) ok = 1 finally: if (not ok): try: os.unlink(topath) except os.error: pass os.unlink(path) self.removefromallsequences([n])
'Copy one message over a specific destination message, which may or may not already exist.'
def copymessage(self, n, tofolder, ton):
path = self.getmessagefilename(n) f = open(path) f.close() del f topath = tofolder.getmessagefilename(ton) backuptopath = tofolder.getmessagefilename((',%d' % ton)) try: os.rename(topath, backuptopath) except os.error: pass ok = 0 try: tofolder.setlast(None) shutil.copy2(path, topath) ok = 1 finally: if (not ok): try: os.unlink(topath) except os.error: pass