home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / IMAPLIB.PY < prev    next >
Encoding:
Text File  |  2000-09-28  |  28.9 KB  |  1,120 lines

  1.  
  2. """IMAP4 client.
  3.  
  4. Based on RFC 2060.
  5.  
  6. Public class:        IMAP4
  7. Public variable:    Debug
  8. Public functions:    Internaldate2tuple
  9.             Int2AP
  10.             ParseFlags
  11.             Time2Internaldate
  12. """
  13.  
  14. # Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
  15. # Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
  16.  
  17. __version__ = "2.39"
  18.  
  19. import binascii, re, socket, string, time, random, sys
  20.  
  21. #    Globals
  22.  
  23. CRLF = '\r\n'
  24. Debug = 0
  25. IMAP4_PORT = 143
  26. AllowedVersions = ('IMAP4REV1', 'IMAP4')    # Most recent first
  27.  
  28. #    Commands
  29.  
  30. Commands = {
  31.     # name          valid states
  32.     'APPEND':    ('AUTH', 'SELECTED'),
  33.     'AUTHENTICATE':    ('NONAUTH',),
  34.     'CAPABILITY':    ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  35.     'CHECK':    ('SELECTED',),
  36.     'CLOSE':    ('SELECTED',),
  37.     'COPY':        ('SELECTED',),
  38.     'CREATE':    ('AUTH', 'SELECTED'),
  39.     'DELETE':    ('AUTH', 'SELECTED'),
  40.     'EXAMINE':    ('AUTH', 'SELECTED'),
  41.     'EXPUNGE':    ('SELECTED',),
  42.     'FETCH':    ('SELECTED',),
  43.     'LIST':        ('AUTH', 'SELECTED'),
  44.     'LOGIN':    ('NONAUTH',),
  45.     'LOGOUT':    ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  46.     'LSUB':        ('AUTH', 'SELECTED'),
  47.     'NOOP':        ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  48.     'PARTIAL':    ('SELECTED',),
  49.     'RENAME':    ('AUTH', 'SELECTED'),
  50.     'SEARCH':    ('SELECTED',),
  51.     'SELECT':    ('AUTH', 'SELECTED'),
  52.     'STATUS':    ('AUTH', 'SELECTED'),
  53.     'STORE':    ('SELECTED',),
  54.     'SUBSCRIBE':    ('AUTH', 'SELECTED'),
  55.     'UID':        ('SELECTED',),
  56.     'UNSUBSCRIBE':    ('AUTH', 'SELECTED'),
  57.     }
  58.  
  59. #    Patterns to match server responses
  60.  
  61. Continuation = re.compile(r'\+( (?P<data>.*))?')
  62. Flags = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
  63. InternalDate = re.compile(r'.*INTERNALDATE "'
  64.     r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
  65.     r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
  66.     r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
  67.     r'"')
  68. Literal = re.compile(r'.*{(?P<size>\d+)}$')
  69. Response_code = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
  70. Untagged_response = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  71. Untagged_status = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
  72.  
  73.  
  74.  
  75. class IMAP4:
  76.  
  77.     """IMAP4 client class.
  78.  
  79.     Instantiate with: IMAP4([host[, port]])
  80.  
  81.         host - host's name (default: localhost);
  82.         port - port number (default: standard IMAP4 port).
  83.  
  84.     All IMAP4rev1 commands are supported by methods of the same
  85.     name (in lower-case).
  86.  
  87.     All arguments to commands are converted to strings, except for
  88.     AUTHENTICATE, and the last argument to APPEND which is passed as
  89.     an IMAP4 literal.  If necessary (the string contains any
  90.     non-printing characters or white-space and isn't enclosed with
  91.     either parentheses or double quotes) each string is quoted.
  92.     However, the 'password' argument to the LOGIN command is always
  93.     quoted.  If you want to avoid having an argument string quoted
  94.     (eg: the 'flags' argument to STORE) then enclose the string in
  95.     parentheses (eg: "(\Deleted)").
  96.  
  97.     Each command returns a tuple: (type, [data, ...]) where 'type'
  98.     is usually 'OK' or 'NO', and 'data' is either the text from the
  99.     tagged response, or untagged results from command.
  100.  
  101.     Errors raise the exception class <instance>.error("<reason>").
  102.     IMAP4 server errors raise <instance>.abort("<reason>"),
  103.     which is a sub-class of 'error'. Mailbox status changes
  104.     from READ-WRITE to READ-ONLY raise the exception class
  105.     <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
  106.  
  107.     "error" exceptions imply a program error.
  108.     "abort" exceptions imply the connection should be reset, and
  109.         the command re-tried.
  110.     "readonly" exceptions imply the command should be re-tried.
  111.  
  112.     Note: to use this module, you must read the RFCs pertaining
  113.     to the IMAP4 protocol, as the semantics of the arguments to
  114.     each IMAP4 command are left to the invoker, not to mention
  115.     the results.
  116.     """
  117.  
  118.     class error(Exception): pass    # Logical errors - debug required
  119.     class abort(error): pass    # Service errors - close and retry
  120.     class readonly(abort): pass    # Mailbox status changed to READ-ONLY
  121.  
  122.     mustquote = re.compile(r"[^\w!#$%&'*+,.:;<=>?^`|~-]")
  123.  
  124.     def __init__(self, host = '', port = IMAP4_PORT):
  125.         self.host = host
  126.         self.port = port
  127.         self.debug = Debug
  128.         self.state = 'LOGOUT'
  129.         self.literal = None        # A literal argument to a command
  130.         self.tagged_commands = {}    # Tagged commands awaiting response
  131.         self.untagged_responses = {}    # {typ: [data, ...], ...}
  132.         self.continuation_response = ''    # Last continuation response
  133.         self.is_readonly = None        # READ-ONLY desired state
  134.         self.tagnum = 0
  135.  
  136.         # Open socket to server.
  137.  
  138.         self.open(host, port)
  139.  
  140.         # Create unique tag for this session,
  141.         # and compile tagged response matcher.
  142.  
  143.         self.tagpre = Int2AP(random.randint(0, 31999))
  144.         self.tagre = re.compile(r'(?P<tag>'
  145.                 + self.tagpre
  146.                 + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  147.  
  148.         # Get server welcome message,
  149.         # request and store CAPABILITY response.
  150.  
  151.         if __debug__:
  152.             if self.debug >= 1:
  153.                 _mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  154.  
  155.         self.welcome = self._get_response()
  156.         if self.untagged_responses.has_key('PREAUTH'):
  157.             self.state = 'AUTH'
  158.         elif self.untagged_responses.has_key('OK'):
  159.             self.state = 'NONAUTH'
  160.         else:
  161.             raise self.error(self.welcome)
  162.  
  163.         cap = 'CAPABILITY'
  164.         self._simple_command(cap)
  165.         if not self.untagged_responses.has_key(cap):
  166.             raise self.error('no CAPABILITY response from server')
  167.         self.capabilities = tuple(string.split(string.upper(self.untagged_responses[cap][-1])))
  168.  
  169.         if __debug__:
  170.             if self.debug >= 3:
  171.                 _mesg('CAPABILITIES: %s' % `self.capabilities`)
  172.  
  173.         for version in AllowedVersions:
  174.             if not version in self.capabilities:
  175.                 continue
  176.             self.PROTOCOL_VERSION = version
  177.             return
  178.  
  179.         raise self.error('server not IMAP4 compliant')
  180.  
  181.  
  182.     def __getattr__(self, attr):
  183.         #    Allow UPPERCASE variants of IMAP4 command methods.
  184.         if Commands.has_key(attr):
  185.             return eval("self.%s" % string.lower(attr))
  186.         raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  187.  
  188.  
  189.  
  190.     #    Public methods
  191.  
  192.  
  193.     def open(self, host, port):
  194.         """Setup 'self.sock' and 'self.file'."""
  195.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  196.         self.sock.connect((self.host, self.port))
  197.         self.file = self.sock.makefile('r')
  198.  
  199.  
  200.     def recent(self):
  201.         """Return most recent 'RECENT' responses if any exist,
  202.         else prompt server for an update using the 'NOOP' command.
  203.  
  204.         (typ, [data]) = <instance>.recent()
  205.  
  206.         'data' is None if no new messages,
  207.         else list of RECENT responses, most recent last.
  208.         """
  209.         name = 'RECENT'
  210.         typ, dat = self._untagged_response('OK', [None], name)
  211.         if dat[-1]:
  212.             return typ, dat
  213.         typ, dat = self.noop()    # Prod server for response
  214.         return self._untagged_response(typ, dat, name)
  215.  
  216.  
  217.     def response(self, code):
  218.         """Return data for response 'code' if received, or None.
  219.  
  220.         Old value for response 'code' is cleared.
  221.  
  222.         (code, [data]) = <instance>.response(code)
  223.         """
  224.         return self._untagged_response(code, [None], string.upper(code))
  225.  
  226.  
  227.     def socket(self):
  228.         """Return socket instance used to connect to IMAP4 server.
  229.  
  230.         socket = <instance>.socket()
  231.         """
  232.         return self.sock
  233.  
  234.  
  235.  
  236.     #    IMAP4 commands
  237.  
  238.  
  239.     def append(self, mailbox, flags, date_time, message):
  240.         """Append message to named mailbox.
  241.  
  242.         (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  243.  
  244.             All args except `message' can be None.
  245.         """
  246.         name = 'APPEND'
  247.         if not mailbox:
  248.             mailbox = 'INBOX'
  249.         if flags:
  250.             if (flags[0],flags[-1]) != ('(',')'):
  251.                 flags = '(%s)' % flags
  252.         else:
  253.             flags = None
  254.         if date_time:
  255.             date_time = Time2Internaldate(date_time)
  256.         else:
  257.             date_time = None
  258.         self.literal = message
  259.         return self._simple_command(name, mailbox, flags, date_time)
  260.  
  261.  
  262.     def authenticate(self, mechanism, authobject):
  263.         """Authenticate command - requires response processing.
  264.  
  265.         'mechanism' specifies which authentication mechanism is to
  266.         be used - it must appear in <instance>.capabilities in the
  267.         form AUTH=<mechanism>.
  268.  
  269.         'authobject' must be a callable object:
  270.  
  271.             data = authobject(response)
  272.  
  273.         It will be called to process server continuation responses.
  274.         It should return data that will be encoded and sent to server.
  275.         It should return None if the client abort response '*' should
  276.         be sent instead.
  277.         """
  278.         mech = string.upper(mechanism)
  279.         cap = 'AUTH=%s' % mech
  280.         if not cap in self.capabilities:
  281.             raise self.error("Server doesn't allow %s authentication." % mech)
  282.         self.literal = _Authenticator(authobject).process
  283.         typ, dat = self._simple_command('AUTHENTICATE', mech)
  284.         if typ != 'OK':
  285.             raise self.error(dat[-1])
  286.         self.state = 'AUTH'
  287.         return typ, dat
  288.  
  289.  
  290.     def check(self):
  291.         """Checkpoint mailbox on server.
  292.  
  293.         (typ, [data]) = <instance>.check()
  294.         """
  295.         return self._simple_command('CHECK')
  296.  
  297.  
  298.     def close(self):
  299.         """Close currently selected mailbox.
  300.  
  301.         Deleted messages are removed from writable mailbox.
  302.         This is the recommended command before 'LOGOUT'.
  303.  
  304.         (typ, [data]) = <instance>.close()
  305.         """
  306.         try:
  307.             typ, dat = self._simple_command('CLOSE')
  308.         finally:
  309.             self.state = 'AUTH'
  310.         return typ, dat
  311.  
  312.  
  313.     def copy(self, message_set, new_mailbox):
  314.         """Copy 'message_set' messages onto end of 'new_mailbox'.
  315.  
  316.         (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  317.         """
  318.         return self._simple_command('COPY', message_set, new_mailbox)
  319.  
  320.  
  321.     def create(self, mailbox):
  322.         """Create new mailbox.
  323.  
  324.         (typ, [data]) = <instance>.create(mailbox)
  325.         """
  326.         return self._simple_command('CREATE', mailbox)
  327.  
  328.  
  329.     def delete(self, mailbox):
  330.         """Delete old mailbox.
  331.  
  332.         (typ, [data]) = <instance>.delete(mailbox)
  333.         """
  334.         return self._simple_command('DELETE', mailbox)
  335.  
  336.  
  337.     def expunge(self):
  338.         """Permanently remove deleted items from selected mailbox.
  339.  
  340.         Generates 'EXPUNGE' response for each deleted message.
  341.  
  342.         (typ, [data]) = <instance>.expunge()
  343.  
  344.         'data' is list of 'EXPUNGE'd message numbers in order received.
  345.         """
  346.         name = 'EXPUNGE'
  347.         typ, dat = self._simple_command(name)
  348.         return self._untagged_response(typ, dat, name)
  349.  
  350.  
  351.     def fetch(self, message_set, message_parts):
  352.         """Fetch (parts of) messages.
  353.  
  354.         (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  355.  
  356.         'message_parts' should be a string of selected parts
  357.         enclosed in parentheses, eg: "(UID BODY[TEXT])".
  358.  
  359.         'data' are tuples of message part envelope and data.
  360.         """
  361.         name = 'FETCH'
  362.         typ, dat = self._simple_command(name, message_set, message_parts)
  363.         return self._untagged_response(typ, dat, name)
  364.  
  365.  
  366.     def list(self, directory='""', pattern='*'):
  367.         """List mailbox names in directory matching pattern.
  368.  
  369.         (typ, [data]) = <instance>.list(directory='""', pattern='*')
  370.  
  371.         'data' is list of LIST responses.
  372.         """
  373.         name = 'LIST'
  374.         typ, dat = self._simple_command(name, directory, pattern)
  375.         return self._untagged_response(typ, dat, name)
  376.  
  377.  
  378.     def login(self, user, password):
  379.         """Identify client using plaintext password.
  380.  
  381.         (typ, [data]) = <instance>.login(user, password)
  382.  
  383.         NB: 'password' will be quoted.
  384.         """
  385.         #if not 'AUTH=LOGIN' in self.capabilities:
  386.         #    raise self.error("Server doesn't allow LOGIN authentication." % mech)
  387.         typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  388.         if typ != 'OK':
  389.             raise self.error(dat[-1])
  390.         self.state = 'AUTH'
  391.         return typ, dat
  392.  
  393.  
  394.     def logout(self):
  395.         """Shutdown connection to server.
  396.  
  397.         (typ, [data]) = <instance>.logout()
  398.  
  399.         Returns server 'BYE' response.
  400.         """
  401.         self.state = 'LOGOUT'
  402.         try: typ, dat = self._simple_command('LOGOUT')
  403.         except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
  404.         self.file.close()
  405.         self.sock.close()
  406.         if self.untagged_responses.has_key('BYE'):
  407.             return 'BYE', self.untagged_responses['BYE']
  408.         return typ, dat
  409.  
  410.  
  411.     def lsub(self, directory='""', pattern='*'):
  412.         """List 'subscribed' mailbox names in directory matching pattern.
  413.  
  414.         (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
  415.  
  416.         'data' are tuples of message part envelope and data.
  417.         """
  418.         name = 'LSUB'
  419.         typ, dat = self._simple_command(name, directory, pattern)
  420.         return self._untagged_response(typ, dat, name)
  421.  
  422.  
  423.     def noop(self):
  424.         """Send NOOP command.
  425.  
  426.         (typ, data) = <instance>.noop()
  427.         """
  428.         if __debug__:
  429.             if self.debug >= 3:
  430.                 _dump_ur(self.untagged_responses)
  431.         return self._simple_command('NOOP')
  432.  
  433.  
  434.     def partial(self, message_num, message_part, start, length):
  435.         """Fetch truncated part of a message.
  436.  
  437.         (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  438.  
  439.         'data' is tuple of message part envelope and data.
  440.         """
  441.         name = 'PARTIAL'
  442.         typ, dat = self._simple_command(name, message_num, message_part, start, length)
  443.         return self._untagged_response(typ, dat, 'FETCH')
  444.  
  445.  
  446.     def rename(self, oldmailbox, newmailbox):
  447.         """Rename old mailbox name to new.
  448.  
  449.         (typ, data) = <instance>.rename(oldmailbox, newmailbox)
  450.         """
  451.         return self._simple_command('RENAME', oldmailbox, newmailbox)
  452.  
  453.  
  454.     def search(self, charset, *criteria):
  455.         """Search mailbox for matching messages.
  456.  
  457.         (typ, [data]) = <instance>.search(charset, criterium, ...)
  458.  
  459.         'data' is space separated list of matching message numbers.
  460.         """
  461.         name = 'SEARCH'
  462.         if charset:
  463.             charset = 'CHARSET ' + charset
  464.         typ, dat = apply(self._simple_command, (name, charset) + criteria)
  465.         return self._untagged_response(typ, dat, name)
  466.  
  467.  
  468.     def select(self, mailbox='INBOX', readonly=None):
  469.         """Select a mailbox.
  470.  
  471.         Flush all untagged responses.
  472.  
  473.         (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=None)
  474.  
  475.         'data' is count of messages in mailbox ('EXISTS' response).
  476.         """
  477.         # Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY')
  478.         self.untagged_responses = {}    # Flush old responses.
  479.         self.is_readonly = readonly
  480.         if readonly:
  481.             name = 'EXAMINE'
  482.         else:
  483.             name = 'SELECT'
  484.         typ, dat = self._simple_command(name, mailbox)
  485.         if typ != 'OK':
  486.             self.state = 'AUTH'    # Might have been 'SELECTED'
  487.             return typ, dat
  488.         self.state = 'SELECTED'
  489.         if self.untagged_responses.has_key('READ-ONLY') \
  490.             and not readonly:
  491.             if __debug__:
  492.                 if self.debug >= 1:
  493.                     _dump_ur(self.untagged_responses)
  494.             raise self.readonly('%s is not writable' % mailbox)
  495.         return typ, self.untagged_responses.get('EXISTS', [None])
  496.  
  497.  
  498.     def status(self, mailbox, names):
  499.         """Request named status conditions for mailbox.
  500.  
  501.         (typ, [data]) = <instance>.status(mailbox, names)
  502.         """
  503.         name = 'STATUS'
  504.         if self.PROTOCOL_VERSION == 'IMAP4':
  505.             raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
  506.         typ, dat = self._simple_command(name, mailbox, names)
  507.         return self._untagged_response(typ, dat, name)
  508.  
  509.  
  510.     def store(self, message_set, command, flags):
  511.         """Alters flag dispositions for messages in mailbox.
  512.  
  513.         (typ, [data]) = <instance>.store(message_set, command, flags)
  514.         """
  515.         if (flags[0],flags[-1]) != ('(',')'):
  516.             flags = '(%s)' % flags    # Avoid quoting the flags
  517.         typ, dat = self._simple_command('STORE', message_set, command, flags)
  518.         return self._untagged_response(typ, dat, 'FETCH')
  519.  
  520.  
  521.     def subscribe(self, mailbox):
  522.         """Subscribe to new mailbox.
  523.  
  524.         (typ, [data]) = <instance>.subscribe(mailbox)
  525.         """
  526.         return self._simple_command('SUBSCRIBE', mailbox)
  527.  
  528.  
  529.     def uid(self, command, *args):
  530.         """Execute "command arg ..." with messages identified by UID,
  531.             rather than message number.
  532.  
  533.         (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  534.  
  535.         Returns response appropriate to 'command'.
  536.         """
  537.         command = string.upper(command)
  538.         if not Commands.has_key(command):
  539.             raise self.error("Unknown IMAP4 UID command: %s" % command)
  540.         if self.state not in Commands[command]:
  541.             raise self.error('command %s illegal in state %s'
  542.                         % (command, self.state))
  543.         name = 'UID'
  544.         typ, dat = apply(self._simple_command, (name, command) + args)
  545.         if command == 'SEARCH':
  546.             name = 'SEARCH'
  547.         else:
  548.             name = 'FETCH'
  549.         return self._untagged_response(typ, dat, name)
  550.  
  551.  
  552.     def unsubscribe(self, mailbox):
  553.         """Unsubscribe from old mailbox.
  554.  
  555.         (typ, [data]) = <instance>.unsubscribe(mailbox)
  556.         """
  557.         return self._simple_command('UNSUBSCRIBE', mailbox)
  558.  
  559.  
  560.     def xatom(self, name, *args):
  561.         """Allow simple extension commands
  562.             notified by server in CAPABILITY response.
  563.  
  564.         (typ, [data]) = <instance>.xatom(name, arg, ...)
  565.         """
  566.         if name[0] != 'X' or not name in self.capabilities:
  567.             raise self.error('unknown extension command: %s' % name)
  568.         return apply(self._simple_command, (name,) + args)
  569.  
  570.  
  571.  
  572.     #    Private methods
  573.  
  574.  
  575.     def _append_untagged(self, typ, dat):
  576.  
  577.         if dat is None: dat = ''
  578.         ur = self.untagged_responses
  579.         if __debug__:
  580.             if self.debug >= 5:
  581.                 _mesg('untagged_responses[%s] %s += ["%s"]' %
  582.                     (typ, len(ur.get(typ,'')), dat))
  583.         if ur.has_key(typ):
  584.             ur[typ].append(dat)
  585.         else:
  586.             ur[typ] = [dat]
  587.  
  588.  
  589.     def _check_bye(self):
  590.         bye = self.untagged_responses.get('BYE')
  591.         if bye:
  592.             raise self.abort(bye[-1])
  593.  
  594.  
  595.     def _command(self, name, *args):
  596.  
  597.         if self.state not in Commands[name]:
  598.             self.literal = None
  599.             raise self.error(
  600.             'command %s illegal in state %s' % (name, self.state))
  601.  
  602.         for typ in ('OK', 'NO', 'BAD'):
  603.             if self.untagged_responses.has_key(typ):
  604.                 del self.untagged_responses[typ]
  605.  
  606.         if self.untagged_responses.has_key('READ-ONLY') \
  607.         and not self.is_readonly:
  608.             raise self.readonly('mailbox status changed to READ-ONLY')
  609.  
  610.         tag = self._new_tag()
  611.         data = '%s %s' % (tag, name)
  612.         for arg in args:
  613.             if arg is None: continue
  614.             data = '%s %s' % (data, self._checkquote(arg))
  615.  
  616.         literal = self.literal
  617.         if literal is not None:
  618.             self.literal = None
  619.             if type(literal) is type(self._command):
  620.                 literator = literal
  621.             else:
  622.                 literator = None
  623.                 data = '%s {%s}' % (data, len(literal))
  624.  
  625.         if __debug__:
  626.             if self.debug >= 4:
  627.                 _mesg('> %s' % data)
  628.             else:
  629.                 _log('> %s' % data)
  630.  
  631.         try:
  632.             self.sock.send('%s%s' % (data, CRLF))
  633.         except socket.error, val:
  634.             raise self.abort('socket error: %s' % val)
  635.  
  636.         if literal is None:
  637.             return tag
  638.  
  639.         while 1:
  640.             # Wait for continuation response
  641.  
  642.             while self._get_response():
  643.                 if self.tagged_commands[tag]:    # BAD/NO?
  644.                     return tag
  645.  
  646.             # Send literal
  647.  
  648.             if literator:
  649.                 literal = literator(self.continuation_response)
  650.  
  651.             if __debug__:
  652.                 if self.debug >= 4:
  653.                     _mesg('write literal size %s' % len(literal))
  654.  
  655.             try:
  656.                 self.sock.send(literal)
  657.                 self.sock.send(CRLF)
  658.             except socket.error, val:
  659.                 raise self.abort('socket error: %s' % val)
  660.  
  661.             if not literator:
  662.                 break
  663.  
  664.         return tag
  665.  
  666.  
  667.     def _command_complete(self, name, tag):
  668.         self._check_bye()
  669.         try:
  670.             typ, data = self._get_tagged_response(tag)
  671.         except self.abort, val:
  672.             raise self.abort('command: %s => %s' % (name, val))
  673.         except self.error, val:
  674.             raise self.error('command: %s => %s' % (name, val))
  675.         self._check_bye()
  676.         if typ == 'BAD':
  677.             raise self.error('%s command error: %s %s' % (name, typ, data))
  678.         return typ, data
  679.  
  680.  
  681.     def _get_response(self):
  682.  
  683.         # Read response and store.
  684.         #
  685.         # Returns None for continuation responses,
  686.         # otherwise first response line received.
  687.  
  688.         resp = self._get_line()
  689.  
  690.         # Command completion response?
  691.  
  692.         if self._match(self.tagre, resp):
  693.             tag = self.mo.group('tag')
  694.             if not self.tagged_commands.has_key(tag):
  695.                 raise self.abort('unexpected tagged response: %s' % resp)
  696.  
  697.             typ = self.mo.group('type')
  698.             dat = self.mo.group('data')
  699.             self.tagged_commands[tag] = (typ, [dat])
  700.         else:
  701.             dat2 = None
  702.  
  703.             # '*' (untagged) responses?
  704.  
  705.             if not self._match(Untagged_response, resp):
  706.                 if self._match(Untagged_status, resp):
  707.                     dat2 = self.mo.group('data2')
  708.  
  709.             if self.mo is None:
  710.                 # Only other possibility is '+' (continuation) response...
  711.  
  712.                 if self._match(Continuation, resp):
  713.                     self.continuation_response = self.mo.group('data')
  714.                     return None    # NB: indicates continuation
  715.  
  716.                 raise self.abort("unexpected response: '%s'" % resp)
  717.  
  718.             typ = self.mo.group('type')
  719.             dat = self.mo.group('data')
  720.             if dat is None: dat = ''    # Null untagged response
  721.             if dat2: dat = dat + ' ' + dat2
  722.  
  723.             # Is there a literal to come?
  724.  
  725.             while self._match(Literal, dat):
  726.  
  727.                 # Read literal direct from connection.
  728.  
  729.                 size = string.atoi(self.mo.group('size'))
  730.                 if __debug__:
  731.                     if self.debug >= 4:
  732.                         _mesg('read literal size %s' % size)
  733.                 data = self.file.read(size)
  734.  
  735.                 # Store response with literal as tuple
  736.  
  737.                 self._append_untagged(typ, (dat, data))
  738.  
  739.                 # Read trailer - possibly containing another literal
  740.  
  741.                 dat = self._get_line()
  742.  
  743.             self._append_untagged(typ, dat)
  744.  
  745.         # Bracketed response information?
  746.  
  747.         if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  748.             self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  749.  
  750.         if __debug__:
  751.             if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  752.                 _mesg('%s response: %s' % (typ, dat))
  753.  
  754.         return resp
  755.  
  756.  
  757.     def _get_tagged_response(self, tag):
  758.  
  759.         while 1:
  760.             result = self.tagged_commands[tag]
  761.             if result is not None:
  762.                 del self.tagged_commands[tag]
  763.                 return result
  764.  
  765.             # Some have reported "unexpected response" exceptions.
  766.             # Note that ignoring them here causes loops.
  767.             # Instead, send me details of the unexpected response and
  768.             # I'll update the code in `_get_response()'.
  769.  
  770.             try:
  771.                 self._get_response()
  772.             except self.abort, val:
  773.                 if __debug__:
  774.                     if self.debug >= 1:
  775.                         print_log()
  776.                 raise
  777.  
  778.  
  779.     def _get_line(self):
  780.  
  781.         line = self.file.readline()
  782.         if not line:
  783.             raise self.abort('socket error: EOF')
  784.  
  785.         # Protocol mandates all lines terminated by CRLF
  786.  
  787.         line = line[:-2]
  788.         if __debug__:
  789.             if self.debug >= 4:
  790.                 _mesg('< %s' % line)
  791.             else:
  792.                 _log('< %s' % line)
  793.         return line
  794.  
  795.  
  796.     def _match(self, cre, s):
  797.  
  798.         # Run compiled regular expression match method on 's'.
  799.         # Save result, return success.
  800.  
  801.         self.mo = cre.match(s)
  802.         if __debug__:
  803.             if self.mo is not None and self.debug >= 5:
  804.                 _mesg("\tmatched r'%s' => %s" % (cre.pattern, `self.mo.groups()`))
  805.         return self.mo is not None
  806.  
  807.  
  808.     def _new_tag(self):
  809.  
  810.         tag = '%s%s' % (self.tagpre, self.tagnum)
  811.         self.tagnum = self.tagnum + 1
  812.         self.tagged_commands[tag] = None
  813.         return tag
  814.  
  815.  
  816.     def _checkquote(self, arg):
  817.  
  818.         # Must quote command args if non-alphanumeric chars present,
  819.         # and not already quoted.
  820.  
  821.         if type(arg) is not type(''):
  822.             return arg
  823.         if (arg[0],arg[-1]) in (('(',')'),('"','"')):
  824.             return arg
  825.         if self.mustquote.search(arg) is None:
  826.             return arg
  827.         return self._quote(arg)
  828.  
  829.  
  830.     def _quote(self, arg):
  831.  
  832.         arg = string.replace(arg, '\\', '\\\\')
  833.         arg = string.replace(arg, '"', '\\"')
  834.  
  835.         return '"%s"' % arg
  836.  
  837.  
  838.     def _simple_command(self, name, *args):
  839.  
  840.         return self._command_complete(name, apply(self._command, (name,) + args))
  841.  
  842.  
  843.     def _untagged_response(self, typ, dat, name):
  844.  
  845.         if typ == 'NO':
  846.             return typ, dat
  847.         if not self.untagged_responses.has_key(name):
  848.             return typ, [None]
  849.         data = self.untagged_responses[name]
  850.         if __debug__:
  851.             if self.debug >= 5:
  852.                 _mesg('untagged_responses[%s] => %s' % (name, data))
  853.         del self.untagged_responses[name]
  854.         return typ, data
  855.  
  856.  
  857.  
  858. class _Authenticator:
  859.  
  860.     """Private class to provide en/decoding
  861.         for base64-based authentication conversation.
  862.     """
  863.  
  864.     def __init__(self, mechinst):
  865.         self.mech = mechinst    # Callable object to provide/process data
  866.  
  867.     def process(self, data):
  868.         ret = self.mech(self.decode(data))
  869.         if ret is None:
  870.             return '*'    # Abort conversation
  871.         return self.encode(ret)
  872.  
  873.     def encode(self, inp):
  874.         #
  875.         #  Invoke binascii.b2a_base64 iteratively with
  876.         #  short even length buffers, strip the trailing
  877.         #  line feed from the result and append.  "Even"
  878.         #  means a number that factors to both 6 and 8,
  879.         #  so when it gets to the end of the 8-bit input
  880.         #  there's no partial 6-bit output.
  881.         #
  882.         oup = ''
  883.         while inp:
  884.             if len(inp) > 48:
  885.                 t = inp[:48]
  886.                 inp = inp[48:]
  887.             else:
  888.                 t = inp
  889.                 inp = ''
  890.             e = binascii.b2a_base64(t)
  891.             if e:
  892.                 oup = oup + e[:-1]
  893.         return oup
  894.   
  895.     def decode(self, inp):
  896.         if not inp:
  897.             return ''
  898.         return binascii.a2b_base64(inp)
  899.  
  900.  
  901.  
  902. Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
  903.     'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
  904.  
  905. def Internaldate2tuple(resp):
  906.  
  907.     """Convert IMAP4 INTERNALDATE to UT.
  908.  
  909.     Returns Python time module tuple.
  910.     """
  911.  
  912.     mo = InternalDate.match(resp)
  913.     if not mo:
  914.         return None
  915.  
  916.     mon = Mon2num[mo.group('mon')]
  917.     zonen = mo.group('zonen')
  918.  
  919.     for name in ('day', 'year', 'hour', 'min', 'sec', 'zoneh', 'zonem'):
  920.         exec "%s = string.atoi(mo.group('%s'))" % (name, name)
  921.  
  922.     # INTERNALDATE timezone must be subtracted to get UT
  923.  
  924.     zone = (zoneh*60 + zonem)*60
  925.     if zonen == '-':
  926.         zone = -zone
  927.  
  928.     tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  929.  
  930.     utc = time.mktime(tt)
  931.  
  932.     # Following is necessary because the time module has no 'mkgmtime'.
  933.     # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
  934.  
  935.     lt = time.localtime(utc)
  936.     if time.daylight and lt[-1]:
  937.         zone = zone + time.altzone
  938.     else:
  939.         zone = zone + time.timezone
  940.  
  941.     return time.localtime(utc - zone)
  942.  
  943.  
  944.  
  945. def Int2AP(num):
  946.  
  947.     """Convert integer to A-P string representation."""
  948.  
  949.     val = ''; AP = 'ABCDEFGHIJKLMNOP'
  950.     num = int(abs(num))
  951.     while num:
  952.         num, mod = divmod(num, 16)
  953.         val = AP[mod] + val
  954.     return val
  955.  
  956.  
  957.  
  958. def ParseFlags(resp):
  959.  
  960.     """Convert IMAP4 flags response to python tuple."""
  961.  
  962.     mo = Flags.match(resp)
  963.     if not mo:
  964.         return ()
  965.  
  966.     return tuple(string.split(mo.group('flags')))
  967.  
  968.  
  969. def Time2Internaldate(date_time):
  970.  
  971.     """Convert 'date_time' to IMAP4 INTERNALDATE representation.
  972.  
  973.     Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
  974.     """
  975.  
  976.     dttype = type(date_time)
  977.     if dttype is type(1) or dttype is type(1.1):
  978.         tt = time.localtime(date_time)
  979.     elif dttype is type(()):
  980.         tt = date_time
  981.     elif dttype is type(""):
  982.         return date_time    # Assume in correct format
  983.     else: raise ValueError
  984.  
  985.     dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
  986.     if dt[0] == '0':
  987.         dt = ' ' + dt[1:]
  988.     if time.daylight and tt[-1]:
  989.         zone = -time.altzone
  990.     else:
  991.         zone = -time.timezone
  992.     return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
  993.  
  994.  
  995.  
  996. if __debug__:
  997.  
  998.     def _mesg(s, secs=None):
  999.         if secs is None:
  1000.             secs = time.time()
  1001.         tm = time.strftime('%M:%S', time.localtime(secs))
  1002.         sys.stderr.write('  %s.%02d %s\n' % (tm, (secs*100)%100, s))
  1003.         sys.stderr.flush()
  1004.  
  1005.     def _dump_ur(dict):
  1006.         # Dump untagged responses (in `dict').
  1007.         l = dict.items()
  1008.         if not l: return
  1009.         t = '\n\t\t'
  1010.         j = string.join
  1011.         l = map(lambda x,j=j:'%s: "%s"' % (x[0], x[1][0] and j(x[1], '" "') or ''), l)
  1012.         _mesg('untagged responses dump:%s%s' % (t, j(l, t)))
  1013.  
  1014.     _cmd_log = []        # Last `_cmd_log_len' interactions
  1015.     _cmd_log_len = 10
  1016.  
  1017.     def _log(line):
  1018.         # Keep log of last `_cmd_log_len' interactions for debugging.
  1019.         if len(_cmd_log) == _cmd_log_len:
  1020.             del _cmd_log[0]
  1021.         _cmd_log.append((time.time(), line))
  1022.  
  1023.     def print_log():
  1024.         _mesg('last %d IMAP4 interactions:' % len(_cmd_log))
  1025.         for secs,line in _cmd_log:
  1026.             _mesg(line, secs)
  1027.  
  1028.  
  1029.  
  1030. if __name__ == '__main__':
  1031.  
  1032.     import getopt, getpass, sys
  1033.  
  1034.     try:
  1035.         optlist, args = getopt.getopt(sys.argv[1:], 'd:')
  1036.     except getopt.error, val:
  1037.         pass
  1038.  
  1039.     for opt,val in optlist:
  1040.         if opt == '-d':
  1041.             Debug = int(val)
  1042.  
  1043.     if not args: args = ('',)
  1044.  
  1045.     host = args[0]
  1046.  
  1047.     USER = getpass.getuser()
  1048.     PASSWD = getpass.getpass("IMAP password for %s on %s" % (USER, host or "localhost"))
  1049.  
  1050.     test_mesg = 'From: %s@localhost\nSubject: IMAP4 test\n\ndata...\n' % USER
  1051.     test_seq1 = (
  1052.     ('login', (USER, PASSWD)),
  1053.     ('create', ('/tmp/xxx 1',)),
  1054.     ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
  1055.     ('CREATE', ('/tmp/yyz 2',)),
  1056.     ('append', ('/tmp/yyz 2', None, None, test_mesg)),
  1057.     ('list', ('/tmp', 'yy*')),
  1058.     ('select', ('/tmp/yyz 2',)),
  1059.     ('search', (None, 'SUBJECT', 'test')),
  1060.     ('partial', ('1', 'RFC822', 1, 1024)),
  1061.     ('store', ('1', 'FLAGS', '(\Deleted)')),
  1062.     ('expunge', ()),
  1063.     ('recent', ()),
  1064.     ('close', ()),
  1065.     )
  1066.  
  1067.     test_seq2 = (
  1068.     ('select', ()),
  1069.     ('response',('UIDVALIDITY',)),
  1070.     ('uid', ('SEARCH', 'ALL')),
  1071.     ('response', ('EXISTS',)),
  1072.     ('append', (None, None, None, test_mesg)),
  1073.     ('recent', ()),
  1074.     ('logout', ()),
  1075.     )
  1076.  
  1077.     def run(cmd, args):
  1078.         _mesg('%s %s' % (cmd, args))
  1079.         typ, dat = apply(eval('M.%s' % cmd), args)
  1080.         _mesg('%s => %s %s' % (cmd, typ, dat))
  1081.         return dat
  1082.  
  1083.     try:
  1084.         M = IMAP4(host)
  1085.         _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1086.  
  1087.         for cmd,args in test_seq1:
  1088.             run(cmd, args)
  1089.  
  1090.         for ml in run('list', ('/tmp/', 'yy%')):
  1091.             mo = re.match(r'.*"([^"]+)"$', ml)
  1092.             if mo: path = mo.group(1)
  1093.             else: path = string.split(ml)[-1]
  1094.             run('delete', (path,))
  1095.  
  1096.         for cmd,args in test_seq2:
  1097.             dat = run(cmd, args)
  1098.  
  1099.             if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
  1100.                 continue
  1101.  
  1102.             uid = string.split(dat[-1])
  1103.             if not uid: continue
  1104.             run('uid', ('FETCH', '%s' % uid[-1],
  1105.                 '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  1106.  
  1107.         print '\nAll tests OK.'
  1108.  
  1109.     except:
  1110.         print '\nTests failed.'
  1111.  
  1112.         if not Debug:
  1113.             print '''
  1114. If you would like to see debugging output,
  1115. try: %s -d5
  1116. ''' % sys.argv[0]
  1117.  
  1118.         raise
  1119.