]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.2/Lib/smtpd.py
edk2: Remove AppPkg, StdLib, StdLibPrivateInternalFiles
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Lib / smtpd.py
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Lib/smtpd.py b/AppPkg/Applications/Python/Python-2.7.2/Lib/smtpd.py
deleted file mode 100644 (file)
index 3ac464f..0000000
+++ /dev/null
@@ -1,555 +0,0 @@
-#! /usr/bin/env python\r
-"""An RFC 2821 smtp proxy.\r
-\r
-Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]\r
-\r
-Options:\r
-\r
-    --nosetuid\r
-    -n\r
-        This program generally tries to setuid `nobody', unless this flag is\r
-        set.  The setuid call will fail if this program is not run as root (in\r
-        which case, use this flag).\r
-\r
-    --version\r
-    -V\r
-        Print the version number and exit.\r
-\r
-    --class classname\r
-    -c classname\r
-        Use `classname' as the concrete SMTP proxy class.  Uses `PureProxy' by\r
-        default.\r
-\r
-    --debug\r
-    -d\r
-        Turn on debugging prints.\r
-\r
-    --help\r
-    -h\r
-        Print this message and exit.\r
-\r
-Version: %(__version__)s\r
-\r
-If localhost is not given then `localhost' is used, and if localport is not\r
-given then 8025 is used.  If remotehost is not given then `localhost' is used,\r
-and if remoteport is not given, then 25 is used.\r
-"""\r
-\r
-# Overview:\r
-#\r
-# This file implements the minimal SMTP protocol as defined in RFC 821.  It\r
-# has a hierarchy of classes which implement the backend functionality for the\r
-# smtpd.  A number of classes are provided:\r
-#\r
-#   SMTPServer - the base class for the backend.  Raises NotImplementedError\r
-#   if you try to use it.\r
-#\r
-#   DebuggingServer - simply prints each message it receives on stdout.\r
-#\r
-#   PureProxy - Proxies all messages to a real smtpd which does final\r
-#   delivery.  One known problem with this class is that it doesn't handle\r
-#   SMTP errors from the backend server at all.  This should be fixed\r
-#   (contributions are welcome!).\r
-#\r
-#   MailmanProxy - An experimental hack to work with GNU Mailman\r
-#   <www.list.org>.  Using this server as your real incoming smtpd, your\r
-#   mailhost will automatically recognize and accept mail destined to Mailman\r
-#   lists when those lists are created.  Every message not destined for a list\r
-#   gets forwarded to a real backend smtpd, as with PureProxy.  Again, errors\r
-#   are not handled correctly yet.\r
-#\r
-# Please note that this script requires Python 2.0\r
-#\r
-# Author: Barry Warsaw <barry@python.org>\r
-#\r
-# TODO:\r
-#\r
-# - support mailbox delivery\r
-# - alias files\r
-# - ESMTP\r
-# - handle error codes from the backend smtpd\r
-\r
-import sys\r
-import os\r
-import errno\r
-import getopt\r
-import time\r
-import socket\r
-import asyncore\r
-import asynchat\r
-\r
-__all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"]\r
-\r
-program = sys.argv[0]\r
-__version__ = 'Python SMTP proxy version 0.2'\r
-\r
-\r
-class Devnull:\r
-    def write(self, msg): pass\r
-    def flush(self): pass\r
-\r
-\r
-DEBUGSTREAM = Devnull()\r
-NEWLINE = '\n'\r
-EMPTYSTRING = ''\r
-COMMASPACE = ', '\r
-\r
-\r
-def usage(code, msg=''):\r
-    print >> sys.stderr, __doc__ % globals()\r
-    if msg:\r
-        print >> sys.stderr, msg\r
-    sys.exit(code)\r
-\r
-\r
-class SMTPChannel(asynchat.async_chat):\r
-    COMMAND = 0\r
-    DATA = 1\r
-\r
-    def __init__(self, server, conn, addr):\r
-        asynchat.async_chat.__init__(self, conn)\r
-        self.__server = server\r
-        self.__conn = conn\r
-        self.__addr = addr\r
-        self.__line = []\r
-        self.__state = self.COMMAND\r
-        self.__greeting = 0\r
-        self.__mailfrom = None\r
-        self.__rcpttos = []\r
-        self.__data = ''\r
-        self.__fqdn = socket.getfqdn()\r
-        try:\r
-            self.__peer = conn.getpeername()\r
-        except socket.error, err:\r
-            # a race condition  may occur if the other end is closing\r
-            # before we can get the peername\r
-            self.close()\r
-            if err[0] != errno.ENOTCONN:\r
-                raise\r
-            return\r
-        print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)\r
-        self.push('220 %s %s' % (self.__fqdn, __version__))\r
-        self.set_terminator('\r\n')\r
-\r
-    # Overrides base class for convenience\r
-    def push(self, msg):\r
-        asynchat.async_chat.push(self, msg + '\r\n')\r
-\r
-    # Implementation of base class abstract method\r
-    def collect_incoming_data(self, data):\r
-        self.__line.append(data)\r
-\r
-    # Implementation of base class abstract method\r
-    def found_terminator(self):\r
-        line = EMPTYSTRING.join(self.__line)\r
-        print >> DEBUGSTREAM, 'Data:', repr(line)\r
-        self.__line = []\r
-        if self.__state == self.COMMAND:\r
-            if not line:\r
-                self.push('500 Error: bad syntax')\r
-                return\r
-            method = None\r
-            i = line.find(' ')\r
-            if i < 0:\r
-                command = line.upper()\r
-                arg = None\r
-            else:\r
-                command = line[:i].upper()\r
-                arg = line[i+1:].strip()\r
-            method = getattr(self, 'smtp_' + command, None)\r
-            if not method:\r
-                self.push('502 Error: command "%s" not implemented' % command)\r
-                return\r
-            method(arg)\r
-            return\r
-        else:\r
-            if self.__state != self.DATA:\r
-                self.push('451 Internal confusion')\r
-                return\r
-            # Remove extraneous carriage returns and de-transparency according\r
-            # to RFC 821, Section 4.5.2.\r
-            data = []\r
-            for text in line.split('\r\n'):\r
-                if text and text[0] == '.':\r
-                    data.append(text[1:])\r
-                else:\r
-                    data.append(text)\r
-            self.__data = NEWLINE.join(data)\r
-            status = self.__server.process_message(self.__peer,\r
-                                                   self.__mailfrom,\r
-                                                   self.__rcpttos,\r
-                                                   self.__data)\r
-            self.__rcpttos = []\r
-            self.__mailfrom = None\r
-            self.__state = self.COMMAND\r
-            self.set_terminator('\r\n')\r
-            if not status:\r
-                self.push('250 Ok')\r
-            else:\r
-                self.push(status)\r
-\r
-    # SMTP and ESMTP commands\r
-    def smtp_HELO(self, arg):\r
-        if not arg:\r
-            self.push('501 Syntax: HELO hostname')\r
-            return\r
-        if self.__greeting:\r
-            self.push('503 Duplicate HELO/EHLO')\r
-        else:\r
-            self.__greeting = arg\r
-            self.push('250 %s' % self.__fqdn)\r
-\r
-    def smtp_NOOP(self, arg):\r
-        if arg:\r
-            self.push('501 Syntax: NOOP')\r
-        else:\r
-            self.push('250 Ok')\r
-\r
-    def smtp_QUIT(self, arg):\r
-        # args is ignored\r
-        self.push('221 Bye')\r
-        self.close_when_done()\r
-\r
-    # factored\r
-    def __getaddr(self, keyword, arg):\r
-        address = None\r
-        keylen = len(keyword)\r
-        if arg[:keylen].upper() == keyword:\r
-            address = arg[keylen:].strip()\r
-            if not address:\r
-                pass\r
-            elif address[0] == '<' and address[-1] == '>' and address != '<>':\r
-                # Addresses can be in the form <person@dom.com> but watch out\r
-                # for null address, e.g. <>\r
-                address = address[1:-1]\r
-        return address\r
-\r
-    def smtp_MAIL(self, arg):\r
-        print >> DEBUGSTREAM, '===> MAIL', arg\r
-        address = self.__getaddr('FROM:', arg) if arg else None\r
-        if not address:\r
-            self.push('501 Syntax: MAIL FROM:<address>')\r
-            return\r
-        if self.__mailfrom:\r
-            self.push('503 Error: nested MAIL command')\r
-            return\r
-        self.__mailfrom = address\r
-        print >> DEBUGSTREAM, 'sender:', self.__mailfrom\r
-        self.push('250 Ok')\r
-\r
-    def smtp_RCPT(self, arg):\r
-        print >> DEBUGSTREAM, '===> RCPT', arg\r
-        if not self.__mailfrom:\r
-            self.push('503 Error: need MAIL command')\r
-            return\r
-        address = self.__getaddr('TO:', arg) if arg else None\r
-        if not address:\r
-            self.push('501 Syntax: RCPT TO: <address>')\r
-            return\r
-        self.__rcpttos.append(address)\r
-        print >> DEBUGSTREAM, 'recips:', self.__rcpttos\r
-        self.push('250 Ok')\r
-\r
-    def smtp_RSET(self, arg):\r
-        if arg:\r
-            self.push('501 Syntax: RSET')\r
-            return\r
-        # Resets the sender, recipients, and data, but not the greeting\r
-        self.__mailfrom = None\r
-        self.__rcpttos = []\r
-        self.__data = ''\r
-        self.__state = self.COMMAND\r
-        self.push('250 Ok')\r
-\r
-    def smtp_DATA(self, arg):\r
-        if not self.__rcpttos:\r
-            self.push('503 Error: need RCPT command')\r
-            return\r
-        if arg:\r
-            self.push('501 Syntax: DATA')\r
-            return\r
-        self.__state = self.DATA\r
-        self.set_terminator('\r\n.\r\n')\r
-        self.push('354 End data with <CR><LF>.<CR><LF>')\r
-\r
-\r
-class SMTPServer(asyncore.dispatcher):\r
-    def __init__(self, localaddr, remoteaddr):\r
-        self._localaddr = localaddr\r
-        self._remoteaddr = remoteaddr\r
-        asyncore.dispatcher.__init__(self)\r
-        try:\r
-            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\r
-            # try to re-use a server port if possible\r
-            self.set_reuse_addr()\r
-            self.bind(localaddr)\r
-            self.listen(5)\r
-        except:\r
-            # cleanup asyncore.socket_map before raising\r
-            self.close()\r
-            raise\r
-        else:\r
-            print >> DEBUGSTREAM, \\r
-                  '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (\r
-                self.__class__.__name__, time.ctime(time.time()),\r
-                localaddr, remoteaddr)\r
-\r
-    def handle_accept(self):\r
-        pair = self.accept()\r
-        if pair is not None:\r
-            conn, addr = pair\r
-            print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)\r
-            channel = SMTPChannel(self, conn, addr)\r
-\r
-    # API for "doing something useful with the message"\r
-    def process_message(self, peer, mailfrom, rcpttos, data):\r
-        """Override this abstract method to handle messages from the client.\r
-\r
-        peer is a tuple containing (ipaddr, port) of the client that made the\r
-        socket connection to our smtp port.\r
-\r
-        mailfrom is the raw address the client claims the message is coming\r
-        from.\r
-\r
-        rcpttos is a list of raw addresses the client wishes to deliver the\r
-        message to.\r
-\r
-        data is a string containing the entire full text of the message,\r
-        headers (if supplied) and all.  It has been `de-transparencied'\r
-        according to RFC 821, Section 4.5.2.  In other words, a line\r
-        containing a `.' followed by other text has had the leading dot\r
-        removed.\r
-\r
-        This function should return None, for a normal `250 Ok' response;\r
-        otherwise it returns the desired response string in RFC 821 format.\r
-\r
-        """\r
-        raise NotImplementedError\r
-\r
-\r
-class DebuggingServer(SMTPServer):\r
-    # Do something with the gathered message\r
-    def process_message(self, peer, mailfrom, rcpttos, data):\r
-        inheaders = 1\r
-        lines = data.split('\n')\r
-        print '---------- MESSAGE FOLLOWS ----------'\r
-        for line in lines:\r
-            # headers first\r
-            if inheaders and not line:\r
-                print 'X-Peer:', peer[0]\r
-                inheaders = 0\r
-            print line\r
-        print '------------ END MESSAGE ------------'\r
-\r
-\r
-class PureProxy(SMTPServer):\r
-    def process_message(self, peer, mailfrom, rcpttos, data):\r
-        lines = data.split('\n')\r
-        # Look for the last header\r
-        i = 0\r
-        for line in lines:\r
-            if not line:\r
-                break\r
-            i += 1\r
-        lines.insert(i, 'X-Peer: %s' % peer[0])\r
-        data = NEWLINE.join(lines)\r
-        refused = self._deliver(mailfrom, rcpttos, data)\r
-        # TBD: what to do with refused addresses?\r
-        print >> DEBUGSTREAM, 'we got some refusals:', refused\r
-\r
-    def _deliver(self, mailfrom, rcpttos, data):\r
-        import smtplib\r
-        refused = {}\r
-        try:\r
-            s = smtplib.SMTP()\r
-            s.connect(self._remoteaddr[0], self._remoteaddr[1])\r
-            try:\r
-                refused = s.sendmail(mailfrom, rcpttos, data)\r
-            finally:\r
-                s.quit()\r
-        except smtplib.SMTPRecipientsRefused, e:\r
-            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'\r
-            refused = e.recipients\r
-        except (socket.error, smtplib.SMTPException), e:\r
-            print >> DEBUGSTREAM, 'got', e.__class__\r
-            # All recipients were refused.  If the exception had an associated\r
-            # error code, use it.  Otherwise,fake it with a non-triggering\r
-            # exception code.\r
-            errcode = getattr(e, 'smtp_code', -1)\r
-            errmsg = getattr(e, 'smtp_error', 'ignore')\r
-            for r in rcpttos:\r
-                refused[r] = (errcode, errmsg)\r
-        return refused\r
-\r
-\r
-class MailmanProxy(PureProxy):\r
-    def process_message(self, peer, mailfrom, rcpttos, data):\r
-        from cStringIO import StringIO\r
-        from Mailman import Utils\r
-        from Mailman import Message\r
-        from Mailman import MailList\r
-        # If the message is to a Mailman mailing list, then we'll invoke the\r
-        # Mailman script directly, without going through the real smtpd.\r
-        # Otherwise we'll forward it to the local proxy for disposition.\r
-        listnames = []\r
-        for rcpt in rcpttos:\r
-            local = rcpt.lower().split('@')[0]\r
-            # We allow the following variations on the theme\r
-            #   listname\r
-            #   listname-admin\r
-            #   listname-owner\r
-            #   listname-request\r
-            #   listname-join\r
-            #   listname-leave\r
-            parts = local.split('-')\r
-            if len(parts) > 2:\r
-                continue\r
-            listname = parts[0]\r
-            if len(parts) == 2:\r
-                command = parts[1]\r
-            else:\r
-                command = ''\r
-            if not Utils.list_exists(listname) or command not in (\r
-                    '', 'admin', 'owner', 'request', 'join', 'leave'):\r
-                continue\r
-            listnames.append((rcpt, listname, command))\r
-        # Remove all list recipients from rcpttos and forward what we're not\r
-        # going to take care of ourselves.  Linear removal should be fine\r
-        # since we don't expect a large number of recipients.\r
-        for rcpt, listname, command in listnames:\r
-            rcpttos.remove(rcpt)\r
-        # If there's any non-list destined recipients left,\r
-        print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)\r
-        if rcpttos:\r
-            refused = self._deliver(mailfrom, rcpttos, data)\r
-            # TBD: what to do with refused addresses?\r
-            print >> DEBUGSTREAM, 'we got refusals:', refused\r
-        # Now deliver directly to the list commands\r
-        mlists = {}\r
-        s = StringIO(data)\r
-        msg = Message.Message(s)\r
-        # These headers are required for the proper execution of Mailman.  All\r
-        # MTAs in existence seem to add these if the original message doesn't\r
-        # have them.\r
-        if not msg.getheader('from'):\r
-            msg['From'] = mailfrom\r
-        if not msg.getheader('date'):\r
-            msg['Date'] = time.ctime(time.time())\r
-        for rcpt, listname, command in listnames:\r
-            print >> DEBUGSTREAM, 'sending message to', rcpt\r
-            mlist = mlists.get(listname)\r
-            if not mlist:\r
-                mlist = MailList.MailList(listname, lock=0)\r
-                mlists[listname] = mlist\r
-            # dispatch on the type of command\r
-            if command == '':\r
-                # post\r
-                msg.Enqueue(mlist, tolist=1)\r
-            elif command == 'admin':\r
-                msg.Enqueue(mlist, toadmin=1)\r
-            elif command == 'owner':\r
-                msg.Enqueue(mlist, toowner=1)\r
-            elif command == 'request':\r
-                msg.Enqueue(mlist, torequest=1)\r
-            elif command in ('join', 'leave'):\r
-                # TBD: this is a hack!\r
-                if command == 'join':\r
-                    msg['Subject'] = 'subscribe'\r
-                else:\r
-                    msg['Subject'] = 'unsubscribe'\r
-                msg.Enqueue(mlist, torequest=1)\r
-\r
-\r
-class Options:\r
-    setuid = 1\r
-    classname = 'PureProxy'\r
-\r
-\r
-def parseargs():\r
-    global DEBUGSTREAM\r
-    try:\r
-        opts, args = getopt.getopt(\r
-            sys.argv[1:], 'nVhc:d',\r
-            ['class=', 'nosetuid', 'version', 'help', 'debug'])\r
-    except getopt.error, e:\r
-        usage(1, e)\r
-\r
-    options = Options()\r
-    for opt, arg in opts:\r
-        if opt in ('-h', '--help'):\r
-            usage(0)\r
-        elif opt in ('-V', '--version'):\r
-            print >> sys.stderr, __version__\r
-            sys.exit(0)\r
-        elif opt in ('-n', '--nosetuid'):\r
-            options.setuid = 0\r
-        elif opt in ('-c', '--class'):\r
-            options.classname = arg\r
-        elif opt in ('-d', '--debug'):\r
-            DEBUGSTREAM = sys.stderr\r
-\r
-    # parse the rest of the arguments\r
-    if len(args) < 1:\r
-        localspec = 'localhost:8025'\r
-        remotespec = 'localhost:25'\r
-    elif len(args) < 2:\r
-        localspec = args[0]\r
-        remotespec = 'localhost:25'\r
-    elif len(args) < 3:\r
-        localspec = args[0]\r
-        remotespec = args[1]\r
-    else:\r
-        usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))\r
-\r
-    # split into host/port pairs\r
-    i = localspec.find(':')\r
-    if i < 0:\r
-        usage(1, 'Bad local spec: %s' % localspec)\r
-    options.localhost = localspec[:i]\r
-    try:\r
-        options.localport = int(localspec[i+1:])\r
-    except ValueError:\r
-        usage(1, 'Bad local port: %s' % localspec)\r
-    i = remotespec.find(':')\r
-    if i < 0:\r
-        usage(1, 'Bad remote spec: %s' % remotespec)\r
-    options.remotehost = remotespec[:i]\r
-    try:\r
-        options.remoteport = int(remotespec[i+1:])\r
-    except ValueError:\r
-        usage(1, 'Bad remote port: %s' % remotespec)\r
-    return options\r
-\r
-\r
-if __name__ == '__main__':\r
-    options = parseargs()\r
-    # Become nobody\r
-    if options.setuid:\r
-        try:\r
-            import pwd\r
-        except ImportError:\r
-            print >> sys.stderr, \\r
-                  'Cannot import module "pwd"; try running with -n option.'\r
-            sys.exit(1)\r
-        nobody = pwd.getpwnam('nobody')[2]\r
-        try:\r
-            os.setuid(nobody)\r
-        except OSError, e:\r
-            if e.errno != errno.EPERM: raise\r
-            print >> sys.stderr, \\r
-                  'Cannot setuid "nobody"; try running with -n option.'\r
-            sys.exit(1)\r
-    classname = options.classname\r
-    if "." in classname:\r
-        lastdot = classname.rfind(".")\r
-        mod = __import__(classname[:lastdot], globals(), locals(), [""])\r
-        classname = classname[lastdot+1:]\r
-    else:\r
-        import __main__ as mod\r
-    class_ = getattr(mod, classname)\r
-    proxy = class_((options.localhost, options.localport),\r
-                   (options.remotehost, options.remoteport))\r
-    try:\r
-        asyncore.loop()\r
-    except KeyboardInterrupt:\r
-        pass\r