blob: b4082786fa147b7771238f4d5e3b5578bfa0fff5 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Barry Warsaw406d46e2001-08-13 21:18:01 +00002"""An RFC 2821 smtp proxy.
Barry Warsaw7e0d9562001-01-31 22:51:35 +00003
Barry Warsaw0e8427e2001-10-04 16:27:04 +00004Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Barry Warsaw7e0d9562001-01-31 22:51:35 +00005
6Options:
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 Warsawf267b622004-10-09 21:44:13 +000020 Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by
Barry Warsaw7e0d9562001-01-31 22:51:35 +000021 default.
22
23 --debug
24 -d
25 Turn on debugging prints.
26
27 --help
28 -h
29 Print this message and exit.
30
31Version: %(__version__)s
32
Barry Warsaw0e8427e2001-10-04 16:27:04 +000033If localhost is not given then `localhost' is used, and if localport is not
34given then 8025 is used. If remotehost is not given then `localhost' is used,
35and if remoteport is not given, then 25 is used.
Barry Warsaw7e0d9562001-01-31 22:51:35 +000036"""
37
Barry Warsaw0e8427e2001-10-04 16:27:04 +000038
Barry Warsaw7e0d9562001-01-31 22:51:35 +000039# 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 Rossumb8b45ea2001-04-15 13:06:04 +000045# SMTPServer - the base class for the backend. Raises NotImplementedError
Barry Warsaw7e0d9562001-01-31 22:51:35 +000046# 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 Warsaw7e0d9562001-01-31 22:51:35 +000062#
Barry Warsawb1027642004-07-12 23:10:08 +000063# Author: Barry Warsaw <barry@python.org>
Barry Warsaw7e0d9562001-01-31 22:51:35 +000064#
65# TODO:
66#
67# - support mailbox delivery
68# - alias files
69# - ESMTP
70# - handle error codes from the backend smtpd
71
72import sys
73import os
74import errno
75import getopt
76import time
77import socket
78import asyncore
79import asynchat
Richard Jones803ef8a2010-07-24 09:51:40 +000080from warnings import warn
Barry Warsaw7e0d9562001-01-31 22:51:35 +000081
Skip Montanaro0de65802001-02-15 22:15:14 +000082__all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"]
Barry Warsaw7e0d9562001-01-31 22:51:35 +000083
84program = sys.argv[0]
85__version__ = 'Python SMTP proxy version 0.2'
86
87
88class Devnull:
89 def write(self, msg): pass
90 def flush(self): pass
91
92
93DEBUGSTREAM = Devnull()
94NEWLINE = '\n'
95EMPTYSTRING = ''
Barry Warsaw0e8427e2001-10-04 16:27:04 +000096COMMASPACE = ', '
Barry Warsaw7e0d9562001-01-31 22:51:35 +000097
98
Barry Warsaw0e8427e2001-10-04 16:27:04 +000099
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000100def usage(code, msg=''):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print(__doc__ % globals(), file=sys.stderr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000102 if msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000103 print(msg, file=sys.stderr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000104 sys.exit(code)
105
106
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000107
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000108class 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 Jones803ef8a2010-07-24 09:51:40 +0000114 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()
124 self.peer = conn.getpeername()
125 print('Peer:', repr(self.peer), file=DEBUGSTREAM)
126 self.push('220 %s %s' % (self.fqdn, __version__))
Josiah Carlsond74900e2008-07-07 04:15:08 +0000127 self.set_terminator(b'\r\n')
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000128
Richard Jones803ef8a2010-07-24 09:51:40 +0000129 # properties for backwards-compatibility
130 @property
131 def __server(self):
132 warn("Access to __server attribute on SMTPChannel is deprecated, "
133 "use 'smtp_server' instead", PendingDeprecationWarning, 2)
134 return self.smtp_server
135 @__server.setter
136 def __server(self, value):
137 warn("Setting __server attribute on SMTPChannel is deprecated, "
138 "set 'smtp_server' instead", PendingDeprecationWarning, 2)
139 self.smtp_server = value
140
141 @property
142 def __line(self):
143 warn("Access to __line attribute on SMTPChannel is deprecated, "
144 "use 'received_lines' instead", PendingDeprecationWarning, 2)
145 return self.received_lines
146 @__line.setter
147 def __line(self, value):
148 warn("Setting __line attribute on SMTPChannel is deprecated, "
149 "set 'received_lines' instead", PendingDeprecationWarning, 2)
150 self.received_lines = value
151
152 @property
153 def __state(self):
154 warn("Access to __state attribute on SMTPChannel is deprecated, "
155 "use 'smtp_state' instead", PendingDeprecationWarning, 2)
156 return self.smtp_state
157 @__state.setter
158 def __state(self, value):
159 warn("Setting __state attribute on SMTPChannel is deprecated, "
160 "set 'smtp_state' instead", PendingDeprecationWarning, 2)
161 self.smtp_state = value
162
163 @property
164 def __greeting(self):
165 warn("Access to __greeting attribute on SMTPChannel is deprecated, "
166 "use 'seen_greeting' instead", PendingDeprecationWarning, 2)
167 return self.seen_greeting
168 @__greeting.setter
169 def __greeting(self, value):
170 warn("Setting __greeting attribute on SMTPChannel is deprecated, "
171 "set 'seen_greeting' instead", PendingDeprecationWarning, 2)
172 self.seen_greeting = value
173
174 @property
175 def __mailfrom(self):
176 warn("Access to __mailfrom attribute on SMTPChannel is deprecated, "
177 "use 'mailfrom' instead", PendingDeprecationWarning, 2)
178 return self.mailfrom
179 @__mailfrom.setter
180 def __mailfrom(self, value):
181 warn("Setting __mailfrom attribute on SMTPChannel is deprecated, "
182 "set 'mailfrom' instead", PendingDeprecationWarning, 2)
183 self.mailfrom = value
184
185 @property
186 def __rcpttos(self):
187 warn("Access to __rcpttos attribute on SMTPChannel is deprecated, "
188 "use 'rcpttos' instead", PendingDeprecationWarning, 2)
189 return self.rcpttos
190 @__rcpttos.setter
191 def __rcpttos(self, value):
192 warn("Setting __rcpttos attribute on SMTPChannel is deprecated, "
193 "set 'rcpttos' instead", PendingDeprecationWarning, 2)
194 self.rcpttos = value
195
196 @property
197 def __data(self):
198 warn("Access to __data attribute on SMTPChannel is deprecated, "
199 "use 'received_data' instead", PendingDeprecationWarning, 2)
200 return self.received_data
201 @__data.setter
202 def __data(self, value):
203 warn("Setting __data attribute on SMTPChannel is deprecated, "
204 "set 'received_data' instead", PendingDeprecationWarning, 2)
205 self.received_data = value
206
207 @property
208 def __fqdn(self):
209 warn("Access to __fqdn attribute on SMTPChannel is deprecated, "
210 "use 'fqdn' instead", PendingDeprecationWarning, 2)
211 return self.fqdn
212 @__fqdn.setter
213 def __fqdn(self, value):
214 warn("Setting __fqdn attribute on SMTPChannel is deprecated, "
215 "set 'fqdn' instead", PendingDeprecationWarning, 2)
216 self.fqdn = value
217
218 @property
219 def __peer(self):
220 warn("Access to __peer attribute on SMTPChannel is deprecated, "
221 "use 'peer' instead", PendingDeprecationWarning, 2)
222 return self.peer
223 @__peer.setter
224 def __peer(self, value):
225 warn("Setting __peer attribute on SMTPChannel is deprecated, "
226 "set 'peer' instead", PendingDeprecationWarning, 2)
227 self.peer = value
228
229 @property
230 def __conn(self):
231 warn("Access to __conn attribute on SMTPChannel is deprecated, "
232 "use 'conn' instead", PendingDeprecationWarning, 2)
233 return self.conn
234 @__conn.setter
235 def __conn(self, value):
236 warn("Setting __conn attribute on SMTPChannel is deprecated, "
237 "set 'conn' instead", PendingDeprecationWarning, 2)
238 self.conn = value
239
240 @property
241 def __addr(self):
242 warn("Access to __addr attribute on SMTPChannel is deprecated, "
243 "use 'addr' instead", PendingDeprecationWarning, 2)
244 return self.addr
245 @__addr.setter
246 def __addr(self, value):
247 warn("Setting __addr attribute on SMTPChannel is deprecated, "
248 "set 'addr' instead", PendingDeprecationWarning, 2)
249 self.addr = value
250
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000251 # Overrides base class for convenience
252 def push(self, msg):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000253 asynchat.async_chat.push(self, bytes(msg + '\r\n', 'ascii'))
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000254
255 # Implementation of base class abstract method
256 def collect_incoming_data(self, data):
Richard Jones803ef8a2010-07-24 09:51:40 +0000257 self.received_lines.append(str(data, "utf8"))
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000258
259 # Implementation of base class abstract method
260 def found_terminator(self):
Richard Jones803ef8a2010-07-24 09:51:40 +0000261 line = EMPTYSTRING.join(self.received_lines)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000262 print('Data:', repr(line), file=DEBUGSTREAM)
Richard Jones803ef8a2010-07-24 09:51:40 +0000263 self.received_lines = []
264 if self.smtp_state == self.COMMAND:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000265 if not line:
266 self.push('500 Error: bad syntax')
267 return
268 method = None
269 i = line.find(' ')
270 if i < 0:
271 command = line.upper()
272 arg = None
273 else:
274 command = line[:i].upper()
275 arg = line[i+1:].strip()
276 method = getattr(self, 'smtp_' + command, None)
277 if not method:
278 self.push('502 Error: command "%s" not implemented' % command)
279 return
280 method(arg)
281 return
282 else:
Richard Jones803ef8a2010-07-24 09:51:40 +0000283 if self.smtp_state != self.DATA:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000284 self.push('451 Internal confusion')
285 return
286 # Remove extraneous carriage returns and de-transparency according
287 # to RFC 821, Section 4.5.2.
288 data = []
289 for text in line.split('\r\n'):
290 if text and text[0] == '.':
291 data.append(text[1:])
292 else:
293 data.append(text)
Richard Jones803ef8a2010-07-24 09:51:40 +0000294 self.received_data = NEWLINE.join(data)
Georg Brandl17e3d692010-07-31 10:08:09 +0000295 status = self.smtp_server.process_message(self.peer,
296 self.mailfrom,
297 self.rcpttos,
298 self.received_data)
Richard Jones803ef8a2010-07-24 09:51:40 +0000299 self.rcpttos = []
300 self.mailfrom = None
301 self.smtp_state = self.COMMAND
Josiah Carlsond74900e2008-07-07 04:15:08 +0000302 self.set_terminator(b'\r\n')
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000303 if not status:
304 self.push('250 Ok')
305 else:
306 self.push(status)
307
308 # SMTP and ESMTP commands
309 def smtp_HELO(self, arg):
310 if not arg:
311 self.push('501 Syntax: HELO hostname')
312 return
Richard Jones803ef8a2010-07-24 09:51:40 +0000313 if self.seen_greeting:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000314 self.push('503 Duplicate HELO/EHLO')
315 else:
Richard Jones803ef8a2010-07-24 09:51:40 +0000316 self.seen_greeting = arg
317 self.push('250 %s' % self.fqdn)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000318
319 def smtp_NOOP(self, arg):
320 if arg:
321 self.push('501 Syntax: NOOP')
322 else:
323 self.push('250 Ok')
324
325 def smtp_QUIT(self, arg):
326 # args is ignored
327 self.push('221 Bye')
328 self.close_when_done()
329
330 # factored
331 def __getaddr(self, keyword, arg):
332 address = None
333 keylen = len(keyword)
334 if arg[:keylen].upper() == keyword:
335 address = arg[keylen:].strip()
Barry Warsawebf54272001-11-04 03:04:25 +0000336 if not address:
337 pass
338 elif address[0] == '<' and address[-1] == '>' and address != '<>':
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000339 # Addresses can be in the form <person@dom.com> but watch out
340 # for null address, e.g. <>
341 address = address[1:-1]
342 return address
343
344 def smtp_MAIL(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000345 print('===> MAIL', arg, file=DEBUGSTREAM)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000346 address = self.__getaddr('FROM:', arg) if arg else None
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000347 if not address:
348 self.push('501 Syntax: MAIL FROM:<address>')
349 return
Richard Jones803ef8a2010-07-24 09:51:40 +0000350 if self.mailfrom:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000351 self.push('503 Error: nested MAIL command')
352 return
Richard Jones803ef8a2010-07-24 09:51:40 +0000353 self.mailfrom = address
354 print('sender:', self.mailfrom, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000355 self.push('250 Ok')
356
357 def smtp_RCPT(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000358 print('===> RCPT', arg, file=DEBUGSTREAM)
Richard Jones803ef8a2010-07-24 09:51:40 +0000359 if not self.mailfrom:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000360 self.push('503 Error: need MAIL command')
361 return
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000362 address = self.__getaddr('TO:', arg) if arg else None
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000363 if not address:
364 self.push('501 Syntax: RCPT TO: <address>')
365 return
Richard Jones803ef8a2010-07-24 09:51:40 +0000366 self.rcpttos.append(address)
367 print('recips:', self.rcpttos, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000368 self.push('250 Ok')
369
370 def smtp_RSET(self, arg):
371 if arg:
372 self.push('501 Syntax: RSET')
373 return
374 # Resets the sender, recipients, and data, but not the greeting
Richard Jones803ef8a2010-07-24 09:51:40 +0000375 self.mailfrom = None
376 self.rcpttos = []
377 self.received_data = ''
378 self.smtp_state = self.COMMAND
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000379 self.push('250 Ok')
380
381 def smtp_DATA(self, arg):
Richard Jones803ef8a2010-07-24 09:51:40 +0000382 if not self.rcpttos:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000383 self.push('503 Error: need RCPT command')
384 return
385 if arg:
386 self.push('501 Syntax: DATA')
387 return
Richard Jones803ef8a2010-07-24 09:51:40 +0000388 self.smtp_state = self.DATA
Josiah Carlsond74900e2008-07-07 04:15:08 +0000389 self.set_terminator(b'\r\n.\r\n')
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000390 self.push('354 End data with <CR><LF>.<CR><LF>')
391
392
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000393
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000394class SMTPServer(asyncore.dispatcher):
Richard Jones803ef8a2010-07-24 09:51:40 +0000395 # SMTPChannel class to use for managing client connections
396 channel_class = SMTPChannel
397
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000398 def __init__(self, localaddr, remoteaddr):
399 self._localaddr = localaddr
400 self._remoteaddr = remoteaddr
401 asyncore.dispatcher.__init__(self)
Giampaolo Rodolà610aa4f2010-06-30 17:47:39 +0000402 try:
403 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
404 # try to re-use a server port if possible
405 self.set_reuse_addr()
406 self.bind(localaddr)
407 self.listen(5)
408 except:
409 self.close()
410 raise
411 else:
412 print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
413 self.__class__.__name__, time.ctime(time.time()),
414 localaddr, remoteaddr), file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000415
416 def handle_accept(self):
417 conn, addr = self.accept()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000418 print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM)
Richard Jones803ef8a2010-07-24 09:51:40 +0000419 channel = self.channel_class(self, conn, addr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000420
421 # API for "doing something useful with the message"
422 def process_message(self, peer, mailfrom, rcpttos, data):
423 """Override this abstract method to handle messages from the client.
424
425 peer is a tuple containing (ipaddr, port) of the client that made the
426 socket connection to our smtp port.
427
428 mailfrom is the raw address the client claims the message is coming
429 from.
430
431 rcpttos is a list of raw addresses the client wishes to deliver the
432 message to.
433
434 data is a string containing the entire full text of the message,
435 headers (if supplied) and all. It has been `de-transparencied'
436 according to RFC 821, Section 4.5.2. In other words, a line
437 containing a `.' followed by other text has had the leading dot
438 removed.
439
440 This function should return None, for a normal `250 Ok' response;
441 otherwise it returns the desired response string in RFC 821 format.
442
443 """
Guido van Rossumb8b45ea2001-04-15 13:06:04 +0000444 raise NotImplementedError
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000445
Tim Peters658cba62001-02-09 20:06:00 +0000446
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000447
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000448class DebuggingServer(SMTPServer):
449 # Do something with the gathered message
450 def process_message(self, peer, mailfrom, rcpttos, data):
451 inheaders = 1
452 lines = data.split('\n')
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000453 print('---------- MESSAGE FOLLOWS ----------')
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000454 for line in lines:
455 # headers first
456 if inheaders and not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000457 print('X-Peer:', peer[0])
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000458 inheaders = 0
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000459 print(line)
460 print('------------ END MESSAGE ------------')
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000461
462
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000463
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000464class PureProxy(SMTPServer):
465 def process_message(self, peer, mailfrom, rcpttos, data):
466 lines = data.split('\n')
467 # Look for the last header
468 i = 0
469 for line in lines:
470 if not line:
471 break
472 i += 1
473 lines.insert(i, 'X-Peer: %s' % peer[0])
474 data = NEWLINE.join(lines)
475 refused = self._deliver(mailfrom, rcpttos, data)
476 # TBD: what to do with refused addresses?
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000477 print('we got some refusals:', refused, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000478
479 def _deliver(self, mailfrom, rcpttos, data):
480 import smtplib
481 refused = {}
482 try:
483 s = smtplib.SMTP()
484 s.connect(self._remoteaddr[0], self._remoteaddr[1])
485 try:
486 refused = s.sendmail(mailfrom, rcpttos, data)
487 finally:
488 s.quit()
Guido van Rossumb940e112007-01-10 16:19:56 +0000489 except smtplib.SMTPRecipientsRefused as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000490 print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000491 refused = e.recipients
Guido van Rossumb940e112007-01-10 16:19:56 +0000492 except (socket.error, smtplib.SMTPException) as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000493 print('got', e.__class__, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000494 # All recipients were refused. If the exception had an associated
495 # error code, use it. Otherwise,fake it with a non-triggering
496 # exception code.
497 errcode = getattr(e, 'smtp_code', -1)
498 errmsg = getattr(e, 'smtp_error', 'ignore')
499 for r in rcpttos:
500 refused[r] = (errcode, errmsg)
501 return refused
502
503
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000504
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000505class MailmanProxy(PureProxy):
506 def process_message(self, peer, mailfrom, rcpttos, data):
Guido van Rossum68937b42007-05-18 00:51:22 +0000507 from io import StringIO
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000508 from Mailman import Utils
509 from Mailman import Message
510 from Mailman import MailList
511 # If the message is to a Mailman mailing list, then we'll invoke the
512 # Mailman script directly, without going through the real smtpd.
513 # Otherwise we'll forward it to the local proxy for disposition.
514 listnames = []
515 for rcpt in rcpttos:
516 local = rcpt.lower().split('@')[0]
517 # We allow the following variations on the theme
518 # listname
519 # listname-admin
520 # listname-owner
521 # listname-request
522 # listname-join
523 # listname-leave
524 parts = local.split('-')
525 if len(parts) > 2:
526 continue
527 listname = parts[0]
528 if len(parts) == 2:
529 command = parts[1]
530 else:
531 command = ''
532 if not Utils.list_exists(listname) or command not in (
533 '', 'admin', 'owner', 'request', 'join', 'leave'):
534 continue
535 listnames.append((rcpt, listname, command))
536 # Remove all list recipients from rcpttos and forward what we're not
537 # going to take care of ourselves. Linear removal should be fine
538 # since we don't expect a large number of recipients.
539 for rcpt, listname, command in listnames:
540 rcpttos.remove(rcpt)
Tim Peters658cba62001-02-09 20:06:00 +0000541 # If there's any non-list destined recipients left,
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000542 print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000543 if rcpttos:
544 refused = self._deliver(mailfrom, rcpttos, data)
545 # TBD: what to do with refused addresses?
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000546 print('we got refusals:', refused, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000547 # Now deliver directly to the list commands
548 mlists = {}
549 s = StringIO(data)
550 msg = Message.Message(s)
551 # These headers are required for the proper execution of Mailman. All
Mark Dickinson934896d2009-02-21 20:59:32 +0000552 # MTAs in existence seem to add these if the original message doesn't
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000553 # have them.
Barry Warsaw820c1202008-06-12 04:06:45 +0000554 if not msg.get('from'):
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000555 msg['From'] = mailfrom
Barry Warsaw820c1202008-06-12 04:06:45 +0000556 if not msg.get('date'):
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000557 msg['Date'] = time.ctime(time.time())
558 for rcpt, listname, command in listnames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000559 print('sending message to', rcpt, file=DEBUGSTREAM)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000560 mlist = mlists.get(listname)
561 if not mlist:
562 mlist = MailList.MailList(listname, lock=0)
563 mlists[listname] = mlist
564 # dispatch on the type of command
565 if command == '':
566 # post
567 msg.Enqueue(mlist, tolist=1)
568 elif command == 'admin':
569 msg.Enqueue(mlist, toadmin=1)
570 elif command == 'owner':
571 msg.Enqueue(mlist, toowner=1)
572 elif command == 'request':
573 msg.Enqueue(mlist, torequest=1)
574 elif command in ('join', 'leave'):
575 # TBD: this is a hack!
576 if command == 'join':
577 msg['Subject'] = 'subscribe'
578 else:
579 msg['Subject'] = 'unsubscribe'
580 msg.Enqueue(mlist, torequest=1)
581
582
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000583
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000584class Options:
585 setuid = 1
586 classname = 'PureProxy'
587
588
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000589
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000590def parseargs():
591 global DEBUGSTREAM
592 try:
593 opts, args = getopt.getopt(
594 sys.argv[1:], 'nVhc:d',
595 ['class=', 'nosetuid', 'version', 'help', 'debug'])
Guido van Rossumb940e112007-01-10 16:19:56 +0000596 except getopt.error as e:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000597 usage(1, e)
598
599 options = Options()
600 for opt, arg in opts:
601 if opt in ('-h', '--help'):
602 usage(0)
603 elif opt in ('-V', '--version'):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000604 print(__version__, file=sys.stderr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000605 sys.exit(0)
606 elif opt in ('-n', '--nosetuid'):
607 options.setuid = 0
608 elif opt in ('-c', '--class'):
609 options.classname = arg
610 elif opt in ('-d', '--debug'):
611 DEBUGSTREAM = sys.stderr
612
613 # parse the rest of the arguments
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000614 if len(args) < 1:
615 localspec = 'localhost:8025'
616 remotespec = 'localhost:25'
617 elif len(args) < 2:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000618 localspec = args[0]
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000619 remotespec = 'localhost:25'
Barry Warsawebf54272001-11-04 03:04:25 +0000620 elif len(args) < 3:
621 localspec = args[0]
622 remotespec = args[1]
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000623 else:
624 usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))
625
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000626 # split into host/port pairs
627 i = localspec.find(':')
628 if i < 0:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000629 usage(1, 'Bad local spec: %s' % localspec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000630 options.localhost = localspec[:i]
631 try:
632 options.localport = int(localspec[i+1:])
633 except ValueError:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000634 usage(1, 'Bad local port: %s' % localspec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000635 i = remotespec.find(':')
636 if i < 0:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000637 usage(1, 'Bad remote spec: %s' % remotespec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000638 options.remotehost = remotespec[:i]
639 try:
640 options.remoteport = int(remotespec[i+1:])
641 except ValueError:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000642 usage(1, 'Bad remote port: %s' % remotespec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000643 return options
644
645
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000646
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000647if __name__ == '__main__':
648 options = parseargs()
649 # Become nobody
650 if options.setuid:
651 try:
652 import pwd
653 except ImportError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000654 print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000655 sys.exit(1)
656 nobody = pwd.getpwnam('nobody')[2]
657 try:
658 os.setuid(nobody)
Guido van Rossumb940e112007-01-10 16:19:56 +0000659 except OSError as e:
Guido van Rossum4ba3d652001-03-02 06:42:34 +0000660 if e.errno != errno.EPERM: raise
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000661 print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000662 sys.exit(1)
Skip Montanaro90e01532004-06-26 19:18:49 +0000663 classname = options.classname
664 if "." in classname:
665 lastdot = classname.rfind(".")
666 mod = __import__(classname[:lastdot], globals(), locals(), [""])
667 classname = classname[lastdot+1:]
668 else:
669 import __main__ as mod
Skip Montanaro90e01532004-06-26 19:18:49 +0000670 class_ = getattr(mod, classname)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000671 proxy = class_((options.localhost, options.localport),
672 (options.remotehost, options.remoteport))
673 try:
674 asyncore.loop()
675 except KeyboardInterrupt:
676 pass