Benjamin Peterson | 90f5ba5 | 2010-03-11 22:53:45 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
Barry Warsaw | 406d46e | 2001-08-13 21:18:01 +0000 | [diff] [blame] | 2 | """An RFC 2821 smtp proxy. |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 3 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 4 | Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 5 | |
| 6 | Options: |
| 7 | |
| 8 | --nosetuid |
| 9 | -n |
| 10 | This program generally tries to setuid `nobody', unless this flag is |
| 11 | set. The setuid call will fail if this program is not run as root (in |
| 12 | which case, use this flag). |
| 13 | |
| 14 | --version |
| 15 | -V |
| 16 | Print the version number and exit. |
| 17 | |
| 18 | --class classname |
| 19 | -c classname |
Barry Warsaw | f267b62 | 2004-10-09 21:44:13 +0000 | [diff] [blame] | 20 | Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 21 | default. |
| 22 | |
| 23 | --debug |
| 24 | -d |
| 25 | Turn on debugging prints. |
| 26 | |
| 27 | --help |
| 28 | -h |
| 29 | Print this message and exit. |
| 30 | |
| 31 | Version: %(__version__)s |
| 32 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 33 | If localhost is not given then `localhost' is used, and if localport is not |
| 34 | given then 8025 is used. If remotehost is not given then `localhost' is used, |
| 35 | and if remoteport is not given, then 25 is used. |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 36 | """ |
| 37 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 38 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 39 | # Overview: |
| 40 | # |
| 41 | # This file implements the minimal SMTP protocol as defined in RFC 821. It |
| 42 | # has a hierarchy of classes which implement the backend functionality for the |
| 43 | # smtpd. A number of classes are provided: |
| 44 | # |
Guido van Rossum | b8b45ea | 2001-04-15 13:06:04 +0000 | [diff] [blame] | 45 | # SMTPServer - the base class for the backend. Raises NotImplementedError |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 46 | # if you try to use it. |
| 47 | # |
| 48 | # DebuggingServer - simply prints each message it receives on stdout. |
| 49 | # |
| 50 | # PureProxy - Proxies all messages to a real smtpd which does final |
| 51 | # delivery. One known problem with this class is that it doesn't handle |
| 52 | # SMTP errors from the backend server at all. This should be fixed |
| 53 | # (contributions are welcome!). |
| 54 | # |
| 55 | # MailmanProxy - An experimental hack to work with GNU Mailman |
| 56 | # <www.list.org>. Using this server as your real incoming smtpd, your |
| 57 | # mailhost will automatically recognize and accept mail destined to Mailman |
| 58 | # lists when those lists are created. Every message not destined for a list |
| 59 | # gets forwarded to a real backend smtpd, as with PureProxy. Again, errors |
| 60 | # are not handled correctly yet. |
| 61 | # |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 62 | # |
Barry Warsaw | b102764 | 2004-07-12 23:10:08 +0000 | [diff] [blame] | 63 | # Author: Barry Warsaw <barry@python.org> |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 64 | # |
| 65 | # TODO: |
| 66 | # |
| 67 | # - support mailbox delivery |
| 68 | # - alias files |
| 69 | # - ESMTP |
| 70 | # - handle error codes from the backend smtpd |
| 71 | |
| 72 | import sys |
| 73 | import os |
| 74 | import errno |
| 75 | import getopt |
| 76 | import time |
| 77 | import socket |
| 78 | import asyncore |
| 79 | import asynchat |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 80 | from warnings import warn |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 81 | |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 82 | __all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"] |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 83 | |
| 84 | program = sys.argv[0] |
| 85 | __version__ = 'Python SMTP proxy version 0.2' |
| 86 | |
| 87 | |
| 88 | class Devnull: |
| 89 | def write(self, msg): pass |
| 90 | def flush(self): pass |
| 91 | |
| 92 | |
| 93 | DEBUGSTREAM = Devnull() |
| 94 | NEWLINE = '\n' |
| 95 | EMPTYSTRING = '' |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 96 | COMMASPACE = ', ' |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 97 | |
| 98 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 99 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 100 | def usage(code, msg=''): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 101 | print(__doc__ % globals(), file=sys.stderr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 102 | if msg: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 103 | print(msg, file=sys.stderr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 104 | sys.exit(code) |
| 105 | |
| 106 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 107 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 108 | class SMTPChannel(asynchat.async_chat): |
| 109 | COMMAND = 0 |
| 110 | DATA = 1 |
| 111 | |
| 112 | def __init__(self, server, conn, addr): |
| 113 | asynchat.async_chat.__init__(self, conn) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 114 | self.smtp_server = server |
| 115 | self.conn = conn |
| 116 | self.addr = addr |
| 117 | self.received_lines = [] |
| 118 | self.smtp_state = self.COMMAND |
| 119 | self.seen_greeting = '' |
| 120 | self.mailfrom = None |
| 121 | self.rcpttos = [] |
| 122 | self.received_data = '' |
| 123 | self.fqdn = socket.getfqdn() |
Giampaolo RodolĂ | 9cf5ef4 | 2010-08-23 22:28:13 +0000 | [diff] [blame] | 124 | try: |
| 125 | self.peer = conn.getpeername() |
| 126 | except socket.error as err: |
| 127 | # a race condition may occur if the other end is closing |
| 128 | # before we can get the peername |
| 129 | self.close() |
| 130 | if err.args[0] != errno.ENOTCONN: |
| 131 | raise |
| 132 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 133 | print('Peer:', repr(self.peer), file=DEBUGSTREAM) |
| 134 | self.push('220 %s %s' % (self.fqdn, __version__)) |
Josiah Carlson | d74900e | 2008-07-07 04:15:08 +0000 | [diff] [blame] | 135 | self.set_terminator(b'\r\n') |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 136 | |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 137 | # properties for backwards-compatibility |
| 138 | @property |
| 139 | def __server(self): |
| 140 | warn("Access to __server attribute on SMTPChannel is deprecated, " |
| 141 | "use 'smtp_server' instead", PendingDeprecationWarning, 2) |
| 142 | return self.smtp_server |
| 143 | @__server.setter |
| 144 | def __server(self, value): |
| 145 | warn("Setting __server attribute on SMTPChannel is deprecated, " |
| 146 | "set 'smtp_server' instead", PendingDeprecationWarning, 2) |
| 147 | self.smtp_server = value |
| 148 | |
| 149 | @property |
| 150 | def __line(self): |
| 151 | warn("Access to __line attribute on SMTPChannel is deprecated, " |
| 152 | "use 'received_lines' instead", PendingDeprecationWarning, 2) |
| 153 | return self.received_lines |
| 154 | @__line.setter |
| 155 | def __line(self, value): |
| 156 | warn("Setting __line attribute on SMTPChannel is deprecated, " |
| 157 | "set 'received_lines' instead", PendingDeprecationWarning, 2) |
| 158 | self.received_lines = value |
| 159 | |
| 160 | @property |
| 161 | def __state(self): |
| 162 | warn("Access to __state attribute on SMTPChannel is deprecated, " |
| 163 | "use 'smtp_state' instead", PendingDeprecationWarning, 2) |
| 164 | return self.smtp_state |
| 165 | @__state.setter |
| 166 | def __state(self, value): |
| 167 | warn("Setting __state attribute on SMTPChannel is deprecated, " |
| 168 | "set 'smtp_state' instead", PendingDeprecationWarning, 2) |
| 169 | self.smtp_state = value |
| 170 | |
| 171 | @property |
| 172 | def __greeting(self): |
| 173 | warn("Access to __greeting attribute on SMTPChannel is deprecated, " |
| 174 | "use 'seen_greeting' instead", PendingDeprecationWarning, 2) |
| 175 | return self.seen_greeting |
| 176 | @__greeting.setter |
| 177 | def __greeting(self, value): |
| 178 | warn("Setting __greeting attribute on SMTPChannel is deprecated, " |
| 179 | "set 'seen_greeting' instead", PendingDeprecationWarning, 2) |
| 180 | self.seen_greeting = value |
| 181 | |
| 182 | @property |
| 183 | def __mailfrom(self): |
| 184 | warn("Access to __mailfrom attribute on SMTPChannel is deprecated, " |
| 185 | "use 'mailfrom' instead", PendingDeprecationWarning, 2) |
| 186 | return self.mailfrom |
| 187 | @__mailfrom.setter |
| 188 | def __mailfrom(self, value): |
| 189 | warn("Setting __mailfrom attribute on SMTPChannel is deprecated, " |
| 190 | "set 'mailfrom' instead", PendingDeprecationWarning, 2) |
| 191 | self.mailfrom = value |
| 192 | |
| 193 | @property |
| 194 | def __rcpttos(self): |
| 195 | warn("Access to __rcpttos attribute on SMTPChannel is deprecated, " |
| 196 | "use 'rcpttos' instead", PendingDeprecationWarning, 2) |
| 197 | return self.rcpttos |
| 198 | @__rcpttos.setter |
| 199 | def __rcpttos(self, value): |
| 200 | warn("Setting __rcpttos attribute on SMTPChannel is deprecated, " |
| 201 | "set 'rcpttos' instead", PendingDeprecationWarning, 2) |
| 202 | self.rcpttos = value |
| 203 | |
| 204 | @property |
| 205 | def __data(self): |
| 206 | warn("Access to __data attribute on SMTPChannel is deprecated, " |
| 207 | "use 'received_data' instead", PendingDeprecationWarning, 2) |
| 208 | return self.received_data |
| 209 | @__data.setter |
| 210 | def __data(self, value): |
| 211 | warn("Setting __data attribute on SMTPChannel is deprecated, " |
| 212 | "set 'received_data' instead", PendingDeprecationWarning, 2) |
| 213 | self.received_data = value |
| 214 | |
| 215 | @property |
| 216 | def __fqdn(self): |
| 217 | warn("Access to __fqdn attribute on SMTPChannel is deprecated, " |
| 218 | "use 'fqdn' instead", PendingDeprecationWarning, 2) |
| 219 | return self.fqdn |
| 220 | @__fqdn.setter |
| 221 | def __fqdn(self, value): |
| 222 | warn("Setting __fqdn attribute on SMTPChannel is deprecated, " |
| 223 | "set 'fqdn' instead", PendingDeprecationWarning, 2) |
| 224 | self.fqdn = value |
| 225 | |
| 226 | @property |
| 227 | def __peer(self): |
| 228 | warn("Access to __peer attribute on SMTPChannel is deprecated, " |
| 229 | "use 'peer' instead", PendingDeprecationWarning, 2) |
| 230 | return self.peer |
| 231 | @__peer.setter |
| 232 | def __peer(self, value): |
| 233 | warn("Setting __peer attribute on SMTPChannel is deprecated, " |
| 234 | "set 'peer' instead", PendingDeprecationWarning, 2) |
| 235 | self.peer = value |
| 236 | |
| 237 | @property |
| 238 | def __conn(self): |
| 239 | warn("Access to __conn attribute on SMTPChannel is deprecated, " |
| 240 | "use 'conn' instead", PendingDeprecationWarning, 2) |
| 241 | return self.conn |
| 242 | @__conn.setter |
| 243 | def __conn(self, value): |
| 244 | warn("Setting __conn attribute on SMTPChannel is deprecated, " |
| 245 | "set 'conn' instead", PendingDeprecationWarning, 2) |
| 246 | self.conn = value |
| 247 | |
| 248 | @property |
| 249 | def __addr(self): |
| 250 | warn("Access to __addr attribute on SMTPChannel is deprecated, " |
| 251 | "use 'addr' instead", PendingDeprecationWarning, 2) |
| 252 | return self.addr |
| 253 | @__addr.setter |
| 254 | def __addr(self, value): |
| 255 | warn("Setting __addr attribute on SMTPChannel is deprecated, " |
| 256 | "set 'addr' instead", PendingDeprecationWarning, 2) |
| 257 | self.addr = value |
| 258 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 259 | # Overrides base class for convenience |
| 260 | def push(self, msg): |
Josiah Carlson | d74900e | 2008-07-07 04:15:08 +0000 | [diff] [blame] | 261 | asynchat.async_chat.push(self, bytes(msg + '\r\n', 'ascii')) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 262 | |
| 263 | # Implementation of base class abstract method |
| 264 | def collect_incoming_data(self, data): |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 265 | self.received_lines.append(str(data, "utf8")) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 266 | |
| 267 | # Implementation of base class abstract method |
| 268 | def found_terminator(self): |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 269 | line = EMPTYSTRING.join(self.received_lines) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 270 | print('Data:', repr(line), file=DEBUGSTREAM) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 271 | self.received_lines = [] |
| 272 | if self.smtp_state == self.COMMAND: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 273 | if not line: |
| 274 | self.push('500 Error: bad syntax') |
| 275 | return |
| 276 | method = None |
| 277 | i = line.find(' ') |
| 278 | if i < 0: |
| 279 | command = line.upper() |
| 280 | arg = None |
| 281 | else: |
| 282 | command = line[:i].upper() |
| 283 | arg = line[i+1:].strip() |
| 284 | method = getattr(self, 'smtp_' + command, None) |
| 285 | if not method: |
| 286 | self.push('502 Error: command "%s" not implemented' % command) |
| 287 | return |
| 288 | method(arg) |
| 289 | return |
| 290 | else: |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 291 | if self.smtp_state != self.DATA: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 292 | self.push('451 Internal confusion') |
| 293 | return |
| 294 | # Remove extraneous carriage returns and de-transparency according |
| 295 | # to RFC 821, Section 4.5.2. |
| 296 | data = [] |
| 297 | for text in line.split('\r\n'): |
| 298 | if text and text[0] == '.': |
| 299 | data.append(text[1:]) |
| 300 | else: |
| 301 | data.append(text) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 302 | self.received_data = NEWLINE.join(data) |
Georg Brandl | 17e3d69 | 2010-07-31 10:08:09 +0000 | [diff] [blame] | 303 | status = self.smtp_server.process_message(self.peer, |
| 304 | self.mailfrom, |
| 305 | self.rcpttos, |
| 306 | self.received_data) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 307 | self.rcpttos = [] |
| 308 | self.mailfrom = None |
| 309 | self.smtp_state = self.COMMAND |
Josiah Carlson | d74900e | 2008-07-07 04:15:08 +0000 | [diff] [blame] | 310 | self.set_terminator(b'\r\n') |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 311 | if not status: |
| 312 | self.push('250 Ok') |
| 313 | else: |
| 314 | self.push(status) |
| 315 | |
| 316 | # SMTP and ESMTP commands |
| 317 | def smtp_HELO(self, arg): |
| 318 | if not arg: |
| 319 | self.push('501 Syntax: HELO hostname') |
| 320 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 321 | if self.seen_greeting: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 322 | self.push('503 Duplicate HELO/EHLO') |
| 323 | else: |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 324 | self.seen_greeting = arg |
| 325 | self.push('250 %s' % self.fqdn) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 326 | |
| 327 | def smtp_NOOP(self, arg): |
| 328 | if arg: |
| 329 | self.push('501 Syntax: NOOP') |
| 330 | else: |
| 331 | self.push('250 Ok') |
| 332 | |
| 333 | def smtp_QUIT(self, arg): |
| 334 | # args is ignored |
| 335 | self.push('221 Bye') |
| 336 | self.close_when_done() |
| 337 | |
| 338 | # factored |
| 339 | def __getaddr(self, keyword, arg): |
| 340 | address = None |
| 341 | keylen = len(keyword) |
| 342 | if arg[:keylen].upper() == keyword: |
| 343 | address = arg[keylen:].strip() |
Barry Warsaw | ebf5427 | 2001-11-04 03:04:25 +0000 | [diff] [blame] | 344 | if not address: |
| 345 | pass |
| 346 | elif address[0] == '<' and address[-1] == '>' and address != '<>': |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 347 | # Addresses can be in the form <person@dom.com> but watch out |
| 348 | # for null address, e.g. <> |
| 349 | address = address[1:-1] |
| 350 | return address |
| 351 | |
| 352 | def smtp_MAIL(self, arg): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 353 | print('===> MAIL', arg, file=DEBUGSTREAM) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 354 | address = self.__getaddr('FROM:', arg) if arg else None |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 355 | if not address: |
| 356 | self.push('501 Syntax: MAIL FROM:<address>') |
| 357 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 358 | if self.mailfrom: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 359 | self.push('503 Error: nested MAIL command') |
| 360 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 361 | self.mailfrom = address |
| 362 | print('sender:', self.mailfrom, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 363 | self.push('250 Ok') |
| 364 | |
| 365 | def smtp_RCPT(self, arg): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 366 | print('===> RCPT', arg, file=DEBUGSTREAM) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 367 | if not self.mailfrom: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 368 | self.push('503 Error: need MAIL command') |
| 369 | return |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 370 | address = self.__getaddr('TO:', arg) if arg else None |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 371 | if not address: |
| 372 | self.push('501 Syntax: RCPT TO: <address>') |
| 373 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 374 | self.rcpttos.append(address) |
| 375 | print('recips:', self.rcpttos, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 376 | self.push('250 Ok') |
| 377 | |
| 378 | def smtp_RSET(self, arg): |
| 379 | if arg: |
| 380 | self.push('501 Syntax: RSET') |
| 381 | return |
| 382 | # Resets the sender, recipients, and data, but not the greeting |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 383 | self.mailfrom = None |
| 384 | self.rcpttos = [] |
| 385 | self.received_data = '' |
| 386 | self.smtp_state = self.COMMAND |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 387 | self.push('250 Ok') |
| 388 | |
| 389 | def smtp_DATA(self, arg): |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 390 | if not self.rcpttos: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 391 | self.push('503 Error: need RCPT command') |
| 392 | return |
| 393 | if arg: |
| 394 | self.push('501 Syntax: DATA') |
| 395 | return |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 396 | self.smtp_state = self.DATA |
Josiah Carlson | d74900e | 2008-07-07 04:15:08 +0000 | [diff] [blame] | 397 | self.set_terminator(b'\r\n.\r\n') |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 398 | self.push('354 End data with <CR><LF>.<CR><LF>') |
| 399 | |
| 400 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 401 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 402 | class SMTPServer(asyncore.dispatcher): |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 403 | # SMTPChannel class to use for managing client connections |
| 404 | channel_class = SMTPChannel |
| 405 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 406 | def __init__(self, localaddr, remoteaddr): |
| 407 | self._localaddr = localaddr |
| 408 | self._remoteaddr = remoteaddr |
| 409 | asyncore.dispatcher.__init__(self) |
Giampaolo RodolĂ | 610aa4f | 2010-06-30 17:47:39 +0000 | [diff] [blame] | 410 | try: |
| 411 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) |
| 412 | # try to re-use a server port if possible |
| 413 | self.set_reuse_addr() |
| 414 | self.bind(localaddr) |
| 415 | self.listen(5) |
| 416 | except: |
| 417 | self.close() |
| 418 | raise |
| 419 | else: |
| 420 | print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( |
| 421 | self.__class__.__name__, time.ctime(time.time()), |
| 422 | localaddr, remoteaddr), file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 423 | |
Giampaolo RodolĂ | 977c707 | 2010-10-04 21:08:36 +0000 | [diff] [blame] | 424 | def handle_accepted(self, conn, addr): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 425 | print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) |
Richard Jones | 803ef8a | 2010-07-24 09:51:40 +0000 | [diff] [blame] | 426 | channel = self.channel_class(self, conn, addr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 427 | |
| 428 | # API for "doing something useful with the message" |
| 429 | def process_message(self, peer, mailfrom, rcpttos, data): |
| 430 | """Override this abstract method to handle messages from the client. |
| 431 | |
| 432 | peer is a tuple containing (ipaddr, port) of the client that made the |
| 433 | socket connection to our smtp port. |
| 434 | |
| 435 | mailfrom is the raw address the client claims the message is coming |
| 436 | from. |
| 437 | |
| 438 | rcpttos is a list of raw addresses the client wishes to deliver the |
| 439 | message to. |
| 440 | |
| 441 | data is a string containing the entire full text of the message, |
| 442 | headers (if supplied) and all. It has been `de-transparencied' |
| 443 | according to RFC 821, Section 4.5.2. In other words, a line |
| 444 | containing a `.' followed by other text has had the leading dot |
| 445 | removed. |
| 446 | |
| 447 | This function should return None, for a normal `250 Ok' response; |
| 448 | otherwise it returns the desired response string in RFC 821 format. |
| 449 | |
| 450 | """ |
Guido van Rossum | b8b45ea | 2001-04-15 13:06:04 +0000 | [diff] [blame] | 451 | raise NotImplementedError |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 452 | |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 453 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 454 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 455 | class DebuggingServer(SMTPServer): |
| 456 | # Do something with the gathered message |
| 457 | def process_message(self, peer, mailfrom, rcpttos, data): |
| 458 | inheaders = 1 |
| 459 | lines = data.split('\n') |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 460 | print('---------- MESSAGE FOLLOWS ----------') |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 461 | for line in lines: |
| 462 | # headers first |
| 463 | if inheaders and not line: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 464 | print('X-Peer:', peer[0]) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 465 | inheaders = 0 |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 466 | print(line) |
| 467 | print('------------ END MESSAGE ------------') |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 468 | |
| 469 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 470 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 471 | class PureProxy(SMTPServer): |
| 472 | def process_message(self, peer, mailfrom, rcpttos, data): |
| 473 | lines = data.split('\n') |
| 474 | # Look for the last header |
| 475 | i = 0 |
| 476 | for line in lines: |
| 477 | if not line: |
| 478 | break |
| 479 | i += 1 |
| 480 | lines.insert(i, 'X-Peer: %s' % peer[0]) |
| 481 | data = NEWLINE.join(lines) |
| 482 | refused = self._deliver(mailfrom, rcpttos, data) |
| 483 | # TBD: what to do with refused addresses? |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 484 | print('we got some refusals:', refused, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 485 | |
| 486 | def _deliver(self, mailfrom, rcpttos, data): |
| 487 | import smtplib |
| 488 | refused = {} |
| 489 | try: |
| 490 | s = smtplib.SMTP() |
| 491 | s.connect(self._remoteaddr[0], self._remoteaddr[1]) |
| 492 | try: |
| 493 | refused = s.sendmail(mailfrom, rcpttos, data) |
| 494 | finally: |
| 495 | s.quit() |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 496 | except smtplib.SMTPRecipientsRefused as e: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 497 | print('got SMTPRecipientsRefused', file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 498 | refused = e.recipients |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 499 | except (socket.error, smtplib.SMTPException) as e: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 500 | print('got', e.__class__, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 501 | # All recipients were refused. If the exception had an associated |
| 502 | # error code, use it. Otherwise,fake it with a non-triggering |
| 503 | # exception code. |
| 504 | errcode = getattr(e, 'smtp_code', -1) |
| 505 | errmsg = getattr(e, 'smtp_error', 'ignore') |
| 506 | for r in rcpttos: |
| 507 | refused[r] = (errcode, errmsg) |
| 508 | return refused |
| 509 | |
| 510 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 511 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 512 | class MailmanProxy(PureProxy): |
| 513 | def process_message(self, peer, mailfrom, rcpttos, data): |
Guido van Rossum | 68937b4 | 2007-05-18 00:51:22 +0000 | [diff] [blame] | 514 | from io import StringIO |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 515 | from Mailman import Utils |
| 516 | from Mailman import Message |
| 517 | from Mailman import MailList |
| 518 | # If the message is to a Mailman mailing list, then we'll invoke the |
| 519 | # Mailman script directly, without going through the real smtpd. |
| 520 | # Otherwise we'll forward it to the local proxy for disposition. |
| 521 | listnames = [] |
| 522 | for rcpt in rcpttos: |
| 523 | local = rcpt.lower().split('@')[0] |
| 524 | # We allow the following variations on the theme |
| 525 | # listname |
| 526 | # listname-admin |
| 527 | # listname-owner |
| 528 | # listname-request |
| 529 | # listname-join |
| 530 | # listname-leave |
| 531 | parts = local.split('-') |
| 532 | if len(parts) > 2: |
| 533 | continue |
| 534 | listname = parts[0] |
| 535 | if len(parts) == 2: |
| 536 | command = parts[1] |
| 537 | else: |
| 538 | command = '' |
| 539 | if not Utils.list_exists(listname) or command not in ( |
| 540 | '', 'admin', 'owner', 'request', 'join', 'leave'): |
| 541 | continue |
| 542 | listnames.append((rcpt, listname, command)) |
| 543 | # Remove all list recipients from rcpttos and forward what we're not |
| 544 | # going to take care of ourselves. Linear removal should be fine |
| 545 | # since we don't expect a large number of recipients. |
| 546 | for rcpt, listname, command in listnames: |
| 547 | rcpttos.remove(rcpt) |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 548 | # If there's any non-list destined recipients left, |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 549 | print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 550 | if rcpttos: |
| 551 | refused = self._deliver(mailfrom, rcpttos, data) |
| 552 | # TBD: what to do with refused addresses? |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 553 | print('we got refusals:', refused, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 554 | # Now deliver directly to the list commands |
| 555 | mlists = {} |
| 556 | s = StringIO(data) |
| 557 | msg = Message.Message(s) |
| 558 | # These headers are required for the proper execution of Mailman. All |
Mark Dickinson | 934896d | 2009-02-21 20:59:32 +0000 | [diff] [blame] | 559 | # MTAs in existence seem to add these if the original message doesn't |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 560 | # have them. |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 561 | if not msg.get('from'): |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 562 | msg['From'] = mailfrom |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 563 | if not msg.get('date'): |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 564 | msg['Date'] = time.ctime(time.time()) |
| 565 | for rcpt, listname, command in listnames: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 566 | print('sending message to', rcpt, file=DEBUGSTREAM) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 567 | mlist = mlists.get(listname) |
| 568 | if not mlist: |
| 569 | mlist = MailList.MailList(listname, lock=0) |
| 570 | mlists[listname] = mlist |
| 571 | # dispatch on the type of command |
| 572 | if command == '': |
| 573 | # post |
| 574 | msg.Enqueue(mlist, tolist=1) |
| 575 | elif command == 'admin': |
| 576 | msg.Enqueue(mlist, toadmin=1) |
| 577 | elif command == 'owner': |
| 578 | msg.Enqueue(mlist, toowner=1) |
| 579 | elif command == 'request': |
| 580 | msg.Enqueue(mlist, torequest=1) |
| 581 | elif command in ('join', 'leave'): |
| 582 | # TBD: this is a hack! |
| 583 | if command == 'join': |
| 584 | msg['Subject'] = 'subscribe' |
| 585 | else: |
| 586 | msg['Subject'] = 'unsubscribe' |
| 587 | msg.Enqueue(mlist, torequest=1) |
| 588 | |
| 589 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 590 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 591 | class Options: |
| 592 | setuid = 1 |
| 593 | classname = 'PureProxy' |
| 594 | |
| 595 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 596 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 597 | def parseargs(): |
| 598 | global DEBUGSTREAM |
| 599 | try: |
| 600 | opts, args = getopt.getopt( |
| 601 | sys.argv[1:], 'nVhc:d', |
| 602 | ['class=', 'nosetuid', 'version', 'help', 'debug']) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 603 | except getopt.error as e: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 604 | usage(1, e) |
| 605 | |
| 606 | options = Options() |
| 607 | for opt, arg in opts: |
| 608 | if opt in ('-h', '--help'): |
| 609 | usage(0) |
| 610 | elif opt in ('-V', '--version'): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 611 | print(__version__, file=sys.stderr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 612 | sys.exit(0) |
| 613 | elif opt in ('-n', '--nosetuid'): |
| 614 | options.setuid = 0 |
| 615 | elif opt in ('-c', '--class'): |
| 616 | options.classname = arg |
| 617 | elif opt in ('-d', '--debug'): |
| 618 | DEBUGSTREAM = sys.stderr |
| 619 | |
| 620 | # parse the rest of the arguments |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 621 | if len(args) < 1: |
| 622 | localspec = 'localhost:8025' |
| 623 | remotespec = 'localhost:25' |
| 624 | elif len(args) < 2: |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 625 | localspec = args[0] |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 626 | remotespec = 'localhost:25' |
Barry Warsaw | ebf5427 | 2001-11-04 03:04:25 +0000 | [diff] [blame] | 627 | elif len(args) < 3: |
| 628 | localspec = args[0] |
| 629 | remotespec = args[1] |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 630 | else: |
| 631 | usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) |
| 632 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 633 | # split into host/port pairs |
| 634 | i = localspec.find(':') |
| 635 | if i < 0: |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 636 | usage(1, 'Bad local spec: %s' % localspec) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 637 | options.localhost = localspec[:i] |
| 638 | try: |
| 639 | options.localport = int(localspec[i+1:]) |
| 640 | except ValueError: |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 641 | usage(1, 'Bad local port: %s' % localspec) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 642 | i = remotespec.find(':') |
| 643 | if i < 0: |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 644 | usage(1, 'Bad remote spec: %s' % remotespec) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 645 | options.remotehost = remotespec[:i] |
| 646 | try: |
| 647 | options.remoteport = int(remotespec[i+1:]) |
| 648 | except ValueError: |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 649 | usage(1, 'Bad remote port: %s' % remotespec) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 650 | return options |
| 651 | |
| 652 | |
Barry Warsaw | 0e8427e | 2001-10-04 16:27:04 +0000 | [diff] [blame] | 653 | |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 654 | if __name__ == '__main__': |
| 655 | options = parseargs() |
| 656 | # Become nobody |
| 657 | if options.setuid: |
| 658 | try: |
| 659 | import pwd |
| 660 | except ImportError: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 661 | print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 662 | sys.exit(1) |
| 663 | nobody = pwd.getpwnam('nobody')[2] |
| 664 | try: |
| 665 | os.setuid(nobody) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 666 | except OSError as e: |
Guido van Rossum | 4ba3d65 | 2001-03-02 06:42:34 +0000 | [diff] [blame] | 667 | if e.errno != errno.EPERM: raise |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 668 | print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 669 | sys.exit(1) |
Skip Montanaro | 90e0153 | 2004-06-26 19:18:49 +0000 | [diff] [blame] | 670 | classname = options.classname |
| 671 | if "." in classname: |
| 672 | lastdot = classname.rfind(".") |
| 673 | mod = __import__(classname[:lastdot], globals(), locals(), [""]) |
| 674 | classname = classname[lastdot+1:] |
| 675 | else: |
| 676 | import __main__ as mod |
Skip Montanaro | 90e0153 | 2004-06-26 19:18:49 +0000 | [diff] [blame] | 677 | class_ = getattr(mod, classname) |
Barry Warsaw | 7e0d956 | 2001-01-31 22:51:35 +0000 | [diff] [blame] | 678 | proxy = class_((options.localhost, options.localport), |
| 679 | (options.remotehost, options.remoteport)) |
| 680 | try: |
| 681 | asyncore.loop() |
| 682 | except KeyboardInterrupt: |
| 683 | pass |