desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'clear(): Explicitly release parsing objects'
def clear(self):
self.pulldom.clear() del self.pulldom self.parser = None self.stream = None
'Returns true iff this element is declared to have an EMPTY content model.'
def isEmpty(self):
return False
'Returns true iff the named attribute is a DTD-style ID.'
def isId(self, aname):
return False
'Returns true iff the identified attribute is a DTD-style ID.'
def isIdNS(self, namespaceURI, localName):
return False
'This method of XMLParser is deprecated.'
def doctype(self, name, pubid, system):
warnings.warn('This method of XMLParser is deprecated. Define doctype() method on the TreeBuilder target.', DeprecationWarning)
'Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may include the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of \'r\', \'rb\', \'a\', \'ab\', \'w\', or \'wb\', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is \'rb\'. Be aware that only the \'rb\', \'ab\', and \'wb\' values should be used for cross-platform portability. The compresslevel argument is an integer from 0 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. 0 is no compression at all. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat().'
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None):
if mode: mode = mode.replace('U', '') if (mode and ('b' not in mode)): mode += 'b' if (fileobj is None): fileobj = self.myfileobj = __builtin__.open(filename, (mode or 'rb')) if (filename is None): if (hasattr(fileobj, 'name') and (fileobj.name != '<fdopen>')): filename = fileobj.name else: filename = '' if (mode is None): if hasattr(fileobj, 'mode'): mode = fileobj.mode else: mode = 'rb' if (mode[0:1] == 'r'): self.mode = READ self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.name = filename self.min_readsize = 100 elif ((mode[0:1] == 'w') or (mode[0:1] == 'a')): self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, (- zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0) else: raise IOError, (('Mode ' + mode) + ' not supported') self.fileobj = fileobj self.offset = 0 self.mtime = mtime if (self.mode == WRITE): self._write_gzip_header()
'Raises a ValueError if the underlying file object has been closed.'
def _check_closed(self):
if self.closed: raise ValueError('I/O operation on closed file.')
'Invoke the underlying file object\'s fileno() method. This will raise AttributeError if the underlying file object doesn\'t support fileno().'
def fileno(self):
return self.fileobj.fileno()
'Return the uncompressed stream file position indicator to the beginning of the file'
def rewind(self):
if (self.mode != READ): raise IOError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.offset = 0
'Push a token onto the stack popped by the get_token method'
def push_token(self, tok):
if (self.debug >= 1): print ('shlex: pushing token ' + repr(tok)) self.pushback.appendleft(tok)
'Push an input source onto the lexer\'s input source stack.'
def push_source(self, newstream, newfile=None):
if isinstance(newstream, basestring): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if (newfile is not None): print ('shlex: pushing to file %s' % (self.infile,)) else: print ('shlex: pushing to stream %s' % (self.instream,))
'Pop the input source stack.'
def pop_source(self):
self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print ('shlex: popping to %s, line %d' % (self.instream, self.lineno)) self.state = ' '
'Get a token from the input stream (or from stack if it\'s nonempty)'
def get_token(self):
if self.pushback: tok = self.pushback.popleft() if (self.debug >= 1): print ('shlex: popping token ' + repr(tok)) return tok raw = self.read_token() if (self.source is not None): while (raw == self.source): spec = self.sourcehook(self.read_token()) if spec: (newfile, newstream) = spec self.push_source(newstream, newfile) raw = self.get_token() while (raw == self.eof): if (not self.filestack): return self.eof else: self.pop_source() raw = self.get_token() if (self.debug >= 1): if (raw != self.eof): print ('shlex: token=' + repr(raw)) else: print 'shlex: token=EOF' return raw
'Hook called on a filename to be sourced.'
def sourcehook(self, newfile):
if (newfile[0] == '"'): newfile = newfile[1:(-1)] if (isinstance(self.infile, basestring) and (not os.path.isabs(newfile))): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, 'r'))
'Emit a C-compiler-like, Emacs-friendly error-message leader.'
def error_leader(self, infile=None, lineno=None):
if (infile is None): infile = self.infile if (lineno is None): lineno = self.lineno return ('"%s", line %d: ' % (infile, lineno))
'Register a virtual subclass of an ABC.'
def register(cls, subclass):
if (not isinstance(subclass, (type, types.ClassType))): raise TypeError('Can only register classes') if issubclass(subclass, cls): return if issubclass(cls, subclass): raise RuntimeError('Refusing to create an inheritance cycle') cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1
'Debug helper to print the ABC registry.'
def _dump_registry(cls, file=None):
print >>file, ('Class: %s.%s' % (cls.__module__, cls.__name__)) print >>file, ('Inv.counter: %s' % ABCMeta._abc_invalidation_counter) for name in sorted(cls.__dict__.keys()): if name.startswith('_abc_'): value = getattr(cls, name) print >>file, ('%s: %r' % (name, value))
'Override for isinstance(instance, cls).'
def __instancecheck__(cls, instance):
subclass = getattr(instance, '__class__', None) if ((subclass is not None) and (subclass in cls._abc_cache)): return True subtype = type(instance) if (subtype is _InstanceType): subtype = subclass if ((subtype is subclass) or (subclass is None)): if ((cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter) and (subtype in cls._abc_negative_cache)): return False return cls.__subclasscheck__(subtype) return (cls.__subclasscheck__(subclass) or cls.__subclasscheck__(subtype))
'Override for issubclass(subclass, cls).'
def __subclasscheck__(cls, subclass):
if (subclass in cls._abc_cache): return True if (cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter): cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif (subclass in cls._abc_negative_cache): return False ok = cls.__subclasshook__(subclass) if (ok is not NotImplemented): assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok if (cls in getattr(subclass, '__mro__', ())): cls._abc_cache.add(subclass) return True for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True cls._abc_negative_cache.add(subclass) return False
'Return true if the scope uses exec'
def has_exec(self):
return bool((self._table.optimized & (OPT_EXEC | OPT_BARE_EXEC)))
'Return true if the scope uses import *'
def has_import_star(self):
return bool((self._table.optimized & OPT_IMPORT_STAR))
'Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.'
def is_namespace(self):
return bool(self.__namespaces)
'Return a list of namespaces bound to this name'
def get_namespaces(self):
return self.__namespaces
'Returns the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces.'
def get_namespace(self):
if (len(self.__namespaces) != 1): raise ValueError, 'name is bound to multiple namespaces' return self.__namespaces[0]
'Template() returns a fresh pipeline template.'
def __init__(self):
self.debugging = 0 self.reset()
't.__repr__() implements repr(t).'
def __repr__(self):
return ('<Template instance, steps=%r>' % (self.steps,))
't.reset() restores a pipeline template to its initial state.'
def reset(self):
self.steps = []
't.clone() returns a new pipeline template with identical initial state as the current one.'
def clone(self):
t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t
't.debug(flag) turns debugging on or off.'
def debug(self, flag):
self.debugging = flag
't.append(cmd, kind) adds a new step at the end.'
def append(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError, 'Template.append: cmd must be a string' if (kind not in stepkinds): raise ValueError, ('Template.append: bad kind %r' % (kind,)) if (kind == SOURCE): raise ValueError, 'Template.append: SOURCE can only be prepended' if (self.steps and (self.steps[(-1)][1] == SINK)): raise ValueError, 'Template.append: already ends with SINK' if ((kind[0] == 'f') and (not re.search('\\$IN\\b', cmd))): raise ValueError, 'Template.append: missing $IN in cmd' if ((kind[1] == 'f') and (not re.search('\\$OUT\\b', cmd))): raise ValueError, 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
't.prepend(cmd, kind) adds a new step at the front.'
def prepend(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError, 'Template.prepend: cmd must be a string' if (kind not in stepkinds): raise ValueError, ('Template.prepend: bad kind %r' % (kind,)) if (kind == SINK): raise ValueError, 'Template.prepend: SINK can only be appended' if (self.steps and (self.steps[0][1] == SOURCE)): raise ValueError, 'Template.prepend: already begins with SOURCE' if ((kind[0] == 'f') and (not re.search('\\$IN\\b', cmd))): raise ValueError, 'Template.prepend: missing $IN in cmd' if ((kind[1] == 'f') and (not re.search('\\$OUT\\b', cmd))): raise ValueError, 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
't.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.'
def open(self, file, rw):
if (rw == 'r'): return self.open_r(file) if (rw == 'w'): return self.open_w(file) raise ValueError, ("Template.open: rw must be 'r' or 'w', not %r" % (rw,))
't.open_r(file) and t.open_w(file) implement t.open(file, \'r\') and t.open(file, \'w\') respectively.'
def open_r(self, file):
if (not self.steps): return open(file, 'r') if (self.steps[(-1)][1] == SINK): raise ValueError, 'Template.open_r: pipeline ends width SINK' cmd = self.makepipeline(file, '') return os.popen(cmd, 'r')
'Constructor. Arguments: get - a function that gets the attribute value (by name) name - a human-readable name for the original object (suggestion: use repr(object))'
def __init__(self, get, name):
self._get_ = get self._name_ = name
'Return a representation string. This includes the name passed in to the constructor, so that if you print the bastion during debugging, at least you have some idea of what it is.'
def __repr__(self):
return ('<Bastion for %s>' % self._name_)
'Get an as-yet undefined attribute value. This calls the get() function that was passed to the constructor. The result is stored as an instance variable so that the next time the same attribute is requested, __getattr__() won\'t be invoked. If the get() function raises an exception, this is simply passed on -- exceptions are not cached.'
def __getattr__(self, name):
attribute = self._get_(name) self.__dict__[name] = attribute return attribute
'Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown.'
def open(self, host='', port=IMAP4_PORT):
self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.file = self.sock.makefile('rb')
'Read \'size\' bytes from remote.'
def read(self, size):
return self.file.read(size)
'Read line from remote.'
def readline(self):
line = self.file.readline((_MAXLINE + 1)) if (len(line) > _MAXLINE): raise self.error(('got more than %d bytes' % _MAXLINE)) return line
'Send data to remote.'
def send(self, data):
self.sock.sendall(data)
'Close I/O established in "open".'
def shutdown(self):
self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except socket.error as e: if (e.errno != errno.ENOTCONN): raise finally: self.sock.close()
'Return socket instance used to connect to IMAP4 server. socket = <instance>.socket()'
def socket(self):
return self.sock
'Return most recent \'RECENT\' responses if any exist, else prompt server for an update using the \'NOOP\' command. (typ, [data]) = <instance>.recent() \'data\' is None if no new messages, else list of RECENT responses, most recent last.'
def recent(self):
name = 'RECENT' (typ, dat) = self._untagged_response('OK', [None], name) if dat[(-1)]: return (typ, dat) (typ, dat) = self.noop() return self._untagged_response(typ, dat, name)
'Return data for response \'code\' if received, or None. Old value for response \'code\' is cleared. (code, [data]) = <instance>.response(code)'
def response(self, code):
return self._untagged_response(code, [None], code.upper())
'Append message to named mailbox. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message) All args except `message\' can be None.'
def append(self, mailbox, flags, date_time, message):
name = 'APPEND' if (not mailbox): mailbox = 'INBOX' if flags: if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) else: flags = None if date_time: date_time = Time2Internaldate(date_time) else: date_time = None self.literal = MapCRLF.sub(CRLF, message) return self._simple_command(name, mailbox, flags, date_time)
'Authenticate command - requires response processing. \'mechanism\' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. \'authobject\' must be a callable object: data = authobject(response) It will be called to process server continuation responses. It should return data that will be encoded and sent to server. It should return None if the client abort response \'*\' should be sent instead.'
def authenticate(self, mechanism, authobject):
mech = mechanism.upper() self.literal = _Authenticator(authobject).process (typ, dat) = self._simple_command('AUTHENTICATE', mech) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'(typ, [data]) = <instance>.capability() Fetch capabilities list from server.'
def capability(self):
name = 'CAPABILITY' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Checkpoint mailbox on server. (typ, [data]) = <instance>.check()'
def check(self):
return self._simple_command('CHECK')
'Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before \'LOGOUT\'. (typ, [data]) = <instance>.close()'
def close(self):
try: (typ, dat) = self._simple_command('CLOSE') finally: self.state = 'AUTH' return (typ, dat)
'Copy \'message_set\' messages onto end of \'new_mailbox\'. (typ, [data]) = <instance>.copy(message_set, new_mailbox)'
def copy(self, message_set, new_mailbox):
return self._simple_command('COPY', message_set, new_mailbox)
'Create new mailbox. (typ, [data]) = <instance>.create(mailbox)'
def create(self, mailbox):
return self._simple_command('CREATE', mailbox)
'Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox)'
def delete(self, mailbox):
return self._simple_command('DELETE', mailbox)
'Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who)'
def deleteacl(self, mailbox, who):
return self._simple_command('DELETEACL', mailbox, who)
'Permanently remove deleted items from selected mailbox. Generates \'EXPUNGE\' response for each deleted message. (typ, [data]) = <instance>.expunge() \'data\' is list of \'EXPUNGE\'d message numbers in order received.'
def expunge(self):
name = 'EXPUNGE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Fetch (parts of) messages. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts) \'message_parts\' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". \'data\' are tuples of message part envelope and data.'
def fetch(self, message_set, message_parts):
name = 'FETCH' (typ, dat) = self._simple_command(name, message_set, message_parts) return self._untagged_response(typ, dat, name)
'Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox)'
def getacl(self, mailbox):
(typ, dat) = self._simple_command('GETACL', mailbox) return self._untagged_response(typ, dat, 'ACL')
'(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.'
def getannotation(self, mailbox, entry, attribute):
(typ, dat) = self._simple_command('GETANNOTATION', mailbox, entry, attribute) return self._untagged_response(typ, dat, 'ANNOTATION')
'Get the quota root\'s resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = <instance>.getquota(root)'
def getquota(self, root):
(typ, dat) = self._simple_command('GETQUOTA', root) return self._untagged_response(typ, dat, 'QUOTA')
'Get the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)'
def getquotaroot(self, mailbox):
(typ, dat) = self._simple_command('GETQUOTAROOT', mailbox) (typ, quota) = self._untagged_response(typ, dat, 'QUOTA') (typ, quotaroot) = self._untagged_response(typ, dat, 'QUOTAROOT') return (typ, [quotaroot, quota])
'List mailbox names in directory matching pattern. (typ, [data]) = <instance>.list(directory=\'""\', pattern=\'*\') \'data\' is list of LIST responses.'
def list(self, directory='""', pattern='*'):
name = 'LIST' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Identify client using plaintext password. (typ, [data]) = <instance>.login(user, password) NB: \'password\' will be quoted.'
def login(self, user, password):
(typ, dat) = self._simple_command('LOGIN', user, self._quote(password)) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'Force use of CRAM-MD5 authentication. (typ, [data]) = <instance>.login_cram_md5(user, password)'
def login_cram_md5(self, user, password):
(self.user, self.password) = (user, password) return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
'Authobject to use with CRAM-MD5 authentication.'
def _CRAM_MD5_AUTH(self, challenge):
import hmac return ((self.user + ' ') + hmac.HMAC(self.password, challenge).hexdigest())
'Shutdown connection to server. (typ, [data]) = <instance>.logout() Returns server \'BYE\' response.'
def logout(self):
self.state = 'LOGOUT' try: (typ, dat) = self._simple_command('LOGOUT') except: (typ, dat) = ('NO', [('%s: %s' % sys.exc_info()[:2])]) self.shutdown() if ('BYE' in self.untagged_responses): return ('BYE', self.untagged_responses['BYE']) return (typ, dat)
'List \'subscribed\' mailbox names in directory matching pattern. (typ, [data, ...]) = <instance>.lsub(directory=\'""\', pattern=\'*\') \'data\' are tuples of message part envelope and data.'
def lsub(self, directory='""', pattern='*'):
name = 'LSUB' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = <instance>.myrights(mailbox)'
def myrights(self, mailbox):
(typ, dat) = self._simple_command('MYRIGHTS', mailbox) return self._untagged_response(typ, dat, 'MYRIGHTS')
'Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = <instance>.namespace()'
def namespace(self):
name = 'NAMESPACE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Send NOOP command. (typ, [data]) = <instance>.noop()'
def noop(self):
if __debug__: if (self.debug >= 3): self._dump_ur(self.untagged_responses) return self._simple_command('NOOP')
'Fetch truncated part of a message. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length) \'data\' is tuple of message part envelope and data.'
def partial(self, message_num, message_part, start, length):
name = 'PARTIAL' (typ, dat) = self._simple_command(name, message_num, message_part, start, length) return self._untagged_response(typ, dat, 'FETCH')
'Assume authentication as "user". Allows an authorised administrator to proxy into any user\'s mailbox. (typ, [data]) = <instance>.proxyauth(user)'
def proxyauth(self, user):
name = 'PROXYAUTH' return self._simple_command('PROXYAUTH', user)
'Rename old mailbox name to new. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)'
def rename(self, oldmailbox, newmailbox):
return self._simple_command('RENAME', oldmailbox, newmailbox)
'Search mailbox for matching messages. (typ, [data]) = <instance>.search(charset, criterion, ...) \'data\' is space separated list of matching message numbers.'
def search(self, charset, *criteria):
name = 'SEARCH' if charset: (typ, dat) = self._simple_command(name, 'CHARSET', charset, *criteria) else: (typ, dat) = self._simple_command(name, *criteria) return self._untagged_response(typ, dat, name)
'Select a mailbox. Flush all untagged responses. (typ, [data]) = <instance>.select(mailbox=\'INBOX\', readonly=False) \'data\' is count of messages in mailbox (\'EXISTS\' response). Mandated responses are (\'FLAGS\', \'EXISTS\', \'RECENT\', \'UIDVALIDITY\'), so other responses should be obtained via <instance>.response(\'FLAGS\') etc.'
def select(self, mailbox='INBOX', readonly=False):
self.untagged_responses = {} self.is_readonly = readonly if readonly: name = 'EXAMINE' else: name = 'SELECT' (typ, dat) = self._simple_command(name, mailbox) if (typ != 'OK'): self.state = 'AUTH' return (typ, dat) self.state = 'SELECTED' if (('READ-ONLY' in self.untagged_responses) and (not readonly)): if __debug__: if (self.debug >= 1): self._dump_ur(self.untagged_responses) raise self.readonly(('%s is not writable' % mailbox)) return (typ, self.untagged_responses.get('EXISTS', [None]))
'Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what)'
def setacl(self, mailbox, who, what):
return self._simple_command('SETACL', mailbox, who, what)
'(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.'
def setannotation(self, *args):
(typ, dat) = self._simple_command('SETANNOTATION', *args) return self._untagged_response(typ, dat, 'ANNOTATION')
'Set the quota root\'s resource limits. (typ, [data]) = <instance>.setquota(root, limits)'
def setquota(self, root, limits):
(typ, dat) = self._simple_command('SETQUOTA', root, limits) return self._untagged_response(typ, dat, 'QUOTA')
'IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)'
def sort(self, sort_criteria, charset, *search_criteria):
name = 'SORT' if ((sort_criteria[0], sort_criteria[(-1)]) != ('(', ')')): sort_criteria = ('(%s)' % sort_criteria) (typ, dat) = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name)
'Request named status conditions for mailbox. (typ, [data]) = <instance>.status(mailbox, names)'
def status(self, mailbox, names):
name = 'STATUS' (typ, dat) = self._simple_command(name, mailbox, names) return self._untagged_response(typ, dat, name)
'Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags)'
def store(self, message_set, command, flags):
if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) (typ, dat) = self._simple_command('STORE', message_set, command, flags) return self._untagged_response(typ, dat, 'FETCH')
'Subscribe to new mailbox. (typ, [data]) = <instance>.subscribe(mailbox)'
def subscribe(self, mailbox):
return self._simple_command('SUBSCRIBE', mailbox)
'IMAPrev1 extension THREAD command. (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)'
def thread(self, threading_algorithm, charset, *search_criteria):
name = 'THREAD' (typ, dat) = self._simple_command(name, threading_algorithm, charset, *search_criteria) return self._untagged_response(typ, dat, name)
'Execute "command arg ..." with messages identified by UID, rather than message number. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...) Returns response appropriate to \'command\'.'
def uid(self, command, *args):
command = command.upper() if (not (command in Commands)): raise self.error(('Unknown IMAP4 UID command: %s' % command)) if (self.state not in Commands[command]): raise self.error(('command %s illegal in state %s, only allowed in states %s' % (command, self.state, ', '.join(Commands[command])))) name = 'UID' (typ, dat) = self._simple_command(name, command, *args) if (command in ('SEARCH', 'SORT', 'THREAD')): name = command else: name = 'FETCH' return self._untagged_response(typ, dat, name)
'Unsubscribe from old mailbox. (typ, [data]) = <instance>.unsubscribe(mailbox)'
def unsubscribe(self, mailbox):
return self._simple_command('UNSUBSCRIBE', mailbox)
'Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = <instance>.xatom(name, arg, ...) Returns response appropriate to extension command `name\'.'
def xatom(self, name, *args):
name = name.upper() if (not (name in Commands)): Commands[name] = (self.state,) return self._simple_command(name, *args)
'Setup a stream connection. This connection will be used by the routines: read, readline, send, shutdown.'
def open(self, host=None, port=None):
self.host = None self.port = None self.sock = None self.file = None self.process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, close_fds=True) self.writefile = self.process.stdin self.readfile = self.process.stdout
'Read \'size\' bytes from remote.'
def read(self, size):
return self.readfile.read(size)
'Read line from remote.'
def readline(self):
return self.readfile.readline()
'Send data to remote.'
def send(self, data):
self.writefile.write(data) self.writefile.flush()
'Close I/O established in "open".'
def shutdown(self):
self.readfile.close() self.writefile.close() self.process.wait()
'Override server_bind to store the server name.'
def server_bind(self):
SocketServer.TCPServer.server_bind(self) (host, port) = self.socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port
'Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.'
def parse_request(self):
self.command = None self.request_version = version = self.default_request_version self.close_connection = 1 requestline = self.raw_requestline requestline = requestline.rstrip('\r\n') self.requestline = requestline words = requestline.split() if (len(words) == 3): (command, path, version) = words if (version[:5] != 'HTTP/'): self.send_error(400, ('Bad request version (%r)' % version)) return False try: base_version_number = version.split('/', 1)[1] version_number = base_version_number.split('.') if (len(version_number) != 2): raise ValueError version_number = (int(version_number[0]), int(version_number[1])) except (ValueError, IndexError): self.send_error(400, ('Bad request version (%r)' % version)) return False if ((version_number >= (1, 1)) and (self.protocol_version >= 'HTTP/1.1')): self.close_connection = 0 if (version_number >= (2, 0)): self.send_error(505, ('Invalid HTTP Version (%s)' % base_version_number)) return False elif (len(words) == 2): (command, path) = words self.close_connection = 1 if (command != 'GET'): self.send_error(400, ('Bad HTTP/0.9 request type (%r)' % command)) return False elif (not words): return False else: self.send_error(400, ('Bad request syntax (%r)' % requestline)) return False (self.command, self.path, self.request_version) = (command, path, version) self.headers = self.MessageClass(self.rfile, 0) conntype = self.headers.get('Connection', '') if (conntype.lower() == 'close'): self.close_connection = 1 elif ((conntype.lower() == 'keep-alive') and (self.protocol_version >= 'HTTP/1.1')): self.close_connection = 0 return True
'Handle a single HTTP request. You normally don\'t need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.'
def handle_one_request(self):
try: self.raw_requestline = self.rfile.readline(65537) if (len(self.raw_requestline) > 65536): self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) return if (not self.raw_requestline): self.close_connection = 1 return if (not self.parse_request()): return mname = ('do_' + self.command) if (not hasattr(self, mname)): self.send_error(501, ('Unsupported method (%r)' % self.command)) return method = getattr(self, mname) method() self.wfile.flush() except socket.timeout as e: self.log_error('Request timed out: %r', e) self.close_connection = 1 return
'Handle multiple requests if necessary.'
def handle(self):
self.close_connection = 1 self.handle_one_request() while (not self.close_connection): self.handle_one_request()
'Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.'
def send_error(self, code, message=None):
try: (short, long) = self.responses[code] except KeyError: (short, long) = ('???', '???') if (message is None): message = short explain = long self.log_error('code %d, message %s', code, message) self.send_response(code, message) self.send_header('Connection', 'close') content = None if ((code >= 200) and (code not in (204, 205, 304))): content = (self.error_message_format % {'code': code, 'message': _quote_html(message), 'explain': explain}) self.send_header('Content-Type', self.error_content_type) self.end_headers() if ((self.command != 'HEAD') and content): self.wfile.write(content)
'Send the response header and log the response code. Also send two standard headers with the server software version and the current date.'
def send_response(self, code, message=None):
self.log_request(code) if (message is None): if (code in self.responses): message = self.responses[code][0] else: message = '' if (self.request_version != 'HTTP/0.9'): self.wfile.write(('%s %d %s\r\n' % (self.protocol_version, code, message))) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
'Send a MIME header.'
def send_header(self, keyword, value):
if (self.request_version != 'HTTP/0.9'): self.wfile.write(('%s: %s\r\n' % (keyword, value))) if (keyword.lower() == 'connection'): if (value.lower() == 'close'): self.close_connection = 1 elif (value.lower() == 'keep-alive'): self.close_connection = 0
'Send the blank line ending the MIME headers.'
def end_headers(self):
if (self.request_version != 'HTTP/0.9'): self.wfile.write('\r\n')
'Log an accepted request. This is called by send_response().'
def log_request(self, code='-', size='-'):
self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
'Log an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). Arguments are the same as for log_message(). XXX This should go to the separate error log.'
def log_error(self, format, *args):
self.log_message(format, *args)
'Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it\'s just like printf!). The client ip address and current date/time are prefixed to every message.'
def log_message(self, format, *args):
sys.stderr.write(('%s - - [%s] %s\n' % (self.client_address[0], self.log_date_time_string(), (format % args))))