| 1 | n/a | #! /usr/bin/env python3 |
|---|
| 2 | n/a | """An RFC 5321 smtp proxy with optional RFC 1870 and RFC 6531 extensions. |
|---|
| 3 | n/a | |
|---|
| 4 | n/a | Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] |
|---|
| 5 | n/a | |
|---|
| 6 | n/a | Options: |
|---|
| 7 | n/a | |
|---|
| 8 | n/a | --nosetuid |
|---|
| 9 | n/a | -n |
|---|
| 10 | n/a | This program generally tries to setuid `nobody', unless this flag is |
|---|
| 11 | n/a | set. The setuid call will fail if this program is not run as root (in |
|---|
| 12 | n/a | which case, use this flag). |
|---|
| 13 | n/a | |
|---|
| 14 | n/a | --version |
|---|
| 15 | n/a | -V |
|---|
| 16 | n/a | Print the version number and exit. |
|---|
| 17 | n/a | |
|---|
| 18 | n/a | --class classname |
|---|
| 19 | n/a | -c classname |
|---|
| 20 | n/a | Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by |
|---|
| 21 | n/a | default. |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | --size limit |
|---|
| 24 | n/a | -s limit |
|---|
| 25 | n/a | Restrict the total size of the incoming message to "limit" number of |
|---|
| 26 | n/a | bytes via the RFC 1870 SIZE extension. Defaults to 33554432 bytes. |
|---|
| 27 | n/a | |
|---|
| 28 | n/a | --smtputf8 |
|---|
| 29 | n/a | -u |
|---|
| 30 | n/a | Enable the SMTPUTF8 extension and behave as an RFC 6531 smtp proxy. |
|---|
| 31 | n/a | |
|---|
| 32 | n/a | --debug |
|---|
| 33 | n/a | -d |
|---|
| 34 | n/a | Turn on debugging prints. |
|---|
| 35 | n/a | |
|---|
| 36 | n/a | --help |
|---|
| 37 | n/a | -h |
|---|
| 38 | n/a | Print this message and exit. |
|---|
| 39 | n/a | |
|---|
| 40 | n/a | Version: %(__version__)s |
|---|
| 41 | n/a | |
|---|
| 42 | n/a | If localhost is not given then `localhost' is used, and if localport is not |
|---|
| 43 | n/a | given then 8025 is used. If remotehost is not given then `localhost' is used, |
|---|
| 44 | n/a | and if remoteport is not given, then 25 is used. |
|---|
| 45 | n/a | """ |
|---|
| 46 | n/a | |
|---|
| 47 | n/a | # Overview: |
|---|
| 48 | n/a | # |
|---|
| 49 | n/a | # This file implements the minimal SMTP protocol as defined in RFC 5321. It |
|---|
| 50 | n/a | # has a hierarchy of classes which implement the backend functionality for the |
|---|
| 51 | n/a | # smtpd. A number of classes are provided: |
|---|
| 52 | n/a | # |
|---|
| 53 | n/a | # SMTPServer - the base class for the backend. Raises NotImplementedError |
|---|
| 54 | n/a | # if you try to use it. |
|---|
| 55 | n/a | # |
|---|
| 56 | n/a | # DebuggingServer - simply prints each message it receives on stdout. |
|---|
| 57 | n/a | # |
|---|
| 58 | n/a | # PureProxy - Proxies all messages to a real smtpd which does final |
|---|
| 59 | n/a | # delivery. One known problem with this class is that it doesn't handle |
|---|
| 60 | n/a | # SMTP errors from the backend server at all. This should be fixed |
|---|
| 61 | n/a | # (contributions are welcome!). |
|---|
| 62 | n/a | # |
|---|
| 63 | n/a | # MailmanProxy - An experimental hack to work with GNU Mailman |
|---|
| 64 | n/a | # <www.list.org>. Using this server as your real incoming smtpd, your |
|---|
| 65 | n/a | # mailhost will automatically recognize and accept mail destined to Mailman |
|---|
| 66 | n/a | # lists when those lists are created. Every message not destined for a list |
|---|
| 67 | n/a | # gets forwarded to a real backend smtpd, as with PureProxy. Again, errors |
|---|
| 68 | n/a | # are not handled correctly yet. |
|---|
| 69 | n/a | # |
|---|
| 70 | n/a | # |
|---|
| 71 | n/a | # Author: Barry Warsaw <barry@python.org> |
|---|
| 72 | n/a | # |
|---|
| 73 | n/a | # TODO: |
|---|
| 74 | n/a | # |
|---|
| 75 | n/a | # - support mailbox delivery |
|---|
| 76 | n/a | # - alias files |
|---|
| 77 | n/a | # - Handle more ESMTP extensions |
|---|
| 78 | n/a | # - handle error codes from the backend smtpd |
|---|
| 79 | n/a | |
|---|
| 80 | n/a | import sys |
|---|
| 81 | n/a | import os |
|---|
| 82 | n/a | import errno |
|---|
| 83 | n/a | import getopt |
|---|
| 84 | n/a | import time |
|---|
| 85 | n/a | import socket |
|---|
| 86 | n/a | import asyncore |
|---|
| 87 | n/a | import asynchat |
|---|
| 88 | n/a | import collections |
|---|
| 89 | n/a | from warnings import warn |
|---|
| 90 | n/a | from email._header_value_parser import get_addr_spec, get_angle_addr |
|---|
| 91 | n/a | |
|---|
| 92 | n/a | __all__ = [ |
|---|
| 93 | n/a | "SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", |
|---|
| 94 | n/a | "MailmanProxy", |
|---|
| 95 | n/a | ] |
|---|
| 96 | n/a | |
|---|
| 97 | n/a | program = sys.argv[0] |
|---|
| 98 | n/a | __version__ = 'Python SMTP proxy version 0.3' |
|---|
| 99 | n/a | |
|---|
| 100 | n/a | |
|---|
| 101 | n/a | class Devnull: |
|---|
| 102 | n/a | def write(self, msg): pass |
|---|
| 103 | n/a | def flush(self): pass |
|---|
| 104 | n/a | |
|---|
| 105 | n/a | |
|---|
| 106 | n/a | DEBUGSTREAM = Devnull() |
|---|
| 107 | n/a | NEWLINE = '\n' |
|---|
| 108 | n/a | COMMASPACE = ', ' |
|---|
| 109 | n/a | DATA_SIZE_DEFAULT = 33554432 |
|---|
| 110 | n/a | |
|---|
| 111 | n/a | |
|---|
| 112 | n/a | def usage(code, msg=''): |
|---|
| 113 | n/a | print(__doc__ % globals(), file=sys.stderr) |
|---|
| 114 | n/a | if msg: |
|---|
| 115 | n/a | print(msg, file=sys.stderr) |
|---|
| 116 | n/a | sys.exit(code) |
|---|
| 117 | n/a | |
|---|
| 118 | n/a | |
|---|
| 119 | n/a | class SMTPChannel(asynchat.async_chat): |
|---|
| 120 | n/a | COMMAND = 0 |
|---|
| 121 | n/a | DATA = 1 |
|---|
| 122 | n/a | |
|---|
| 123 | n/a | command_size_limit = 512 |
|---|
| 124 | n/a | command_size_limits = collections.defaultdict(lambda x=command_size_limit: x) |
|---|
| 125 | n/a | |
|---|
| 126 | n/a | @property |
|---|
| 127 | n/a | def max_command_size_limit(self): |
|---|
| 128 | n/a | try: |
|---|
| 129 | n/a | return max(self.command_size_limits.values()) |
|---|
| 130 | n/a | except ValueError: |
|---|
| 131 | n/a | return self.command_size_limit |
|---|
| 132 | n/a | |
|---|
| 133 | n/a | def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT, |
|---|
| 134 | n/a | map=None, enable_SMTPUTF8=False, decode_data=False): |
|---|
| 135 | n/a | asynchat.async_chat.__init__(self, conn, map=map) |
|---|
| 136 | n/a | self.smtp_server = server |
|---|
| 137 | n/a | self.conn = conn |
|---|
| 138 | n/a | self.addr = addr |
|---|
| 139 | n/a | self.data_size_limit = data_size_limit |
|---|
| 140 | n/a | self.enable_SMTPUTF8 = enable_SMTPUTF8 |
|---|
| 141 | n/a | self._decode_data = decode_data |
|---|
| 142 | n/a | if enable_SMTPUTF8 and decode_data: |
|---|
| 143 | n/a | raise ValueError("decode_data and enable_SMTPUTF8 cannot" |
|---|
| 144 | n/a | " be set to True at the same time") |
|---|
| 145 | n/a | if decode_data: |
|---|
| 146 | n/a | self._emptystring = '' |
|---|
| 147 | n/a | self._linesep = '\r\n' |
|---|
| 148 | n/a | self._dotsep = '.' |
|---|
| 149 | n/a | self._newline = NEWLINE |
|---|
| 150 | n/a | else: |
|---|
| 151 | n/a | self._emptystring = b'' |
|---|
| 152 | n/a | self._linesep = b'\r\n' |
|---|
| 153 | n/a | self._dotsep = ord(b'.') |
|---|
| 154 | n/a | self._newline = b'\n' |
|---|
| 155 | n/a | self._set_rset_state() |
|---|
| 156 | n/a | self.seen_greeting = '' |
|---|
| 157 | n/a | self.extended_smtp = False |
|---|
| 158 | n/a | self.command_size_limits.clear() |
|---|
| 159 | n/a | self.fqdn = socket.getfqdn() |
|---|
| 160 | n/a | try: |
|---|
| 161 | n/a | self.peer = conn.getpeername() |
|---|
| 162 | n/a | except OSError as err: |
|---|
| 163 | n/a | # a race condition may occur if the other end is closing |
|---|
| 164 | n/a | # before we can get the peername |
|---|
| 165 | n/a | self.close() |
|---|
| 166 | n/a | if err.args[0] != errno.ENOTCONN: |
|---|
| 167 | n/a | raise |
|---|
| 168 | n/a | return |
|---|
| 169 | n/a | print('Peer:', repr(self.peer), file=DEBUGSTREAM) |
|---|
| 170 | n/a | self.push('220 %s %s' % (self.fqdn, __version__)) |
|---|
| 171 | n/a | |
|---|
| 172 | n/a | def _set_post_data_state(self): |
|---|
| 173 | n/a | """Reset state variables to their post-DATA state.""" |
|---|
| 174 | n/a | self.smtp_state = self.COMMAND |
|---|
| 175 | n/a | self.mailfrom = None |
|---|
| 176 | n/a | self.rcpttos = [] |
|---|
| 177 | n/a | self.require_SMTPUTF8 = False |
|---|
| 178 | n/a | self.num_bytes = 0 |
|---|
| 179 | n/a | self.set_terminator(b'\r\n') |
|---|
| 180 | n/a | |
|---|
| 181 | n/a | def _set_rset_state(self): |
|---|
| 182 | n/a | """Reset all state variables except the greeting.""" |
|---|
| 183 | n/a | self._set_post_data_state() |
|---|
| 184 | n/a | self.received_data = '' |
|---|
| 185 | n/a | self.received_lines = [] |
|---|
| 186 | n/a | |
|---|
| 187 | n/a | |
|---|
| 188 | n/a | # properties for backwards-compatibility |
|---|
| 189 | n/a | @property |
|---|
| 190 | n/a | def __server(self): |
|---|
| 191 | n/a | warn("Access to __server attribute on SMTPChannel is deprecated, " |
|---|
| 192 | n/a | "use 'smtp_server' instead", DeprecationWarning, 2) |
|---|
| 193 | n/a | return self.smtp_server |
|---|
| 194 | n/a | @__server.setter |
|---|
| 195 | n/a | def __server(self, value): |
|---|
| 196 | n/a | warn("Setting __server attribute on SMTPChannel is deprecated, " |
|---|
| 197 | n/a | "set 'smtp_server' instead", DeprecationWarning, 2) |
|---|
| 198 | n/a | self.smtp_server = value |
|---|
| 199 | n/a | |
|---|
| 200 | n/a | @property |
|---|
| 201 | n/a | def __line(self): |
|---|
| 202 | n/a | warn("Access to __line attribute on SMTPChannel is deprecated, " |
|---|
| 203 | n/a | "use 'received_lines' instead", DeprecationWarning, 2) |
|---|
| 204 | n/a | return self.received_lines |
|---|
| 205 | n/a | @__line.setter |
|---|
| 206 | n/a | def __line(self, value): |
|---|
| 207 | n/a | warn("Setting __line attribute on SMTPChannel is deprecated, " |
|---|
| 208 | n/a | "set 'received_lines' instead", DeprecationWarning, 2) |
|---|
| 209 | n/a | self.received_lines = value |
|---|
| 210 | n/a | |
|---|
| 211 | n/a | @property |
|---|
| 212 | n/a | def __state(self): |
|---|
| 213 | n/a | warn("Access to __state attribute on SMTPChannel is deprecated, " |
|---|
| 214 | n/a | "use 'smtp_state' instead", DeprecationWarning, 2) |
|---|
| 215 | n/a | return self.smtp_state |
|---|
| 216 | n/a | @__state.setter |
|---|
| 217 | n/a | def __state(self, value): |
|---|
| 218 | n/a | warn("Setting __state attribute on SMTPChannel is deprecated, " |
|---|
| 219 | n/a | "set 'smtp_state' instead", DeprecationWarning, 2) |
|---|
| 220 | n/a | self.smtp_state = value |
|---|
| 221 | n/a | |
|---|
| 222 | n/a | @property |
|---|
| 223 | n/a | def __greeting(self): |
|---|
| 224 | n/a | warn("Access to __greeting attribute on SMTPChannel is deprecated, " |
|---|
| 225 | n/a | "use 'seen_greeting' instead", DeprecationWarning, 2) |
|---|
| 226 | n/a | return self.seen_greeting |
|---|
| 227 | n/a | @__greeting.setter |
|---|
| 228 | n/a | def __greeting(self, value): |
|---|
| 229 | n/a | warn("Setting __greeting attribute on SMTPChannel is deprecated, " |
|---|
| 230 | n/a | "set 'seen_greeting' instead", DeprecationWarning, 2) |
|---|
| 231 | n/a | self.seen_greeting = value |
|---|
| 232 | n/a | |
|---|
| 233 | n/a | @property |
|---|
| 234 | n/a | def __mailfrom(self): |
|---|
| 235 | n/a | warn("Access to __mailfrom attribute on SMTPChannel is deprecated, " |
|---|
| 236 | n/a | "use 'mailfrom' instead", DeprecationWarning, 2) |
|---|
| 237 | n/a | return self.mailfrom |
|---|
| 238 | n/a | @__mailfrom.setter |
|---|
| 239 | n/a | def __mailfrom(self, value): |
|---|
| 240 | n/a | warn("Setting __mailfrom attribute on SMTPChannel is deprecated, " |
|---|
| 241 | n/a | "set 'mailfrom' instead", DeprecationWarning, 2) |
|---|
| 242 | n/a | self.mailfrom = value |
|---|
| 243 | n/a | |
|---|
| 244 | n/a | @property |
|---|
| 245 | n/a | def __rcpttos(self): |
|---|
| 246 | n/a | warn("Access to __rcpttos attribute on SMTPChannel is deprecated, " |
|---|
| 247 | n/a | "use 'rcpttos' instead", DeprecationWarning, 2) |
|---|
| 248 | n/a | return self.rcpttos |
|---|
| 249 | n/a | @__rcpttos.setter |
|---|
| 250 | n/a | def __rcpttos(self, value): |
|---|
| 251 | n/a | warn("Setting __rcpttos attribute on SMTPChannel is deprecated, " |
|---|
| 252 | n/a | "set 'rcpttos' instead", DeprecationWarning, 2) |
|---|
| 253 | n/a | self.rcpttos = value |
|---|
| 254 | n/a | |
|---|
| 255 | n/a | @property |
|---|
| 256 | n/a | def __data(self): |
|---|
| 257 | n/a | warn("Access to __data attribute on SMTPChannel is deprecated, " |
|---|
| 258 | n/a | "use 'received_data' instead", DeprecationWarning, 2) |
|---|
| 259 | n/a | return self.received_data |
|---|
| 260 | n/a | @__data.setter |
|---|
| 261 | n/a | def __data(self, value): |
|---|
| 262 | n/a | warn("Setting __data attribute on SMTPChannel is deprecated, " |
|---|
| 263 | n/a | "set 'received_data' instead", DeprecationWarning, 2) |
|---|
| 264 | n/a | self.received_data = value |
|---|
| 265 | n/a | |
|---|
| 266 | n/a | @property |
|---|
| 267 | n/a | def __fqdn(self): |
|---|
| 268 | n/a | warn("Access to __fqdn attribute on SMTPChannel is deprecated, " |
|---|
| 269 | n/a | "use 'fqdn' instead", DeprecationWarning, 2) |
|---|
| 270 | n/a | return self.fqdn |
|---|
| 271 | n/a | @__fqdn.setter |
|---|
| 272 | n/a | def __fqdn(self, value): |
|---|
| 273 | n/a | warn("Setting __fqdn attribute on SMTPChannel is deprecated, " |
|---|
| 274 | n/a | "set 'fqdn' instead", DeprecationWarning, 2) |
|---|
| 275 | n/a | self.fqdn = value |
|---|
| 276 | n/a | |
|---|
| 277 | n/a | @property |
|---|
| 278 | n/a | def __peer(self): |
|---|
| 279 | n/a | warn("Access to __peer attribute on SMTPChannel is deprecated, " |
|---|
| 280 | n/a | "use 'peer' instead", DeprecationWarning, 2) |
|---|
| 281 | n/a | return self.peer |
|---|
| 282 | n/a | @__peer.setter |
|---|
| 283 | n/a | def __peer(self, value): |
|---|
| 284 | n/a | warn("Setting __peer attribute on SMTPChannel is deprecated, " |
|---|
| 285 | n/a | "set 'peer' instead", DeprecationWarning, 2) |
|---|
| 286 | n/a | self.peer = value |
|---|
| 287 | n/a | |
|---|
| 288 | n/a | @property |
|---|
| 289 | n/a | def __conn(self): |
|---|
| 290 | n/a | warn("Access to __conn attribute on SMTPChannel is deprecated, " |
|---|
| 291 | n/a | "use 'conn' instead", DeprecationWarning, 2) |
|---|
| 292 | n/a | return self.conn |
|---|
| 293 | n/a | @__conn.setter |
|---|
| 294 | n/a | def __conn(self, value): |
|---|
| 295 | n/a | warn("Setting __conn attribute on SMTPChannel is deprecated, " |
|---|
| 296 | n/a | "set 'conn' instead", DeprecationWarning, 2) |
|---|
| 297 | n/a | self.conn = value |
|---|
| 298 | n/a | |
|---|
| 299 | n/a | @property |
|---|
| 300 | n/a | def __addr(self): |
|---|
| 301 | n/a | warn("Access to __addr attribute on SMTPChannel is deprecated, " |
|---|
| 302 | n/a | "use 'addr' instead", DeprecationWarning, 2) |
|---|
| 303 | n/a | return self.addr |
|---|
| 304 | n/a | @__addr.setter |
|---|
| 305 | n/a | def __addr(self, value): |
|---|
| 306 | n/a | warn("Setting __addr attribute on SMTPChannel is deprecated, " |
|---|
| 307 | n/a | "set 'addr' instead", DeprecationWarning, 2) |
|---|
| 308 | n/a | self.addr = value |
|---|
| 309 | n/a | |
|---|
| 310 | n/a | # Overrides base class for convenience. |
|---|
| 311 | n/a | def push(self, msg): |
|---|
| 312 | n/a | asynchat.async_chat.push(self, bytes( |
|---|
| 313 | n/a | msg + '\r\n', 'utf-8' if self.require_SMTPUTF8 else 'ascii')) |
|---|
| 314 | n/a | |
|---|
| 315 | n/a | # Implementation of base class abstract method |
|---|
| 316 | n/a | def collect_incoming_data(self, data): |
|---|
| 317 | n/a | limit = None |
|---|
| 318 | n/a | if self.smtp_state == self.COMMAND: |
|---|
| 319 | n/a | limit = self.max_command_size_limit |
|---|
| 320 | n/a | elif self.smtp_state == self.DATA: |
|---|
| 321 | n/a | limit = self.data_size_limit |
|---|
| 322 | n/a | if limit and self.num_bytes > limit: |
|---|
| 323 | n/a | return |
|---|
| 324 | n/a | elif limit: |
|---|
| 325 | n/a | self.num_bytes += len(data) |
|---|
| 326 | n/a | if self._decode_data: |
|---|
| 327 | n/a | self.received_lines.append(str(data, 'utf-8')) |
|---|
| 328 | n/a | else: |
|---|
| 329 | n/a | self.received_lines.append(data) |
|---|
| 330 | n/a | |
|---|
| 331 | n/a | # Implementation of base class abstract method |
|---|
| 332 | n/a | def found_terminator(self): |
|---|
| 333 | n/a | line = self._emptystring.join(self.received_lines) |
|---|
| 334 | n/a | print('Data:', repr(line), file=DEBUGSTREAM) |
|---|
| 335 | n/a | self.received_lines = [] |
|---|
| 336 | n/a | if self.smtp_state == self.COMMAND: |
|---|
| 337 | n/a | sz, self.num_bytes = self.num_bytes, 0 |
|---|
| 338 | n/a | if not line: |
|---|
| 339 | n/a | self.push('500 Error: bad syntax') |
|---|
| 340 | n/a | return |
|---|
| 341 | n/a | if not self._decode_data: |
|---|
| 342 | n/a | line = str(line, 'utf-8') |
|---|
| 343 | n/a | i = line.find(' ') |
|---|
| 344 | n/a | if i < 0: |
|---|
| 345 | n/a | command = line.upper() |
|---|
| 346 | n/a | arg = None |
|---|
| 347 | n/a | else: |
|---|
| 348 | n/a | command = line[:i].upper() |
|---|
| 349 | n/a | arg = line[i+1:].strip() |
|---|
| 350 | n/a | max_sz = (self.command_size_limits[command] |
|---|
| 351 | n/a | if self.extended_smtp else self.command_size_limit) |
|---|
| 352 | n/a | if sz > max_sz: |
|---|
| 353 | n/a | self.push('500 Error: line too long') |
|---|
| 354 | n/a | return |
|---|
| 355 | n/a | method = getattr(self, 'smtp_' + command, None) |
|---|
| 356 | n/a | if not method: |
|---|
| 357 | n/a | self.push('500 Error: command "%s" not recognized' % command) |
|---|
| 358 | n/a | return |
|---|
| 359 | n/a | method(arg) |
|---|
| 360 | n/a | return |
|---|
| 361 | n/a | else: |
|---|
| 362 | n/a | if self.smtp_state != self.DATA: |
|---|
| 363 | n/a | self.push('451 Internal confusion') |
|---|
| 364 | n/a | self.num_bytes = 0 |
|---|
| 365 | n/a | return |
|---|
| 366 | n/a | if self.data_size_limit and self.num_bytes > self.data_size_limit: |
|---|
| 367 | n/a | self.push('552 Error: Too much mail data') |
|---|
| 368 | n/a | self.num_bytes = 0 |
|---|
| 369 | n/a | return |
|---|
| 370 | n/a | # Remove extraneous carriage returns and de-transparency according |
|---|
| 371 | n/a | # to RFC 5321, Section 4.5.2. |
|---|
| 372 | n/a | data = [] |
|---|
| 373 | n/a | for text in line.split(self._linesep): |
|---|
| 374 | n/a | if text and text[0] == self._dotsep: |
|---|
| 375 | n/a | data.append(text[1:]) |
|---|
| 376 | n/a | else: |
|---|
| 377 | n/a | data.append(text) |
|---|
| 378 | n/a | self.received_data = self._newline.join(data) |
|---|
| 379 | n/a | args = (self.peer, self.mailfrom, self.rcpttos, self.received_data) |
|---|
| 380 | n/a | kwargs = {} |
|---|
| 381 | n/a | if not self._decode_data: |
|---|
| 382 | n/a | kwargs = { |
|---|
| 383 | n/a | 'mail_options': self.mail_options, |
|---|
| 384 | n/a | 'rcpt_options': self.rcpt_options, |
|---|
| 385 | n/a | } |
|---|
| 386 | n/a | status = self.smtp_server.process_message(*args, **kwargs) |
|---|
| 387 | n/a | self._set_post_data_state() |
|---|
| 388 | n/a | if not status: |
|---|
| 389 | n/a | self.push('250 OK') |
|---|
| 390 | n/a | else: |
|---|
| 391 | n/a | self.push(status) |
|---|
| 392 | n/a | |
|---|
| 393 | n/a | # SMTP and ESMTP commands |
|---|
| 394 | n/a | def smtp_HELO(self, arg): |
|---|
| 395 | n/a | if not arg: |
|---|
| 396 | n/a | self.push('501 Syntax: HELO hostname') |
|---|
| 397 | n/a | return |
|---|
| 398 | n/a | # See issue #21783 for a discussion of this behavior. |
|---|
| 399 | n/a | if self.seen_greeting: |
|---|
| 400 | n/a | self.push('503 Duplicate HELO/EHLO') |
|---|
| 401 | n/a | return |
|---|
| 402 | n/a | self._set_rset_state() |
|---|
| 403 | n/a | self.seen_greeting = arg |
|---|
| 404 | n/a | self.push('250 %s' % self.fqdn) |
|---|
| 405 | n/a | |
|---|
| 406 | n/a | def smtp_EHLO(self, arg): |
|---|
| 407 | n/a | if not arg: |
|---|
| 408 | n/a | self.push('501 Syntax: EHLO hostname') |
|---|
| 409 | n/a | return |
|---|
| 410 | n/a | # See issue #21783 for a discussion of this behavior. |
|---|
| 411 | n/a | if self.seen_greeting: |
|---|
| 412 | n/a | self.push('503 Duplicate HELO/EHLO') |
|---|
| 413 | n/a | return |
|---|
| 414 | n/a | self._set_rset_state() |
|---|
| 415 | n/a | self.seen_greeting = arg |
|---|
| 416 | n/a | self.extended_smtp = True |
|---|
| 417 | n/a | self.push('250-%s' % self.fqdn) |
|---|
| 418 | n/a | if self.data_size_limit: |
|---|
| 419 | n/a | self.push('250-SIZE %s' % self.data_size_limit) |
|---|
| 420 | n/a | self.command_size_limits['MAIL'] += 26 |
|---|
| 421 | n/a | if not self._decode_data: |
|---|
| 422 | n/a | self.push('250-8BITMIME') |
|---|
| 423 | n/a | if self.enable_SMTPUTF8: |
|---|
| 424 | n/a | self.push('250-SMTPUTF8') |
|---|
| 425 | n/a | self.command_size_limits['MAIL'] += 10 |
|---|
| 426 | n/a | self.push('250 HELP') |
|---|
| 427 | n/a | |
|---|
| 428 | n/a | def smtp_NOOP(self, arg): |
|---|
| 429 | n/a | if arg: |
|---|
| 430 | n/a | self.push('501 Syntax: NOOP') |
|---|
| 431 | n/a | else: |
|---|
| 432 | n/a | self.push('250 OK') |
|---|
| 433 | n/a | |
|---|
| 434 | n/a | def smtp_QUIT(self, arg): |
|---|
| 435 | n/a | # args is ignored |
|---|
| 436 | n/a | self.push('221 Bye') |
|---|
| 437 | n/a | self.close_when_done() |
|---|
| 438 | n/a | |
|---|
| 439 | n/a | def _strip_command_keyword(self, keyword, arg): |
|---|
| 440 | n/a | keylen = len(keyword) |
|---|
| 441 | n/a | if arg[:keylen].upper() == keyword: |
|---|
| 442 | n/a | return arg[keylen:].strip() |
|---|
| 443 | n/a | return '' |
|---|
| 444 | n/a | |
|---|
| 445 | n/a | def _getaddr(self, arg): |
|---|
| 446 | n/a | if not arg: |
|---|
| 447 | n/a | return '', '' |
|---|
| 448 | n/a | if arg.lstrip().startswith('<'): |
|---|
| 449 | n/a | address, rest = get_angle_addr(arg) |
|---|
| 450 | n/a | else: |
|---|
| 451 | n/a | address, rest = get_addr_spec(arg) |
|---|
| 452 | n/a | if not address: |
|---|
| 453 | n/a | return address, rest |
|---|
| 454 | n/a | return address.addr_spec, rest |
|---|
| 455 | n/a | |
|---|
| 456 | n/a | def _getparams(self, params): |
|---|
| 457 | n/a | # Return params as dictionary. Return None if not all parameters |
|---|
| 458 | n/a | # appear to be syntactically valid according to RFC 1869. |
|---|
| 459 | n/a | result = {} |
|---|
| 460 | n/a | for param in params: |
|---|
| 461 | n/a | param, eq, value = param.partition('=') |
|---|
| 462 | n/a | if not param.isalnum() or eq and not value: |
|---|
| 463 | n/a | return None |
|---|
| 464 | n/a | result[param] = value if eq else True |
|---|
| 465 | n/a | return result |
|---|
| 466 | n/a | |
|---|
| 467 | n/a | def smtp_HELP(self, arg): |
|---|
| 468 | n/a | if arg: |
|---|
| 469 | n/a | extended = ' [SP <mail-parameters>]' |
|---|
| 470 | n/a | lc_arg = arg.upper() |
|---|
| 471 | n/a | if lc_arg == 'EHLO': |
|---|
| 472 | n/a | self.push('250 Syntax: EHLO hostname') |
|---|
| 473 | n/a | elif lc_arg == 'HELO': |
|---|
| 474 | n/a | self.push('250 Syntax: HELO hostname') |
|---|
| 475 | n/a | elif lc_arg == 'MAIL': |
|---|
| 476 | n/a | msg = '250 Syntax: MAIL FROM: <address>' |
|---|
| 477 | n/a | if self.extended_smtp: |
|---|
| 478 | n/a | msg += extended |
|---|
| 479 | n/a | self.push(msg) |
|---|
| 480 | n/a | elif lc_arg == 'RCPT': |
|---|
| 481 | n/a | msg = '250 Syntax: RCPT TO: <address>' |
|---|
| 482 | n/a | if self.extended_smtp: |
|---|
| 483 | n/a | msg += extended |
|---|
| 484 | n/a | self.push(msg) |
|---|
| 485 | n/a | elif lc_arg == 'DATA': |
|---|
| 486 | n/a | self.push('250 Syntax: DATA') |
|---|
| 487 | n/a | elif lc_arg == 'RSET': |
|---|
| 488 | n/a | self.push('250 Syntax: RSET') |
|---|
| 489 | n/a | elif lc_arg == 'NOOP': |
|---|
| 490 | n/a | self.push('250 Syntax: NOOP') |
|---|
| 491 | n/a | elif lc_arg == 'QUIT': |
|---|
| 492 | n/a | self.push('250 Syntax: QUIT') |
|---|
| 493 | n/a | elif lc_arg == 'VRFY': |
|---|
| 494 | n/a | self.push('250 Syntax: VRFY <address>') |
|---|
| 495 | n/a | else: |
|---|
| 496 | n/a | self.push('501 Supported commands: EHLO HELO MAIL RCPT ' |
|---|
| 497 | n/a | 'DATA RSET NOOP QUIT VRFY') |
|---|
| 498 | n/a | else: |
|---|
| 499 | n/a | self.push('250 Supported commands: EHLO HELO MAIL RCPT DATA ' |
|---|
| 500 | n/a | 'RSET NOOP QUIT VRFY') |
|---|
| 501 | n/a | |
|---|
| 502 | n/a | def smtp_VRFY(self, arg): |
|---|
| 503 | n/a | if arg: |
|---|
| 504 | n/a | address, params = self._getaddr(arg) |
|---|
| 505 | n/a | if address: |
|---|
| 506 | n/a | self.push('252 Cannot VRFY user, but will accept message ' |
|---|
| 507 | n/a | 'and attempt delivery') |
|---|
| 508 | n/a | else: |
|---|
| 509 | n/a | self.push('502 Could not VRFY %s' % arg) |
|---|
| 510 | n/a | else: |
|---|
| 511 | n/a | self.push('501 Syntax: VRFY <address>') |
|---|
| 512 | n/a | |
|---|
| 513 | n/a | def smtp_MAIL(self, arg): |
|---|
| 514 | n/a | if not self.seen_greeting: |
|---|
| 515 | n/a | self.push('503 Error: send HELO first') |
|---|
| 516 | n/a | return |
|---|
| 517 | n/a | print('===> MAIL', arg, file=DEBUGSTREAM) |
|---|
| 518 | n/a | syntaxerr = '501 Syntax: MAIL FROM: <address>' |
|---|
| 519 | n/a | if self.extended_smtp: |
|---|
| 520 | n/a | syntaxerr += ' [SP <mail-parameters>]' |
|---|
| 521 | n/a | if arg is None: |
|---|
| 522 | n/a | self.push(syntaxerr) |
|---|
| 523 | n/a | return |
|---|
| 524 | n/a | arg = self._strip_command_keyword('FROM:', arg) |
|---|
| 525 | n/a | address, params = self._getaddr(arg) |
|---|
| 526 | n/a | if not address: |
|---|
| 527 | n/a | self.push(syntaxerr) |
|---|
| 528 | n/a | return |
|---|
| 529 | n/a | if not self.extended_smtp and params: |
|---|
| 530 | n/a | self.push(syntaxerr) |
|---|
| 531 | n/a | return |
|---|
| 532 | n/a | if self.mailfrom: |
|---|
| 533 | n/a | self.push('503 Error: nested MAIL command') |
|---|
| 534 | n/a | return |
|---|
| 535 | n/a | self.mail_options = params.upper().split() |
|---|
| 536 | n/a | params = self._getparams(self.mail_options) |
|---|
| 537 | n/a | if params is None: |
|---|
| 538 | n/a | self.push(syntaxerr) |
|---|
| 539 | n/a | return |
|---|
| 540 | n/a | if not self._decode_data: |
|---|
| 541 | n/a | body = params.pop('BODY', '7BIT') |
|---|
| 542 | n/a | if body not in ['7BIT', '8BITMIME']: |
|---|
| 543 | n/a | self.push('501 Error: BODY can only be one of 7BIT, 8BITMIME') |
|---|
| 544 | n/a | return |
|---|
| 545 | n/a | if self.enable_SMTPUTF8: |
|---|
| 546 | n/a | smtputf8 = params.pop('SMTPUTF8', False) |
|---|
| 547 | n/a | if smtputf8 is True: |
|---|
| 548 | n/a | self.require_SMTPUTF8 = True |
|---|
| 549 | n/a | elif smtputf8 is not False: |
|---|
| 550 | n/a | self.push('501 Error: SMTPUTF8 takes no arguments') |
|---|
| 551 | n/a | return |
|---|
| 552 | n/a | size = params.pop('SIZE', None) |
|---|
| 553 | n/a | if size: |
|---|
| 554 | n/a | if not size.isdigit(): |
|---|
| 555 | n/a | self.push(syntaxerr) |
|---|
| 556 | n/a | return |
|---|
| 557 | n/a | elif self.data_size_limit and int(size) > self.data_size_limit: |
|---|
| 558 | n/a | self.push('552 Error: message size exceeds fixed maximum message size') |
|---|
| 559 | n/a | return |
|---|
| 560 | n/a | if len(params.keys()) > 0: |
|---|
| 561 | n/a | self.push('555 MAIL FROM parameters not recognized or not implemented') |
|---|
| 562 | n/a | return |
|---|
| 563 | n/a | self.mailfrom = address |
|---|
| 564 | n/a | print('sender:', self.mailfrom, file=DEBUGSTREAM) |
|---|
| 565 | n/a | self.push('250 OK') |
|---|
| 566 | n/a | |
|---|
| 567 | n/a | def smtp_RCPT(self, arg): |
|---|
| 568 | n/a | if not self.seen_greeting: |
|---|
| 569 | n/a | self.push('503 Error: send HELO first'); |
|---|
| 570 | n/a | return |
|---|
| 571 | n/a | print('===> RCPT', arg, file=DEBUGSTREAM) |
|---|
| 572 | n/a | if not self.mailfrom: |
|---|
| 573 | n/a | self.push('503 Error: need MAIL command') |
|---|
| 574 | n/a | return |
|---|
| 575 | n/a | syntaxerr = '501 Syntax: RCPT TO: <address>' |
|---|
| 576 | n/a | if self.extended_smtp: |
|---|
| 577 | n/a | syntaxerr += ' [SP <mail-parameters>]' |
|---|
| 578 | n/a | if arg is None: |
|---|
| 579 | n/a | self.push(syntaxerr) |
|---|
| 580 | n/a | return |
|---|
| 581 | n/a | arg = self._strip_command_keyword('TO:', arg) |
|---|
| 582 | n/a | address, params = self._getaddr(arg) |
|---|
| 583 | n/a | if not address: |
|---|
| 584 | n/a | self.push(syntaxerr) |
|---|
| 585 | n/a | return |
|---|
| 586 | n/a | if not self.extended_smtp and params: |
|---|
| 587 | n/a | self.push(syntaxerr) |
|---|
| 588 | n/a | return |
|---|
| 589 | n/a | self.rcpt_options = params.upper().split() |
|---|
| 590 | n/a | params = self._getparams(self.rcpt_options) |
|---|
| 591 | n/a | if params is None: |
|---|
| 592 | n/a | self.push(syntaxerr) |
|---|
| 593 | n/a | return |
|---|
| 594 | n/a | # XXX currently there are no options we recognize. |
|---|
| 595 | n/a | if len(params.keys()) > 0: |
|---|
| 596 | n/a | self.push('555 RCPT TO parameters not recognized or not implemented') |
|---|
| 597 | n/a | return |
|---|
| 598 | n/a | self.rcpttos.append(address) |
|---|
| 599 | n/a | print('recips:', self.rcpttos, file=DEBUGSTREAM) |
|---|
| 600 | n/a | self.push('250 OK') |
|---|
| 601 | n/a | |
|---|
| 602 | n/a | def smtp_RSET(self, arg): |
|---|
| 603 | n/a | if arg: |
|---|
| 604 | n/a | self.push('501 Syntax: RSET') |
|---|
| 605 | n/a | return |
|---|
| 606 | n/a | self._set_rset_state() |
|---|
| 607 | n/a | self.push('250 OK') |
|---|
| 608 | n/a | |
|---|
| 609 | n/a | def smtp_DATA(self, arg): |
|---|
| 610 | n/a | if not self.seen_greeting: |
|---|
| 611 | n/a | self.push('503 Error: send HELO first'); |
|---|
| 612 | n/a | return |
|---|
| 613 | n/a | if not self.rcpttos: |
|---|
| 614 | n/a | self.push('503 Error: need RCPT command') |
|---|
| 615 | n/a | return |
|---|
| 616 | n/a | if arg: |
|---|
| 617 | n/a | self.push('501 Syntax: DATA') |
|---|
| 618 | n/a | return |
|---|
| 619 | n/a | self.smtp_state = self.DATA |
|---|
| 620 | n/a | self.set_terminator(b'\r\n.\r\n') |
|---|
| 621 | n/a | self.push('354 End data with <CR><LF>.<CR><LF>') |
|---|
| 622 | n/a | |
|---|
| 623 | n/a | # Commands that have not been implemented |
|---|
| 624 | n/a | def smtp_EXPN(self, arg): |
|---|
| 625 | n/a | self.push('502 EXPN not implemented') |
|---|
| 626 | n/a | |
|---|
| 627 | n/a | |
|---|
| 628 | n/a | class SMTPServer(asyncore.dispatcher): |
|---|
| 629 | n/a | # SMTPChannel class to use for managing client connections |
|---|
| 630 | n/a | channel_class = SMTPChannel |
|---|
| 631 | n/a | |
|---|
| 632 | n/a | def __init__(self, localaddr, remoteaddr, |
|---|
| 633 | n/a | data_size_limit=DATA_SIZE_DEFAULT, map=None, |
|---|
| 634 | n/a | enable_SMTPUTF8=False, decode_data=False): |
|---|
| 635 | n/a | self._localaddr = localaddr |
|---|
| 636 | n/a | self._remoteaddr = remoteaddr |
|---|
| 637 | n/a | self.data_size_limit = data_size_limit |
|---|
| 638 | n/a | self.enable_SMTPUTF8 = enable_SMTPUTF8 |
|---|
| 639 | n/a | self._decode_data = decode_data |
|---|
| 640 | n/a | if enable_SMTPUTF8 and decode_data: |
|---|
| 641 | n/a | raise ValueError("decode_data and enable_SMTPUTF8 cannot" |
|---|
| 642 | n/a | " be set to True at the same time") |
|---|
| 643 | n/a | asyncore.dispatcher.__init__(self, map=map) |
|---|
| 644 | n/a | try: |
|---|
| 645 | n/a | gai_results = socket.getaddrinfo(*localaddr, |
|---|
| 646 | n/a | type=socket.SOCK_STREAM) |
|---|
| 647 | n/a | self.create_socket(gai_results[0][0], gai_results[0][1]) |
|---|
| 648 | n/a | # try to re-use a server port if possible |
|---|
| 649 | n/a | self.set_reuse_addr() |
|---|
| 650 | n/a | self.bind(localaddr) |
|---|
| 651 | n/a | self.listen(5) |
|---|
| 652 | n/a | except: |
|---|
| 653 | n/a | self.close() |
|---|
| 654 | n/a | raise |
|---|
| 655 | n/a | else: |
|---|
| 656 | n/a | print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( |
|---|
| 657 | n/a | self.__class__.__name__, time.ctime(time.time()), |
|---|
| 658 | n/a | localaddr, remoteaddr), file=DEBUGSTREAM) |
|---|
| 659 | n/a | |
|---|
| 660 | n/a | def handle_accepted(self, conn, addr): |
|---|
| 661 | n/a | print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) |
|---|
| 662 | n/a | channel = self.channel_class(self, |
|---|
| 663 | n/a | conn, |
|---|
| 664 | n/a | addr, |
|---|
| 665 | n/a | self.data_size_limit, |
|---|
| 666 | n/a | self._map, |
|---|
| 667 | n/a | self.enable_SMTPUTF8, |
|---|
| 668 | n/a | self._decode_data) |
|---|
| 669 | n/a | |
|---|
| 670 | n/a | # API for "doing something useful with the message" |
|---|
| 671 | n/a | def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): |
|---|
| 672 | n/a | """Override this abstract method to handle messages from the client. |
|---|
| 673 | n/a | |
|---|
| 674 | n/a | peer is a tuple containing (ipaddr, port) of the client that made the |
|---|
| 675 | n/a | socket connection to our smtp port. |
|---|
| 676 | n/a | |
|---|
| 677 | n/a | mailfrom is the raw address the client claims the message is coming |
|---|
| 678 | n/a | from. |
|---|
| 679 | n/a | |
|---|
| 680 | n/a | rcpttos is a list of raw addresses the client wishes to deliver the |
|---|
| 681 | n/a | message to. |
|---|
| 682 | n/a | |
|---|
| 683 | n/a | data is a string containing the entire full text of the message, |
|---|
| 684 | n/a | headers (if supplied) and all. It has been `de-transparencied' |
|---|
| 685 | n/a | according to RFC 821, Section 4.5.2. In other words, a line |
|---|
| 686 | n/a | containing a `.' followed by other text has had the leading dot |
|---|
| 687 | n/a | removed. |
|---|
| 688 | n/a | |
|---|
| 689 | n/a | kwargs is a dictionary containing additional information. It is |
|---|
| 690 | n/a | empty if decode_data=True was given as init parameter, otherwise |
|---|
| 691 | n/a | it will contain the following keys: |
|---|
| 692 | n/a | 'mail_options': list of parameters to the mail command. All |
|---|
| 693 | n/a | elements are uppercase strings. Example: |
|---|
| 694 | n/a | ['BODY=8BITMIME', 'SMTPUTF8']. |
|---|
| 695 | n/a | 'rcpt_options': same, for the rcpt command. |
|---|
| 696 | n/a | |
|---|
| 697 | n/a | This function should return None for a normal `250 Ok' response; |
|---|
| 698 | n/a | otherwise, it should return the desired response string in RFC 821 |
|---|
| 699 | n/a | format. |
|---|
| 700 | n/a | |
|---|
| 701 | n/a | """ |
|---|
| 702 | n/a | raise NotImplementedError |
|---|
| 703 | n/a | |
|---|
| 704 | n/a | |
|---|
| 705 | n/a | class DebuggingServer(SMTPServer): |
|---|
| 706 | n/a | |
|---|
| 707 | n/a | def _print_message_content(self, peer, data): |
|---|
| 708 | n/a | inheaders = 1 |
|---|
| 709 | n/a | lines = data.splitlines() |
|---|
| 710 | n/a | for line in lines: |
|---|
| 711 | n/a | # headers first |
|---|
| 712 | n/a | if inheaders and not line: |
|---|
| 713 | n/a | peerheader = 'X-Peer: ' + peer[0] |
|---|
| 714 | n/a | if not isinstance(data, str): |
|---|
| 715 | n/a | # decoded_data=false; make header match other binary output |
|---|
| 716 | n/a | peerheader = repr(peerheader.encode('utf-8')) |
|---|
| 717 | n/a | print(peerheader) |
|---|
| 718 | n/a | inheaders = 0 |
|---|
| 719 | n/a | if not isinstance(data, str): |
|---|
| 720 | n/a | # Avoid spurious 'str on bytes instance' warning. |
|---|
| 721 | n/a | line = repr(line) |
|---|
| 722 | n/a | print(line) |
|---|
| 723 | n/a | |
|---|
| 724 | n/a | def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): |
|---|
| 725 | n/a | print('---------- MESSAGE FOLLOWS ----------') |
|---|
| 726 | n/a | if kwargs: |
|---|
| 727 | n/a | if kwargs.get('mail_options'): |
|---|
| 728 | n/a | print('mail options: %s' % kwargs['mail_options']) |
|---|
| 729 | n/a | if kwargs.get('rcpt_options'): |
|---|
| 730 | n/a | print('rcpt options: %s\n' % kwargs['rcpt_options']) |
|---|
| 731 | n/a | self._print_message_content(peer, data) |
|---|
| 732 | n/a | print('------------ END MESSAGE ------------') |
|---|
| 733 | n/a | |
|---|
| 734 | n/a | |
|---|
| 735 | n/a | class PureProxy(SMTPServer): |
|---|
| 736 | n/a | def __init__(self, *args, **kwargs): |
|---|
| 737 | n/a | if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: |
|---|
| 738 | n/a | raise ValueError("PureProxy does not support SMTPUTF8.") |
|---|
| 739 | n/a | super(PureProxy, self).__init__(*args, **kwargs) |
|---|
| 740 | n/a | |
|---|
| 741 | n/a | def process_message(self, peer, mailfrom, rcpttos, data): |
|---|
| 742 | n/a | lines = data.split('\n') |
|---|
| 743 | n/a | # Look for the last header |
|---|
| 744 | n/a | i = 0 |
|---|
| 745 | n/a | for line in lines: |
|---|
| 746 | n/a | if not line: |
|---|
| 747 | n/a | break |
|---|
| 748 | n/a | i += 1 |
|---|
| 749 | n/a | lines.insert(i, 'X-Peer: %s' % peer[0]) |
|---|
| 750 | n/a | data = NEWLINE.join(lines) |
|---|
| 751 | n/a | refused = self._deliver(mailfrom, rcpttos, data) |
|---|
| 752 | n/a | # TBD: what to do with refused addresses? |
|---|
| 753 | n/a | print('we got some refusals:', refused, file=DEBUGSTREAM) |
|---|
| 754 | n/a | |
|---|
| 755 | n/a | def _deliver(self, mailfrom, rcpttos, data): |
|---|
| 756 | n/a | import smtplib |
|---|
| 757 | n/a | refused = {} |
|---|
| 758 | n/a | try: |
|---|
| 759 | n/a | s = smtplib.SMTP() |
|---|
| 760 | n/a | s.connect(self._remoteaddr[0], self._remoteaddr[1]) |
|---|
| 761 | n/a | try: |
|---|
| 762 | n/a | refused = s.sendmail(mailfrom, rcpttos, data) |
|---|
| 763 | n/a | finally: |
|---|
| 764 | n/a | s.quit() |
|---|
| 765 | n/a | except smtplib.SMTPRecipientsRefused as e: |
|---|
| 766 | n/a | print('got SMTPRecipientsRefused', file=DEBUGSTREAM) |
|---|
| 767 | n/a | refused = e.recipients |
|---|
| 768 | n/a | except (OSError, smtplib.SMTPException) as e: |
|---|
| 769 | n/a | print('got', e.__class__, file=DEBUGSTREAM) |
|---|
| 770 | n/a | # All recipients were refused. If the exception had an associated |
|---|
| 771 | n/a | # error code, use it. Otherwise,fake it with a non-triggering |
|---|
| 772 | n/a | # exception code. |
|---|
| 773 | n/a | errcode = getattr(e, 'smtp_code', -1) |
|---|
| 774 | n/a | errmsg = getattr(e, 'smtp_error', 'ignore') |
|---|
| 775 | n/a | for r in rcpttos: |
|---|
| 776 | n/a | refused[r] = (errcode, errmsg) |
|---|
| 777 | n/a | return refused |
|---|
| 778 | n/a | |
|---|
| 779 | n/a | |
|---|
| 780 | n/a | class MailmanProxy(PureProxy): |
|---|
| 781 | n/a | def __init__(self, *args, **kwargs): |
|---|
| 782 | n/a | if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: |
|---|
| 783 | n/a | raise ValueError("MailmanProxy does not support SMTPUTF8.") |
|---|
| 784 | n/a | super(PureProxy, self).__init__(*args, **kwargs) |
|---|
| 785 | n/a | |
|---|
| 786 | n/a | def process_message(self, peer, mailfrom, rcpttos, data): |
|---|
| 787 | n/a | from io import StringIO |
|---|
| 788 | n/a | from Mailman import Utils |
|---|
| 789 | n/a | from Mailman import Message |
|---|
| 790 | n/a | from Mailman import MailList |
|---|
| 791 | n/a | # If the message is to a Mailman mailing list, then we'll invoke the |
|---|
| 792 | n/a | # Mailman script directly, without going through the real smtpd. |
|---|
| 793 | n/a | # Otherwise we'll forward it to the local proxy for disposition. |
|---|
| 794 | n/a | listnames = [] |
|---|
| 795 | n/a | for rcpt in rcpttos: |
|---|
| 796 | n/a | local = rcpt.lower().split('@')[0] |
|---|
| 797 | n/a | # We allow the following variations on the theme |
|---|
| 798 | n/a | # listname |
|---|
| 799 | n/a | # listname-admin |
|---|
| 800 | n/a | # listname-owner |
|---|
| 801 | n/a | # listname-request |
|---|
| 802 | n/a | # listname-join |
|---|
| 803 | n/a | # listname-leave |
|---|
| 804 | n/a | parts = local.split('-') |
|---|
| 805 | n/a | if len(parts) > 2: |
|---|
| 806 | n/a | continue |
|---|
| 807 | n/a | listname = parts[0] |
|---|
| 808 | n/a | if len(parts) == 2: |
|---|
| 809 | n/a | command = parts[1] |
|---|
| 810 | n/a | else: |
|---|
| 811 | n/a | command = '' |
|---|
| 812 | n/a | if not Utils.list_exists(listname) or command not in ( |
|---|
| 813 | n/a | '', 'admin', 'owner', 'request', 'join', 'leave'): |
|---|
| 814 | n/a | continue |
|---|
| 815 | n/a | listnames.append((rcpt, listname, command)) |
|---|
| 816 | n/a | # Remove all list recipients from rcpttos and forward what we're not |
|---|
| 817 | n/a | # going to take care of ourselves. Linear removal should be fine |
|---|
| 818 | n/a | # since we don't expect a large number of recipients. |
|---|
| 819 | n/a | for rcpt, listname, command in listnames: |
|---|
| 820 | n/a | rcpttos.remove(rcpt) |
|---|
| 821 | n/a | # If there's any non-list destined recipients left, |
|---|
| 822 | n/a | print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM) |
|---|
| 823 | n/a | if rcpttos: |
|---|
| 824 | n/a | refused = self._deliver(mailfrom, rcpttos, data) |
|---|
| 825 | n/a | # TBD: what to do with refused addresses? |
|---|
| 826 | n/a | print('we got refusals:', refused, file=DEBUGSTREAM) |
|---|
| 827 | n/a | # Now deliver directly to the list commands |
|---|
| 828 | n/a | mlists = {} |
|---|
| 829 | n/a | s = StringIO(data) |
|---|
| 830 | n/a | msg = Message.Message(s) |
|---|
| 831 | n/a | # These headers are required for the proper execution of Mailman. All |
|---|
| 832 | n/a | # MTAs in existence seem to add these if the original message doesn't |
|---|
| 833 | n/a | # have them. |
|---|
| 834 | n/a | if not msg.get('from'): |
|---|
| 835 | n/a | msg['From'] = mailfrom |
|---|
| 836 | n/a | if not msg.get('date'): |
|---|
| 837 | n/a | msg['Date'] = time.ctime(time.time()) |
|---|
| 838 | n/a | for rcpt, listname, command in listnames: |
|---|
| 839 | n/a | print('sending message to', rcpt, file=DEBUGSTREAM) |
|---|
| 840 | n/a | mlist = mlists.get(listname) |
|---|
| 841 | n/a | if not mlist: |
|---|
| 842 | n/a | mlist = MailList.MailList(listname, lock=0) |
|---|
| 843 | n/a | mlists[listname] = mlist |
|---|
| 844 | n/a | # dispatch on the type of command |
|---|
| 845 | n/a | if command == '': |
|---|
| 846 | n/a | # post |
|---|
| 847 | n/a | msg.Enqueue(mlist, tolist=1) |
|---|
| 848 | n/a | elif command == 'admin': |
|---|
| 849 | n/a | msg.Enqueue(mlist, toadmin=1) |
|---|
| 850 | n/a | elif command == 'owner': |
|---|
| 851 | n/a | msg.Enqueue(mlist, toowner=1) |
|---|
| 852 | n/a | elif command == 'request': |
|---|
| 853 | n/a | msg.Enqueue(mlist, torequest=1) |
|---|
| 854 | n/a | elif command in ('join', 'leave'): |
|---|
| 855 | n/a | # TBD: this is a hack! |
|---|
| 856 | n/a | if command == 'join': |
|---|
| 857 | n/a | msg['Subject'] = 'subscribe' |
|---|
| 858 | n/a | else: |
|---|
| 859 | n/a | msg['Subject'] = 'unsubscribe' |
|---|
| 860 | n/a | msg.Enqueue(mlist, torequest=1) |
|---|
| 861 | n/a | |
|---|
| 862 | n/a | |
|---|
| 863 | n/a | class Options: |
|---|
| 864 | n/a | setuid = True |
|---|
| 865 | n/a | classname = 'PureProxy' |
|---|
| 866 | n/a | size_limit = None |
|---|
| 867 | n/a | enable_SMTPUTF8 = False |
|---|
| 868 | n/a | |
|---|
| 869 | n/a | |
|---|
| 870 | n/a | def parseargs(): |
|---|
| 871 | n/a | global DEBUGSTREAM |
|---|
| 872 | n/a | try: |
|---|
| 873 | n/a | opts, args = getopt.getopt( |
|---|
| 874 | n/a | sys.argv[1:], 'nVhc:s:du', |
|---|
| 875 | n/a | ['class=', 'nosetuid', 'version', 'help', 'size=', 'debug', |
|---|
| 876 | n/a | 'smtputf8']) |
|---|
| 877 | n/a | except getopt.error as e: |
|---|
| 878 | n/a | usage(1, e) |
|---|
| 879 | n/a | |
|---|
| 880 | n/a | options = Options() |
|---|
| 881 | n/a | for opt, arg in opts: |
|---|
| 882 | n/a | if opt in ('-h', '--help'): |
|---|
| 883 | n/a | usage(0) |
|---|
| 884 | n/a | elif opt in ('-V', '--version'): |
|---|
| 885 | n/a | print(__version__) |
|---|
| 886 | n/a | sys.exit(0) |
|---|
| 887 | n/a | elif opt in ('-n', '--nosetuid'): |
|---|
| 888 | n/a | options.setuid = False |
|---|
| 889 | n/a | elif opt in ('-c', '--class'): |
|---|
| 890 | n/a | options.classname = arg |
|---|
| 891 | n/a | elif opt in ('-d', '--debug'): |
|---|
| 892 | n/a | DEBUGSTREAM = sys.stderr |
|---|
| 893 | n/a | elif opt in ('-u', '--smtputf8'): |
|---|
| 894 | n/a | options.enable_SMTPUTF8 = True |
|---|
| 895 | n/a | elif opt in ('-s', '--size'): |
|---|
| 896 | n/a | try: |
|---|
| 897 | n/a | int_size = int(arg) |
|---|
| 898 | n/a | options.size_limit = int_size |
|---|
| 899 | n/a | except: |
|---|
| 900 | n/a | print('Invalid size: ' + arg, file=sys.stderr) |
|---|
| 901 | n/a | sys.exit(1) |
|---|
| 902 | n/a | |
|---|
| 903 | n/a | # parse the rest of the arguments |
|---|
| 904 | n/a | if len(args) < 1: |
|---|
| 905 | n/a | localspec = 'localhost:8025' |
|---|
| 906 | n/a | remotespec = 'localhost:25' |
|---|
| 907 | n/a | elif len(args) < 2: |
|---|
| 908 | n/a | localspec = args[0] |
|---|
| 909 | n/a | remotespec = 'localhost:25' |
|---|
| 910 | n/a | elif len(args) < 3: |
|---|
| 911 | n/a | localspec = args[0] |
|---|
| 912 | n/a | remotespec = args[1] |
|---|
| 913 | n/a | else: |
|---|
| 914 | n/a | usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) |
|---|
| 915 | n/a | |
|---|
| 916 | n/a | # split into host/port pairs |
|---|
| 917 | n/a | i = localspec.find(':') |
|---|
| 918 | n/a | if i < 0: |
|---|
| 919 | n/a | usage(1, 'Bad local spec: %s' % localspec) |
|---|
| 920 | n/a | options.localhost = localspec[:i] |
|---|
| 921 | n/a | try: |
|---|
| 922 | n/a | options.localport = int(localspec[i+1:]) |
|---|
| 923 | n/a | except ValueError: |
|---|
| 924 | n/a | usage(1, 'Bad local port: %s' % localspec) |
|---|
| 925 | n/a | i = remotespec.find(':') |
|---|
| 926 | n/a | if i < 0: |
|---|
| 927 | n/a | usage(1, 'Bad remote spec: %s' % remotespec) |
|---|
| 928 | n/a | options.remotehost = remotespec[:i] |
|---|
| 929 | n/a | try: |
|---|
| 930 | n/a | options.remoteport = int(remotespec[i+1:]) |
|---|
| 931 | n/a | except ValueError: |
|---|
| 932 | n/a | usage(1, 'Bad remote port: %s' % remotespec) |
|---|
| 933 | n/a | return options |
|---|
| 934 | n/a | |
|---|
| 935 | n/a | |
|---|
| 936 | n/a | if __name__ == '__main__': |
|---|
| 937 | n/a | options = parseargs() |
|---|
| 938 | n/a | # Become nobody |
|---|
| 939 | n/a | classname = options.classname |
|---|
| 940 | n/a | if "." in classname: |
|---|
| 941 | n/a | lastdot = classname.rfind(".") |
|---|
| 942 | n/a | mod = __import__(classname[:lastdot], globals(), locals(), [""]) |
|---|
| 943 | n/a | classname = classname[lastdot+1:] |
|---|
| 944 | n/a | else: |
|---|
| 945 | n/a | import __main__ as mod |
|---|
| 946 | n/a | class_ = getattr(mod, classname) |
|---|
| 947 | n/a | proxy = class_((options.localhost, options.localport), |
|---|
| 948 | n/a | (options.remotehost, options.remoteport), |
|---|
| 949 | n/a | options.size_limit, enable_SMTPUTF8=options.enable_SMTPUTF8) |
|---|
| 950 | n/a | if options.setuid: |
|---|
| 951 | n/a | try: |
|---|
| 952 | n/a | import pwd |
|---|
| 953 | n/a | except ImportError: |
|---|
| 954 | n/a | print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) |
|---|
| 955 | n/a | sys.exit(1) |
|---|
| 956 | n/a | nobody = pwd.getpwnam('nobody')[2] |
|---|
| 957 | n/a | try: |
|---|
| 958 | n/a | os.setuid(nobody) |
|---|
| 959 | n/a | except PermissionError: |
|---|
| 960 | n/a | print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) |
|---|
| 961 | n/a | sys.exit(1) |
|---|
| 962 | n/a | try: |
|---|
| 963 | n/a | asyncore.loop() |
|---|
| 964 | n/a | except KeyboardInterrupt: |
|---|
| 965 | n/a | pass |
|---|