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