blob: 6dace59b91ead45fbe02b2deee9411db30ae46a6 [file] [log] [blame]
Barry Warsaw7e0d9562001-01-31 22:51:35 +00001#! /usr/bin/env python
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
20 Use `classname' as the concrete SMTP proxy class. Uses `SMTPProxy' by
21 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#
62# Please note that this script requires Python 2.0
63#
64# Author: Barry Warsaw <barry@digicool.com>
65#
66# TODO:
67#
68# - support mailbox delivery
69# - alias files
70# - ESMTP
71# - handle error codes from the backend smtpd
72
73import sys
74import os
75import errno
76import getopt
77import time
78import socket
79import asyncore
80import asynchat
81
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=''):
101 print >> sys.stderr, __doc__ % globals()
102 if msg:
103 print >> sys.stderr, msg
104 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)
114 self.__server = server
115 self.__conn = conn
116 self.__addr = addr
117 self.__line = []
118 self.__state = self.COMMAND
119 self.__greeting = 0
120 self.__mailfrom = None
121 self.__rcpttos = []
122 self.__data = ''
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000123 self.__fqdn = socket.getfqdn()
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000124 self.__peer = conn.getpeername()
125 print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
126 self.push('220 %s %s' % (self.__fqdn, __version__))
127 self.set_terminator('\r\n')
128
129 # Overrides base class for convenience
130 def push(self, msg):
131 asynchat.async_chat.push(self, msg + '\r\n')
132
133 # Implementation of base class abstract method
134 def collect_incoming_data(self, data):
135 self.__line.append(data)
136
137 # Implementation of base class abstract method
138 def found_terminator(self):
139 line = EMPTYSTRING.join(self.__line)
Barry Warsaw406d46e2001-08-13 21:18:01 +0000140 print >> DEBUGSTREAM, 'Data:', repr(line)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000141 self.__line = []
142 if self.__state == self.COMMAND:
143 if not line:
144 self.push('500 Error: bad syntax')
145 return
146 method = None
147 i = line.find(' ')
148 if i < 0:
149 command = line.upper()
150 arg = None
151 else:
152 command = line[:i].upper()
153 arg = line[i+1:].strip()
154 method = getattr(self, 'smtp_' + command, None)
155 if not method:
156 self.push('502 Error: command "%s" not implemented' % command)
157 return
158 method(arg)
159 return
160 else:
Guido van Rossum4ba3d652001-03-02 06:42:34 +0000161 if self.__state != self.DATA:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000162 self.push('451 Internal confusion')
163 return
164 # Remove extraneous carriage returns and de-transparency according
165 # to RFC 821, Section 4.5.2.
166 data = []
167 for text in line.split('\r\n'):
168 if text and text[0] == '.':
169 data.append(text[1:])
170 else:
171 data.append(text)
172 self.__data = NEWLINE.join(data)
173 status = self.__server.process_message(self.__peer,
174 self.__mailfrom,
175 self.__rcpttos,
176 self.__data)
177 self.__rcpttos = []
178 self.__mailfrom = None
179 self.__state = self.COMMAND
180 self.set_terminator('\r\n')
181 if not status:
182 self.push('250 Ok')
183 else:
184 self.push(status)
185
186 # SMTP and ESMTP commands
187 def smtp_HELO(self, arg):
188 if not arg:
189 self.push('501 Syntax: HELO hostname')
190 return
191 if self.__greeting:
192 self.push('503 Duplicate HELO/EHLO')
193 else:
194 self.__greeting = arg
195 self.push('250 %s' % self.__fqdn)
196
197 def smtp_NOOP(self, arg):
198 if arg:
199 self.push('501 Syntax: NOOP')
200 else:
201 self.push('250 Ok')
202
203 def smtp_QUIT(self, arg):
204 # args is ignored
205 self.push('221 Bye')
206 self.close_when_done()
207
208 # factored
209 def __getaddr(self, keyword, arg):
210 address = None
211 keylen = len(keyword)
212 if arg[:keylen].upper() == keyword:
213 address = arg[keylen:].strip()
Guido van Rossum4ba3d652001-03-02 06:42:34 +0000214 if address[0] == '<' and address[-1] == '>' and address != '<>':
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000215 # Addresses can be in the form <person@dom.com> but watch out
216 # for null address, e.g. <>
217 address = address[1:-1]
218 return address
219
220 def smtp_MAIL(self, arg):
221 print >> DEBUGSTREAM, '===> MAIL', arg
222 address = self.__getaddr('FROM:', arg)
223 if not address:
224 self.push('501 Syntax: MAIL FROM:<address>')
225 return
226 if self.__mailfrom:
227 self.push('503 Error: nested MAIL command')
228 return
229 self.__mailfrom = address
230 print >> DEBUGSTREAM, 'sender:', self.__mailfrom
231 self.push('250 Ok')
232
233 def smtp_RCPT(self, arg):
234 print >> DEBUGSTREAM, '===> RCPT', arg
235 if not self.__mailfrom:
236 self.push('503 Error: need MAIL command')
237 return
238 address = self.__getaddr('TO:', arg)
239 if not address:
240 self.push('501 Syntax: RCPT TO: <address>')
241 return
242 if address.lower().startswith('stimpy'):
243 self.push('503 You suck %s' % address)
244 return
245 self.__rcpttos.append(address)
246 print >> DEBUGSTREAM, 'recips:', self.__rcpttos
247 self.push('250 Ok')
248
249 def smtp_RSET(self, arg):
250 if arg:
251 self.push('501 Syntax: RSET')
252 return
253 # Resets the sender, recipients, and data, but not the greeting
254 self.__mailfrom = None
255 self.__rcpttos = []
256 self.__data = ''
257 self.__state = self.COMMAND
258 self.push('250 Ok')
259
260 def smtp_DATA(self, arg):
261 if not self.__rcpttos:
262 self.push('503 Error: need RCPT command')
263 return
264 if arg:
265 self.push('501 Syntax: DATA')
266 return
267 self.__state = self.DATA
268 self.set_terminator('\r\n.\r\n')
269 self.push('354 End data with <CR><LF>.<CR><LF>')
270
271
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000272
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000273class SMTPServer(asyncore.dispatcher):
274 def __init__(self, localaddr, remoteaddr):
275 self._localaddr = localaddr
276 self._remoteaddr = remoteaddr
277 asyncore.dispatcher.__init__(self)
278 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
279 # try to re-use a server port if possible
280 self.socket.setsockopt(
281 socket.SOL_SOCKET, socket.SO_REUSEADDR,
282 self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1)
283 self.bind(localaddr)
284 self.listen(5)
285 print '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
286 self.__class__.__name__, time.ctime(time.time()),
287 localaddr, remoteaddr)
288
289 def handle_accept(self):
290 conn, addr = self.accept()
291 print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
292 channel = SMTPChannel(self, conn, addr)
293
294 # API for "doing something useful with the message"
295 def process_message(self, peer, mailfrom, rcpttos, data):
296 """Override this abstract method to handle messages from the client.
297
298 peer is a tuple containing (ipaddr, port) of the client that made the
299 socket connection to our smtp port.
300
301 mailfrom is the raw address the client claims the message is coming
302 from.
303
304 rcpttos is a list of raw addresses the client wishes to deliver the
305 message to.
306
307 data is a string containing the entire full text of the message,
308 headers (if supplied) and all. It has been `de-transparencied'
309 according to RFC 821, Section 4.5.2. In other words, a line
310 containing a `.' followed by other text has had the leading dot
311 removed.
312
313 This function should return None, for a normal `250 Ok' response;
314 otherwise it returns the desired response string in RFC 821 format.
315
316 """
Guido van Rossumb8b45ea2001-04-15 13:06:04 +0000317 raise NotImplementedError
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000318
Tim Peters658cba62001-02-09 20:06:00 +0000319
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000320
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000321class DebuggingServer(SMTPServer):
322 # Do something with the gathered message
323 def process_message(self, peer, mailfrom, rcpttos, data):
324 inheaders = 1
325 lines = data.split('\n')
326 print '---------- MESSAGE FOLLOWS ----------'
327 for line in lines:
328 # headers first
329 if inheaders and not line:
330 print 'X-Peer:', peer[0]
331 inheaders = 0
332 print line
333 print '------------ END MESSAGE ------------'
334
335
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000336
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000337class PureProxy(SMTPServer):
338 def process_message(self, peer, mailfrom, rcpttos, data):
339 lines = data.split('\n')
340 # Look for the last header
341 i = 0
342 for line in lines:
343 if not line:
344 break
345 i += 1
346 lines.insert(i, 'X-Peer: %s' % peer[0])
347 data = NEWLINE.join(lines)
348 refused = self._deliver(mailfrom, rcpttos, data)
349 # TBD: what to do with refused addresses?
350 print >> DEBUGSTREAM, 'we got some refusals'
351
352 def _deliver(self, mailfrom, rcpttos, data):
353 import smtplib
354 refused = {}
355 try:
356 s = smtplib.SMTP()
357 s.connect(self._remoteaddr[0], self._remoteaddr[1])
358 try:
359 refused = s.sendmail(mailfrom, rcpttos, data)
360 finally:
361 s.quit()
362 except smtplib.SMTPRecipientsRefused, e:
363 print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
364 refused = e.recipients
365 except (socket.error, smtplib.SMTPException), e:
366 print >> DEBUGSTREAM, 'got', e.__class__
367 # All recipients were refused. If the exception had an associated
368 # error code, use it. Otherwise,fake it with a non-triggering
369 # exception code.
370 errcode = getattr(e, 'smtp_code', -1)
371 errmsg = getattr(e, 'smtp_error', 'ignore')
372 for r in rcpttos:
373 refused[r] = (errcode, errmsg)
374 return refused
375
376
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000377
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000378class MailmanProxy(PureProxy):
379 def process_message(self, peer, mailfrom, rcpttos, data):
380 from cStringIO import StringIO
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000381 from Mailman import Utils
382 from Mailman import Message
383 from Mailman import MailList
384 # If the message is to a Mailman mailing list, then we'll invoke the
385 # Mailman script directly, without going through the real smtpd.
386 # Otherwise we'll forward it to the local proxy for disposition.
387 listnames = []
388 for rcpt in rcpttos:
389 local = rcpt.lower().split('@')[0]
390 # We allow the following variations on the theme
391 # listname
392 # listname-admin
393 # listname-owner
394 # listname-request
395 # listname-join
396 # listname-leave
397 parts = local.split('-')
398 if len(parts) > 2:
399 continue
400 listname = parts[0]
401 if len(parts) == 2:
402 command = parts[1]
403 else:
404 command = ''
405 if not Utils.list_exists(listname) or command not in (
406 '', 'admin', 'owner', 'request', 'join', 'leave'):
407 continue
408 listnames.append((rcpt, listname, command))
409 # Remove all list recipients from rcpttos and forward what we're not
410 # going to take care of ourselves. Linear removal should be fine
411 # since we don't expect a large number of recipients.
412 for rcpt, listname, command in listnames:
413 rcpttos.remove(rcpt)
Tim Peters658cba62001-02-09 20:06:00 +0000414 # If there's any non-list destined recipients left,
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000415 print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
416 if rcpttos:
417 refused = self._deliver(mailfrom, rcpttos, data)
418 # TBD: what to do with refused addresses?
419 print >> DEBUGSTREAM, 'we got refusals'
420 # Now deliver directly to the list commands
421 mlists = {}
422 s = StringIO(data)
423 msg = Message.Message(s)
424 # These headers are required for the proper execution of Mailman. All
425 # MTAs in existance seem to add these if the original message doesn't
426 # have them.
427 if not msg.getheader('from'):
428 msg['From'] = mailfrom
429 if not msg.getheader('date'):
430 msg['Date'] = time.ctime(time.time())
431 for rcpt, listname, command in listnames:
432 print >> DEBUGSTREAM, 'sending message to', rcpt
433 mlist = mlists.get(listname)
434 if not mlist:
435 mlist = MailList.MailList(listname, lock=0)
436 mlists[listname] = mlist
437 # dispatch on the type of command
438 if command == '':
439 # post
440 msg.Enqueue(mlist, tolist=1)
441 elif command == 'admin':
442 msg.Enqueue(mlist, toadmin=1)
443 elif command == 'owner':
444 msg.Enqueue(mlist, toowner=1)
445 elif command == 'request':
446 msg.Enqueue(mlist, torequest=1)
447 elif command in ('join', 'leave'):
448 # TBD: this is a hack!
449 if command == 'join':
450 msg['Subject'] = 'subscribe'
451 else:
452 msg['Subject'] = 'unsubscribe'
453 msg.Enqueue(mlist, torequest=1)
454
455
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000456
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000457class Options:
458 setuid = 1
459 classname = 'PureProxy'
460
461
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000462
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000463def parseargs():
464 global DEBUGSTREAM
465 try:
466 opts, args = getopt.getopt(
467 sys.argv[1:], 'nVhc:d',
468 ['class=', 'nosetuid', 'version', 'help', 'debug'])
469 except getopt.error, e:
470 usage(1, e)
471
472 options = Options()
473 for opt, arg in opts:
474 if opt in ('-h', '--help'):
475 usage(0)
476 elif opt in ('-V', '--version'):
477 print >> sys.stderr, __version__
478 sys.exit(0)
479 elif opt in ('-n', '--nosetuid'):
480 options.setuid = 0
481 elif opt in ('-c', '--class'):
482 options.classname = arg
483 elif opt in ('-d', '--debug'):
484 DEBUGSTREAM = sys.stderr
485
486 # parse the rest of the arguments
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000487 if len(args) < 1:
488 localspec = 'localhost:8025'
489 remotespec = 'localhost:25'
490 elif len(args) < 2:
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000491 localspec = args[0]
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000492 remotespec = 'localhost:25'
493 else:
494 usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))
495
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000496 # split into host/port pairs
497 i = localspec.find(':')
498 if i < 0:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000499 usage(1, 'Bad local spec: %s' % localspec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000500 options.localhost = localspec[:i]
501 try:
502 options.localport = int(localspec[i+1:])
503 except ValueError:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000504 usage(1, 'Bad local port: %s' % localspec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000505 i = remotespec.find(':')
506 if i < 0:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000507 usage(1, 'Bad remote spec: %s' % remotespec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000508 options.remotehost = remotespec[:i]
509 try:
510 options.remoteport = int(remotespec[i+1:])
511 except ValueError:
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000512 usage(1, 'Bad remote port: %s' % remotespec)
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000513 return options
514
515
Barry Warsaw0e8427e2001-10-04 16:27:04 +0000516
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000517if __name__ == '__main__':
518 options = parseargs()
519 # Become nobody
520 if options.setuid:
521 try:
522 import pwd
523 except ImportError:
524 print >> sys.stderr, \
525 'Cannot import module "pwd"; try running with -n option.'
526 sys.exit(1)
527 nobody = pwd.getpwnam('nobody')[2]
528 try:
529 os.setuid(nobody)
530 except OSError, e:
Guido van Rossum4ba3d652001-03-02 06:42:34 +0000531 if e.errno != errno.EPERM: raise
Barry Warsaw7e0d9562001-01-31 22:51:35 +0000532 print >> sys.stderr, \
533 'Cannot setuid "nobody"; try running with -n option.'
534 sys.exit(1)
535 import __main__
536 class_ = getattr(__main__, options.classname)
537 proxy = class_((options.localhost, options.localport),
538 (options.remotehost, options.remoteport))
539 try:
540 asyncore.loop()
541 except KeyboardInterrupt:
542 pass