pymilter  0.9.6
milter-template.py
1 ## To roll your own milter, create a class that extends Milter.
2 # See the pymilter project at http://bmsi.com/python/milter.html
3 # based on Sendmail's milter API http://www.milter.org/milter_api/api.html
4 # This code is open-source on the same terms as Python.
5 
6 ## Milter calls methods of your class at milter events.
7 ## Return REJECT,TEMPFAIL,ACCEPT to short circuit processing for a message.
8 ## You can also add/del recipients, replacebody, add/del headers, etc.
9 
10 import Milter
11 import StringIO
12 import time
13 import email
14 import sys
15 from socket import AF_INET, AF_INET6
16 from Milter.utils import parse_addr
17 if True:
18  from multiprocessing import Process as Thread, Queue
19 else:
20  from threading import Thread
21  from Queue import Queue
22 
23 logq = Queue(maxsize=4)
24 
25 class myMilter(Milter.Base):
26 
27  def __init__(self): # A new instance with each new connection.
28  self.id = Milter.uniqueID() # Integer incremented with each call.
29 
30  # each connection runs in its own thread and has its own myMilter
31  # instance. Python code must be thread safe. This is trivial if only stuff
32  # in myMilter instances is referenced.
33  @Milter.noreply
34  def connect(self, IPname, family, hostaddr):
35  # (self, 'ip068.subnet71.example.com', AF_INET, ('215.183.71.68', 4720) )
36  # (self, 'ip6.mxout.example.com', AF_INET6,
37  # ('3ffe:80e8:d8::1', 4720, 1, 0) )
38  self.IP = hostaddr[0]
39  self.port = hostaddr[1]
40  if family == AF_INET6:
41  self.flow = hostaddr[2]
42  self.scope = hostaddr[3]
43  else:
44  self.flow = None
45  self.scope = None
46  self.IPname = IPname # Name from a reverse IP lookup
47  self.H = None
48  self.fp = None
49  self.receiver = self.getsymval('j')
50  self.log("connect from %s at %s" % (IPname, hostaddr) )
51 
52  return Milter.CONTINUE
53 
54 
55  ## def hello(self,hostname):
56  def hello(self, heloname):
57  # (self, 'mailout17.dallas.texas.example.com')
58  self.H = heloname
59  self.log("HELO %s" % heloname)
60  if heloname.find('.') < 0: # illegal helo name
61  # NOTE: example only - too many real braindead clients to reject on this
62  self.setreply('550','5.7.1','Sheesh people! Use a proper helo name!')
63  return Milter.REJECT
64 
65  return Milter.CONTINUE
66 
67  ## def envfrom(self,f,*str):
68  def envfrom(self, mailfrom, *str):
69  self.F = mailfrom
70  self.R = [] # list of recipients
71  self.fromparms = Milter.dictfromlist(str) # ESMTP parms
72  self.user = self.getsymval('{auth_authen}') # authenticated user
73  self.log("mail from:", mailfrom, *str)
74  self.fp = StringIO.StringIO()
75  self.canon_from = '@'.join(parse_addr(mailfrom))
76  self.fp.write('From %s %s\n' % (self.canon_from,time.ctime()))
77  return Milter.CONTINUE
78 
79 
80  ## def envrcpt(self, to, *str):
81  @Milter.noreply
82  def envrcpt(self, to, *str):
83  rcptinfo = to,Milter.dictfromlist(str)
84  self.R.append(rcptinfo)
85 
86  return Milter.CONTINUE
87 
88 
89  @Milter.noreply
90  def header(self, name, hval):
91  self.fp.write("%s: %s\n" % (name,hval)) # add header to buffer
92  return Milter.CONTINUE
93 
94  @Milter.noreply
95  def eoh(self):
96  self.fp.write("\n") # terminate headers
97  return Milter.CONTINUE
98 
99  @Milter.noreply
100  def body(self, chunk):
101  self.fp.write(chunk)
102  return Milter.CONTINUE
103 
104  def eom(self):
105  self.fp.seek(0)
106  msg = email.message_from_file(self.fp)
107  self.setreply('250','2.5.1','Grokked by pymilter')
108  # many milter functions can only be called from eom()
109  # example of adding a Bcc:
110  self.addrcpt('<%s>' % 'spy@example.com')
111  return Milter.ACCEPT
112 
113  def close(self):
114  # always called, even when abort is called. Clean up
115  # any external resources here.
116  return Milter.CONTINUE
117 
118  def abort(self):
119  # client disconnected prematurely
120  return Milter.CONTINUE
121 
122  ## === Support Functions ===
123 
124  def log(self,*msg):
125  logq.put((msg,self.id,time.time()))
126 
127 def background():
128  while True:
129  t = logq.get()
130  if not t: break
131  msg,id,ts = t
132  print "%s [%d]" % (time.strftime('%Y%b%d %H:%M:%S',time.localtime(ts)),id),
133  # 2005Oct13 02:34:11 [1] msg1 msg2 msg3 ...
134  for i in msg: print i,
135  print
136 
137 ## ===
138 
139 def main():
140  bt = Thread(target=background)
141  bt.start()
142  socketname = "/home/stuart/pythonsock"
143  timeout = 600
144  # Register to have the Milter factory create instances of your class:
145  Milter.factory = myMilter
146  flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
147  flags += Milter.ADDRCPT
148  flags += Milter.DELRCPT
149  Milter.set_flags(flags) # tell Sendmail which features we use
150  print "%s milter startup" % time.strftime('%Y%b%d %H:%M:%S')
151  sys.stdout.flush()
152  Milter.runmilter("pythonfilter",socketname,timeout)
153  logq.put(None)
154  bt.join()
155  print "%s bms milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
156 
157 if __name__ == "__main__":
158  main()